68
Computational Finance and Risk Management Quantitative Trading Strategies in R Part 3 of 3 Guy Yollin Principal Consultant, r-programming.org Visiting Lecturer, University of Washington Guy Yollin (Copyright 2011) Quantitative Trading Strategies in R quantstrat-III 1 / 68

Quantitative Trading Strategies in R Part 3 of 3

Embed Size (px)

DESCRIPTION

Quantitative Trading Strategies in RPart 3 of 3

Citation preview

Page 1: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Computational Finance and Risk Management

Quantitative Trading Strategies in R

Part 3 of 3

Guy YollinPrincipal Consultant, r-programming.org

Visiting Lecturer, University of Washington

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 1 / 68

Page 2: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Outline

1 MACD example

2 MACD example extended to multiple assets

3 Optimizing the MACD trading system

4 RSI example

5 Bollinger band example

6 Summary

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 2 / 68

Page 3: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Lecture references

TradeAnalytics project page on R-forge:http://r-forge.r-project.org/projects/blotter/

documents and demos for:

blotter packagequantstrat package

R-SIG-FINANCE:https://stat.ethz.ch/mailman/listinfo/r-sig-finance

Kent Russell’s Timely Portfolio blog:http://timelyportfolio.blogspot.com/

6-part quantstrat example

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 3 / 68

Page 4: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Quantstrat demos

faber maCross bbands rsi macd faberMC

name='sigCrossover' Y Y Y N N Y

name='sigThreshold' N N N Y Y N

ordertype='market' Y Y Y Y Y Y

ordertype='stoplimit' N N N N Y N

type='enter' Y Y Y Y Y Y

type='exit' Y Y Y Y Y Y

type='risk' N N N N Y N

orderside='long' Y Y N Y Y Y

orderside='short' N N N Y N N

applyStrategy parameters N N Y Y Y N

index.class='Date' N Y Y Y Y N

index.class='POSIXt' Y N N N N N

multiasset Y N N Y N Y

multicurrency N N N N N Y

data adjusted N Y N N N N

updates Account N N N N N N

demos are located in ∼/R-2.13.1/library/quantstrat/demo

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 4 / 68

Page 5: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Outline

1 MACD example

2 MACD example extended to multiple assets

3 Optimizing the MACD trading system

4 RSI example

5 Bollinger band example

6 Summary

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 5 / 68

Page 6: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

MACD (Moving Average Convergence-Divergence)

Trend-following momentum indicator

Published by Gerald Appel in the late 1970

MACD Calculation

MACD = 12-day EMA - 26-day EMAMACD Signal Line = 9-day EMA of MACDMACD histogram = MACD - Signal Line

Interpretation

Buy/Sell when MACD Signal Line crosses 0

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 6 / 68

Page 7: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

MACD system in TradeStation

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 7 / 68

Page 8: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

MACD code in EasyLanguage

EasyLanguage code

i n p u t s : Fas tLength ( 12 ) , SlowLength ( 26 ) , MACDLength( 9 ) ;v a r i a b l e s : MyMACD( 0 ) , MACDSig( 0 ) ;

MyMACD = MACD( Close , FastLength , SlowLength ) ;MACDSig = XAverage ( MyMACD, MACDLength ) ;

i f MACDSig c r o s s e s above 0 thenBuy ( ”MacdLE ” ) next bar at market ;

i f MACDSig c r o s s e s below 0 thenS e l l ( ”MacdLX” ) next bar at market ;

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 8 / 68

Page 9: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

MACD indicator from TTR

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 9 / 68

Page 10: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Initialize currency and trading instruments

Initialize portfolio, account, orders,

strategy

Add indicators, signals, and rules

Generate performance reports

and graphs

Initialize currency and

instruments, and load historic data

Apply strategy to portfolio

InitializationBar-by-bar processing

Reporting

Update portfolio, account, equity

Define strategy Update

R Code:

> library(quantstrat)

> # inz currency and stocks

> dummy <- currency('USD')

> stock.str = c("XLF")

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

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

Page 11: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Initialize portfolio, account, and orders object

Initialize portfolio, account, orders,

strategy

Add indicators, signals, and rules

Generate performance reports

and graphs

Initialize currency and

instruments, and load historic data

Apply strategy to portfolio

