Computational Finance and Risk Management

mm 40 60 80 100 120

Quantitative Trading Strategies in R
40

Part 3 of 3
60

Guy Yollin
Principal Consultant, r-programming.org Visiting Lecturer, University of Washington

80

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

1 / 68

Outline
mm
1

40

60

80

100

120

MACD example MACD example extended to multiple assets
40

2

3

Optimizing the MACD trading system RSI example
60

4

5

Bollinger band example Summary
80

6

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

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

Kent Russell’s Timely Portfolio blog: http://timelyportfolio.blogspot.com/
6-part quantstrat example 80

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

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

demos are located in ∼/R-2.13.1/library/quantstrat/demo
Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

4 / 68

Outline
mm
1

40

60

80

100

120

MACD example MACD example extended to multiple assets
40

2

3

Optimizing the MACD trading system RSI example
60

4

5

Bollinger band example Summary
80

6

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

5 / 68

MACD (Moving Average Convergence-Divergence)
mm 40 60 80 100 120

Trend-following momentum indicator Published by Gerald Appel in the late 1970
40

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

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

6 / 68

MACD system in TradeStation
mm 40 60 80 100 120

40

60

80

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

7 / 68

MACD code in EasyLanguage
mm
EasyLanguage code
inputs : F a s t L e n g t h ( 12 ) , S l o w L e n g t h ( 26 ) , MACDLength ( 9 ) ; v a r i a b l e s : MyMACD( 0 ) , MACDSig ( 0 ) ;

40

60

80

100

120

40

MyMACD = MACD( C l o s e , F a s t L e n g t h , S l o w L e n g t h ) ; MACDSig = XAverage ( MyMACD, MACDLength ) ; i f MACDSig c r o s s e s a b o v e 0 t h e n Buy ( ”MacdLE ” ) n e x t b a r a t m a r k e t ;

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

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

8 / 68

MACD indicator from TTR
mm 40 60 80 100 120

40

60

80

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

9 / 68

Initialize currency and trading instruments
Initialization Define strategy

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

Add indicators, signals, and rules

Apply strategy to portfolio

Update portfolio, account, equity

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 <-

> for(symbol in stock.str) getSymbols(symbol,from=start.data,to=end.data,adjust=T)
Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

10 / 68

Initialize portfolio, account, and orders object
mm Initialization 40
Define strategy

60

Bar-by-bar processing

80

Update

100

Reporting

120

Initialize currency and instruments, and load historic data

40

Initialize portfolio, account, orders, strategy

Add indicators, signals, and rules

Apply strategy to portfolio

Update portfolio, account, equity

Generate performance reports and graphs

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)

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

11 / 68

The add.signals function
quantstrat supports the following signal types: sigCrossover crossover signal (”gt”, ”lt”, ”eq”, ”gte”, ” 100 lte” ) mm 40 60 80 sigComparison comparison signal (”gt”, ”lt”, ”eq”, ”gte” ” ) , lte” sigThreshold threshold signal (”gt”, ”lt”, ”eq”, ”gte”, ” ) lte” sigPeak peak/valley signals (”peak”, ”bottom”) 40 sigFormula signal calculated from a formula
R Code: The add.signals function
> args(add.signal) function (strategy, name, arguments, parameters = NULL, label = NULL, 60 ..., enabled = TRUE, indexnum = NULL, store = FALSE) NULL

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)

Quantitative Trading Strategies in R

quantstrat-III

12 / 68

The sigThreshold function
The sigThreshold function generates a threshold signal
mm
> args(sigThreshold) function (label, data = mktdata, column, threshold = 0, relationship = c("gt", "lt", "eq", "gte", "lte"), cross = FALSE) 40 NULL

40

60

80

100

120

R Code: The sigThreshold function

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 first observation to cross the threshold
Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

13 / 68

Define indicators and signals
Initialization mm

40

Define strategy

60

Bar-by-bar processing

80

Update

100

Reporting

120

Initialize currency and instruments, and load historic data

40

Initialize portfolio, account, orders, strategy

Add indicators, signals, and rules

Apply strategy to portfolio

Update portfolio, account, equity

