Professional Documents
Culture Documents
mm 40 60 80 100 120
Part 3 of 3
60
Guy Yollin
Principal Consultant, r-programming.org Visiting Lecturer, University of Washington
80
2011)
quantstrat-III
1 / 68
Outline
mm
1
40
60
80
100
120
2011)
quantstrat-III
2 / 68
Lecture references
mm 40 60 100 TradeAnalytics project page on R-forge: 80 http://r-forge.r-project.org/projects/blotter/ documents and demos for: 40
blotter package quantstrat package
120
R-SIG-FINANCE: https://stat.ethz.ch/mailman/listinfo/r-sig-finance
60
2011)
quantstrat-III
3 / 68
Quantstrat demos
mm
name='sigCrossover' name='sigThreshold' ordertype='market' ordertype='stoplimit' type='enter' 40 type='exit' type='risk' orderside='long' orderside='short' applyStrategy parameters index.class='Date' 60 index.class='POSIXt' multiasset multicurrency data adjusted updates Account
40
faber Y N Y N Y Y N Y N N N Y Y N N N
60 maCross Y N Y N Y Y N Y N N Y N N N Y N
bbands 80 Y N Y N Y Y N N N Y Y N N N N N
rsi N Y Y N Y Y N Y Y Y Y N Y N N N
100 macd
N Y Y Y Y Y Y Y N Y Y N N N N N
120 faberMC Y N Y N Y Y N Y N N N N Y Y N N
80
2011)
quantstrat-III
4 / 68
Outline
mm
1
40
60
80
100
120
2011)
quantstrat-III
5 / 68
MACD Calculation
MACD = 12-day EMA - 26-day EMA MACD Signal Line = 9-day EMA of MACD MACD histogram = MACD - Signal Line 60
Interpretation
Buy/Sell when MACD Signal Line crosses 0 80
2011)
quantstrat-III
6 / 68
40
60
80
2011)
quantstrat-III
7 / 68
40
60
80
100
120
40
60
i f MACDSig c r o s s e s b e l o w 0 t h e n S e l l ( MacdLX ) n e x t b a r a t m a r k e t ;
80
2011)
quantstrat-III
8 / 68
40
60
80
2011)
quantstrat-III
9 / 68
mm
Initialize currency and instruments, and load historic data
40
Initialize portfolio, account, orders, strategy
60
Bar-by-bar processing
Update
Reporting
80
100
120
Generate performance reports and graphs
40
R Code:
> > > > > > > > > library(quantstrat) # inz currency and stocks dummy <- currency('USD') stock.str = c("XLF") 60 for(symbol in stock.str) stock(symbol, currency="USD",multiplier=1) # download stocks start.data <- as.Date("1998-12-22") end.data <- as.Date("2011-08-09") initDate80 start.data-1 <-
2011)
quantstrat-III
10 / 68
60
Bar-by-bar processing
80
Update
100
Reporting
120
40
R Code:
> > > > > > # inz portfolio, account, orders, strategy strat.name <- "MACD" 60 initEq=1000000 trade.percent = 0.05 dummy <- initPortf(name=strat.name,symbols=stock.str, initDate=initDate) dummy <- initAcct(name=strat.name,portfolios=strat.name, initDate=initDate, initEq=initEq) > initOrders(portfolio=strat.name,initDate=initDate) 80 > strat <- strategy(strat.name)
2011)
quantstrat-III
11 / 68
120
Main arguments: strategy 80 strategy object name name of the signal (one of the 5 supported signals) arguments arguments to be passed to the indicator function
Guy Yollin (Copyright
2011)
quantstrat-III
12 / 68
40
60
80
100
120
Main arguments: label text label to apply to the output 60 data data to apply comparison column column name to apply comparison threshold numeric threshold to compare relationship relationship to test (gt, lt, eq, gte, ) lte 80 cross if TRUE, then signal will be TRUE only for the rst observation to cross the threshold
Guy Yollin (Copyright
2011)
quantstrat-III
13 / 68
40
Define strategy
60
Bar-by-bar processing
80
Update
100
Reporting
120
40
R Code:
> # indicators: > strat <- add.indicator(strategy = strat, name = "MACD", 60 arguments = list(x=quote(Cl(mktdata))) ) > # signals: > strat <- add.signal(strategy = strat, name="sigThreshold", arguments = list(column="signal",relationship="gt",threshold=0,cross=TRUE), label="signal.gt.zero") > strat <- add.signal(strategy = strat,name="sigThreshold", 80 arguments = list(column="signal",relationship="lt",threshold=0,cross=TRUE), label="signal.lt.zero")
2011)
quantstrat-III
14 / 68
mm
Initialize currency and instruments, and load historic data
Bar-by-bar processing
Update
Reporting
40
Initialize portfolio, account, orders, strategy
60
80
100
120
Generate performance reports and graphs
40
R Code:
> osPercentEquity <- function (timestamp,orderqty,portfolio,symbol,ruletype,...) { tempPortfolio <- getPortfolio(portfolio) dummy <- updatePortf(Portfolio=portfolio, 60 Dates=paste('::',as.Date(timestamp),sep='')) trading.pl <- sum(getPortfolio(portfolio)$summary$Net.Trading.PL) assign(paste("portfolio.",portfolio,sep=""),tempPortfolio,pos=.blotter) total.equity <- initEq+trading.pl tradeSize <- total.equity * trade.percent ClosePrice <- as.numeric(Cl(mktdata[timestamp,])) 80 orderqty <- sign(orderqty)*round(tradeSize/ClosePrice) return(orderqty) }
Guy Yollin (Copyright
2011)
quantstrat-III
15 / 68
40
60
Define strategy
Bar-by-bar processing
80
Update
100
Reporting
120
40
R Code:
> # rules: > strat <-60 add.rule(strategy = strat,name='ruleSignal', arguments = list(sigcol="signal.gt.zero",sigval=TRUE, orderqty=100, ordertype='market', orderside='long', osFUN='osPercentEquity'),type='enter') > strat <- add.rule(strategy = strat,name='ruleSignal', arguments = list(sigcol="signal.lt.zero",sigval=TRUE, orderqty='all', ordertype='market', orderside='long'),type='exit')
80
2011)
quantstrat-III
16 / 68
60
Bar-by-bar processing
80
Update
100
Reporting
120
40
R Code:
> > > > > > > # parameters: fastMA =60 12 slowMA = 26 signalMA = 9 maType="EMA" # apply strategy out<-try(applyStrategy(strategy=strat, portfolios=strat.name, parameters=list(nFast=fastMA, nSlow=slowMA, nSig=signalMA,maType=maType), 80 verbose=F))
2011)
quantstrat-III
17 / 68
40
Define strategy
60
Bar-by-bar processing
80
Update
100
Reporting
120
40
R Code:
> dummy <- updatePortf(Portfolio=strat.name, Dates=paste('::',as.Date(Sys.time()),sep='')) 60 > if(sum(duplicated(index(getPortfolio(strat.name)$summary)))>0) { tempPortfolio <- getPortfolio(strat.name) tempPortfolio$summary <- as.xts(aggregate(x=tempPortfolio$summary, by=index(tempPortfolio$summary), FUN=sum)) assign(paste("portfolio.",strat.name,sep=""),tempPortfolio,pos=.blotter) 80 warning("duplicates removed after update") }
2011)
quantstrat-III
18 / 68
40
60
Define strategy
80
Bar-by-bar processing Update
100
Reporting
120
40
R Code:
60
80
2011)
quantstrat-III
19 / 68
40
60
80
2011)
quantstrat-III
20 / 68
Outline
mm
1
40
60
80
100
120
2011)
quantstrat-III
21 / 68
Due to the additional calculations required, working with multi-asset portfolios can be time consuming 80
2011)
quantstrat-III
22 / 68
mm
Initialize currency and instruments, and load historic data
40
Initialize portfolio, account, orders, strategy
60
Add indicators, signals, and rules
80
Apply strategy to portfolio
100
Update portfolio, account, equity
120
Generate performance reports and graphs
R Code:
> > > > > > > > > >
40
# clear out old portfolios and orders try(rm(list=ls(pos=.blotter),pos=.blotter),silent=TRUE) try(rm(list=ls(pos=.strategy),pos=.strategy),silent=TRUE) # inz currency and stocks 60 stock.str = c("XLF", "XLP", "XLE", "XLY", "XLV", "XLI", "XLB", "XLK", "XLU") for(symbol in stock.str) stock(symbol, currency="USD",multiplier=1) # download stocks start.data <- as.Date("1998-12-22") end.data <- as.Date("2011-08-09") initDate80 start.data-1 <-
2011)
quantstrat-III
23 / 68
60
Bar-by-bar processing
80
Update
100
Reporting
120
40
R Code:
> > > > > > # inz portfolio, account, orders, strategy strat.name <- "MACD" 60 initEq=1000000 trade.percent = 0.05 dummy <- initPortf(name=strat.name,symbols=stock.str, initDate=initDate) dummy <- initAcct(name=strat.name,portfolios=strat.name, initDate=initDate, initEq=initEq) > initOrders(portfolio=strat.name,initDate=initDate) 80 > strat <- strategy(strat.name)
2011)
quantstrat-III
24 / 68
80
100
120
40
60
Txn.Qty Txn.Price Txn.Value Txn.Avg.Cost Pos.Qty Pos.Avg.Cost Gross.Txn.Realized.PL Txn.Fees Net.Txn.Realized.PL Con.Mult Pos.Qty Con.Mult Ccy.Mult Pos.Value Pos.Avg.Cost Txn.Value Period.Realized.PL Period.Unrealized.PL Gross.Trading.PL Txn.Fees Net.Trading.PL
80
2011)
quantstrat-III
25 / 68
40
60
80
100
120
40
60 > names(macdPortfolio$symbols)
[1] "XLF" "XLP" "XLE" "XLY" "XLV" "XLI" "XLB" "XLK" "XLU"
80
2011)
quantstrat-III
26 / 68
40
Define strategy
60
Bar-by-bar processing
80
Update
100
Reporting
120
40
R Code:
> # indicators: > strat <- add.indicator(strategy = strat, name = "MACD", 60 arguments = list(x=quote(Cl(mktdata))) ) > # signals: > strat <- add.signal(strategy = strat, name="sigThreshold", arguments = list(column="signal",relationship="gt",threshold=0,cross=TRUE), label="signal.gt.zero") > strat <- add.signal(strategy = strat,name="sigThreshold", 80 arguments = list(column="signal",relationship="lt",threshold=0,cross=TRUE), label="signal.lt.zero")
2011)
quantstrat-III
27 / 68
mm
Initialize currency and instruments, and load historic data
Bar-by-bar processing
Update
Reporting
40
Initialize portfolio, account, orders, strategy
60
80
100
120
Generate performance reports and graphs
40
R Code:
> osPercentEquity <- function (timestamp,orderqty,portfolio,symbol,ruletype,...) { tempPortfolio <- getPortfolio(portfolio) dummy <- updatePortf(Portfolio=portfolio, 60 Dates=paste('::',as.Date(timestamp),sep='')) trading.pl <- sum(getPortfolio(portfolio)$summary$Net.Trading.PL) assign(paste("portfolio.",portfolio,sep=""),tempPortfolio,pos=.blotter) total.equity <- initEq+trading.pl tradeSize <- total.equity * trade.percent ClosePrice <- as.numeric(Cl(mktdata[timestamp,])) 80 orderqty <- sign(orderqty)*round(tradeSize/ClosePrice) return(orderqty) }
Guy Yollin (Copyright
2011)
quantstrat-III
28 / 68
40
60
Define strategy
Bar-by-bar processing
80
Update
100
Reporting
120
40
R Code:
> # rules: > strat <-60 add.rule(strategy = strat,name='ruleSignal', arguments = list(sigcol="signal.gt.zero",sigval=TRUE, orderqty=100, ordertype='market', orderside='long', osFUN='osPercentEquity'),type='enter') > strat <- add.rule(strategy = strat,name='ruleSignal', arguments = list(sigcol="signal.lt.zero",sigval=TRUE, orderqty='all', ordertype='market', orderside='long'),type='exit')
80
2011)
quantstrat-III
29 / 68
60
Bar-by-bar processing
80
Update
100
Reporting
120
40
R Code:
> > > > > > > # parameters: fastMA =60 12 slowMA = 26 signalMA = 9 maType="EMA" # apply strategy out<-try(applyStrategy(strategy=strat, portfolios=strat.name, parameters=list(nFast=fastMA, nSlow=slowMA, nSig=signalMA,maType=maType), 80 verbose=F))
2011)
quantstrat-III
30 / 68
40
Define strategy
60
Bar-by-bar processing
80
Update
100
Reporting
120
40
R Code:
> dummy <- updatePortf(Portfolio=strat.name, Dates=paste('::',as.Date(Sys.time()),sep='')) 60 > if(sum(duplicated(index(getPortfolio(strat.name)$summary)))>0) { tempPortfolio <- getPortfolio(strat.name) tempPortfolio$summary <- as.xts(aggregate(x=tempPortfolio$summary, by=index(tempPortfolio$summary), FUN=sum)) assign(paste("portfolio.",strat.name,sep=""),tempPortfolio,pos=.blotter) 80 warning("duplicates removed after update") }
2011)
quantstrat-III
31 / 68
40
60
Define strategy
80
Bar-by-bar processing Update
100
Reporting
120
40
R Code:
> > > >
60
80
2011)
quantstrat-III
32 / 68
mm
Cumulative Return
0.005
40
60
80
100
120
0.005
40
0.015
Daily Return
0.000
0.005
60
Drawdown
0.010
0.005
0.025
80
19981221 20000703 20020102 20030701 20050103 20060703 20080102 20090701 20110103
2011)
quantstrat-III
33 / 68
Outline
mm
1
40
60
80
100
120
2011)
quantstrat-III
34 / 68
MACD optimization
mm 40 60 80 100 120
The inventor of MACD suggests that the dierence between a 12-day and 26-day exponential moving average be calculated and then smooth via a 9-day exponential moving average Our research interest is to explore if other values provide superior results We will try 3 dierent values for each of fastMA, slowMA, and 60 signalMA, 27 dierent settings All testing will be done on the 9-asset portfolio of S&P Sector Select ETFs with data from Dec-1998 through Aug-2011
80 40
2011)
quantstrat-III
35 / 68
Omega uses all of the information in the return series and is thus well suited for non-normal distributions Omega is essentially the ratio of a call price to a put price
60
Omega performance measure is calculated by the Omega function in PerformanceAnalytics C (L) (L) = 80 P(L)
Shadwick and Keating. Universal Performance Measure. Journal of Performance A Measurement, Spring 2002 Guy Yollin (Copyright
2011)
quantstrat-III
36 / 68
mm
40
60
80
100
120
0.8 Proportion <= x Density 0.4 0.2 0.00.0 0.5 a -1.0 -0.5 -0.5 0.6 1.0
1.5
40
60
80
L 0.0 b 0.0 daily return 0.5 0.5 1.0 1.5 1.0
2011)
quantstrat-III
37 / 68
MACD optimization
R Code:
> > > > > fastMA mm <- c(5,10,15) 40 60 80 100 slowMA <- c(20,25,30) signalMA <- c(1,5,10) parm.comb <- expand.grid(fastMA=fastMA,slowMA=slowMA,signalMA=signalMA) head(parm.comb,12) fastMA slowMA signalMA 40 5 20 1 10 20 1 15 20 1 5 25 1 10 25 1 15 60 25 1 5 30 1 10 30 1 15 30 1 5 20 5 10 20 5 15 80 20 5
120
1 2 3 4 5 6 7 8 9 10 11 12
2011)
quantstrat-III
38 / 68
Optimization loop
R Code:
mm 40 60 80 100 120 > for(i in 1:num.opts) { # initialize portfolio and orders try(rm(list=ls(pos=.blotter),pos=.blotter),silent=TRUE) try(rm(list=ls(pos=.strategy),pos=.strategy),silent=TRUE) dummy <- initPortf(name=strat.name,symbols=stock.str, initDate=initDate) initOrders(portfolio=strat.name,initDate=initDate) # apply40 strategy fastMA = parm.comb[i,"fastMA"] slowMA = parm.comb[i,"slowMA"] signalMA = parm.comb[i,"signalMA"] out<-try(applyStrategy(strategy=strat, portfolios=strat.name, parameters=list(nFast=fastMA, nSlow=slowMA, nSig=signalMA,maType=maType), 60 verbose=F)) # calculate performance matric dummy <- updatePortf(Portfolio=strat.name, Dates=paste('::',as.Date(Sys.time()),sep='')) trading.pl <- getPortfolio(strat.name)$summary$Net.Trading.PL rets <- trading.pl/initEq 80 omega <- as.numeric(Omega(rets)) res.vec[i] <- omega }
Guy Yollin (Copyright
2011)
quantstrat-III
39 / 68
Optimization
mm 40 60 80 100 120
40
60
80
2011)
quantstrat-III
40 / 68
Optimization summary
mm 40 60 80 100 120
Process ran for approximately 8.5 hours on the RStudio cloud Embarrassingly parallel problem that would be idea for any of Rs parallel computing capabilities (e.g. snow, NetWorkSpaces etc.) 80
2011)
quantstrat-III
41 / 68
Outline
mm
1
40
60
80
100
120
2011)
quantstrat-III
42 / 68
RSI = 100 RS =
60
100 1 + RS
Interpretation
80 Trade reversals between thresholds (e.g. 70/30) Trade break-outs above/below thresholds (e.g. 70/30)
Guy Yollin (Copyright
2011)
quantstrat-III
43 / 68
HOLDRS are ETFs that represent a basket of stocks in a specic industry segment The Semiconductor HOLDR includes large-cap semiconductor 40 manufacturers as well as semiconductor equipment manufacturers Well apply the RSI system to 5 components of the semiconductor HOLDR ETF
INTC - Intel 60 TXN - Texas Instrument AMAT - Applied Materials ADI - Analog Devices ALTR - Altera 80
2011)
quantstrat-III
44 / 68
40
Define strategy
60
Bar-by-bar processing
80
Update
100
Reporting
120
40
R Code:
> # inz currency and stocks > stock.str = c("INTC","TXN","AMAT","ADI","ALTR") > for(symbol in stock.str) 60 stock(symbol, currency="USD",multiplier=1) > # download stocks > start.data <- as.Date("1998-12-22") > end.data <- as.Date("2011-08-09") > initDate <- start.data-1 > for(symbol in stock.str) getSymbols(symbol,from=start.data,to=end.data,adjust=T)
Guy Yollin (Copyright
80
2011)
quantstrat-III
45 / 68
60
Bar-by-bar processing
80
Update
100
Reporting
120
40
R Code:
> > > > > > # inz portfolio, account, orders, strategy strat.name <- "RSI" 60 initEq=1000000 trade.percent = 0.05 dummy <- initPortf(name=strat.name,symbols=stock.str, initDate=initDate) dummy <- initAcct(name=strat.name,portfolios=strat.name, initDate=initDate, initEq=initEq) > initOrders(portfolio=strat.name,initDate=initDate) 80 > strat <- strategy(strat.name)
2011)
quantstrat-III
46 / 68
60
Bar-by-bar processing
80
Update
100
Reporting
120
40
R Code:
> # indicators: > strat <- add.indicator(strategy = strat, name = "RSI", 60 arguments = list(price = quote(getPrice(mktdata))), label="RSI") > # signals: > strat <- add.signal(strategy = strat, name="sigThreshold", arguments = list(threshold=70, column="RSI",relationship="gt", cross=TRUE), label="RSI.gt.70") > strat <- add.signal(strategy = strat, name="sigThreshold", 80 arguments = list(threshold=30, column="RSI",relationship="lt",cross=TRUE), label="RSI.lt.30")
2011)
quantstrat-III
47 / 68
60
Bar-by-bar processing
80
Update
100
Reporting
120
40
R Code:
> # rules: > strat <-60 add.rule(strategy = strat, name='ruleSignal', arguments = list(sigcol="RSI.gt.70", sigval=TRUE, orderqty=-1000, ordertype='market', orderside='short', osFUN='osPercentEquity', replace=FALSE), type='enter', path.dep=TRUE) > strat <- add.rule(strategy = strat, name='ruleSignal', arguments = list(sigcol="RSI.lt.30", sigval=TRUE, orderqty='all', ordertype='market', orderside='short', replace=FALSE), 80 type='exit', path.dep=TRUE)
2011)
quantstrat-III
48 / 68
60
Bar-by-bar processing
80
Update
100
Reporting
120
40
R Code:
> # rules: > strat <-60 add.rule(strategy = strat, name='ruleSignal', arguments = list(sigcol="RSI.lt.30", sigval=TRUE, orderqty= 1000, ordertype='market', orderside='long', osFUN='osPercentEquity', replace=FALSE), type='enter', path.dep=TRUE) > strat <- add.rule(strategy = strat, name='ruleSignal', arguments = list(sigcol="RSI.gt.70", sigval=TRUE, orderqty='all', ordertype='market', orderside='long', replace=FALSE), 80 type='exit', path.dep=TRUE)
2011)
quantstrat-III
49 / 68
40
60
Define strategy
80
Bar-by-bar processing Update
100
Reporting
120
40
Initialize currency and instruments, and load historic data Initialize portfolio, account, orders, strategy Add indicators, signals, and rules Apply strategy to portfolio Update portfolio, account, equity
R Code: 60
> # apply strategy > out<-try(applyStrategy(strategy=strat, portfolios=strat.name, parameters=list(n=2),verbose=F))
80
2011)
quantstrat-III
50 / 68
40
Define strategy
60
Bar-by-bar processing
80
Update
100
Reporting
120
40
R Code:
> dummy <- updatePortf(Portfolio=strat.name, Dates=paste('::',as.Date(Sys.time()),sep='')) 60 > if(sum(duplicated(index(getPortfolio(strat.name)$summary)))>0) { tempPortfolio <- getPortfolio(strat.name) tempPortfolio$summary <- as.xts(aggregate(x=tempPortfolio$summary, by=index(tempPortfolio$summary), FUN=sum)) assign(paste("portfolio.",strat.name,sep=""),tempPortfolio,pos=.blotter) 80 warning("duplicates removed after update") }
2011)
quantstrat-III
51 / 68
40
60
Define strategy
80
Bar-by-bar processing Update
100
Reporting
120
40
R Code:
> chart_Posn(Portfolio=strat.name,Symbol="AMAT",Dates="2009::2011") 60 > plot(add_RSI()) > trading.pl <- getPortfolio(strat.name)$summary$Net.Trading.PL > rets <- trading.pl/initEq > charts.PerformanceSummary(rets,colorset = bluefocus,xlab="")
80
2011)
quantstrat-III
52 / 68
40
60
80
2011)
quantstrat-III
53 / 68
mm
Cumulative Return
1.5
40
60
80
100
120
0.5
1.0
40
Daily Return
0.02 0.04
0.0
60
0.05 0.00 0.02
Drawdown
80
0.15 19981221 20000703 20020102 20030701 20050103 20060703 20080102 20090701 20110103
2011)
quantstrat-III
54 / 68
Outline
mm
1
40
60
80
100
120
2011)
quantstrat-III
55 / 68
Bollinger bands
mm 40 60 80 100 120
Bollinger bands are a volatility-sensitive price channel Published by John Bollinger in the early 1980s RSI 40 Calculation
Calculate a simple moving average (typically 20 days) of the C (either the close or weighted-close) Upper band: MA + N StdDev(C ) Lower band: MA N StdDev(C ) 60 typically in the range of 2 to 3 N
Interpretation
Trade reversals between the upper and lower bands Trade break-outs above/below the bands 80
2011)
quantstrat-III
56 / 68
HOLDRS are ETFs that represent a basket of stocks in a specic industry segment The oil services HOLDR includes companies specically involved in oil 40 drilling and related services Well apply the Bollinger band system to 5 components of the oil services HOLDR ETF
SLB 60 - Schlumberger RIG - Transocean HAL - Haliburton BHI - Baker Hughes DO - Diamond Oshore 80
2011)
quantstrat-III
57 / 68
40
Define strategy
60
Bar-by-bar processing
80
Update
100
Reporting
120
40
R Code:
> # inz currency and stocks > stock.str = c("SLB","RIG","HAL","BHI","DO") > for(symbol in stock.str) 60 stock(symbol, currency="USD",multiplier=1) > # download stocks > start.data <- as.Date("1998-12-22") > end.data <- as.Date("2011-08-09") > initDate <- start.data-1 > for(symbol in stock.str) getSymbols(symbol,from=start.data,to=end.data,adjust=T)
Guy Yollin (Copyright
80
2011)
quantstrat-III
58 / 68
60
Bar-by-bar processing
80
Update
100
Reporting
120
40
R Code:
> > > > > > # inz portfolio, account, orders, strategy strat.name <- "BBANDS" 60 initEq=1000000 trade.percent = 0.05 dummy <- initPortf(name=strat.name,symbols=stock.str, initDate=initDate) dummy <- initAcct(name=strat.name,portfolios=strat.name, initDate=initDate, initEq=initEq) > initOrders(portfolio=strat.name,initDate=initDate) 80 > strat <- strategy(strat.name)
2011)
quantstrat-III
59 / 68
mm
Initialize currency and instruments, and load historic data
Bar-by-bar processing
Update
Reporting
40
Initialize portfolio, account, orders, strategy
60
80
100
120
Generate performance reports and graphs
40
R Code:
> # indicators: > strat <- add.indicator(strategy = strat, name = "BBands", arguments = list(HLC = quote(HLC(mktdata)), maType='SMA')) > # signals: > strat <-60 add.signal(strat,name="sigCrossover", arguments = list(columns=c("Close","up"),relationship="gt"), label="Cl.gt.UpperBand") > strat <- add.signal(strat,name="sigCrossover", arguments = list(columns=c("Close","dn"),relationship="lt"), label="Cl.lt.LowerBand") > strat <-80 add.signal(strat,name="sigCrossover", arguments = list(columns=c("High","Low","mavg"),relationship="op"), label="Cross.Mid")
Guy Yollin (Copyright
2011)
quantstrat-III
60 / 68
40
Define strategy
60
Bar-by-bar processing
80
Update
100 Reporting
120
40
R Code:
> # rules: > strat <- add.rule(strat,name='ruleSignal', arguments = list(sigcol="Cl.gt.UpperBand",sigval=TRUE, orderqty=-100, 60 ordertype='market', orderside=NULL, threshold=NULL),type='enter') > strat <- add.rule(strat,name='ruleSignal', arguments = list(sigcol="Cl.lt.LowerBand",sigval=TRUE, orderqty= 100, ordertype='market', orderside=NULL, threshold=NULL),type='enter') > strat <- add.rule(strat,name='ruleSignal', arguments = list(sigcol="Cross.Mid",sigval=TRUE, orderqty= 'all', 80 ordertype='market', orderside=NULL, threshold=NULL),type='exit')
2011)
quantstrat-III
61 / 68
40
60
Define strategy
80
Bar-by-bar processing Update
100
Reporting
120
40
R Code:
> > > > > # parameters: 60 SD = 2 N = 20 # apply strategy out<-try(applyStrategy(strategy=strat, portfolios=strat.name, parameters=list(sd=SD,n=N),verbose=F))
80
2011)
quantstrat-III
62 / 68
40
Define strategy
60
Bar-by-bar processing
80
Update
100
Reporting
120
40
R Code:
> dummy <- updatePortf(Portfolio=strat.name, Dates=paste('::',as.Date(Sys.time()),sep='')) 60 > if(sum(duplicated(index(getPortfolio(strat.name)$summary)))>0) { tempPortfolio <- getPortfolio(strat.name) tempPortfolio$summary <- as.xts(aggregate(x=tempPortfolio$summary, by=index(tempPortfolio$summary), FUN=sum)) assign(paste("portfolio.",strat.name,sep=""),tempPortfolio,pos=.blotter) 80 warning("duplicates removed after update") }
2011)
quantstrat-III
63 / 68
40
60
Define strategy
80
Bar-by-bar processing Update
100
Reporting
120
40
R Code:
> chart_Posn(Portfolio=strat.name,Symbol="DO",Dates="2009::2011") 60 > plot(add_BBands()) > trading.pl <- getPortfolio(strat.name)$summary$Net.Trading.PL > rets <- trading.pl/initEq > charts.PerformanceSummary(rets,colorset = bluefocus,xlab="")
80
2011)
quantstrat-III
64 / 68
40
60
80
2011)
quantstrat-III
65 / 68
mm
Cumulative Return
0.02 0.03
40
60
80
100
120
0.01
40
Daily Return
0.000
0.010
0.00
60
Drawdown
0.010
0.010
0.025
80
19981221 20000703 20020102 20030701 20050103 20060703 20080102 20090701 20110103
2011)
quantstrat-III
66 / 68
Outline
mm
1
40
60
80
100
120
2011)
quantstrat-III
67 / 68
Transaction infrastructure for dening instruments, transactions, portfolios and accounts for trading systems and simulation. Provides portfolio support for multi-asset class and multi-currency portfolios. Still40 heavy development. in Despite beta-status, software is used everyday by hearty working professions in asset management Inherent exibility provided by R allows analysis that is still 60 unavailable in some dedicated commercial packages
Although the software is free, be prepared to pay some dues in terms of time and eort to get things working
R-SIG-FINANCE is your friend
80
2011)
quantstrat-III
68 / 68