Quantitative Trading Strategies in R Part 1 of 3
February 17, 2017 | Author: lycancapital | Category: N/A
Short Description
Download Quantitative Trading Strategies in R Part 1 of 3 ...
Description
Computational Finance and Risk Management mm
40
60
80
100
120
Quantitative Trading Strategies in R 40
Part 1 of 3 60
Guy Yollin Principal Consultant, r-programming.org Visiting Lecturer, University of Washington
80
Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
1 / 72
Outline mm
1
40
60
80
100
120
The blotter package 40
2
The quantstrat package
3
Performance analytics
60
80
Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
2 / 72
Packages for trading system development in R PerformanceAnalytics: Econometric tools for performance and risk analysis
mm
40
60
80
Performance metrics and graphs
100
120
quantstrat: quantitative strategy model framework blotter: tools for transaction-oriented trading systems development
40 Quantitative trading rules and trading accouting
quantmod: quantitative financial modelling framework TTR: technical trading rules
60
Data access, charting, indicators
xts: extensible time series zoo: ordered observations
80
Time series objects
Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
3 / 72
About blotter and quantstrat mm 40 80 100 120 Transaction infrastructure for60defining instruments, transactions, portfolios and accounts for trading systems and simulation. Provides portfolio support for multi-asset class and multi-currency portfolios. Still in heavy development. 40
The software is in an alpha/beta stage some things are not completely implemented (or documented) some things invariably have errors some implementations will change in the future 60
Software has been in development for a number of years blotter: Dec-2008 quantstrat: Feb-2010 80
Software is used everyday by working professions in asset management
Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
4 / 72
Lecture references mm 40 60 R-forge: 80 100 TradeAnalytics project page on http://r-forge.r-project.org/projects/blotter/
120
documents and demos for: 40
blotter package quantstrat package
R-SIG-FINANCE: https://stat.ethz.ch/mailman/listinfo/r-sig-finance 60
Kent Russell’s Timely Portfolio blog: http://timelyportfolio.blogspot.com/ 6-part quantstrat example 80
Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
5 / 72
Outline mm
1
40
60
80
100
120
The blotter package 40
2
The quantstrat package
3
Performance analytics
60
80
Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
6 / 72
The blotter package mm 40 60 80 100 120 Description Transaction infrastructure for defining instruments, transactions, portfolios and accounts for trading systems and simulation. Provides portfolio support for multi-asset class and multi-currency portfolios. 40
Key features supports portfolios of multiple assets supports accounts of multiple portfolios supports 60 P&L calculation and roll-up Authors Peter Carl Brian 80Peterson
Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
7 / 72
Basic strategy backtesting workflow for blotter mm
40
60
Initialization
80
100
Bar-by-bar processing
120
Reporting
40 Initialize currency and instruments, and load historic data
Initialize portfolio and account
Check prices and indicators to see if Buy or Sell triggered
Update position and equity
End of Data
Generate performance reports and graphs
60
80
Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
8 / 72
Key blotter functions mmFunction initPortf initAcct getEndEq
40getPosQty addTxn updatePortf updateAcct updateEndEq
60
chart.Posn PortfReturns getAccount getPortfolio getTxns 80tradeStats
Guy Yollin (Copyright
©
2011)
40
60 80 100 Description Initialization initializes a portfolio object initializes an account object Processing retrieves the most recent value of the capital account gets position at Date add transactions to a portfolio calculate P&L for each symbol for each period calculate equity from portfolio data update ending equity for an account Analysis chart market data, position size, and cumulative P&L calculate portfolio instrument returns get an account object from the .blotter environment get a portfolio object from the .blotter environment retrieve transactions from a portfolio calculate trade statistics
Quantitative Trading Strategies in R
quantstrat-I
120
9 / 72
Loading the blotter package R Code: mm
40
60
80
100
120
> library(blotter) > search() [1] [3] [5] [7] [9] [11] [13] [15]
".GlobalEnv" "package:FinancialInstrument" "package:TTR" 40 "package:xts" "package:stats" "package:grDevices" "package:datasets" "Autoloads"
"package:blotter" "package:quantmod" "package:Defaults" "package:zoo" "package:graphics" "package:utils" "package:methods" "package:base"
60
Loading blotter causes these other libraries to be loaded automatically FinancialInstrument
FinancialInstrument
quantmod
xts
TTR
80
Guy Yollin (Copyright
zoo
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
10 / 72
The .blotter and .instrument environment mm
40
60
80
100
120
The blotter package creates an environment named .blotter for private storage of portfolio and account objects Likewise, 40 the FinancialInstrument package creates an environment called .instrument for private storage of defined instruments (e.g. currency, stock, future, etc.) R Code:
60
> ls(all=T) [1] ".blotter"
".instrument"
80
Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
11 / 72
Basic strategy backtesting workflow for blotter mm
40
60
Initialization
80
100
Bar-by-bar processing
120
Reporting
40 Initialize currency and instruments, and load historic data
Initialize portfolio and account
Check prices and indicators to see if Buy or Sell triggered
Update position and equity
End of Data
Generate performance reports and graphs
60
80
Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
12 / 72
Instrument class constructors The FinancialInstrument package provides the facility to deal with varying types and different currencies mm of instruments 40 60 80 100 120 R Code: Instrument constructors > args(currency) function (primary_id, currency = NULL, multiplier = 1, identifiers = NULL, ...) 40 NULL > args(stock) function (primary_id, currency = NULL, multiplier = 1, tick_size = 0.01, identifiers = NULL, ...) 60 NULL
Main arguments: primary id character string providing a unique ID for the instrument currency 80 string describing the currency ID multiplier numeric multiplier (multiplier × price = notional values) tick size tick increment of the instrument price Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
13 / 72
Initialize the currency instrument R Code: > currency("USD")
mm
40
60
80
100
120
[1] "USD" > get("USD",envir=.instrument) $primary_id [1] "USD"
40
$currency [1] "USD" $multiplier [1] 1
60
$tick_size [1] 0.01 $identifiers NULL
80
$type [1] "currency" attr(,"class") Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
14 / 72
Initialize the trading instrument R Code: > stock("SPY",currency="USD",multiplier=1)
mm
40
60
80
100
120
[1] "SPY" > get("SPY",envir=.instrument) $primary_id [1] "SPY"
40
$currency [1] "USD" $multiplier [1] 1
60
$tick_size [1] 0.01 $identifiers list()
80
$type [1] "stock" attr(,"class") Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
15 / 72
Fetch historic data R Code: mm
40
60
80
100
120
> getSymbols('SPY', from='1998-01-01', to='2011-07-31', adjust=T) > SPY=to.monthly(SPY, indexAt='endof') > SPY$SMA10m tail(SPY)
40
SPY.Open 2011-02-28 128.2641 2011-03-31 132.3362 2011-04-29 132.7519 2011-05-31 136.3938 2011-06-3060 133.8464 2011-07-29 132.0900
SPY.High 133.4458 132.5031 135.8963 136.5033 134.2544 135.7000
SPY.Low SPY.Close SPY.Volume SPY.Adjusted SMA10m 128.1849 131.9201 2846131894 131.92 114.9287 124.1228 131.9359 4825610492 131.94 117.4512 128.8711 135.7570 2826839043 135.76 120.9079 130.7319 134.2345 3354154109 134.23 123.5213 125.6968 131.9700 4723424476 131.97 126.3944 127.9700 129.3300 3840839000 129.33 128.0790
Note conversion from daily data to monthly data using the last trading day of the month (xts functionality) 80
Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
16 / 72
Basic strategy backtesting workflow for blotter mm
40
60
Initialization
80
100
Bar-by-bar processing
120
Reporting
40 Initialize currency and instruments, and load historic data
Initialize portfolio and account
Check prices and indicators to see if Buy or Sell triggered
Update position and equity
End of Data
Generate performance reports and graphs
60
80
Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
17 / 72
The initPortf function The initPortf function constructs and initializes a portfolio object, which is used to contain transactions, positions, and 80 aggregate level mm 40 60 100 values. 120 R Code: The initPortf function > args(initPortf) function (name = "default", symbols, initPosQty = 0, initDate = "1950-01-01", 40 currency = "USD", ...) NULL
Main arguments: name symbols
60 name for the resulting portfolio object
list of symbols to be included in the portfolio
initPosQty initial position quantity initDate 80 date for initial account equity and position (prior to the first close price) currency
currency identifier
Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
18 / 72
The initAcct function The initAcct function constructs the data container used to store calculated account values aggregated P&L, equity,100 etc. mm 40 such as 60 80
120
R Code: The initAcct function > args(initAcct) function (name = "default", portfolios, initDate = "1950-01-01", 40 initEq = 0, currency = "USD", ...) NULL
Main arguments: name
60 name for the resulting account object
portfolios vector of strings naming portfolios included in this account initDate initEq currency
80
date for initial account equity and position (prior to the first close price) initial account equity currency identifier
Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
19 / 72
Initialize portfolio and account mm
40
60
80
100
120
R Code: > b.strategy initPortf(b.strategy, 'SPY', initDate='1997-12-31') 40 [1] "bFaber" > initAcct(b.strategy,portfolios=b.strategy, initDate='1997-12-31', initEq=1e6) [1] "bFaber"
60
Note that initDate is prior to the start of the data
80
Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
20 / 72
The .blotter and .instrument environment R Code: mm
40
60
80
100
120
> ls() [1] "SPY"
"b.strategy"
> ls(.blotter)
40 [1] "account.bFaber"
"portfolio.bFaber"
> ls(.instrument) [1] "SPY" "USD"
60 objects (including the historic price xts object) stored in the various global environment
portfolio and account objects stored in .blotter environment currency and trading instrument objects stored in the .instrument 80 environment Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
21 / 72
Basic strategy backtesting workflow for blotter mm
40
60
Initialization
80
100
Bar-by-bar processing
120
Reporting
40 Initialize currency and instruments, and load historic data
Initialize portfolio and account
Check prices and indicators to see if Buy or Sell triggered
Update position and equity
End of Data
Generate performance reports and graphs
60
80
Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
22 / 72
Plot monthly SPY and 10-month SMA mm
40
60
80
100
120
R Code: > > > > > > >
theme chart_Posn(b.strategy, Symbol = 'SPY', Dates = '1998::') > plot(add_SMA(n=10,col=4, on=1, lwd=2))
60
80
Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
31 / 72
Performance plot SPY
1998−01−30 / 2011−07−29
140
mm
40
60
80
140
100
120
130
130
120
120 115
110
110 105
100
100
40
90
95 90 85
80
80 75
70
1000
70
Positionfill 1000 ●
800
●
●
●
●
●
1000
● ●
800
60
600
600
400
400
200
200
0 120000
●
●
●
●
●
0 120000
● ●
CumPL 98314.97275 100000
100000
80000
80000
60000
60000
40000
40000
80
20000
20000
0
0 1998 Jan 1998
Jul 1998
1999 Jan 1999
Jul 1999
2000 Jan 2000
Guy Yollin (Copyright
Jul 2000
©
2001 Jan 2001
Jul 2001
2011)
2002 Jan 2002
Jul 2002
2003 Jan 2003
Jul 2003
2004 Jan 2004
Jul 2004
2005 Jan 2005
Jul 2005
2006 Jan 2006
Jul 2006
2007 Jan 2007
Quantitative Trading Strategies in R
Jul 2007
2008 Jan 2008
Jul 2008
2009 Jan 2009
Jul 2009
2010 Jan 2010
Jul 2010
2011 Jan 2011
quantstrat-I
Jul 2011
32 / 72
Transactions R Code: mm
40
60
80
100
120
> getTxns(Portfolio=b.strategy, Symbol="SPY") Txn.Qty 1997-12-31 0 1998-10-30 1000 1999-09-3040 -1000 1999-10-29 1000 2000-09-29 -1000 2002-03-28 1000 2002-04-30 -1000 2003-04-30 1000 2004-08-3160 -1000 2004-09-30 1000 2007-12-31 -1000 2009-06-30 1000 2010-06-30 -1000 2010-07-30 1000 2010-08-3180 -1000 2010-09-30 1000
Guy Yollin (Copyright
©
Txn.Price Txn.Fees Txn.Value Txn.Avg.Cost Net.Txn.Realized.PL 0.00000 0 0.00 0.00000 0.000 89.25095 0 89250.95 89.25095 0.000 105.61590 0 -105615.90 105.61590 16364.951 112.38352 0 112383.52 112.38352 0.000 118.98858 0 -118988.58 118.98858 6605.062 96.28988 0 96289.88 96.28988 0.000 90.69007 0 -90690.07 90.69007 -5599.813 78.59565 0 78595.65 78.59565 0.000 96.86532 0 -96865.32 96.86532 18269.669 97.83755 0 97837.55 97.83755 0.000 136.15069 0 -136150.69 136.15069 38313.139 88.81119 0 88811.19 88.81119 0.000 101.18979 0 -101189.79 101.18979 12378.598 108.10113 0 108101.13 108.10113 0.000 103.23868 0 -103238.68 103.23868 -4862.443 112.48419 0 112484.19 112.48419 0.000
2011)
Quantitative Trading Strategies in R
quantstrat-I
33 / 72
Outline mm
1
40
60
80
100
120
The blotter package 40
2
The quantstrat package
3
Performance analytics
60
80
Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
34 / 72
The quantstrat package mm 40 60 80 100 120 Description Specify, build, and back-test quantitative financial trading and portfolio strategies.
Key features 40
supports strategies which include indicators, signals, and rules allows strategies to be applied to portfolios leverages the blotter package for trade accounting Authors
60
Peter Carl Brian Peterson 80 Ryan Jeffrey
Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
35 / 72
Basic strategy backtesting workflow for quantstrat mm
40
Initialization
60
80
100
120
Define strategy
Bar-by-bar processing
Update
Reporting
Add indicators, signals, and rules
Apply strategy to portfolio
Update portfolio, account, equity
Generate performance reports and graphs
40 Initialize currency and instruments, and load historic data
Initialize portfolio, account, orders, strategy
60
80
Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
36 / 72
Key quantstrat functions mm Function 40 initOrders strategy add.indicator
40 add.signal add.rule
sigComparison sigCrossover 60 sigFormula sigPeak sigThreshold ruleSignal osNoOp
80 applyStrategy
Guy Yollin (Copyright
©
2011)
60 80 100 Description Initialization initialize order container constructor for strategy object Strategy definition add an indicator to a strategy add a signal to a strategy add a rule to a strategy Default functions generate comparison signal generate a crossover signal generate a signal from a formula signal function for peak/valley signals generate a threshold signal default rule to generate a trade order on a signal default order sizing function Processing apply the strategy to arbitrary market data
Quantitative Trading Strategies in R
quantstrat-I
120
37 / 72
Basic strategy backtesting workflow for quantstrat mm
40
Initialization
60
80
100
120
Define strategy
Bar-by-bar processing
Update
Reporting
Add indicators, signals, and rules
Apply strategy to portfolio
Update portfolio, account, equity
Generate performance reports and graphs
40 Initialize currency and instruments, and load historic data
Initialize portfolio, account, orders, strategy
60
80
Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
38 / 72
Initialize portfolio and account mm
40
60
80
100
120
R Code: > # inz portfolio, account, and orders > qs.strategy initPortf(qs.strategy, 'SPY', initDate='1997-12-31') [1] "qsFaber" > initAcct(qs.strategy,portfolios=qs.strategy, initDate='1997-12-31', initEq=1e6) [1] "qsFaber"
60
Identical code used earlier 80
Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
39 / 72
Initialize orders and strategy mm
40
60
80
100
120
R Code: > > > > >
# initialize orders container 40 library(quantstrat) initOrders(portfolio=qs.strategy,initDate='1997-12-31') # instantiate a new strategy object strat class(strat) [1] "strategy" > summary(strat) 40 Length name 1 assets 0 indicators 0 signals 600 rules 1 constraints 0 init 0 wrapup 0 call 2
Class -none-none-none-none-none-none-none-none-none-
Mode character NULL list list list NULL list list call
80
Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
41 / 72
Basic strategy backtesting workflow for quantstrat mm
40
Initialization
60
80
100
120
Define strategy
Bar-by-bar processing
Update
Reporting
Add indicators, signals, and rules
Apply strategy to portfolio
Update portfolio, account, equity
Generate performance reports and graphs
40 Initialize currency and instruments, and load historic data
Initialize portfolio, account, orders, strategy
60
80
Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
42 / 72
The add.indicator function Indicators are typically standard technical or statistical analysis mm such as 40 60 100 120 outputs, moving averages, bands,80 or pricing models Indicators are applied before signals and rules, and the output of indicators may be used as inputs to construct signals or fire rules 40 add.indicator function R Code: The > args(add.indicator) function (strategy, name, arguments, parameters = NULL, label = NULL, ..., enabled = TRUE, indexnum = NULL, store = FALSE) NULL
60
Main arguments: strategy strategy object name name of the indicator (must be an R function) 80 arguments arguments to be passed to the indicator function label name to reference the indicator Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
43 / 72
Adding an indicator to a strategy mm
40
60
add a 10-month simple moving average
80
100
120
R Code: > strat summary(strat) Length name 1 assets 0 indicators 1 60 signals 0 rules 1 constraints 0 init 0 wrapup 0 call 2
80
Guy Yollin (Copyright
©
Class -none-none-none-none-none-none-none-none-none-
2011)
Mode character NULL list list list NULL list list call
Quantitative Trading Strategies in R
quantstrat-I
44 / 72
The add.signals function quantstrat supports the following signal types: sigCrossover crossover ) mm 40 signal (”gt”, 60 ”lt”, ”eq”, 80”gte”, ”lte”100 sigComparison comparison signal (”gt”, ”lt”, ”eq”, ”gte”, ”lte”) sigThreshold threshold signal (”gt”, ”lt”, ”eq”, ”gte”, ”lte”) sigPeak peak/valley signals (”peak”, ”bottom”) 40 sigFormula signal calculated from a formula
120
R Code: The add.signals function > args(add.signal) function (strategy, name, arguments, parameters = NULL, label = NULL, 60 ..., enabled = TRUE, indexnum = NULL, store = FALSE) NULL
Main arguments: strategy 80 strategy object name name of the signal (one of the 5 supported signals) arguments arguments to be passed to the indicator function Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
45 / 72
Adding signals to a strategy add signal for crossing above SMA 40 addmm signal for crossing below 60 SMA
80
100
120
R Code: > strat strat summary(strat) Length 601 name assets 0 indicators 1 signals 2 rules 1 constraints 0 800 init wrapup 0 call 2 Guy Yollin (Copyright
©
Class -none-none-none-none-none-none-none-none-none2011)
Mode character NULL list list list NULL list list call Quantitative Trading Strategies in R
quantstrat-I
46 / 72
The add.rules function The function mm add.rule 40 adds a rule 60 to a strategy 80
100
120
R Code: The add.rule function > args(add.rule) function (strategy, name, arguments, parameters = NULL, label = NULL, type =40 c(NULL, "risk", "order", "rebalance", "exit", "enter"), ..., enabled = TRUE, indexnum = NULL, path.dep = TRUE, timespan = NULL, store = FALSE) NULL
Main arguments: 60 strategy
strategy object
name
name of the rule (typically ruleSignal)
arguments type
80
arguments to be passed to the rule function type of rule (”risk”,”order”,”rebalance”,”exit”,”enter”)
Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
47 / 72
The ruleSignal function ruleSignal is the default rule to generate a trade order on a signal mm
40
R Code: The ruleSignal function
60
80
100
120
> args(ruleSignal) function (data = mktdata, timestamp, sigcol, sigval, orderqty = 0, ordertype, orderside = NULL, threshold = NULL, tmult = FALSE, replace 40= TRUE, delay = 1e-04, osFUN = "osNoOp", pricemethod = c("market", "opside", "maker"), portfolio, symbol, ..., ruletype, TxnFees = 0, prefer = NULL, sethold = FALSE) NULL
Main arguments: 60 data an xts object containing market data (defaults to mktdata) sigcol column name to check for signal sigval signal value to match orderqty quantity for order or ’all’, modified by osFUN ordertype80 ”market”,”limit”,”stoplimit”,”stoptrailing”,”iceberg” orderside ”long”, ”short”, or NULL osFUN function or name of order sizing function (default is osNoOp) Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
48 / 72
Add rules to a strategy mm
40
60
80
100
120
add rule to enter when Cl.gt.SMA is true add rule to exit when Cl.lt.SMA is true R Code: 40 > # go long when close > MA > strat # exit60 when close < MA > strat summary(strat) Length 401 name assets 0 indicators 1 signals 2 rules 3 constraints 0 600 init wrapup 0 call 2
Class -none-none-none-none-none-none-none-none-none-
Mode character NULL list list list NULL list list call
The strategy object contains: 1 user 80 defined indicator 2 user defined signals 2 user defined trading rules Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
50 / 72
Basic strategy backtesting workflow for quantstrat mm
40
Initialization
60
80
100
120
Define strategy
Bar-by-bar processing
Update
Reporting
Add indicators, signals, and rules
Apply strategy to portfolio
Update portfolio, account, equity
Generate performance reports and graphs
40 Initialize currency and instruments, and load historic data
Initialize portfolio, account, orders, strategy
60
80
Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
51 / 72
The applyStrategy function mm 60 the strategy 80 to arbitrary 100 market data 120 The applyStrategy 40 function applies R Code: The applyStrategy function > args(applyStrategy) function (strategy, portfolios, mktdata = NULL, parameters = NULL, 40 ..., verbose = TRUE) NULL
Main arguments: strategy 60 an object of type ’strategy’ portfolios
a list of portfolios to apply the strategy to
parameters
named list of parameters to be applied during evaluation of the strategy
80
Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
52 / 72
Apply the strategy mm
40
60
80
100
120
R Code: > out names(out)
40 [1] "qsFaber" > names(out$qsFaber) [1] "SPY" > names(out$qsFaber$SPY)
60
[1] "indicators" "signals"
"rules"
> class(out$qsFaber$SPY$indicators) [1] "xts" "zoo"
80
Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
53 / 72
The mktdata object mktdata is a special variable constructed during the execution of mm applyStrategy. It is40a time series the historic price 60object which 80 contains 100 120 data as well as the calculated indicators, signals, and rules: R Code: > tail(mktdata[,-(1:5)],12)
40
2010-08-31 2010-09-30 2010-10-29 2010-11-30 2010-12-31 2011-01-31 2011-02-28 2011-03-31 2011-04-29 2011-05-31 2011-06-30 2011-07-29
SPY.Adjusted 103.24 112.48 116.78 116.78 124.59 127.49 131.92 131.94 135.76 134.23 131.97 129.33
60
SMA10m 107.7569 108.3360 109.1411 110.3413 111.9953 113.3289 114.9287 117.4512 120.9079 123.5213 126.3944 128.0790
SMA10 Cl.gt.SMA Cl.lt.SMA 107.7569 NA 1 108.3360 1 NA 109.1411 NA NA 110.3413 NA NA 111.9953 NA NA 113.3289 NA NA 114.9287 NA NA 117.4512 NA NA 120.9079 NA NA 123.5213 NA NA 126.3944 NA NA 128.0790 NA NA
80 Inspecting mktdata can be very helpful in understanding strategy processing and debugging Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
54 / 72
Basic strategy backtesting workflow for quantstrat mm
40
Initialization
60
80
100
120
Define strategy
Bar-by-bar processing
Update
Reporting
Add indicators, signals, and rules
Apply strategy to portfolio
Update portfolio, account, equity
Generate performance reports and graphs
40 Initialize currency and instruments, and load historic data
Initialize portfolio, account, orders, strategy
60
80
Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
55 / 72
update P&L mm
40
60
80
100
120
updates an entire date range at once functions must be called in order R Code:
40
> updatePortf(Portfolio=qs.strategy,Dates=paste('::',as.Date(Sys.time()),sep='')) [1] "qsFaber" > updateAcct(name=qs.strategy,Dates=index(SPY))
60
[1] "qsFaber" > dummy chart_Posn(qs.strategy, Symbol = 'SPY', Dates = '1998::') > plot(add_SMA(n=10,col=4, on=1, lwd=2))
60
80
Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
58 / 72
Faber/quanstrat system performance SPY
1998−01−30 / 2011−07−29
140
mm
40
60
80
140
100
120
130
130
120
120 115
110
110 105
100
100
40
90
95 90 85
80
80 75
70
1000
70
Positionfill 1000
800
●
●
●
●
●
1000
● ●
800
60
600
600
400
400
200
200
0 1e+05
●
●
●
●
0 1e+05
● ●
CumPL 81950.02164 8e+04
8e+04
6e+04
6e+04
4e+04
4e+04
80
2e+04
2e+04
0e+00
0e+00 1998
Jan 1998
Jul 1998
1999 Jan 1999
Jul 1999
2000 Jan 2000
Guy Yollin (Copyright
Jul 2000
©
2001 Jan 2001
Jul 2001
2011)
2002 Jan 2002
Jul 2002
2003 Jan 2003
Jul 2003
2004 Jan 2004
Jul 2004
2005 Jan 2005
Jul 2005
2006 Jan 2006
Jul 2006
2007 Jan 2007
Quantitative Trading Strategies in R
Jul 2007
2008 Jan 2008
Jul 2008
2009 Jan 2009
Jul 2009
2010 Jan 2010
Jul 2010
2011 Jan 2011
quantstrat-I
Jul 2011
59 / 72
Transactions R Code:
mm
40
60
80
100
120
> getTxns(Portfolio=qs.strategy, Symbol="SPY") Txn.Qty 1997-12-31 0 1999-10-29 1000 40 2000-09-29 -1000 2002-03-28 1000 2002-04-30 -1000 2003-04-30 1000 2004-08-31 -1000 2004-09-3060 1000 2007-12-31 -1000 2009-06-30 1000 2010-06-30 -1000 2010-07-30 1000 2010-08-31 -1000 2010-09-3080 1000
Guy Yollin (Copyright
©
Txn.Price Txn.Fees Txn.Value Txn.Avg.Cost Net.Txn.Realized.PL 0.00000 0 0.00 0.00000 0.000 112.38352 0 112383.52 112.38352 0.000 118.98858 0 -118988.58 118.98858 6605.062 96.28988 0 96289.88 96.28988 0.000 90.69007 0 -90690.07 90.69007 -5599.813 78.59565 0 78595.65 78.59565 0.000 96.86532 0 -96865.32 96.86532 18269.669 97.83755 0 97837.55 97.83755 0.000 136.15069 0 -136150.69 136.15069 38313.139 88.81119 0 88811.19 88.81119 0.000 101.18979 0 -101189.79 101.18979 12378.598 108.10113 0 108101.13 108.10113 0.000 103.23868 0 -103238.68 103.23868 -4862.443 112.48419 0 112484.19 112.48419 0.000
2011)
Quantitative Trading Strategies in R
quantstrat-I
60 / 72
Outline mm
1
40
60
80
100
120
The blotter package 40
2
The quantstrat package
3
Performance analytics
60
80
Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
61 / 72
The blotter portfolio object R Code: mm
40
60
80
100
120
> thePortfolio = getPortfolio(b.strategy) > names(thePortfolio) [1] "symbols" "summary" > names(thePortfolio$symbols)
40
[1] "SPY" > names(thePortfolio$symbols$SPY) [1] "txn"
"posPL"
"posPL.USD"
60 > names(thePortfolio$summary) [1] "Long.Value" [5] "Realized.PL" [9] "Net.Trading.PL"
"Short.Value" "Unrealized.PL"
"Net.Value" "Gross.Value" "Gross.Trading.PL" "Txn.Fees"
> library(lattice) 80 > plot(xyplot(thePortfolio$summary,xlab="",type="h",col=4))
Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
62 / 72
Plot of portfolio summary time series object 60
2010
120
Gross.Value
Unrealized.PL
−0.4 0.0 0.4−40000
0
0 20000
Realized.PL
−10000 0 10000 −10000 0 10000
2005
Short.Value 100
100000
80
0
40
0
100000
Net.Value
−0.4 0.0 0.4
Long.Value 40
0
100000
2000
mm
Gross.Trading.PL
60 Net.Trading.PL
Txn.Fees
80 2000
Guy Yollin (Copyright
2005
©
2011)
2010
Quantitative Trading Strategies in R
quantstrat-I
63 / 72
The blotter account object R Code: mm
40
60
80
100
120
> theAccount = getAccount(b.strategy) > names(theAccount) [1] "portfolios" "summary" > names(theAccount$portfolios) 40 [1] "bFaber" > names(theAccount$portfolios$bFaber) [1] "Long.Value" [5] "Realized.PL" 60 [9] "Net.Trading.PL"
"Short.Value" "Unrealized.PL"
"Net.Value" "Gross.Value" "Gross.Trading.PL" "Txn.Fees"
> names(theAccount$summary) [1] "Additions" [5] "Int.Income" [9] "Advisory.Fees" 80
Guy Yollin (Copyright
©
2011)
"Withdrawals" "Realized.PL" "Gross.Trading.PL" "Txn.Fees" "Net.Performance" "End.Eq"
"Unrealized.PL" "Net.Trading.PL"
Quantitative Trading Strategies in R
quantstrat-I
64 / 72
Trade statistics mm
40
60
80
100
120
R Code: > (tstats library(PerformanceAnalytics) > rets tail(rets,12) SPY 2010-08-3140 -4.862443e-03 2010-09-30 0.000000e+00 2010-10-29 4.297123e-03 2010-11-30 0.000000e+00 2010-12-31 7.807092e-03 2011-01-31 2.902940e-03 2011-02-28604.428709e-03 2011-03-31 1.584192e-05 2011-04-29 3.821053e-03 2011-05-31 -1.522454e-03 2011-06-30 -2.264505e-03 2011-07-29 -2.640000e-03
80
> charts.PerformanceSummary(rets,colorset = bluefocus)
Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
67 / 72
Cumulative return and drawdown SPY Performance
60
80
100
120
0.04
0.06
0.08
40
40
0.000 0.005 0.010
60
−0.010
80
−0.020
Drawdown
0.000 −0.010
Monthly Return
0.00
0.02
Cumulative Return
0.10
mm
Dec 97
Jul 98
Jul 99
Jul 00
Jul 01
Jul 02
Jul 03
Jul 04
Jul 05
Jul 06
Jul 07
Jul 08
Jul 09
Jul 10
Jul 11
Date
Guy Yollin (Copyright
©
2011)
Quantitative Trading Strategies in R
quantstrat-I
68 / 72
Compute return statistics mm
40
60
80
100
120
R Code: > PA1.tab PA2.tab tab1 res.tab1 res.tab2 res.tab3 tab2
View more...
Comments