40 60 80 100 120
40
60
80
mm
Computational Finance and Risk Management
Quantitative Trading Strategies in R
Part 2 of 3
Guy YollinPrincipal Consultant, r-programming.org
Visiting Lecturer, University of Washington
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 1 / 68
40 60 80 100 120
40
60
80
mm
Outline
1 The applyStrategy and updatePortf functions
2 Position sizing
3 Passing parameters at apply-time
4 Parameter optimization
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 2 / 68
40 60 80 100 120
40
60
80
mm
Packages for trading system development in R
Data access, charting, indicators
Time series objects
Quantitative trading rules and trading accouting
Performance metrics and graphs
zoo: ordered observations
xts: extensible time series
TTR: technical trading rules
quantmod: quantitative financial modelling framework
blotter: tools for transaction-oriented trading systems development
quantstrat: quantitative strategy model framework
PerformanceAnalytics: Econometric tools for performance and risk analysis
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 3 / 68
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-II 4 / 68
40 60 80 100 120
40
60
80
mm
Outline
1 The applyStrategy and updatePortf functions
2 Position sizing
3 Passing parameters at apply-time
4 Parameter optimization
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 5 / 68
40 60 80 100 120
40
60
80
mm
Basic strategy backtesting workflow for quantstrat
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
processingReporting
Update portfolio,
account, equity
Define strategy Update
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 6 / 68
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)
> # define stock list
> stock.str=c("SPY")
> # inz currency and stocks
> dummy <- currency('USD')
> for(symbol in stock.str){
stock(symbol, currency="USD",multiplier=1)
}
> # download stocks
> start.data <- as.Date("2001-01-01")
> initDate <- start.data-1
> getSymbols(stock.str,from=start.data,adjust=T)
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 7 / 68
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 <- "MAX"
> initEq=1000000
> 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-II 8 / 68
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 = "SMA",
arguments = list(x=quote(Cl(mktdata)), n=50),label= "ma50" )
> strat <- add.indicator(strategy = strat, name = "SMA",
arguments = list(x=quote(Cl(mktdata)), n=200),label= "ma200")
> # signals:
> strat <- add.signal(strategy = strat,name="sigCrossover",
arguments = list(columns=c("ma50","ma200"), relationship="gte"),
label="ma50.gt.ma200")
> strat <- add.signal(strategy = strat,name="sigCrossover",
arguments = list(column=c("ma50","ma200"),relationship="lt"),
label="ma50.lt.ma200")
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 9 / 68
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="ma50.gt.ma200",sigval=TRUE, orderqty=100,
ordertype='market', orderside='long'),type='enter')
> strat <- add.rule(strategy = strat,name='ruleSignal',
arguments = list(sigcol="ma50.lt.ma200",sigval=TRUE, orderqty=-100,
ordertype='market', orderside='long'),type='exit')
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 10 / 68
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-II 11 / 68
40 60 80 100 120
40
60
80
mm
The str function
The str function compactly displays the internal structure of an R object
R Code: The str function
> args(str)
function (object, ...)
NULL
Main arguments:
object the R object to be inspected
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 12 / 68
40 60 80 100 120
40
60
80
mm
blotter_portfolio object before applyStrategy
R Code:> str(getPortfolio(strat.name))
List of 2
$ symbols:List of 1
..$ SPY:List of 3
.. ..$ txn :An aAYxtsaAZ object from 2000-12-31 to 2000-12-31 containing:
Data: num [1, 1:10] 0 0 0 0 0 0 0 0 0 0
- attr(*, "dimnames")=List of 2
..$ : NULL
..$ : chr [1:10] "Txn.Qty" "Txn.Price" "Txn.Value" "Txn.Avg.Cost" ...
Indexed by objects of class: [POSIXct,POSIXt] TZ:
xts Attributes:
NULL
.. ..$ posPL :An aAYxtsaAZ object from 2000-12-31 to 2000-12-31 containing:
Data: num [1, 1:11] 0 1 1 0 0 0 0 0 0 0 ...
- attr(*, "dimnames")=List of 2
..$ : NULL
..$ : chr [1:11] "Pos.Qty" "Con.Mult" "Ccy.Mult" "Pos.Value" ...
Indexed by objects of class: [POSIXct,POSIXt] TZ:
xts Attributes:
NULL
.. ..$ posPL.USD:An aAYxtsaAZ object from 2000-12-31 to 2000-12-31 containing:
Data: num [1, 1:11] 0 1 1 0 0 0 0 0 0 0 ...
- attr(*, "dimnames")=List of 2
..$ : NULL
..$ : chr [1:11] "Pos.Qty" "Con.Mult" "Ccy.Mult" "Pos.Value" ...
Indexed by objects of class: [POSIXct,POSIXt] TZ:
xts Attributes:
NULL
$ summary:An aAYxtsaAZ object from 2000-12-31 to 2000-12-31 containing:
Data: num [1, 1:9] 0 0 0 0 0 0 0 0 0
- attr(*, "dimnames")=List of 2
..$ : NULL
..$ : chr [1:9] "Long.Value" "Short.Value" "Net.Value" "Gross.Value" ...
Indexed by objects of class: [POSIXct,POSIXt] TZ:
xts Attributes:
NULL
- attr(*, "class")= chr [1:2] "blotter_portfolio" "portfolio"
- attr(*, "currency")= chr "USD"
- attr(*, "initDate")= Date[1:1], format: "2000-12-31"
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 13 / 68
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:
> out <- try(applyStrategy(strategy=strat , portfolios=strat.name))
[1] "2002-04-24 SPY 100 @ 91.9933301492183"
[1] "2002-04-29 SPY -100 @ 89.8492574695683"
[1] "2002-04-30 SPY 100 @ 90.6900702851173"
[1] "2002-05-14 SPY -100 @ 92.674388529813"
[1] "2003-05-12 SPY 100 @ 81.1354076349475"
[1] "2004-08-25 SPY -100 @ 96.8566013672453"
[1] "2004-10-27 SPY 100 @ 98.8180303441752"
[1] "2006-07-25 SPY -100 @ 114.662711057191"
[1] "2006-08-29 SPY 100 @ 118.211406993905"
[1] "2007-12-28 SPY -100 @ 137.165700378348"
[1] "2009-06-18 SPY 100 @ 88.5716570825431"
[1] "2010-07-06 SPY -100 @ 100.84667390332"
[1] "2010-10-15 SPY 100 @ 116.002709490181"
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 14 / 68
40 60 80 100 120
40
60
80
mm
blotter_portfolio object after applyStrategy
R Code:> str(getPortfolio(strat.name))
List of 2
$ symbols:List of 1
..$ SPY:List of 3
.. ..$ txn :An aAYxtsaAZ object from 2000-12-31 to 2010-10-15 containing:
Data: num [1:14, 1:10] 0 100 -100 100 -100 100 -100 100 -100 100 ...
- attr(*, "dimnames")=List of 2
..$ : NULL
..$ : chr [1:10] "Txn.Qty" "Txn.Price" "Txn.Value" "Txn.Avg.Cost" ...
Indexed by objects of class: [POSIXct,POSIXt] TZ:
xts Attributes:
NULL
.. ..$ posPL :An aAYxtsaAZ object from 2000-12-31 to 2000-12-31 containing:
Data: num [1, 1:11] 0 1 1 0 0 0 0 0 0 0 ...
- attr(*, "dimnames")=List of 2
..$ : NULL
..$ : chr [1:11] "Pos.Qty" "Con.Mult" "Ccy.Mult" "Pos.Value" ...
Indexed by objects of class: [POSIXct,POSIXt] TZ:
xts Attributes:
NULL
.. ..$ posPL.USD:An aAYxtsaAZ object from 2000-12-31 to 2000-12-31 containing:
Data: num [1, 1:11] 0 1 1 0 0 0 0 0 0 0 ...
- attr(*, "dimnames")=List of 2
..$ : NULL
..$ : chr [1:11] "Pos.Qty" "Con.Mult" "Ccy.Mult" "Pos.Value" ...
Indexed by objects of class: [POSIXct,POSIXt] TZ:
xts Attributes:
NULL
$ summary:An aAYxtsaAZ object from 2000-12-31 to 2000-12-31 containing:
Data: num [1, 1:9] 0 0 0 0 0 0 0 0 0
- attr(*, "dimnames")=List of 2
..$ : NULL
..$ : chr [1:9] "Long.Value" "Short.Value" "Net.Value" "Gross.Value" ...
Indexed by objects of class: [POSIXct,POSIXt] TZ:
xts Attributes:
NULL
- attr(*, "class")= chr [1:2] "blotter_portfolio" "portfolio"
- attr(*, "currency")= chr "USD"
- attr(*, "initDate")= Date[1:1], format: "2000-12-31"
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 15 / 68
40 60 80 100 120
40
60
80
mm
Transactions in the blotter_portfolio object
R Code:> getPortfolio(strat.name)$symbols$SPY$txn
Txn.Qty Txn.Price Txn.Value Txn.Avg.Cost Pos.Qty Pos.Avg.Cost Gross.Txn.Realized.PL Txn.Fees
2000-12-31 0 0.00000 0.000 0.00000 0 0.00000 0.0000 0
2002-04-24 100 91.99333 9199.333 91.99333 100 91.99333 0.0000 0
2002-04-29 -100 89.84926 -8984.926 89.84926 0 0.00000 -214.4073 0
2002-04-30 100 90.69007 9069.007 90.69007 100 90.69007 0.0000 0
2002-05-14 -100 92.67439 -9267.439 92.67439 0 0.00000 198.4318 0
2003-05-12 100 81.13541 8113.541 81.13541 100 81.13541 0.0000 0
2004-08-25 -100 96.85660 -9685.660 96.85660 0 0.00000 1572.1194 0
2004-10-27 100 98.81803 9881.803 98.81803 100 98.81803 0.0000 0
2006-07-25 -100 114.66271 -11466.271 114.66271 0 0.00000 1584.4681 0
2006-08-29 100 118.21141 11821.141 118.21141 100 118.21141 0.0000 0
2007-12-28 -100 137.16570 -13716.570 137.16570 0 0.00000 1895.4293 0
2009-06-18 100 88.57166 8857.166 88.57166 100 88.57166 0.0000 0
2010-07-06 -100 100.84667 -10084.667 100.84667 0 0.00000 1227.5017 0
2010-10-15 100 116.00271 11600.271 116.00271 100 116.00271 0.0000 0
Net.Txn.Realized.PL Con.Mult
2000-12-31 0.0000 0
2002-04-24 0.0000 1
2002-04-29 -214.4073 1
2002-04-30 0.0000 1
2002-05-14 198.4318 1
2003-05-12 0.0000 1
2004-08-25 1572.1194 1
2004-10-27 0.0000 1
2006-07-25 1584.4681 1
2006-08-29 0.0000 1
2007-12-28 1895.4293 1
2009-06-18 0.0000 1
2010-07-06 1227.5017 1
2010-10-15 0.0000 1
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 16 / 68
40 60 80 100 120
40
60
80
mm
Retrieving transactions
R Code:
> getTxns(Portfolio=strat.name, Symbol=stock.str)
Txn.Qty Txn.Price Txn.Fees Txn.Value Txn.Avg.Cost Net.Txn.Realized.PL
2000-12-31 0 0.00000 0 0.000 0.00000 0.0000
2002-04-24 100 91.99333 0 9199.333 91.99333 0.0000
2002-04-29 -100 89.84926 0 -8984.926 89.84926 -214.4073
2002-04-30 100 90.69007 0 9069.007 90.69007 0.0000
2002-05-14 -100 92.67439 0 -9267.439 92.67439 198.4318
2003-05-12 100 81.13541 0 8113.541 81.13541 0.0000
2004-08-25 -100 96.85660 0 -9685.660 96.85660 1572.1194
2004-10-27 100 98.81803 0 9881.803 98.81803 0.0000
2006-07-25 -100 114.66271 0 -11466.271 114.66271 1584.4681
2006-08-29 100 118.21141 0 11821.141 118.21141 0.0000
2007-12-28 -100 137.16570 0 -13716.570 137.16570 1895.4293
2009-06-18 100 88.57166 0 8857.166 88.57166 0.0000
2010-07-06 -100 100.84667 0 -10084.667 100.84667 1227.5017
2010-10-15 100 116.00271 0 11600.271 116.00271 0.0000
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 17 / 68
40 60 80 100 120
40
60
80
mm
Calling updatePortf
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:
> getPortfolio(strat.name)$summary
Long.Value Short.Value Net.Value Gross.Value Realized.PL
2000-12-31 0 0 0 0 0
Unrealized.PL Gross.Trading.PL Txn.Fees Net.Trading.PL
2000-12-31 0 0 0 0
> dummy <- updatePortf(Portfolio=strat.name,
Dates=paste('::',as.Date(Sys.time()),sep=''))
> # updatePortf(Portfolio=strat.name,Dates=paste('::',tail(index(SPY),1),sep=''))
> # updatePortf(Portfolio=strat.name)
> library(lattice)
> plot(xyplot(getPortfolio(strat.name)$summary,type="h",col=4,xlab=""))
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 18 / 68
40 60 80 100 120
40
60
80
mm
blotter_portfolio object after updatePortf
R Code:> str(getPortfolio(strat.name))
List of 2
$ symbols:List of 1
..$ SPY:List of 3
.. ..$ txn :An aAYxtsaAZ object from 2000-12-31 to 2010-10-15 containing:
Data: num [1:14, 1:10] 0 100 -100 100 -100 100 -100 100 -100 100 ...
- attr(*, "dimnames")=List of 2
..$ : NULL
..$ : chr [1:10] "Txn.Qty" "Txn.Price" "Txn.Value" "Txn.Avg.Cost" ...
Indexed by objects of class: [POSIXct,POSIXt] TZ:
xts Attributes:
NULL
.. ..$ posPL :An aAYxtsaAZ object from 2000-12-31 to 2011-08-05 containing:
Data: num [1:2666, 1:11] 0 0 0 0 0 0 0 0 0 0 ...
- attr(*, "dimnames")=List of 2
..$ : NULL
..$ : chr [1:11] "Pos.Qty" "Con.Mult" "Ccy.Mult" "Pos.Value" ...
Indexed by objects of class: [POSIXct,POSIXt] TZ:
xts Attributes:
NULL
.. ..$ posPL.USD:An aAYxtsaAZ object from 2000-12-31 to 2011-08-05 containing:
Data: num [1:2666, 1:11] 0 0 0 0 0 0 0 0 0 0 ...
- attr(*, "dimnames")=List of 2
..$ : NULL
..$ : chr [1:11] "Pos.Qty" "Con.Mult" "Ccy.Mult" "Pos.Value" ...
Indexed by objects of class: [POSIXct,POSIXt] TZ:
xts Attributes:
NULL
$ summary:An aAYxtsaAZ object from 2000-12-31 to 2011-08-05 containing:
Data: num [1:2666, 1:9] 0 0 0 0 0 0 0 0 0 0 ...
- attr(*, "dimnames")=List of 2
..$ : NULL
..$ : chr [1:9] "Long.Value" "Short.Value" "Net.Value" "Gross.Value" ...
Indexed by objects of class: [POSIXct,POSIXt] TZ:
xts Attributes:
NULL
- attr(*, "class")= chr [1:2] "blotter_portfolio" "portfolio"
- attr(*, "currency")= chr "USD"
- attr(*, "initDate")= Date[1:1], format: "2000-12-31"
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 19 / 68
40 60 80 100 120
40
60
80
mm
Plot of blotter_portfolio$summary object0
5000
1500
0 Long.Value
2002 2004 2006 2008 2010 2012
−0.
40.
00.
4
Short.Value
050
0015
000 Net.Value
050
0015
000 Gross.Value
010
00
Period.Realized.PL
−20
00−
500
Period.Unrealized.PL
−60
00
400
Gross.Trading.PL
−0.
40.
00.
4
Txn.Fees
−60
00
400
2002 2004 2006 2008 2010 2012
Net.Trading.PL
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 20 / 68
40 60 80 100 120
40
60
80
mm
How the blotter_portfolio object gets updated
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
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
txn
--------------------
transactions xts
Updated by
applyStrategy
Updated by
updatePortf
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 21 / 68
40 60 80 100 120
40
60
80
mm
Chart of moving average crossover 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:
> source("chart_Posn.R")
> chart_Posn(Portfolio=strat.name,Symbol=stock.str)
> add_SMA(n=50 , on=1,col='blue',lwd=2)
> add_SMA(n=200, on=1,col='red',lwd=2)
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 22 / 68
40 60 80 100 120
40
60
80
mm
Chart of moving average crossover performance
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 23 / 68
40 60 80 100 120
40
60
80
mm
Outline
1 The applyStrategy and updatePortf functions
2 Position sizing
3 Passing parameters at apply-time
4 Parameter optimization
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 24 / 68
40 60 80 100 120
40
60
80
mm
The ruleSignal function
ruleSignal is the default rule to generate a trade order on a signal
R Code: The ruleSignal function
> args(ruleSignal)
function (data = mktdata, timestamp, sigcol, sigval, orderqty = 0,
ordertype, orderside = NULL, threshold = NULL, tmult = FALSE,
replace = TRUE, delay = 1e-04, osFUN = "osNoOp", pricemethod = c("market",
"opside", "maker"), portfolio, symbol, ..., ruletype,
TxnFees = 0, prefer = NULL, sethold = FALSE)
NULL
Main arguments:
data an xts object containing market data (defaults to mktdata)sigcol column name to check for signalsigval signal value to matchorderqty quantity for order or ’all’, modified by osFUNordertype ”market”,”limit”,”stoplimit”,”stoptrailing”,”iceberg”orderside ”long”, ”short”, or NULLosFUN function or name of order sizing function (default is osNoOp)
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 25 / 68
40 60 80 100 120
40
60
80
mm
The osNoOp function
The function osNoOp is the default order sizing function
R Code: The osNoOp function
> args(osNoOp)
function (timestamp, orderqty, portfolio, symbol, ruletype, ...)
NULL
Main arguments:
timestamp timestamp (coercible into a POSIXct object) that will markthe time of order insertion
orderqty the order quanty; modified by osFUN
portfolio name of the portfolio for the order
symbol symbol of instrument
ruletype one of ”risk”, ”order”, ”rebalance”, ”enter”, ”exit”
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 26 / 68
40 60 80 100 120
40
60
80
mm
Fixed-dollar order sizing function
This order sizing function adjusts the share quantity such that thetransaction value is approximately equal to a pre-defined tradesize
R Code:
> osFixedDollar <- function(timestamp,orderqty, portfolio, symbol, ruletype, ...)
{
ClosePrice <- as.numeric(Cl(mktdata[timestamp,]))
orderqty <- sign(orderqty)*round(tradeSize/ClosePrice)
return(orderqty)
}
function retrieves the current close price and sets order quantity asfollows:
orderqty =tradeSize
ClosePrice
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 27 / 68
40 60 80 100 120
40
60
80
mm
Re-initializing the .blotter and .strategy environments
It is not possible to run initPortf, initAcct, or initOrders a secondtime in the same R session using the same names
It is necessary to either remove the individual objects or remove all objectsfrom the .blotter and .strategy environments
R Code:
> try(rm(list=ls(pos=.blotter),pos=.blotter),silent=TRUE)
> try(rm(list=ls(pos=.strategy),pos=.strategy),silent=TRUE)
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 28 / 68
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 <- "MAX"
> initEq=1000000
> trade.percent <- 0.01
> tradeSize <- initEq * trade.percent
> 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-II 29 / 68
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 = "SMA",
arguments = list(x=quote(Cl(mktdata)), n=50),label= "ma50" )
> strat <- add.indicator(strategy = strat, name = "SMA",
arguments = list(x=quote(Cl(mktdata)), n=200),label= "ma200")
> # signals:
> strat <- add.signal(strategy = strat,name="sigCrossover",
arguments = list(columns=c("ma50","ma200"), relationship="gte"),
label="ma50.gt.ma200")
> strat <- add.signal(strategy = strat,name="sigCrossover",
arguments = list(column=c("ma50","ma200"),relationship="lt"),
label="ma50.lt.ma200")
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 30 / 68
40 60 80 100 120
40
60
80
mm
Add rules with an order sizing function specified
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="ma50.gt.ma200",sigval=TRUE, orderqty=100,
ordertype='market', orderside='long', osFUN='osFixedDollar'),type='enter')
> strat <- add.rule(strategy = strat,name='ruleSignal',
arguments = list(sigcol="ma50.lt.ma200",sigval=TRUE, orderqty='all',
ordertype='market', orderside='long'),type='exit')
The ruleSignal argument osFUN is now set to the name of ourcustom order sizing function for the entry rule
The argument orderqty is now set to ’all’ for the exit rule
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 31 / 68
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:
> out <- try(applyStrategy(strategy=strat , portfolios=strat.name))
[1] "2002-04-24 SPY 109 @ 91.9933301492183"
[1] "2002-04-29 SPY -109 @ 89.8492574695683"
[1] "2002-04-30 SPY 110 @ 90.6900702851173"
[1] "2002-05-14 SPY -110 @ 92.674388529813"
[1] "2003-05-12 SPY 123 @ 81.1354076349475"
[1] "2004-08-25 SPY -123 @ 96.8566013672453"
[1] "2004-10-27 SPY 101 @ 98.8180303441752"
[1] "2006-07-25 SPY -101 @ 114.662711057191"
[1] "2006-08-29 SPY 85 @ 118.211406993905"
[1] "2007-12-28 SPY -85 @ 137.165700378348"
[1] "2009-06-18 SPY 113 @ 88.5716570825431"
[1] "2010-07-06 SPY -113 @ 100.84667390332"
[1] "2010-10-15 SPY 86 @ 116.002709490181"
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 32 / 68
40 60 80 100 120
40
60
80
mm
Transactions with varying quantities
R Code:
> getTxns(Portfolio=strat.name, Symbol=stock.str)
Txn.Qty Txn.Price Txn.Fees Txn.Value Txn.Avg.Cost Net.Txn.Realized.PL
2000-12-31 0 0.00000 0 0.000 0.00000 0.0000
2002-04-24 109 91.99333 0 10027.273 91.99333 0.0000
2002-04-29 -109 89.84926 0 -9793.569 89.84926 -233.7039
2002-04-30 110 90.69007 0 9975.908 90.69007 0.0000
2002-05-14 -110 92.67439 0 -10194.183 92.67439 218.2750
2003-05-12 123 81.13541 0 9979.655 81.13541 0.0000
2004-08-25 -123 96.85660 0 -11913.362 96.85660 1933.7068
2004-10-27 101 98.81803 0 9980.621 98.81803 0.0000
2006-07-25 -101 114.66271 0 -11580.934 114.66271 1600.3128
2006-08-29 85 118.21141 0 10047.970 118.21141 0.0000
2007-12-28 -85 137.16570 0 -11659.085 137.16570 1611.1149
2009-06-18 113 88.57166 0 10008.597 88.57166 0.0000
2010-07-06 -113 100.84667 0 -11395.674 100.84667 1387.0769
2010-10-15 86 116.00271 0 9976.233 116.00271 0.0000
Each entry has an approximate value of $10,000
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 33 / 68
40 60 80 100 120
40
60
80
mm
Calling updatePortf
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=''))
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 34 / 68
40 60 80 100 120
40
60
80
mm
Chart of fixed-dollar MA crossover 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=stock.str)
> add_SMA(n=50 , on=1,col='blue',lwd=2)
> add_SMA(n=200, on=1,col='red',lwd=2)
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 35 / 68
40 60 80 100 120
40
60
80
mm
Moving average crossover with fixed-dollar entries
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 36 / 68
40 60 80 100 120
40
60
80
mm
Percent-of-available-equity order sizing function
This order sizing function adjusts the share quantity such that each tradeis approximately a fixed percentage of the available account equity
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)
}
orderqty =(initEq + trading P&L) × trade.percent
ClosePriceGuy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 37 / 68
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:
> try(rm(list=ls(pos=.blotter),pos=.blotter),silent=TRUE)
> try(rm(list=ls(pos=.strategy),pos=.strategy),silent=TRUE)
> # inz portfolio, account, orders, strategy
> trade.percent <- 0.02
> 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-II 38 / 68
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 = "SMA",
arguments = list(x=quote(Cl(mktdata)), n=50),label= "ma50" )
> strat <- add.indicator(strategy = strat, name = "SMA",
arguments = list(x=quote(Cl(mktdata)), n=200),label= "ma200")
> # signals:
> strat <- add.signal(strategy = strat,name="sigCrossover",
arguments = list(columns=c("ma50","ma200"), relationship="gte"),
label="ma50.gt.ma200")
> strat <- add.signal(strategy = strat,name="sigCrossover",
arguments = list(column=c("ma50","ma200"),relationship="lt"),
label="ma50.lt.ma200")
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 39 / 68
40 60 80 100 120
40
60
80
mm
Add rules with an order sizing function specified
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="ma50.gt.ma200",sigval=TRUE, orderqty=100,
ordertype='market', orderside='long', osFUN='osPercentEquity'),type='enter')
> strat <- add.rule(strategy = strat,name='ruleSignal',
arguments = list(sigcol="ma50.lt.ma200",sigval=TRUE, orderqty='all',
ordertype='market', orderside='long'),type='exit')
The ruleSignal argument osFUN is now set to the name of ourcustom order sizing function for the entry rule
The argument orderqty is now set to ’all’ for the exit rule
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 40 / 68
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:
> out <- try(applyStrategy(strategy=strat , portfolios=strat.name))
[1] "2002-04-24 SPY 217 @ 91.9933301492183"
[1] "2002-04-29 SPY -217 @ 89.8492574695683"
[1] "2002-04-30 SPY 220 @ 90.6900702851173"
[1] "2002-05-14 SPY -220 @ 92.674388529813"
[1] "2003-05-12 SPY 246 @ 81.1354076349475"
[1] "2004-08-25 SPY -246 @ 96.8566013672453"
[1] "2004-10-27 SPY 203 @ 98.8180303441752"
[1] "2006-07-25 SPY -203 @ 114.662711057191"
[1] "2006-08-29 SPY 170 @ 118.211406993905"
[1] "2007-12-28 SPY -170 @ 137.165700378348"
[1] "2009-06-18 SPY 228 @ 88.5716570825431"
[1] "2010-07-06 SPY -228 @ 100.84667390332"
[1] "2010-10-15 SPY 175 @ 116.002709490181"
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 41 / 68
40 60 80 100 120
40
60
80
mm
Transactions with varying quantities
R Code:
> getTxns(Portfolio=strat.name, Symbol=stock.str)
Txn.Qty Txn.Price Txn.Fees Txn.Value Txn.Avg.Cost Net.Txn.Realized.PL
2000-12-31 0 0.00000 0 0.00 0.00000 0.0000
2002-04-24 217 91.99333 0 19962.55 91.99333 0.0000
2002-04-29 -217 89.84926 0 -19497.29 89.84926 -465.2638
2002-04-30 220 90.69007 0 19951.82 90.69007 0.0000
2002-05-14 -220 92.67439 0 -20388.37 92.67439 436.5500
2003-05-12 246 81.13541 0 19959.31 81.13541 0.0000
2004-08-25 -246 96.85660 0 -23826.72 96.85660 3867.4137
2004-10-27 203 98.81803 0 20060.06 98.81803 0.0000
2006-07-25 -203 114.66271 0 -23276.53 114.66271 3216.4702
2006-08-29 170 118.21141 0 20095.94 118.21141 0.0000
2007-12-28 -170 137.16570 0 -23318.17 137.16570 3222.2299
2009-06-18 228 88.57166 0 20194.34 88.57166 0.0000
2010-07-06 -228 100.84667 0 -22993.04 100.84667 2798.7038
2010-10-15 175 116.00271 0 20300.47 116.00271 0.0000
Each entry is approximately 2% of the account value
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 42 / 68
40 60 80 100 120
40
60
80
mm
Call updatePortf
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=''))
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 43 / 68
40 60 80 100 120
40
60
80
mm
Chart of percent-equity MA crossover 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=stock.str)
> add_SMA(n=50 , on=1,col='blue',lwd=2)
> add_SMA(n=200, on=1,col='red',lwd=2)
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 44 / 68
40 60 80 100 120
40
60
80
mm
Moving average crossover with percent-equity entries
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 45 / 68
40 60 80 100 120
40
60
80
mm
Outline
1 The applyStrategy and updatePortf functions
2 Position sizing
3 Passing parameters at apply-time
4 Parameter optimization
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 46 / 68
40 60 80 100 120
40
60
80
mm
Reload price history and convert to monthly bars
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:
> # download all of SPY
> start.data <- as.Date("1993-01-01")
> initDate <- start.data-1
> getSymbols(stock.str,from=start.data,adjust=T)
> SPY=to.monthly(SPY, indexAt='endof')
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 47 / 68
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:
> # clear .blotter and .strategy environments
> try(rm(list=ls(pos=.blotter),pos=.blotter),silent=TRUE)
> try(rm(list=ls(pos=.strategy),pos=.strategy),silent=TRUE)
> # inz portfolio, account, orders, strategy
> 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-II 48 / 68
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 = "SMA",
arguments = list(x = quote(Cl(mktdata)), n=10), label="SMA10")
> # signals:
> strat <- add.signal(strat,name="sigCrossover",
arguments = list(columns=c("Close","SMA10"),relationship="gt"),
label="Cl.gt.SMA")
> strat <- add.signal(strat,name="sigCrossover",
arguments = list(columns=c("Close","SMA10"),relationship="lt"),
label="Cl.lt.SMA")
MA length (n=10) passed in arguments list to add.indicator
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 49 / 68
40 60 80 100 120
40
60
80
mm
Add rules with an order sizing function specified
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.SMA", sigval=TRUE, ordertype='market',
orderside='long', pricemethod='market',osFUN='osPercentEquity'), type='enter')
> strat <- add.rule(strat, name='ruleSignal',
arguments = list(sigcol="Cl.lt.SMA", sigval=TRUE, orderqty='all',
ordertype='market', orderside='long'), type='exit')
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 50 / 68
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:
> out <- try(applyStrategy(strategy=strat , portfolios=strat.name))
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 51 / 68
40 60 80 100 120
40
60
80
mm
Call updatePortf
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=''))
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 52 / 68
40 60 80 100 120
40
60
80
mm
Chart Faber 10-month SMA system
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=stock.str)
> add_SMA(n=10 , on=1,col='blue',lwd=2)
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 53 / 68
40 60 80 100 120
40
60
80
mm
Faber 10-month SMA system
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 54 / 68
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:
> # clear .blotter and .strategy environments
> try(rm(list=ls(pos=.blotter),pos=.blotter),silent=TRUE)
> try(rm(list=ls(pos=.strategy),pos=.strategy),silent=TRUE)
> # inz portfolio, account, orders, strategy
> 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-II 55 / 68
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 = "SMA",
arguments = list(x = quote(Cl(mktdata))), label="SMAn")
> # signals:
> strat <- add.signal(strat,name="sigCrossover",
arguments = list(columns=c("Close","SMAn"),relationship="gt"),
label="Cl.gt.SMA")
> strat <- add.signal(strat,name="sigCrossover",
arguments = list(columns=c("Close","SMAn"),relationship="lt"),
label="Cl.lt.SMA")
No MA length parameter specified in add.indicator
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 56 / 68
40 60 80 100 120
40
60
80
mm
Add rules with an order sizing function specified
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.SMA", sigval=TRUE, ordertype='market',
orderside='long', pricemethod='market',osFUN='osPercentEquity'), type='enter')
> strat <- add.rule(strat, name='ruleSignal',
arguments = list(sigcol="Cl.lt.SMA", sigval=TRUE, orderqty='all',
ordertype='market', orderside='long'), type='exit')
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 57 / 68
40 60 80 100 120
40
60
80
mm
Applying the strategy with apply-time parameter passing
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:
> out <- try(applyStrategy(strategy=strat , portfolios=strat.name,
parameters=list(n=5)))
The moving average length (n=5) is passed in the named-listparameters argument
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 58 / 68
40 60 80 100 120
40
60
80
mm
Call updatePortf
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=''))
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 59 / 68
40 60 80 100 120
40
60
80
mm
Chart Faber 5-month SMA system
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=stock.str)
> add_SMA(n=5 , on=1,col='blue',lwd=2)
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 60 / 68
40 60 80 100 120
40
60
80
mm
Faber 5-month SMA system
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 61 / 68
40 60 80 100 120
40
60
80
mm
Outline
1 The applyStrategy and updatePortf functions
2 Position sizing
3 Passing parameters at apply-time
4 Parameter optimization
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 62 / 68
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:
> # define GSPC instrument
> dummy <- stock("GSPC", currency="USD",multiplier=1)
> # download stocks
> start.data <- as.Date("1950-01-01")
> initDate <- start.data-1
> getSymbols("^GSPC",from=start.data,adjust=T)
> GSPC=to.monthly(GSPC, indexAt='endof')
> trade.percent <- 1.0
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 63 / 68
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:
> strat <- strategy(strat.name)
> # indicators:
> strat <- add.indicator(strategy = strat, name = "SMA",
arguments = list(x = quote(Cl(mktdata))), label="SMAn")
> # signals:
> strat <- add.signal(strat,name="sigCrossover",
arguments = list(columns=c("Close","SMAn"),relationship="gt"),
label="Cl.gt.SMA")
> strat <- add.signal(strat,name="sigCrossover",
arguments = list(columns=c("Close","SMAn"),relationship="lt"),
label="Cl.lt.SMA")
No MA length parameter specified in add.indicator
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 64 / 68
40 60 80 100 120
40
60
80
mm
Add rules with an order sizing function specified
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.SMA", sigval=TRUE, ordertype='market',
orderside='long', pricemethod='market',osFUN='osPercentEquity'), type='enter')
> strat <- add.rule(strat, name='ruleSignal',
arguments = list(sigcol="Cl.lt.SMA", sigval=TRUE, orderqty='all',
ordertype='market', orderside='long'), type='exit')
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 65 / 68
40 60 80 100 120
40
60
80
mm
Applying the strategy across range of parameter values
R Code:
> parm.seq <- seq(3,20,by=1)
> res.vec <- rep(NA,length(parm.seq))
> for(i in 1:length(parm.seq)) {
# 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="GSPC", initDate=initDate)
initOrders(portfolio=strat.name,initDate=initDate)
# apply strategy
N <- parm.seq[i]
applyStrategy(strategy=strat , portfolios=strat.name, parameters=list(n=N))
# calculate performance matric
dummy <- updatePortf(Portfolio=strat.name,
Dates=paste('::',as.Date(Sys.time()),sep=''))
tstats <- tradeStats(Portfolio=strat.name, Symbol="GSPC")
if(is.numeric(tstats$maxDrawdown))
{
returnOnMDD <- tstats$Net.Trading.PL / abs(tstats$maxDrawdown)
res.vec[i] <- returnOnMDD
}
}
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 66 / 68
40 60 80 100 120
40
60
80
mm
Plot optimization results
R Code: Plot code
> names(res.vec) <- parm.seq
> sort(res.vec,decreasing=T)
17 18 10 9 8 16 20 19 12
7.182873 7.154502 7.140314 7.125639 7.113975 6.941945 5.842226 5.210899 4.945895
15 13 11 14 6 7 5 3 4
4.938753 4.934645 4.928929 4.926389 4.557785 3.924239 3.583817 2.945360 2.925350
> barplot(height=res.vec,names.arg=parm.seq,col="lightslateblue",
xlab="length of MA (months)",ylab="Return on MaxDD")
> title("Return on Maximum Drawdown versus Moving Average Length")
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 67 / 68
40 60 80 100 120
40
60
80
mm
Optimization performance metric
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
length of MA (months)
Ret
urn
on M
axD
D
01
23
45
67
Return on Maximum Drawdown versus Moving Average Length
Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-II 68 / 68