-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIM.SWING-ALO.1.0.Rmd
544 lines (468 loc) · 25.6 KB
/
IM.SWING-ALO.1.0.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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
---
title: "Result Summary for Algorithm trading on NIFTY Options (SWING-ALO)"
output:
pdf_document:
number_sections: true
keep_tex: yes
---
<style type="text/css">
body{ /* Normal */
font-size: 12px;
}
td { /* Table */
font-size: 12px;
}
th {
font-family: Arial;
font-size: 12pt;
height: 20px;
font-weight: bold;
background-color: #ccccff;
}
h1 { /* Header 1 */
font-size: 28px;
/* color: DarkBlue;*/
}
h2 { /* Header 2 */
font-size: 22px;
/* color: DarkBlue;*/
}
h3 { /* Header 3 */
font-size: 18px;
/*color: DarkBlue;*/
}
code.r{ /* Code block */
font-size: 10px;
}
pre { /* Code block */
font-size: 10px
}
</style>
# About SWING-ALO
SWING-ALO is a trading algorithm that trades based on the perdiction for NIFTY50 Index for the forthcoming day. The algorithm attempts to predict if the next business day will be an up-day or a down-day. Based on the prediction, the algorithm buys options on NIFTY50 futures.
The investment algorithm is a combination of money management and price prediction.
##Key Definitions
###Full Hand
The maximum quantity of NIFTY50 contracts that the client wants to trade using the algorithm.
###Trade Size
The quantity of NIFTY50 contracts that the client actually trades using the algorithm. *Trade Size* will vary during the life of the algorithm.
###Underlying Algorithm
The algorithm models its *Trade Size* on the performance of an underlying algorithm that trades using *Full Hand*. The actual trades are just a mirror of trades generated by the *Full Hand* algorithm, except that the size of trades in the alogirthm is dependent on the performance of the *Full Hand* algorithm.
###HighWaterMark
The maximum profit(realized + unrealized) achieved by *Underlying Algorithm* over its life.
###Drawdown Percent
The difference between the current profit of *Underlying Algorithm* and its *HighWaterMark*, expressed as a percentage of the notional exposure arising from a *Full Hand*.
###Threshold Drawdown
A specifed *Drawdown Percent* below which the algorithm pauses trading.
##Money Management
1. The algorithm attempts to keep the *Trade Size* as a function of the *Drawdown Percent*. The maximum *Trade Size* will be the *Full Hand*, if *Drawdown Percent* is near zero, i.e. the underlying algorithm is near the *HighWaterMark*. As *Drawdown Percent* increases, the *Trade Size* reduces.
2. *Trade Size* can become zero, i.e. the algorithm will pause trading, if *Drawdown Percent* rises above *Threshold Drawdown*, i.e. the *Underlying Algorithm* has incurred a drop in profit from the *HighWaterMark* greater than the *Threshold Drawdown*.
3. The algorithm can be run with the Money Management feature or without. For SWING family of algorithm, we trade on futures with Money Management (i.e. contract sizes changes based on performance of the algorithm with *Full Hand*). Option trades are without Money Managment, and always trade with *Full Hand*
##Trading Signals
1. The algorithm predicts the direction for the next day, before the market closing. The prediction is in three categories
a. Up Day - Expect the market to make a higher high and higher low the next day.
b. Down Day - Expect the market to make a lower high and a lower low the next day.
2. Each trade is held till the next prediction (on the next day), or if a stop loss occurs.
3. The strategy does not have an explict take profit signal. Profits are realized via exits generated via the predictions.
```{r setoptions,echo=FALSE,results="hide"}
library(knitr)
opts_chunk$set(echo=FALSE,results="hide")
```
<P style="page-break-before: always">
\newpage
#Run Results [1 year committment, starting Apr 2013]
```{r maincodeline,cache=TRUE,message=FALSE}
#v1.2
#Support backtest using options
library(caret)
library(nnet)
library(doParallel)
library(RcppRoll)
library(TTR)
library(rredis)
library(log4r)
library(RTrade)
library(RQuantLib)
options(scipen=999)
args.commandline=commandArgs(trailingOnly=TRUE)
if(length(args.commandline)>0){
args<-args.commandline
}
# args<-c("2","swing01","3")
# args[1] is a flag for model building. 0=> Build Model, 1=> Generate Signals in Production 2=> Backtest and BootStrap 4=>Save BOD Signals to Redis
# args[2] is the strategy name
# args[3] is the redisdatabase
redisConnect()
redisSelect(1)
if(length(args)>1){
static<-redisHGetAll(toupper(args[2]))
}else{
static<-redisHGetAll("SWINGA")
}
newargs<-unlist(strsplit(static$args,','))
if(length(args)<=1 && length(newargs>1)){
args<-newargs
}
redisClose()
kWriteToRedis <- as.logical(static$WriteToRedis)
kGetMarketData<-as.logical(static$GetMarketData)
kDataCutOffBefore<-static$DataCutOffBefore
kBackTestStartDate<-static$BackTestStartDate
kBackTestEndDate<-static$BackTestEndDate
kFNODataFolder <- static$FNODataFolder
kNiftyDataFolder <- static$NiftyDataFolder
kTimeZone <- static$TimeZone
kIndex<-static$Index
kMLFile<-static$MLFile
kBrokerage<-as.numeric(static$SingleLegBrokerageAsPercentOfValue)/100
kPerContractBrokerage=as.numeric(static$SingleLegBrokerageAsValuePerContract)
kContractSize=as.numeric(static$ContractSize)
kMaxContracts=as.numeric(static$MaxContracts)
kHomeDirectory=static$HomeDirectory
kExchangeMargin=as.numeric(static$ExchangeMargin)
kDrawdownPercentThreshold=as.numeric(static$DrawdownPercentThreshold)
kDrawdownDaysThreshold=as.numeric(static$DrawdownDaysThreshold)
kDrawdownCost=as.numeric(static$DrawdownCost)
kRecoveryBonus=as.numeric(static$RecoveryBonus)
kMoneyManagement=as.numeric(static$MoneyManagement)
setwd(kHomeDirectory)
today<-strftime(Sys.Date(),tz=kTimeZone,format="%Y-%m-%d")
logger <- create.logger()
logfile(logger) <- static$LogFile
level(logger) <- 'INFO'
levellog(logger,"INFO",args)
###### Load Data #############
kairos.symbol <- unlist(strsplit(kIndex, split = "_"))[1]
endtime <- format(Sys.time(), format = "%Y-%m-%d %H:%M:%S")
md <- data.frame()
if (file.exists(paste(kNiftyDataFolder,kIndex, ".Rdata", sep = ""))) {
load(paste(kNiftyDataFolder,kIndex, ".Rdata", sep = ""))
start <- strftime(md[nrow(md), c("date")] + 1, tz = kTimeZone, "%Y-%m-%d %H:%M:%S")
} else{
start <- "2012-10-21 09:15:00"
}
if(kGetMarketData){
temp <-
kGetOHLCV(
paste("symbol", tolower(kairos.symbol), sep = "="),
df=md,
start = start,
end = endtime,
timezone = kTimeZone,
name = "india.nse.index.s4.daily",
ts = c("open", "high", "low","settle", "volume"),
aggregators = c("first", "max", "min", "last", "sum"),
aValue = "1",
aUnit = "days",
splits = data.frame(
date = as.POSIXct(character(), tz = kTimeZone),
symbol = character(),
oldshares = numeric(),
newshares = numeric()
)
)
if (nrow(temp) > 0) {
temp$symbol <- kIndex
}
md<-temp
save(md, file = paste(kNiftyDataFolder,kIndex, ".Rdata", sep = "")) # save new market data to disc
}
if (length(args) > 1 && args[1]==1) {
#Backtesting with today's data from realtime sources
newrow <- getPriceArrayFromRedis(9,"NSENIFTY_IND___","tick","close",paste(today, " 09:12:00"))
newrow <-
data.frame(
"symbol" = "NSENIFTY",
"date" = newrow$date[1],
"open" = newrow$open[1],
"high" = newrow$high[1],
"low" = newrow$low[1],
"settle" = newrow$settle[1],
"close" = newrow$settle[1],
"volume" = 0,
"aopen" = newrow$open[1],
"ahigh" = newrow$high[1],
"alow" = newrow$low[1],
"asettle" = newrow$settle[1],
"aclose" = newrow$settle[1],
"avolume" = 0,
"splitadjust" = 1
)
redisString<-paste(newrow$date[1],newrow$open[1],newrow$high[1],newrow$low[1],newrow$settle[1],newrow$volume[1],sep=",")
levellog(logger,"INFO",paste(args[2], redisString, sep = ":"))
md <- rbind(md, newrow)
}
if (nrow(md) > 0) {
#change col name of settle to close, if temp is returned with data
md<-md[, !(names(md) %in% c("close","aclose"))]
colnames(md) <- c( "date","open","high","low","close","volume","symbol","splitadjust",
"aopen","ahigh","alow","aclose","avolume")
}
md <- unique(md) # remove duplicate rows
load(kMLFile)
##### 1. Calculate Indicators ########
trend <- Trend(md$date, md$high, md$low, md$close)
md$trend <- trend$trend
sd <- roll_sd(md$close, 10) * sqrt(9 / 10)
NA9Vec <- rep(NA, 9)
sd <- c(NA9Vec, sd)
md$closezscore <- (md$close - SMA(md$close, 10)) / sd
md$highzscore <- (md$high - SMA(md$high, 10)) / c(NA9Vec, roll_sd(md$high, 10) * sqrt(9 /10))
md$lowzscore <- (md$low - SMA(md$low, 10)) / c(NA9Vec, roll_sd(md$low, 10) * sqrt(9 / 10))
ma <- SMA(md$close, 10)
md$mazscore <- (ma - SMA(ma, 10)) / c(NA9Vec, roll_sd(ma, 10) * sqrt(9 / 10))
daysinupswing = BarsSince(trend$updownbar <= 0)
daysindownswing = BarsSince(trend$updownbar >= 0)
md$swing = ifelse(daysinupswing > 0, 1, 0)
md$daysinuptrend = BarsSince(trend$trend <= 0)
md$daysindowntrend = BarsSince(trend$trend >= 0)
md$daysintrend = ifelse(trend$trend == 1,md$daysinuptrend,
ifelse(trend$trend == -1, md$daysindowntrend, 0))
md$daysinswing = daysinupswing + daysindownswing
md$atr <- ATR(md[, c("high", "low", "close")], 10)[, 2]
md <- na.omit(md)
trainingsize = sum(md$date < "2013-01-01")
a <-(md$daysintrend - mean(md$daysintrend[md$date < "2013-01-01"])) / (3 * sd(md$daysintrend[md$date <"2013-01-01"]) * sqrt((trainingsize - 1) / trainingsize) / (2 * pi))
md$softmax_daysintrend <- 1 / (1 + exp(-a))
b <- (md$daysinswing - mean(md$daysinswing[md$date < "2013-01-01"])) / (3 * sd(md$daysinswing[md$date <"2013-01-01"]) * sqrt((trainingsize - 1) / trainingsize) / (2 * pi))
md$softmax_daysinswing <- 1 / (1 + exp(-b))
md$dayreturn <- (log(md$close) - log(Ref(md$close, -1))) * 100
####### 2. Generate Buy/Sell Arrays ##########
md$predict.raw <- predict(fit, md, type = 'prob')
md$predict.class <- predict(fit, md)
md$buy = as.numeric(md$predict.class) == 2
md$sell = as.numeric(md$predict.class) == 1
md$short = as.numeric(md$predict.class) == 1
md$cover = as.numeric(md$predict.class) == 2
md$buy = ExRem(md$buy, md$sell)
md$sell = ExRem(md$sell, md$buy)
md$short = ExRem(md$short, md$cover)
md$cover = ExRem(md$cover, md$short)
md$buyprice <- md$close
md$sellprice <- md$close
md$shortprice <- md$close
md$coverprice <- md$close
md$inlongtrade <- Flip(md$buy, md$sell)
md$inshorttrade <- Flip(md$short, md$cover)
###### 3. Create SL/TP Array ############
md$stoploss1 <- ifelse(md$inlongtrade == 1,md$close - md$low,
ifelse(md$inshorttrade == 1, md$high - md$close, 0))
md$stoploss2 <- ifelse(md$inlongtrade == 1 | md$inshorttrade == 1,0.5 * md$atr,0)
md$stoplosslevel <- pmin(md$stoploss1, md$stoploss2)
##### 4. Generate Cash Trades #########
startindex <- which(md$date == kBackTestStartDate)
mdsubset<-md[startindex:nrow(md),]
signals <- ApplyStop(mdsubset, mdsubset$stoplosslevel)
trades <- GenerateTrades(signals)
trades$brokerage <- 2*kBrokerage
trades$netpercentprofit <-
trades$percentprofit - trades$brokerage
equity <-
CalculatePortfolioEquityCurve("NSENIFTY",
mdsubset,
trades,
rep(kMaxContracts*kContractSize, nrow(md) - startindex),
brokerage = kBrokerage)
##### Generate Derived Trades ########
returns <- trades$netpercentprofit
bars <- trades$bars
amendedsize<-RTrade::calcDerivedContracts(dddays=kDrawdownDaysThreshold,ddamt=kDrawdownPercentThreshold,recoverybonus=kRecoveryBonus,ddcost=kDrawdownCost,stop=0,margin=1,charttitle="swing01",
returnvector=returns,
tradebarvector=bars,
contractsize=kMaxContracts,
derivedleg=1)
tmp<-data.frame(date=trades$entrytime,amendedsize=amendedsize)
tmp1<-merge(tmp,mdsubset,by="date",all=TRUE)
amendedsize<-na.locf(tmp1$amendedsize)
#make amendedsize of same length as nrow(mdsubset)
amendedsize<-c(rep(head(amendedsize,1),nrow(tmp1)-length(amendedsize)),amendedsize)
derivedequity <-
CalculatePortfolioEquityCurve(kIndex, mdsubset, trades, amendedsize *
kContractSize, brokerage = kBrokerage)
########### Generate Option Trades ################
signals$strike<-round((signals$buyprice+signals$shortprice) / 100) * 100
signals$currentmonthexpiry <- as.Date(sapply(signals$date, getExpiryDate), tz = kTimeZone)
nextexpiry <- as.Date(sapply(
as.Date(signals$currentmonthexpiry + 20, tz = kTimeZone),
getExpiryDate
), tz = kTimeZone)
signals$entrycontractexpiry <- as.Date(ifelse(
businessDaysBetween("India",as.Date(signals$date, tz = kTimeZone),signals$currentmonthexpiry) <= 3,
nextexpiry,signals$currentmonthexpiry),tz = kTimeZone)
optionSignals<-optionTradeSignalsLongOnly(signals,kFNODataFolder,kNiftyDataFolder)
optionTrades<-GenerateTrades(optionSignals)
optionTrades<-optionTrades[order(optionTrades$entrytime),]
for(i in 1:nrow(optionTrades)){
if(optionTrades$exittime[i]<"2000-01-01"){
optionTrades$exittime[i]<-strptime(NA,format="%Y-%m-%d",tz=kTimeZone)
}
}
if(kMoneyManagement){
amendedsizedf<-data.frame(date=mdsubset$date,close=mdsubset$close,size=amendedsize)
}else{
amendedsize<-kMaxContracts
amendedsizedf<-data.frame(date=mdsubset$date,close=mdsubset$close,size=amendedsize)
}
optionTrades$size<-merge(optionTrades,amendedsizedf,by.x="entrytime",by.y="date")$size*kContractSize
optionTrades$underlying<-merge(optionTrades,amendedsizedf,by.x="entrytime",by.y="date")$close
pricediff<-optionTrades$exitprice-optionTrades$entryprice
absprofit<-ifelse(grepl("BUY",optionTrades$trade),pricediff,-pricediff)
optionTrades$percentprofit<-absprofit/optionTrades$underlying
optionTrades$brokerage <- (2*kPerContractBrokerage/kContractSize)/trades$entryprice
optionTrades$netpercentprofit <- optionTrades$percentprofit - optionTrades$brokerage
# update option prices for trades today
# update entry prices
out <- which(as.Date(optionTrades$entrytime,tz=kTimeZone) == Sys.Date())
if(length(out)>0){
for(o in 1:length(out)){
index<-out[o]
newrow <- getPriceArrayFromRedis(9,optionTrades$symbol[index],"tick","close",paste(today, " 09:12:00"))
if(nrow(newrow)==1){
optionTrades$entryprice[index]<-newrow$settle[1]
optionTrades$exitprice[index]<-newrow$settle[1]
}
}
}
# update exit prices
out <- which(as.Date(optionTrades$exittime,tz=kTimeZone) == Sys.Date()|is.na(optionTrades$exittime))
if(length(out)>0){
for(o in 1:length(out)){
index<-out[o]
newrow <- getPriceArrayFromRedis(9,optionTrades$symbol[index],"tick","close",paste(today, " 09:12:00"))
if(nrow(newrow)==1){
optionTrades$exitprice[index]<-newrow$settle[1]
}
}
}
if(length(args)>1 && args[1]==1){
save(md,file=paste(args[2],"md.R",sep="."))
save(optionTrades,file=paste(args[2],"optionTrades.R",sep="."))
}
############### METRICS ##############
if (length(args)>1 && args[1] == 2) {
#Derived Trades
pnl <- pnl<-data.frame(bizdays=as.Date(mdsubset$date,tz=kTimeZone),realized=0,unrealized=0,brokerage=0)
cumpnl<-CalculateDailyPNL(optionTrades[complete.cases(optionTrades),],pnl,kFNODataFolder,kPerContractBrokerage/75,per.contract.brokerage = TRUE)
cumpnl$daily.pnl <- (cumpnl$realized + cumpnl$unrealized-cumpnl$brokerage) - Ref(cumpnl$realized + cumpnl$unrealized-cumpnl$brokerage, -1)
cumpnl$daily.pnl <- ifelse(is.na(cumpnl$daily.pnl), 0, cumpnl$daily.pnl)
cumpnl$daily.return <- cumpnl$daily.pnl*100/(mdsubset$close*kContractSize*75)
cumpnl$daily.return <- ifelse(is.na(cumpnl$daily.return), 0, cumpnl$daily.return)
cumpnl$daily.return <- ifelse(is.infinite(cumpnl$daily.return), 0, cumpnl$daily.return)
grosspnl<-(optionTrades$exitprice-optionTrades$entryprice)*optionTrades$size
brokerage<- 2*optionTrades$size*kPerContractBrokerage/75
optionTrades$grosspnl<-ifelse(grepl("BUY",optionTrades$trade),grosspnl,-grosspnl)
optionTrades$brokerage<-brokerage
NetProfit<-sum(optionTrades$grosspnl-optionTrades$brokerage)
AverageMargin=sum(optionTrades$entryprice*optionTrades$size*optionTrades$bars)/sum(optionTrades$bars)
fy.tmp <- seq( as.POSIXct('2013-04-01'), length=10, by='year')
cumpnl$fiscalyear=(2014:2023)[ findInterval(as.POSIXct(cumpnl$bizdays,tz=kTimeZone),fy.tmp) ]
optionTrades$fiscalyear=(2014:2023)[ findInterval(optionTrades$entrytime,fy.tmp) ]
fiscal.pnl<-tapply(cumpnl$daily.pnl,cumpnl$fiscalyear,sum)
fiscal.sharpe<-tapply(cumpnl$daily.return,cumpnl$fiscalyear,sharpe)
fiscal.pnl.recon<-tapply(optionTrades$grosspnl-optionTrades$brokerage,optionTrades$fiscalyear,sum)
fiscal.margin.num<-tapply(optionTrades$size*optionTrades$entryprice*optionTrades$bars,optionTrades$fiscalyear,sum)
fiscal.margin.den<-tapply(optionTrades$bars,optionTrades$fiscalyear,sum)
fiscal.margin<-fiscal.margin.num/fiscal.margin.den
fiscal.winratio.num<-tapply((optionTrades$grosspnl-optionTrades$brokerage)>0,optionTrades$fiscalyear,sum)
fiscal.winratio.den<-tapply(optionTrades$grosspnl,optionTrades$fiscalyear,length)
fiscal.winratio=fiscal.winratio.num/fiscal.winratio.den
fiscal.underlying.max<-tapply(optionTrades$entryprice,optionTrades$fiscalyear,max)
reporting<-as.data.frame(fiscal.sharpe)
reporting=data.frame(reporting,as.data.frame(fiscal.winratio)$fiscal.winratio)
reporting=data.frame(reporting,as.data.frame(fiscal.pnl)$fiscal.pnl)
reporting=data.frame(reporting,as.data.frame(fiscal.margin)$fiscal.margin)
reporting=data.frame(reporting,as.data.frame(fiscal.underlying.max)$fiscal.underlying.max*kContractSize*kMaxContracts)
colnames(reporting)<-c("Sharpe","WinRatio","NetP&L","AverageMarginUtil","BudgetedMargin")
reporting$Sharpe<-format(round(reporting$Sharpe,2),nsmall = 2)
reporting$WinRatio<-format(round(reporting$WinRatio*100,2),nsmall = 2)
reporting$`NetP&L`<-formatC(reporting$`NetP&L`,format="d", big.mark=',')
reporting$AverageMarginUtil<- formatC(reporting$AverageMarginUtil,format="d", big.mark=',')
reporting$BudgetedMargin<- formatC(reporting$BudgetedMargin,format="d", big.mark=',')
}
```
The parameters for the run were set as follows:
##Envelope Parameters
Full Hand : `r kMaxContracts ` Contracts
Brokerage : INR `r kPerContractBrokerage` per contract, one-way
Threshold Drawdown : `r kDrawdownPercentThreshold*100`%
MoneyManagement : `r ifelse(kMoneyManagement==0,"OFF","ON")`
BackTest Start Date : `r kBackTestStartDate`
BackTest End Date : `r kBackTestEndDate`
##Algorithm Performance Metrics
The performace summary is aggregated by fiscal years - covering a 12 month period between April to March.
`r kable(reporting[c("2014","2015","2016"),],caption="Performance Metrics")`
These metrics include brokerage costs but exclude impact of license fees to be paid for running this Algorithm.
## Profit & Loss Graph
```{r ProfitPlot, setoptions,echo=FALSE, results="asis",fig.height=6,fig.width=10,cache=TRUE}
truncatedpnl<-cumpnl[cumpnl$bizdays<kBackTestEndDate,]
plot(x = truncatedpnl$bizdays,
y = (truncatedpnl$realized + truncatedpnl$unrealized - truncatedpnl$brokerage),
type = 'l',main="Profit & Loss",xlab="Date",ylab="Profit",axes=FALSE)
axis.Date(1,truncatedpnl$bizdays,at=seq(min(truncatedpnl$bizdays), max(truncatedpnl$bizdays)+90, by="3 mon"),, format="%m-%Y")
minProfit=min(truncatedpnl$realized+truncatedpnl$unrealized-truncatedpnl$brokerage)
maxProfit=max(truncatedpnl$realized+truncatedpnl$unrealized-truncatedpnl$brokerage)
points=pretty(seq(minProfit,maxProfit,by=(maxProfit-minProfit)/5))
axis(2,at=points,labels=paste(points/1000000,"M",sep=""),las=1)
```
## BootStrap
Bootstrapping helps us identify the variations in performance, assuming that the historical returns are a good estimate of the population. Bootstrapping over 1000 runs provides the following picture
```{r BootStrap,setoptions, message=FALSE, echo=FALSE, results="as-is",fig.height=6,fig.width=12,cache=TRUE}
library(RTrade)
trades<-trades[complete.cases(optionTrades),]
optionTrades<-optionTrades[complete.cases(optionTrades),]
# par(mfrow = c(2, 4))
returns <-
trades[trades$entrytime >= "2013-04-01" & trades$entrytime <= "2016-03-31" , c("netpercentprofit")]
derivedreturns <-
optionTrades[optionTrades$entrytime >= "2013-04-01" & optionTrades$entrytime <= "2016-03-31" , c("netpercentprofit")]
bars <- trades[trades$entrytime >= "2013-04-01" & trades$entrytime <= "2016-03-31", c("bars")]
count <- length(returns)
bootstrap.results=bootstrap(dddays=kDrawdownDaysThreshold,ddamt=kDrawdownPercentThreshold,recoverybonus=kRecoveryBonus,ddcost=kDrawdownCost,stop=0,margin=1,charttitle=args[2],
returnvector=returns,
derivedreturn=derivedreturns,
tradebarvector=bars,
samples=1000,
samplesize=as.integer(count/3),
contractsize=kMaxContracts,
derivedleg=kMoneyManagement)
#bootstrap estimates
capital.at.loss=1000000
max.exposure=capital.at.loss/bootstrap.results$ddvalue95percavg[2]
margin.requirement = max.exposure*0.03
return.lower.range=(as.numeric(bootstrap.results$retavg[2])-as.numeric(bootstrap.results$retsd[2]))
return.upper.range=(as.numeric(bootstrap.results$retavg[2])+as.numeric(bootstrap.results$retsd[2]))
pnl.lower.range=return.lower.range*capital.at.loss/ as.numeric(bootstrap.results$ddvalue95percavg[2])
pnl.upper.range=return.upper.range*capital.at.loss/ as.numeric(bootstrap.results$ddvalue95percavg[2])
roce.lower.range=pnl.lower.range/(capital.at.loss+margin.requirement)
roce.upper.range=pnl.upper.range/(capital.at.loss+margin.requirement)
```
The first row illustrates the results over a run with *Full Hand* irrespective of any drawdown. The results are acceptable, from a return perspective. However, maximum drawdown values (chart# 4 in the first row) are high.
This is allieviated by reducing contract size with increasing drawdown. The results from this derived algorithm are plotted in the second row. Whilst the maximum drawdown percentage reduces on implementing this money management rule, the returns are also negatively impacted. However, the returns are also postively skewed, which we believe reduces the probability of large losses.
The bootstrap expects us to have an average of `r bootstrap.results$ddvalue95percavg*100`% maximum drawdown over a one year holding.
Example:
a. Trading Capital (At High Risk of Loss) : INR `r formatC(capital.at.loss,format="d",big.mark=",")`
b. Maximum Exposure Taken by Algorithm : INR `r formatC(max.exposure,format="d",big.mark=",")`
c. Margin Requirement @ `r 0.03*100`% as option premium : INR `r formatC(margin.requirement,format="d",big.mark=",")`
d. Total Capital Needed with broker (a+c) : INR `r formatC(capital.at.loss+margin.requirement,format="d",big.mark=",")`
e. Expected Return on Maximum Exposure at lower bound at 1 standard deviation = `r return.lower.range*100`%
f. Expected Return on Maximum Exposure at upper bound at 1 standard deviation= `r return.upper.range*100`%
g. Lower prediction of Absolute PNL at 1 standard deviation : INR `r formatC(pnl.lower.range,format="d",big.mark=',')`
h. Higher prediction of Absolute PNL at 1 standard deviation : INR `r formatC(pnl.upper.range,format="d",big.mark=',')`
i. Expected Range of annualized return on at one standard deviation = `r round(as.numeric(roce.lower.range)*100,0)`% to `r round(as.numeric(roce.upper.range)*100,0)`%
The calculations above are illustrative based on simulation of backtested results, and provide guiding posts for allocation of funds the algorithm. By no means are any returns guaranteed. This is a strategy with a "HIGH RISK" of capital loss.
\newpage
# Risks
## Historical returns may not be indicator of future returns
The reported Algorithm performance is on backtested or simulated results, unless otherwise stated. In either case, historical returns are not an indictor of the returns in future.
## Data Quality
The Algorithm identifies buy and sell strategies via a combination of public data and private data distributed from data providers. Any change in quality of data provided and changes in data defintions can adversely affect the performance of the Algorithm.
## Execution
The Algorithm performance is affected by any difference between the execution price of a contract assumed by the Algorithm, and its actual execution price in the market. The actual execution price depends on the availability of the contract for trading, liquidity of the contract and the time of execution vs the time of the trade opportunity identifed by the Algorithm. Any slippage in prices can adversely affect the performance of the Algorithm.
## Model inadequacies
The Algorithm is built upon a model and rules for identifying buy and sell opportunities. The model defines a relationship between some external variables, but does not cover all possible external variables. It is possible that the performance of the Algorithm will be impacted by variables outside the model. In addition, the variables used in the model might lose their efficacy over a period of time. Any such model inadequacies can adversely affect the performance of the Algorithm.
## Regulations
Changes to business environment and new regulations can introduce market events that are not modelled by the Algorithm. Any such development can adversely affect the performance of the Algorithm.
## Tax Implications
The returns illustrated by this document are before any tax payments. The returns also exclude any license fees to be paid as a result of the contract to run this Algorithm. Potential clients are urged to work with their tax consultants and review tax implications of running the Algorithm on their own funds.
## Technology
The timely generation of buy and sell opportunities is based on the availability of technology infrastructure, including but not limited to availability of internet, market data and corporate actions. Disruption in any enabling infrastructure could delay generation of buy and sell opportunities and could adversely affect the performance of the Algorithm.