InitializationBar-by-bar processing

Reporting

Update portfolio, account, equity

Define strategy Update

R Code:

> # inz portfolio, account, orders, strategy

> strat.name <- "MACD"

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

> strat <- strategy(strat.name)

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 11 / 68

Page 12: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

The add.signals function

quantstrat supports the following signal types:

sigCrossover crossover signal (”gt”, ”lt”, ”eq”, ”gte”, ”lte”)

sigComparison comparison signal (”gt”, ”lt”, ”eq”, ”gte”, ”lte”)

sigThreshold threshold signal (”gt”, ”lt”, ”eq”, ”gte”, ”lte”)

sigPeak peak/valley signals (”peak”, ”bottom”)

sigFormula signal calculated from a formula

R Code: The add.signals function

> args(add.signal)

function (strategy, name, arguments, parameters = NULL, label = NULL,

..., enabled = TRUE, indexnum = NULL, store = FALSE)

NULL

Main arguments:

strategy strategy object

name name of the signal (one of the 5 supported signals)

arguments arguments to be passed to the indicator functionGuy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 12 / 68

Page 13: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

The sigThreshold function

The sigThreshold function generates a threshold signal

R Code: The sigThreshold function

> args(sigThreshold)

function (label, data = mktdata, column, threshold = 0, relationship = c("gt",

"lt", "eq", "gte", "lte"), cross = FALSE)

NULL

Main arguments:

label text label to apply to the output

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

cross if TRUE, then signal will be TRUE only for the firstobservation to cross the threshold

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 13 / 68

Page 14: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Define indicators and signals

Initialize portfolio, account, orders,

strategy

Add indicators, signals, and rules

Generate performance reports

and graphs

Initialize currency and

instruments, and load historic data

Apply strategy to portfolio

InitializationBar-by-bar processing

Reporting

Update portfolio, account, equity

Define strategy Update

R Code:

> # indicators:

> strat <- add.indicator(strategy = strat, name = "MACD",

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

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

Page 15: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Define order sizing function

Initialize portfolio, account, orders,

strategy

Add indicators, signals, and rules

Generate performance reports

and graphs

Initialize currency and

instruments, and load historic data

Apply strategy to portfolio

InitializationBar-by-bar processing

Reporting

Update portfolio, account, equity

Define strategy Update

R Code:

> osPercentEquity <- function (timestamp,orderqty,portfolio,symbol,ruletype,...)

tempPortfolio <- getPortfolio(portfolio)

dummy <- updatePortf(Portfolio=portfolio,

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

orderqty <- sign(orderqty)*round(tradeSize/ClosePrice)

return(orderqty)

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 15 / 68

Page 16: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Define entry and exit rules

Initialize portfolio, account, orders,

strategy

Add indicators, signals, and rules

Generate performance reports

and graphs

Initialize currency and

instruments, and load historic data

Apply strategy to portfolio

InitializationBar-by-bar processing

Reporting

Update portfolio, account, equity

Define strategy Update

R Code:

> # rules:

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

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 16 / 68

Page 17: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Applying the strategy to a portfolio

Initialize portfolio, account, orders,

strategy

Add indicators, signals, and rules

Generate performance reports

and graphs

Initialize currency and

instruments, and load historic data

Apply strategy to portfolio

InitializationBar-by-bar processing

Reporting

Update portfolio, account, equity

Define strategy Update

R Code:

> # parameters:

> fastMA = 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),

verbose=F))

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 17 / 68

Page 18: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Call updatePortf to update portfolio P&L

Initialize portfolio, account, orders,

strategy

Add indicators, signals, and rules

Generate performance reports

and graphs

Initialize currency and

instruments, and load historic data

Apply strategy to portfolio

InitializationBar-by-bar processing

Reporting

Update portfolio, account, equity

Define strategy Update

R Code:

> dummy <- updatePortf(Portfolio=strat.name,

Dates=paste('::',as.Date(Sys.time()),sep=''))

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

warning("duplicates removed after update")

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 18 / 68

Page 19: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Chart MACD system performance for XLF

Initialize portfolio, account, orders,

strategy

Add indicators, signals, and rules

Generate performance reports

and graphs

Initialize currency and

instruments, and load historic data

Apply strategy to portfolio

InitializationBar-by-bar processing