Generate performance reports and graphs

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")

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

14 / 68

Define order sizing function
Initialization Define strategy

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

Add indicators, signals, and rules

Apply strategy to portfolio

Update portfolio, account, equity

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)

Quantitative Trading Strategies in R

quantstrat-III

15 / 68

Define entry and exit rules
mm
Initialization

40

60
Define strategy

Bar-by-bar processing

80
Update

100
Reporting

120

Initialize currency and instruments, and load historic data

40

Initialize portfolio, account, orders, strategy

Add indicators, signals, and rules

Apply strategy to portfolio

Update portfolio, account, equity

Generate performance reports and graphs

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

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

16 / 68

Applying the strategy to a portfolio
mm Initialization 40
Define strategy

60

Bar-by-bar processing

80

Update

100

Reporting

120

Initialize currency and instruments, and load historic data

40

Initialize portfolio, account, orders, strategy

Add indicators, signals, and rules

Apply strategy to portfolio

Update portfolio, account, equity

Generate performance reports and graphs

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))

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

17 / 68

Call updatePortf to update portfolio P&L
Initialization mm

40

Define strategy

60

Bar-by-bar processing

80

Update

100

Reporting

120

Initialize currency and instruments, and load historic data

40

Initialize portfolio, account, orders, strategy

Add indicators, signals, and rules

Apply strategy to portfolio

Update portfolio, account, equity

Generate performance reports and graphs

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") }

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

18 / 68

Chart MACD system performance for XLF
mm
Initialization

40

60
Define strategy

80
Bar-by-bar processing Update

100
Reporting

120

Initialize currency and instruments, and load historic data

40

Initialize portfolio, account, orders, strategy

Add indicators, signals, and rules

Apply strategy to portfolio

Update portfolio, account, equity

Generate performance reports and graphs

R Code:

60

> source("chart_Posn.R") > chart_Posn(Portfolio=strat.name,Symbol="XLF") > plot(add_MACD())

80

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

19 / 68

MACD system performance for XLF
mm 40 60 80 100 120

40

60

80

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

20 / 68

Outline
mm
1

40

60

80

100

120

MACD example MACD example extended to multiple assets
40

2

3

Optimizing the MACD trading system RSI example
60

4

5

Bollinger band example Summary
80

6

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

21 / 68

Quantstrat/Blotter portfolios with multiple assets
While most of the quantstrat demos use a single asset, the real power of the architecture is that it supports multiple assets To use a multiple-asset portfolio, simply supply a symbol list when calling initPortf 40 All functionality should simply work with the entire portfolio of assets
applying a strategy via applyStrategy will generate transactions for all assets according to the define trading rules 60 calculating portfolio P&L via updatePortf will accumulate the P&L for all assets mm 40 60 80 100 120

Due to the additional calculations required, working with multi-asset portfolios can be time consuming 80

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

22 / 68

Initialize currency and trading instruments
Initialization Define strategy Bar-by-bar processing Update Reporting

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 <-

> for(symbol in stock.str) getSymbols(symbol,from=start.data,to=end.data,adjust=T)
Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

23 / 68

Initialize portfolio, account, and orders object
mm Initialization 40
Define strategy

60

Bar-by-bar processing

80

Update

100

Reporting

120

Initialize currency and instruments, and load historic data

40

Initialize portfolio, account, orders, strategy

Add indicators, signals, and rules

Apply strategy to portfolio

Update portfolio, account, equity

Generate performance reports and graphs

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)

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

24 / 68

The blotter_portfolio object
mm 40
blotter_portfolio 60 myPortfolio --------------------

80

100

120

40

symbols -------------------symbols -------------------symbols list list -------------------list

summary -------------------portfolio_summary xts

txn -------------------transactions xts

posPL -------------------posPL xts

posPL.USD -------------------posPL xts

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

Long.Value Short.Value Net.Value Gross.Value Period.Realized.PL Period.Unrealized.PL Gross.Trading.PL Txn.Fees Net.Trading.PL

80

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

25 / 68

Symbols in the botter_portfolio object
mm
R Code:
> macdPortfolio <- getPortfolio(strat.name) > names(macdPortfolio)

