-
Notifications
You must be signed in to change notification settings - Fork 61
/
analyzing-results.Rmd
305 lines (241 loc) · 7.14 KB
/
analyzing-results.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# Analyzing Results
```{r analyzing-results-create-objects}
portfolio.st <- "Port.Luxor"
account.st <- "Acct.Luxor"
strategy.st <- "Strat.Luxor"
```
```{r analyzing-results-apply-paramset, results = "hide"}
cwd <- getwd()
setwd("./_data/")
load.strategy(strategy.st)
setwd(cwd)
```
```{r analyzing-results-rm-strat}
rm.strat(portfolio.st)
rm.strat(account.st)
```
```{r analyzing-results-init-portf}
initPortf(name = portfolio.st,
symbols = symbols,
initDate = init_date)
```
```{r analyzing-results-init-acct}
initAcct(name = account.st,
portfolios = portfolio.st,
initDate = init_date,
initEq = init_equity)
```
```{r analyzing-results-init-orders}
initOrders(portfolio = portfolio.st,
initDate = init_date)
```
## Apply Strategy
```{r analyzing-results-apply-strategy, results = "hide"}
# Results hidden to save space
applyStrategy(strategy.st, portfolios = portfolio.st)
```
```{r analyzing-results-checkBlotterUpdate}
checkBlotterUpdate(portfolio.st, account.st, verbose = TRUE)
```
```{r analyzing-results-update}
updatePortf(portfolio.st)
updateAcct(account.st)
updateEndEq(account.st)
```
## Chart Positions
```{r}
for(symbol in symbols) {
chart.Posn(portfolio.st, Symbol = symbol,
TA = "add_SMA(n = 10, col = 4); add_SMA(n = 30, col = 2)")
}
```
## Trade Statistics
```{r}
tstats <- tradeStats(portfolio.st)
kable(t(tstats))
```
### Trade Related
```{r}
tab.trades <- tstats %>%
mutate(Trades = Num.Trades,
Win.Percent = Percent.Positive,
Loss.Percent = Percent.Negative,
WL.Ratio = Percent.Positive/Percent.Negative) %>%
select(Trades, Win.Percent, Loss.Percent, WL.Ratio)
kable(t(tab.trades))
```
### Profit Related
```{r}
tab.profit <- tstats %>%
select(Net.Trading.PL, Gross.Profits, Gross.Losses, Profit.Factor)
kable(t(tab.profit))
```
### Averages
```{r}
tab.wins <- tstats %>%
select(Avg.Trade.PL, Avg.Win.Trade, Avg.Losing.Trade, Avg.WinLoss.Ratio)
kable(t(tab.wins))
```
### Performance Summary
```{r}
rets <- PortfReturns(Account = account.st)
rownames(rets) <- NULL
charts.PerformanceSummary(rets, colorset = bluefocus)
```
### Per Trade Statistics
```{r}
for(symbol in symbols) {
pts <- perTradeStats(portfolio.st, Symbol = symbol)
kable(pts, booktabs = TRUE, caption = symbol)
}
kable(pts)
```
### Performance Statistics
```{r}
tab.perf <- table.Arbitrary(rets,
metrics=c(
"Return.cumulative",
"Return.annualized",
"SharpeRatio.annualized",
"CalmarRatio"),
metricsNames=c(
"Cumulative Return",
"Annualized Return",
"Annualized Sharpe Ratio",
"Calmar Ratio"))
kable(tab.perf)
```
### Risk Statistics
```{r}
tab.risk <- table.Arbitrary(rets,
metrics=c(
"StdDev.annualized",
"maxDrawdown",
"VaR",
"ES"),
metricsNames=c(
"Annualized StdDev",
"Max DrawDown",
"Value-at-Risk",
"Conditional VaR"))
kable(tab.risk)
```
### Buy and Hold Performance
```{r}
rm.strat("buyHold")
# initialize portfolio and account
initPortf("buyHold", "SPY", initDate = init_date)
initAcct("buyHold", portfolios = "buyHold",
initDate = init_date, initEq = init_equity)
# place an entry order
CurrentDate <- time(getTxns(Portfolio = portfolio.st, Symbol = "SPY"))[2]
equity = getEndEq("buyHold", CurrentDate)
ClosePrice <- as.numeric(Cl(SPY[CurrentDate,]))
UnitSize = as.numeric(trunc(equity/ClosePrice))
addTxn("buyHold", Symbol = "SPY", TxnDate = CurrentDate, TxnPrice = ClosePrice,
TxnQty = UnitSize, TxnFees = 0)
# place an exit order
LastDate <- last(time(SPY))
LastPrice <- as.numeric(Cl(SPY[LastDate,]))
addTxn("buyHold", Symbol = "SPY", TxnDate = LastDate, TxnPrice = LastPrice,
TxnQty = -UnitSize , TxnFees = 0)
# update portfolio and account
updatePortf(Portfolio = "buyHold")
updateAcct(name = "buyHold")
updateEndEq(Account = "buyHold")
chart.Posn("buyHold", Symbol = "SPY")
```
### Strategy vs. Market
```{r}
rets <- PortfReturns(Account = account.st)
rets.bh <- PortfReturns(Account = "buyHold")
returns <- cbind(rets, rets.bh)
charts.PerformanceSummary(returns, geometric = FALSE, wealth.index = TRUE,
main = "Strategy vs. Market")
```
### Risk/Return Scatterplot
```{r}
chart.RiskReturnScatter(returns, Rf = 0, add.sharpe = c(1, 2),
main = "Return vs. Risk", colorset = c("red", "blue"))
```
### Relative Performance
```{r}
for(n in 1:(ncol(returns) - 1)) {
chart.RelativePerformance(returns[, n], returns[, ncol(returns)],
colorset = c("red", "blue"), lwd = 2,
legend.loc = "topleft")
}
```
### Portfolio Summary
```{r}
#' Error
pf <- getPortfolio(portfolio.st)
xyplot(pf$summary, type = "h", col = 4)
```
### Order Book
```{r}
ob <- getOrderBook(portfolio.st)
```
### Maximum Adverse Excursion
```{r}
for(symbol in symbols) {
chart.ME(Portfolio = portfolio.st, Symbol = symbol, type = "MAE",
scale = "percent")
}
```
### Maximum Favorable Excursion
```{r}
for(symbol in symbols) {
chart.ME(Portfolio = portfolio.st, Symbol = symbol, type = "MFE",
scale = "percent")
}
```
## Account Summary
```{r}
a <- getAccount(account.st)
xyplot(a$summary, type = "h", col = 4)
```
### Equity Curve
```{r}
equity <- a$summary$End.Eq
plot(equity, main = "Equity Curve")
```
### Account Performance Summary
```{r}
ret <- Return.calculate(equity, method = "log")
charts.PerformanceSummary(ret, colorset = bluefocus,
main = "Strategy Performance")
```
### Cumulative Returns
```{r}
rets <- PortfReturns(Account = account.st)
chart.CumReturns(rets, colorset = rich10equal, legend.loc = "topleft",
main="SPDR Cumulative Returns")
```
### Distribution Analysis
```{r}
chart.Boxplot(rets, main = "SPDR Returns", colorset= rich10equal)
```
### Annualized Returns
```{r}
(ar.tab <- table.AnnualizedReturns(rets))
```
### Performance Scatter Plot
```{r}
max.risk <- max(ar.tab["Annualized Std Dev",])
max.return <- max(ar.tab["Annualized Return",])
chart.RiskReturnScatter(rets,
main = "SPDR Performance", colorset = rich10equal,
xlim = c(0, max.risk * 1.1), ylim = c(0, max.return))
```
### Notional Costs
```{r}
#quantstratII pp. 67/69
mnc <- pts$Max.Notional.Cost
pe <- sapply(pts$Start,getEndEq, Account = account.st)/3
barplot(rbind(pe,mnc),beside=T,col=c(2,4),names.arg=format(pts$Start,"%m/%d/%y"),
ylim=c(0,1.5e5),ylab="$",xlab="Trade Date")
legend(x="topleft",legend=c("(Portfolio Equity)/9","Order Size"),
pch=15,col=c(2,4),bty="n")
title("Percent of Portfolio Equity versus Trade Size for XLU")
```