Reporting

Update portfolio, account, equity

Define strategy Update

R Code:

> source("chart_Posn.R")

> chart_Posn(Portfolio=strat.name,Symbol="XLF")

> plot(add_MACD())

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 19 / 68

Page 20: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

MACD system performance for XLF

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 20 / 68

Page 21: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Outline

1 MACD example

2 MACD example extended to multiple assets

3 Optimizing the MACD trading system

4 RSI example

5 Bollinger band example

6 Summary

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 21 / 68

Page 22: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Quantstrat/Blotter portfolios with multiple assets

While most of the quantstrat demos use a single asset, the real powerof the architecture is that it supports multiple assets

To use a multiple-asset portfolio, simply supply a symbol list whencalling initPortf

All functionality should simply work with the entire portfolio of assets

applying a strategy via applyStrategy will generate transactions forall assets according to the define trading rulescalculating portfolio P&L via updatePortf will accumulate the P&Lfor all assets

Due to the additional calculations required, working with multi-assetportfolios can be time consuming

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 22 / 68

Page 23: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Initialize currency and trading instruments

Initialize portfolio, account, orders,

strategy

Add indicators, signals, and rules

Generate performance reports

and graphs

Initialize currency and

instruments, and load historic data

Apply strategy to portfolio

InitializationBar-by-bar processing

Reporting

Update portfolio, account, equity

Define strategy Update

R Code:

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

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

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

Page 24: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Initialize portfolio, account, and orders object

Initialize portfolio, account, orders,

strategy

Add indicators, signals, and rules

Generate performance reports

and graphs

Initialize currency and

instruments, and load historic data

Apply strategy to portfolio

InitializationBar-by-bar processing

Reporting

Update portfolio, account, equity

Define strategy Update

R Code:

> # inz portfolio, account, orders, strategy

> strat.name <- "MACD"

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

> strat <- strategy(strat.name)

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 24 / 68

Page 25: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

The blotter_portfolio object

myPortfolio

--------------------

blotter_portfolio

symbols

--------------------

listsymbols

--------------------

listsymbols

--------------------

list

summary

--------------------

portfolio_summary xts

Long.Value

Short.Value

Net.Value

Gross.Value

Period.Realized.PL

Period.Unrealized.PL

Gross.Trading.PL

Txn.Fees

Net.Trading.PL

txn

--------------------

transactions xts

posPL

--------------------

posPL xts

posPL.USD

--------------------

posPL xts

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

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

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 25 / 68

Page 26: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Symbols in the botter_portfolio object

R Code:

> macdPortfolio <- getPortfolio(strat.name)

> names(macdPortfolio)

[1] "symbols" "summary"

> length(macdPortfolio$symbols)

[1] 9

> names(macdPortfolio$symbols)

[1] "XLF" "XLP" "XLE" "XLY" "XLV" "XLI" "XLB" "XLK" "XLU"

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 26 / 68

Page 27: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Define indicators and signals

Initialize portfolio, account, orders,

strategy

Add indicators, signals, and rules

Generate performance reports

and graphs

Initialize currency and

instruments, and load historic data

Apply strategy to portfolio

InitializationBar-by-bar processing

Reporting

Update portfolio, account, equity

Define strategy Update

R Code:

> # indicators:

> strat <- add.indicator(strategy = strat, name = "MACD",

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

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

Page 28: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Define order sizing function

Initialize portfolio, account, orders,

strategy

Add indicators, signals, and rules

Generate performance reports

and graphs

Initialize currency and

instruments, and load historic data

Apply strategy to portfolio

InitializationBar-by-bar processing

Reporting

Update portfolio, account, equity

Define strategy Update

R Code:

> osPercentEquity <- function (timestamp,orderqty,portfolio,symbol,ruletype,...)

tempPortfolio <- getPortfolio(portfolio)

dummy <- updatePortf(Portfolio=portfolio,

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

orderqty <- sign(orderqty)*round(tradeSize/ClosePrice)

return(orderqty)

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 28 / 68

Page 29: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Define entry and exit rules

Initialize portfolio, account, orders,

strategy

Add indicators, signals, and rules

Generate performance reports

and graphs

Initialize currency and

instruments, and load historic data

Apply strategy to portfolio

InitializationBar-by-bar processing

Reporting

Update portfolio, account, equity

Define strategy Update

R Code:

> # rules:

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

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 29 / 68

Page 30: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Applying the strategy to a portfolio

Initialize portfolio, account, orders,

strategy

Add indicators, signals, and rules

Generate performance reports

and graphs

Initialize currency and

instruments, and load historic data

Apply strategy to portfolio

InitializationBar-by-bar processing

Reporting

Update portfolio, account, equity

Define strategy Update

R Code:

> # parameters:

> fastMA = 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),

verbose=F))

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 30 / 68