40

60

80

100

120

40

[1] "symbols" "summary" > length(macdPortfolio$symbols) [1] 9

60 > names(macdPortfolio$symbols)
[1] "XLF" "XLP" "XLE" "XLY" "XLV" "XLI" "XLB" "XLK" "XLU"

80

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

26 / 68

Define indicators and signals
Initialization mm

40

Define strategy

60

Bar-by-bar processing

80

Update

100

Reporting

120

Initialize currency and instruments, and load historic data

40

Initialize portfolio, account, orders, strategy

Add indicators, signals, and rules

Apply strategy to portfolio

Update portfolio, account, equity

Generate performance reports and graphs

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")

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

27 / 68

Define order sizing function
Initialization Define strategy

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

Add indicators, signals, and rules

Apply strategy to portfolio

Update portfolio, account, equity

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)

Quantitative Trading Strategies in R

quantstrat-III

28 / 68

Define entry and exit rules
mm
Initialization

40

60
Define strategy

Bar-by-bar processing

80
Update

100
Reporting

120

Initialize currency and instruments, and load historic data

40

Initialize portfolio, account, orders, strategy

Add indicators, signals, and rules

Apply strategy to portfolio

Update portfolio, account, equity

Generate performance reports and graphs

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

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

29 / 68

Applying the strategy to a portfolio
mm Initialization 40
Define strategy

60

Bar-by-bar processing

80

Update

100

Reporting

120

Initialize currency and instruments, and load historic data

40

Initialize portfolio, account, orders, strategy

Add indicators, signals, and rules

Apply strategy to portfolio

Update portfolio, account, equity

Generate performance reports and graphs

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))

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

30 / 68

Call updatePortf to update portfolio P&L
Initialization mm

40

Define strategy

60

Bar-by-bar processing

80

Update

100

Reporting

120

Initialize currency and instruments, and load historic data

40

Initialize portfolio, account, orders, strategy

Add indicators, signals, and rules

Apply strategy to portfolio

Update portfolio, account, equity

Generate performance reports and graphs

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") }

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

31 / 68

Chart portfolio performance
mm
Initialization

40

60
Define strategy

80
Bar-by-bar processing Update

100
Reporting

120

Initialize currency and instruments, and load historic data

40

Initialize portfolio, account, orders, strategy

Add indicators, signals, and rules

Apply strategy to portfolio

Update portfolio, account, equity

Generate performance reports and graphs

R Code:
> > > >

library(PerformanceAnalytics) trading.pl <- getPortfolio(strat.name)$summary$Net.Trading.PL rets <- trading.pl/initEq charts.PerformanceSummary(rets,colorset = bluefocus,xlab="")

60

80

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

32 / 68

MACD portfolio performance
Net.Trading.PL Performance

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
1998−12−21 2000−07−03 2002−01−02 2003−07−01 2005−01−03 2006−07−03 2008−01−02 2009−07−01 2011−01−03

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

33 / 68

Outline
mm
1

40

60

80

100

120

MACD example MACD example extended to multiple assets
40

2

3

Optimizing the MACD trading system RSI example
60

4

5

Bollinger band example Summary
80

6

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

34 / 68

MACD optimization
mm 40 60 80 100 120

The inventor of MACD suggests that the difference 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 different values for each of fastMA, slowMA, and 60 signalMA, 27 different 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

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

35 / 68

The Omega performance measure
The Omega performance measure† is a reward-to-risk ratio that can be mm 40 80 100 120 applied to a time-series of returns 60 Ω(L) =
40
b L (1 − F (r ))dr L a F (r )dr

where L is some return threshold (e.g. 0)

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)

Quantitative Trading Strategies in R

quantstrat-III

36 / 68

Omega Performance Measure The Omega performance measure
Portfolio Returns Cumulative Distribution Function P/L Distribution
1.0

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

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

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

> num.opts <- nrow(parm.comb) > res.vec <- rep(NA,num.opts)
Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

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)

Quantitative Trading Strategies in R

quantstrat-III

39 / 68

Optimization
mm 40 60 80 100 120

40

60

80

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

40 / 68