Page 31: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Call updatePortf to update portfolio P&L

Initialize portfolio, account, orders,

strategy

Add indicators, signals, and rules

Generate performance reports

and graphs

Initialize currency and

instruments, and load historic data

Apply strategy to portfolio

InitializationBar-by-bar processing

Reporting

Update portfolio, account, equity

Define strategy Update

R Code:

> dummy <- updatePortf(Portfolio=strat.name,

Dates=paste('::',as.Date(Sys.time()),sep=''))

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

warning("duplicates removed after update")

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 31 / 68

Page 32: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Chart portfolio performance

Initialize portfolio, account, orders,

strategy

Add indicators, signals, and rules

Generate performance reports

and graphs

Initialize currency and

instruments, and load historic data

Apply strategy to portfolio

InitializationBar-by-bar processing

Reporting

Update portfolio, account, equity

Define strategy Update

R Code:

> library(PerformanceAnalytics)

> trading.pl <- getPortfolio(strat.name)$summary$Net.Trading.PL

> rets <- trading.pl/initEq

> charts.PerformanceSummary(rets,colorset = bluefocus,xlab="")

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 32 / 68

Page 33: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

MACD portfolio performance−

0.01

5−

0.00

50.

005

Cum

ulat

ive

Ret

urn

Net.Trading.PL Performance

−0.

005

0.00

00.

005

Dai

ly R

etur

n

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

−0.

025

−0.

010

Dra

wdo

wn

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 33 / 68

Page 34: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Outline

1 MACD example

2 MACD example extended to multiple assets

3 Optimizing the MACD trading system

4 RSI example

5 Bollinger band example

6 Summary

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 34 / 68

Page 35: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

MACD optimization

The inventor of MACD suggests that the difference between a 12-dayand 26-day exponential moving average be calculated and thensmooth via a 9-day exponential moving average

Our research interest is to explore if other values provide superiorresults

We will try 3 different values for each of fastMA, slowMA, andsignalMA, 27 different settings

All testing will be done on the 9-asset portfolio of S&P Sector SelectETFs with data from Dec-1998 through Aug-2011

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 35 / 68

Page 36: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

The Omega performance measure

The Omega performance measure† is a reward-to-risk ratio that can beapplied to a time-series of returns

Ω(L) =

∫ bL (1 − F (r))dr∫ L

a F (r)drwhere L is some return threshold (e.g. 0)

Omega uses all of the information in the return series and is thus wellsuited for non-normal distributions

Omega is essentially the ratio of a call price to a put price

Omega performance measure is calculated by the Omega function inPerformanceAnalytics

Ω(L) =C (L)

P(L)

†Shadwick and Keating. ”A Universal Performance Measure.”Journal of PerformanceMeasurement, Spring 2002

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 36 / 68

Page 37: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

The Omega performance measure

0.6

0.8

1.0

Portfolio Returns Cumulative Distribution Function

Pro

port

ion <

= x

Omega Performance Measure

P/L Distribution

Density

1.0

1.5

0.6

0.8

1.0

Portfolio Returns Cumulative Distribution Function

Pro

port

ion <

= x 0

.60.8

1.0

Portfolio Returns Cumulative Distribution Function

Pro

port

ion <

= x

R Tools for Portfolio Optimization26

-0.5 0.0 0.5 1.0

0.0

0.2

0.4

daily return

Pro

port

ion <

= x

daily return

Density

-1.0 -0.5 0.0 0.5 1.0 1.5

0.0

0.5

-0.5 0.0 0.5 1.0

0.0

0.2

0.4

daily return

Pro

port

ion <

= x

a bL

-0.5 0.0 0.5 1.0

0.0

0.2

0.4

daily return

Pro

port

ion <

= x

a bLa bL

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 37 / 68

Page 38: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

MACD optimization

R Code:

> fastMA <- c(5,10,15)

> 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

1 5 20 1

2 10 20 1

3 15 20 1

4 5 25 1

5 10 25 1

6 15 25 1

7 5 30 1

8 10 30 1

9 15 30 1

10 5 20 5

11 10 20 5

12 15 20 5

> num.opts <- nrow(parm.comb)

> res.vec <- rep(NA,num.opts)

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 38 / 68

Page 39: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Optimization loop

R Code:

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

# apply 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),

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

omega <- as.numeric(Omega(rets))

res.vec[i] <- omega

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 39 / 68

Page 40: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Optimization

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 40 / 68

Page 41: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Optimization summary

Performed a true multi-parameter grid search on a multi-assetportfolio

Functionality not supported within TradeStation or similar packages

Optimal values:

fastMA = 15 (default = 12)slowMA = 25 (default = 26)signalMA = 10 (default = 9)

Process ran for approximately 8.5 hours on the RStudio cloud

Embarrassingly parallel problem that would be idea for any of R’sparallel computing capabilities (e.g. snow, NetWorkSpaces etc.)

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 41 / 68

Page 42: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Outline

1 MACD example

2 MACD example extended to multiple assets

3 Optimizing the MACD trading system

4 RSI example

5 Bollinger band example

6 Summary

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 42 / 68

Page 43: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

RSI (Relative Strength Index)

Momentum oscillator (value between 0 and 100)

Published by Welles Wilder in the late 1970

RSI Calculation

RSI = 100 − 100

1 + RS

RS =mean(up changes)

mean(down changes)

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

Interpretation

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

Page 44: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Semiconductor HOLDR stocks

HOLDRS are ETFs that represent a basket of stocks in a specificindustry segment

The Semiconductor HOLDR includes large-cap semiconductormanufacturers as well as semiconductor equipment manufacturers

We’ll apply the RSI system to 5 components of the semiconductorHOLDR ETF

INTC - IntelTXN - Texas InstrumentAMAT - Applied MaterialsADI - Analog DevicesALTR - Altera

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 44 / 68

Page 45: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Initialize currency and trading instruments

Initialize portfolio, account, orders,

strategy

Add indicators, signals, and rules

Generate performance reports

and graphs

Initialize currency and

instruments, and load historic data

Apply strategy to portfolio

InitializationBar-by-bar processing

Reporting

Update portfolio, account, equity

Define strategy Update

R Code:

> # inz currency and stocks

> stock.str = c("INTC","TXN","AMAT","ADI","ALTR")

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

> initDate <- 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 45 / 68

Page 46: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Initialize portfolio, account, and orders object

Initialize portfolio, account, orders,

strategy

Add indicators, signals, and rules

Generate performance reports

and graphs

Initialize currency and

instruments, and load historic data

Apply strategy to portfolio

InitializationBar-by-bar processing

Reporting

Update portfolio, account, equity

Define strategy Update

R Code:

> # inz portfolio, account, orders, strategy

> strat.name <- "RSI"

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

> strat <- strategy(strat.name)

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 46 / 68

Page 47: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Define indicators and signals

Initialize portfolio, account, orders,

strategy

Add indicators, signals, and rules

Generate performance reports

and graphs

Initialize currency and

instruments, and load historic data

Apply strategy to portfolio

InitializationBar-by-bar processing

Reporting

Update portfolio, account, equity

Define strategy Update

R Code:

> # indicators:

> strat <- add.indicator(strategy = strat, name = "RSI",

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

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

Page 48: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Define short entry and exit rules

Initialize portfolio, account, orders,

strategy

Add indicators, signals, and rules

Generate performance reports

and graphs

Initialize currency and

instruments, and load historic data

Apply strategy to portfolio

InitializationBar-by-bar processing

Reporting

Update portfolio, account, equity

Define strategy Update

R Code:

> # rules:

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

type='exit', path.dep=TRUE)

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 48 / 68

Page 49: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Define long entry and exit rules

Initialize portfolio, account, orders,

strategy

Add indicators, signals, and rules

Generate performance reports

and graphs

Initialize currency and

instruments, and load historic data

Apply strategy to portfolio

InitializationBar-by-bar processing

Reporting