Optimization summary
mm 40 60 80 100 120

Performed a true multi-parameter grid search on a multi-asset portfolio

Functionality not supported within TradeStation or similar packages Optimal values:
fastMA = 15 (default = 12) slowMA = 25 (default = 26) signalMA = 10 (default = 9) 60 40

Process ran for approximately 8.5 hours on the RStudio cloud Embarrassingly parallel problem that would be idea for any of R’s parallel computing capabilities (e.g. snow, NetWorkSpaces etc.) 80

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

41 / 68

Outline
mm
1

40

60

80

100

120

MACD example MACD example extended to multiple assets
40

2

3

Optimizing the MACD trading system RSI example
60

4

5

Bollinger band example Summary
80

6

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

42 / 68

RSI (Relative Strength Index)
Momentum oscillator (value between 0 and 100) mm 40 60 80 Published by Welles Wilder in the late 1970 RSI Calculation
40 100 120

RSI = 100 − RS =
60

100 1 + RS

mean(up changes) mean(down changes)

typical lengths are 14-days, 9-days, or 25-days

Interpretation
80 Trade reversals between thresholds (e.g. 70/30) Trade break-outs above/below thresholds (e.g. 70/30)
Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

43 / 68

Semiconductor HOLDR stocks
mm 40 60 80 100 120

HOLDRS are ETFs that represent a basket of stocks in a specific industry segment The Semiconductor HOLDR includes large-cap semiconductor 40 manufacturers as well as semiconductor equipment manufacturers We’ll 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

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

44 / 68

Initialize currency and trading instruments
Initialization mm

40

Define strategy

60

Bar-by-bar processing

80

Update

100

Reporting

120

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

Generate performance reports and graphs

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)

Quantitative Trading Strategies in R

quantstrat-III

45 / 68

Initialize portfolio, account, and orders object
mm Initialization 40
Define strategy

60

Bar-by-bar processing

80

Update

100

Reporting

120

Initialize currency and instruments, and load historic data

40

Initialize portfolio, account, orders, strategy

Add indicators, signals, and rules

Apply strategy to portfolio

Update portfolio, account, equity

Generate performance reports and graphs

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)

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

46 / 68

Define indicators and signals
mm Initialization 40
Define strategy

60

Bar-by-bar processing

80

Update

100

Reporting

120

Initialize currency and instruments, and load historic data

40

Initialize portfolio, account, orders, strategy

Add indicators, signals, and rules

Apply strategy to portfolio

Update portfolio, account, equity

Generate performance reports and graphs

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")

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

47 / 68

Define short entry and exit rules
mm Initialization 40
Define strategy

60

Bar-by-bar processing

80

Update

100

Reporting

120

Initialize currency and instruments, and load historic data

40

Initialize portfolio, account, orders, strategy

Add indicators, signals, and rules

Apply strategy to portfolio

Update portfolio, account, equity

Generate performance reports and graphs

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)

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

48 / 68

Define long entry and exit rules
mm Initialization 40
Define strategy

60

Bar-by-bar processing

80

Update

100

Reporting

120

Initialize currency and instruments, and load historic data

40

Initialize portfolio, account, orders, strategy

Add indicators, signals, and rules

Apply strategy to portfolio

Update portfolio, account, equity

Generate performance reports and graphs

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)

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

49 / 68

Applying the strategy to a portfolio
mm
Initialization

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

Generate performance reports and graphs

R Code: 60
> # apply strategy > out<-try(applyStrategy(strategy=strat, portfolios=strat.name, parameters=list(n=2),verbose=F))

80

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

50 / 68

Call updatePortf to update portfolio P&L
Initialization mm

40

Define strategy

60

Bar-by-bar processing

80

Update

100

Reporting

120

Initialize currency and instruments, and load historic data

40

Initialize portfolio, account, orders, strategy

Add indicators, signals, and rules

Apply strategy to portfolio

Update portfolio, account, equity

Generate performance reports and graphs

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") }

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

51 / 68

Chart portfolio performance
mm
Initialization

40

60
Define strategy

80
Bar-by-bar processing Update

100
Reporting

120

Initialize currency and instruments, and load historic data