Update portfolio, account, equity

Define strategy Update

R Code:

> # rules:

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

type='exit', path.dep=TRUE)

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 49 / 68

Page 50: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Applying the strategy to a portfolio

Initialize portfolio, account, orders,

strategy

Add indicators, signals, and rules

Generate performance reports

and graphs

Initialize currency and

instruments, and load historic data

Apply strategy to portfolio

InitializationBar-by-bar processing

Reporting

Update portfolio, account, equity

Define strategy Update

R Code:

> # apply strategy

> out<-try(applyStrategy(strategy=strat, portfolios=strat.name,

parameters=list(n=2),verbose=F))

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 50 / 68

Page 51: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Call updatePortf to update portfolio P&L

Initialize portfolio, account, orders,

strategy

Add indicators, signals, and rules

Generate performance reports

and graphs

Initialize currency and

instruments, and load historic data

Apply strategy to portfolio

InitializationBar-by-bar processing

Reporting

Update portfolio, account, equity

Define strategy Update

R Code:

> dummy <- updatePortf(Portfolio=strat.name,

Dates=paste('::',as.Date(Sys.time()),sep=''))

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

warning("duplicates removed after update")

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 51 / 68

Page 52: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Chart portfolio performance

Initialize portfolio, account, orders,

strategy

Add indicators, signals, and rules

Generate performance reports

and graphs

Initialize currency and

instruments, and load historic data

Apply strategy to portfolio

InitializationBar-by-bar processing

Reporting

Update portfolio, account, equity

Define strategy Update

R Code:

> chart_Posn(Portfolio=strat.name,Symbol="AMAT",Dates="2009::2011")

> plot(add_RSI())

> trading.pl <- getPortfolio(strat.name)$summary$Net.Trading.PL

> rets <- trading.pl/initEq

> charts.PerformanceSummary(rets,colorset = bluefocus,xlab="")

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 52 / 68

Page 53: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

AMAT performance for RSI strategy

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 53 / 68

Page 54: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

RSI portfolio performance0.

00.

51.

01.

5

Cum

ulat

ive

Ret

urn

Net.Trading.PL Performance

−0.

020.

020.

04

Dai

ly R

etur

n

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

−0.

15−

0.05

0.00

Dra

wdo

wn

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 54 / 68

Page 55: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Outline

1 MACD example

2 MACD example extended to multiple assets

3 Optimizing the MACD trading system

4 RSI example

5 Bollinger band example

6 Summary

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 55 / 68

Page 56: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Bollinger bands

Bollinger bands are a volatility-sensitive price channel

Published by John Bollinger in the early 1980s

RSI Calculation

Calculate a simple moving average (typically 20 days) of the C (eitherthe close or weighted-close)Upper band: MA + N × StdDev(C )Lower band: MA− N × StdDev(C )N typically in the range of 2 to 3

Interpretation

Trade reversals between the upper and lower bandsTrade break-outs above/below the bands

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 56 / 68

Page 57: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Oil services HOLDR stocks

HOLDRS are ETFs that represent a basket of stocks in a specificindustry segment

The oil services HOLDR includes companies specifically involved in oildrilling and related services

We’ll apply the Bollinger band system to 5 components of the oilservices HOLDR ETF

SLB - SchlumbergerRIG - TransoceanHAL - HaliburtonBHI - Baker HughesDO - Diamond Offshore

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 57 / 68

Page 58: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Initialize currency and trading instruments

Initialize portfolio, account, orders,

strategy

Add indicators, signals, and rules

Generate performance reports

and graphs

Initialize currency and

instruments, and load historic data

Apply strategy to portfolio

InitializationBar-by-bar processing

Reporting

Update portfolio, account, equity

Define strategy Update

R Code:

> # inz currency and stocks

> stock.str = c("SLB","RIG","HAL","BHI","DO")

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

> initDate <- 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 58 / 68

Page 59: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Initialize portfolio, account, and orders object

Initialize portfolio, account, orders,

strategy

Add indicators, signals, and rules

Generate performance reports

and graphs

Initialize currency and

instruments, and load historic data

Apply strategy to portfolio

InitializationBar-by-bar processing

Reporting

Update portfolio, account, equity

Define strategy Update

R Code:

> # inz portfolio, account, orders, strategy

> strat.name <- "BBANDS"

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

> strat <- strategy(strat.name)

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 59 / 68

Page 60: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Define indicators and signals

Initialize portfolio, account, orders,

strategy

Add indicators, signals, and rules

Generate performance reports

and graphs

Initialize currency and

instruments, and load historic data

Apply strategy to portfolio

InitializationBar-by-bar processing

Reporting

Update portfolio, account, equity

Define strategy Update

R Code:

> # indicators:

> strat <- add.indicator(strategy = strat, name = "BBands",

arguments = list(HLC = quote(HLC(mktdata)), maType='SMA'))

> # signals:

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

Page 61: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Define entry and exit rules

Initialize portfolio, account, orders,

strategy

Add indicators, signals, and rules

Generate performance reports

and graphs

Initialize currency and

instruments, and load historic data

Apply strategy to portfolio

InitializationBar-by-bar processing

Reporting

Update portfolio, account, equity

Define strategy Update

R Code:

> # rules:

> strat <- add.rule(strat,name='ruleSignal',

arguments = list(sigcol="Cl.gt.UpperBand",sigval=TRUE, orderqty=-100,

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

ordertype='market', orderside=NULL, threshold=NULL),type='exit')

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 61 / 68

Page 62: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Applying the strategy to a portfolio

Initialize portfolio, account, orders,

strategy

Add indicators, signals, and rules

Generate performance reports

and graphs

Initialize currency and

instruments, and load historic data

Apply strategy to portfolio

InitializationBar-by-bar processing

Reporting

Update portfolio, account, equity

Define strategy Update

R Code:

> # parameters:

> SD = 2

> N = 20

> # apply strategy

> out<-try(applyStrategy(strategy=strat, portfolios=strat.name,

parameters=list(sd=SD,n=N),verbose=F))

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 62 / 68

Page 63: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Call updatePortf to update portfolio P&L

Initialize portfolio, account, orders,

strategy

Add indicators, signals, and rules

Generate performance reports

and graphs

Initialize currency and

instruments, and load historic data

Apply strategy to portfolio

InitializationBar-by-bar processing

Reporting

Update portfolio, account, equity

Define strategy Update

R Code:

> dummy <- updatePortf(Portfolio=strat.name,

Dates=paste('::',as.Date(Sys.time()),sep=''))

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

warning("duplicates removed after update")

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 63 / 68

Page 64: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Chart portfolio performance

Initialize portfolio, account, orders,

strategy

Add indicators, signals, and rules

Generate performance reports

and graphs

Initialize currency and

instruments, and load historic data

Apply strategy to portfolio

InitializationBar-by-bar processing

Reporting

Update portfolio, account, equity

Define strategy Update

R Code:

> chart_Posn(Portfolio=strat.name,Symbol="DO",Dates="2009::2011")

> plot(add_BBands())

> trading.pl <- getPortfolio(strat.name)$summary$Net.Trading.PL

> rets <- trading.pl/initEq

> charts.PerformanceSummary(rets,colorset = bluefocus,xlab="")

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 64 / 68

Page 65: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

DO performance for BBands strategy

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 65 / 68

Page 66: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Bollinger bands portfolio performance0.

000.

010.

020.

03

Cum

ulat

ive

Ret

urn

Net.Trading.PL Performance

−0.

010

0.00

00.

010

Dai

ly R

etur

n

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

−0.

025

−0.

010

Dra

wdo

wn

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 66 / 68

Page 67: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Outline

1 MACD example

2 MACD example extended to multiple assets

3 Optimizing the MACD trading system

4 RSI example

5 Bollinger band example

6 Summary

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 67 / 68

Page 68: Quantitative Trading Strategies in R    Part 3 of 3

40 60 80 100 120

40

60

80

mm

Summary of blotter and quantstrat

Transaction infrastructure for defining instruments, transactions,portfolios and accounts for trading systems and simulation. Providesportfolio support for multi-asset class and multi-currency portfolios.Still in heavy development.

Despite beta-status, software is used everyday by hearty workingprofessions in asset management

Inherent flexibility provided by R allows analysis that is stillunavailable in some dedicated commercial packages

Although the software is free, be prepared to pay some dues in terms oftime and effort to get things working

R-SIG-FINANCE is your friend

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-III 68 / 68