40

Initialize portfolio, account, orders, strategy

Add indicators, signals, and rules

Apply strategy to portfolio

Update portfolio, account, equity

Generate performance reports and graphs

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

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

52 / 68

AMAT performance for RSI strategy
mm 40 60 80 100 120

40

60

80

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

53 / 68

RSI portfolio performance
Net.Trading.PL Performance

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 1998−12−21 2000−07−03 2002−01−02 2003−07−01 2005−01−03 2006−07−03 2008−01−02 2009−07−01 2011−01−03

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

54 / 68

Outline
mm
1

40

60

80

100

120

MACD example MACD example extended to multiple assets
40

2

3

Optimizing the MACD trading system RSI example
60

4

5

Bollinger band example Summary
80

6

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

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

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

56 / 68

Oil services HOLDR stocks
mm 40 60 80 100 120

HOLDRS are ETFs that represent a basket of stocks in a specific industry segment The oil services HOLDR includes companies specifically involved in oil 40 drilling and related services We’ll 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 Offshore 80

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

57 / 68

Initialize currency and trading instruments
Initialization mm

40

Define strategy

60

Bar-by-bar processing

80

Update

100

Reporting

120

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

Generate performance reports and graphs

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)

Quantitative Trading Strategies in R

quantstrat-III

58 / 68

Initialize portfolio, account, and orders object
mm Initialization 40
Define strategy

60

Bar-by-bar processing

80

Update

100

Reporting

120

Initialize currency and instruments, and load historic data

40

Initialize portfolio, account, orders, strategy

Add indicators, signals, and rules

Apply strategy to portfolio

Update portfolio, account, equity

Generate performance reports and graphs

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)

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

59 / 68

Define indicators and signals
Initialization Define strategy

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

Add indicators, signals, and rules

Apply strategy to portfolio

Update portfolio, account, equity

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)

Quantitative Trading Strategies in R

quantstrat-III

60 / 68

Define entry and exit rules
mm
Initialization

40

Define strategy

60

Bar-by-bar processing

80

Update

100 Reporting

120

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

Generate performance reports and graphs

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')

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

61 / 68

Applying the strategy to a portfolio
mm
Initialization

40

60
Define strategy

80
Bar-by-bar processing Update

100
Reporting

120

Initialize currency and instruments, and load historic data

40

Initialize portfolio, account, orders, strategy

Add indicators, signals, and rules

Apply strategy to portfolio

Update portfolio, account, equity

Generate performance reports and graphs

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

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

62 / 68

Call updatePortf to update portfolio P&L
Initialization mm

40

Define strategy

60

Bar-by-bar processing

80

Update

100

Reporting

120

Initialize currency and instruments, and load historic data

40

Initialize portfolio, account, orders, strategy

Add indicators, signals, and rules

Apply strategy to portfolio

Update portfolio, account, equity

Generate performance reports and graphs

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") }

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

63 / 68

Chart portfolio performance
mm
Initialization

40

60
Define strategy

80
Bar-by-bar processing Update

100
Reporting

120

Initialize currency and instruments, and load historic data

40

Initialize portfolio, account, orders, strategy

Add indicators, signals, and rules

Apply strategy to portfolio

Update portfolio, account, equity

Generate performance reports and graphs

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

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

64 / 68

DO performance for BBands strategy
mm 40 60 80 100 120

40

60

80

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

65 / 68

Bollinger bands portfolio performance
Net.Trading.PL Performance

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
1998−12−21 2000−07−03 2002−01−02 2003−07−01 2005−01−03 2006−07−03 2008−01−02 2009−07−01 2011−01−03

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

66 / 68

Outline
mm
1

40

60

80

100

120

MACD example MACD example extended to multiple assets
40

2

3

Optimizing the MACD trading system RSI example
60

4

5

Bollinger band example Summary
80

6

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

67 / 68

Summary of blotter and quantstrat
mm 40 60 80 100 120

Transaction infrastructure for defining 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 flexibility 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 effort to get things working
R-SIG-FINANCE is your friend

80

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

68 / 68

Master your semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master your semester with Scribd & The New York Times

Cancel anytime.