Você está na página 1de 72

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 40 60 80 100 120

The blotter package


40

The quantstrat package


60

Performance analytics

80

Guy Yollin (Copyright

2011)

Quantitative Trading Strategies in R

quantstrat-I

2 / 72

Packages for trading system development in R


mm
PerformanceAnalytics: Econometric tools for performance and risk analysis

40

Performance metrics and graphs

60

80

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

80

zoo: ordered observations

Time series objects

Guy Yollin (Copyright

2011)

Quantitative Trading Strategies in R

quantstrat-I

3 / 72

About blotter and quantstrat


mm 40 80 100 Transaction infrastructure for60 dening instruments, transactions, 120 portfolios and accounts for trading systems and simulation. Provides portfolio support for multi-asset class and multi-currency portfolios. Still in heavy development.

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

40

Software has been in development for a number of years


blotter: Dec-2008 quantstrat: Feb-2010

Software is used everyday by working professions in asset management

80

Guy Yollin (Copyright

2011)

Quantitative Trading Strategies in R

quantstrat-I

4 / 72

Lecture references
mm 40 60 100 TradeAnalytics project page on R-forge: 80 http://r-forge.r-project.org/projects/blotter/ documents and demos for: 40
blotter package quantstrat package

120

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

Kent Russells 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 40 60 80 100 120

The blotter package


40

The quantstrat package


60

Performance analytics

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 dening instruments, transactions, portfolios and accounts for trading systems and simulation. Provides portfolio support for multi-asset class and multi-currency portfolios.

Key features supports portfolios of multiple assets supports accounts of multiple portfolios supports P&L calculation and roll-up 60 Authors Peter Carl Brian Peterson 80

40

Guy Yollin (Copyright

2011)

Quantitative Trading Strategies in R

quantstrat-I

7 / 72

Basic strategy backtesting workow for blotter


mm 40 60 80 100 120

Initialization

Bar-by-bar processing

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

40

40 getPosQty
addTxn updatePortf updateAcct updateEndEq

getEndEq

60

chart.Posn PortfReturns getAccount getPortfolio getTxns tradeStats 80

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

120

Guy Yollin (Copyright

2011)

Quantitative Trading Strategies in R

quantstrat-I

9 / 72

Loading the blotter package


R Code: mm
> 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"

40

60

80

100

120

60

Loading blotter causes these other libraries to be loaded automatically FinancialInstrument quantmod TTR
80

FinancialInstrument xts zoo

Guy Yollin (Copyright

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 FinancialInstrument package creates an environment the called .instrument for private storage of dened instruments (e.g. currency, stock, future, etc.)
R Code:

60
".instrument"

> ls(all=T) [1] ".blotter"

80

Guy Yollin (Copyright

2011)

Quantitative Trading Strategies in R

quantstrat-I

11 / 72

Basic strategy backtesting workow for blotter


mm 40 60 80 100 120

Initialization

Bar-by-bar processing

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 of instruments and dierent currencies mm 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" $currency [1] "USD" $multiplier [1] 1 $tick_size [1] 0.01 $identifiers NULL

40

60

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" $currency [1] "USD" $multiplier [1] 1 $tick_size [1] 0.01 $identifiers list()

40

60

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 <- SMA(Cl(SPY), 10) > 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 workow for blotter


mm 40 60 80 100 120

Initialization

Bar-by-bar processing

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 values. 120 mm 40 60 100
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 rst close price) currency currency identier
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 such as 60 aggregated P&L, equity,100 etc. mm 40 80
R Code: The initAcct function
> args(initAcct) function (name = "default", portfolios, initDate = "1950-01-01", 40 initEq = 0, currency = "USD", ...) NULL

120

Main arguments: name initDate initEq currency


80 60 name for the resulting account object

portfolios vector of strings naming portfolios included in this account date for initial account equity and position (prior to the rst close price) initial account equity currency identier

Guy Yollin (Copyright

2011)

Quantitative Trading Strategies in R

quantstrat-I

19 / 72

Initialize portfolio and account


mm
R Code:
> b.strategy <- "bFaber" > 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"

40

60

80

100

120

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
> ls() [1] "SPY" > ls(.blotter) "b.strategy"

40

60

80

100

120

40 [1] "account.bFaber"
> ls(.instrument) [1] "SPY" "USD"

"portfolio.bFaber"

60 various objects (including the historic price xts object) stored in the 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 workow for blotter


mm 40 60 80 100 120

Initialization

Bar-by-bar processing

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_theme() 40 theme$col$up.col<-'lightgreen' theme$col$up.border<-'lightgreen' theme$col$dn.col<-'pink' theme$col$dn.border<-'pink' chart_Series(SPY,theme=theme,name="SPY") plot(add_SMA(n=10,col=4,lwd=2)) 60

80

Guy Yollin (Copyright

2011)

Quantitative Trading Strategies in R

quantstrat-I

23 / 72

Monthly SPY and 10-month SMA


SPY
19980130 / 20110729

mm
140 130

40

60

80

100

120
140 130

120

40

120

110

110

100

100

60
90 90 80 80

70

80
1998 1999 Jan 1999 Jul 1999 Jan 2000 2000 Jul 2000 Jan 2001 2001 Jul 2001 Jan 2002 2002 Jul 2002 Jan 2003 2003 Jul 2003 Jan 2004 2004 Jul 2004 Jan 2005 2005 Jul 2005 Jan 2006 2006 Jul 2006 Jan 2007 2007 Jul 2007 Jan 2008 2008 Jul 2008 Jan 2009 2009 Jul 2009 Jan 2010 2010 Jul 2010 2011 Jan 2011 Jul 1998

70

Jan 1998

Guy Yollin (Copyright

Jul 2011

2011)

Quantitative Trading Strategies in R

quantstrat-I

24 / 72

Simple trend-following strategy


mm 40 60 80 100 120

Buy-Sell rules: buy when monthly price > 10-month SMA sell and move to cash when monthly price < 10-month SMA
40

Notes: all entry and exit prices are on the day of the signal at the close
60 all data series are total return series including dividends, updated monthly

commissions and slippage are excluded


80

Guy Yollin (Copyright

2011)

Quantitative Trading Strategies in R

quantstrat-I

25 / 72

Apply trading logic


R Code:
> for( i in 1:nrow(SPY) ) { mm 40 60 80 100 CurrentDate <- time(SPY)[i] ClosePrice <- as.numeric(Cl(SPY[i,])) Posn <- getPosQty(b.strategy, Symbol='SPY', Date=CurrentDate) if( !is.na(as.numeric(SPY[i,'SMA10m'])) ) { if( Posn == 0 ) { # No position, test to go Long if( ClosePrice > as.numeric(SPY[i,'SMA10m']) ) { #40 enter long position addTxn(b.strategy, Symbol='SPY', TxnDate=CurrentDate, TxnPrice=ClosePrice, TxnQty = 1000 , TxnFees=0) } } else { # Have a position, so check exit if( ClosePrice < as.numeric(SPY[i,'SMA10m']) ) { # exit position 60 addTxn(b.strategy, Symbol='SPY', TxnDate=CurrentDate, TxnPrice=ClosePrice, TxnQty = -Posn , TxnFees=0) } } } # Calculate P&L and resulting equity with blotter updatePortf(b.strategy, Dates = CurrentDate) 80 updateAcct(b.strategy, Dates = CurrentDate) updateEndEq(b.strategy, Dates = CurrentDate) } # End dates loop
Guy Yollin (Copyright

120

2011)

Quantitative Trading Strategies in R

quantstrat-I

26 / 72

The updatePortf function


The updatePortf function goes through each80 symbol and calculates the mm 40 60 100 120 PL for each period prices are available
R Code: The updatePortf function
> args(updatePortf)

40

function (Portfolio, Symbols = NULL, Dates = NULL, Prices = NULL, ...) NULL

Main arguments: 60 Portfolio Symbols Dates portfolio object containing transactions character vector of symbols
80

dates for calculation (these dates must appear in the price stream)

Guy Yollin (Copyright

2011)

Quantitative Trading Strategies in R

quantstrat-I

27 / 72

The updateAcct function


mm 40 60 100 120 The updateAcct function performs the equity80 account calculations from the portfolio data and corresponding close prices
R Code: The updateAcct function
> args(updateAcct) 40 function (name = "default", Dates = NULL) NULL

Main arguments: 60 name name of account Dates dates for calculation requires that updatePortf has already been run
80

Guy Yollin (Copyright

2011)

Quantitative Trading Strategies in R

quantstrat-I

28 / 72

The updateEndEq function


mm 40 60 80 100 120

The updateEndEq calculates End.Eq and Net.Performance


R Code: The updateEndEq function
> args(updateEndEq) function (Account, Dates = NULL) NULL

40

Main arguments: Account 60 name of account Dates dates for calculation

requires that updateAcct has already been run


80

Guy Yollin (Copyright

2011)

Quantitative Trading Strategies in R

quantstrat-I

29 / 72

Basic strategy backtesting workow for blotter


mm 40 60 80 100 120

Initialization

Bar-by-bar processing

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

30 / 72

Performance plot
mm 40 60 80 100 120

R Code: 40
> source("chart_Posn.R") > 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
140

19980130 / 20110729

mm

40

60

80

100

120
130 120 115

140

130

120

110

110 105

100

100

90

40

95 90 85

80

80 75

70

70

1000 800 600 400 200 0 120000

Positionfill 1000
q

q q

1000 800 600 400 200

60
q q q q q q q

0 120000 100000 80000 60000

CumPL 98314.97275 100000 80000 60000 40000 20000 0 1998 Jan 1998 Jul 1998 Jan 1999 1999 Jul 1999 Jan 2000 2000 Jul 2000 Jan 2001 2001 Jul 2001 Jan 2002 2002 Jul 2002 Jan 2003 2003 Jul 2003 Jan 2004 2004 Jul 2004 Jan 2005 2005 Jul 2005 Jan 2006 2006 Jul 2006 Jan 2007 2007 Jul 2007 Jan 2008 2008 Jul 2008 Jan 2009 2009 Jul 2009 Jan 2010 2010 Jul 2010 2011 Jan 2011 Jul 2011

80

40000 20000 0

Guy Yollin (Copyright

2011)

Quantitative Trading Strategies in R

quantstrat-I

32 / 72

Transactions
R Code: mm
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

40

60

80

100

120

> getTxns(Portfolio=b.strategy, Symbol="SPY") 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

Guy Yollin (Copyright

2011)

Quantitative Trading Strategies in R

quantstrat-I

33 / 72

Outline
mm 40 60 80 100 120

The blotter package


40

The quantstrat package


60

Performance analytics

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 nancial trading and portfolio strategies.

Key features supports strategies which include indicators, signals, and rules allows strategies to be applied to portfolios leverages the blotter package for trade accounting Authors
60 40

Peter Carl Brian Peterson


80 Jerey Ryan

Guy Yollin (Copyright

2011)

Quantitative Trading Strategies in R

quantstrat-I

35 / 72

Basic strategy backtesting workow for quantstrat


mm 40 60 80 100 120

Initialization

Define strategy

Bar-by-bar processing

Update

Reporting

40
Initialize currency and instruments, and load historic data Initialize portfolio, account, orders, strategy Add indicators, signals, and rules Apply strategy to portfolio Update portfolio, account, equity Generate performance reports and graphs

60

80

Guy Yollin (Copyright

2011)

Quantitative Trading Strategies in R

quantstrat-I

36 / 72

Key quantstrat functions


mm Function 40
initOrders strategy

40 add.signal
add.rule

add.indicator

sigComparison sigCrossover 60 sigFormula sigPeak sigThreshold ruleSignal osNoOp

80 applyStrategy

60 80 100 Description Initialization initialize order container constructor for strategy object Strategy denition 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

120

Guy Yollin (Copyright

2011)

Quantitative Trading Strategies in R

quantstrat-I

37 / 72

Basic strategy backtesting workow for quantstrat


mm 40 60 80 100 120

Initialization

Define strategy

Bar-by-bar processing

Update

Reporting

40
Initialize currency and instruments, and load historic data Initialize portfolio, account, orders, strategy Add indicators, signals, and rules Apply strategy to portfolio Update portfolio, account, equity Generate performance reports and graphs

60

80

Guy Yollin (Copyright

2011)

Quantitative Trading Strategies in R

quantstrat-I

38 / 72

Initialize portfolio and account


mm
R Code:
> # inz portfolio, account, and orders > qs.strategy <- "qsFaber" 40 > initPortf(qs.strategy,'SPY', initDate='1997-12-31') [1] "qsFaber" > initAcct(qs.strategy,portfolios=qs.strategy, initDate='1997-12-31', initEq=1e6) [1] "qsFaber"

40

60

80

100

120

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<- strategy(qs.strategy)

60 quantstrat specic initialization

80

Guy Yollin (Copyright

2011)

Quantitative Trading Strategies in R

quantstrat-I

40 / 72

The quantstrat strategy object


mm
R Code:
> 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-noneMode character NULL list list list NULL list list call

40

60

80

100

120

80

Guy Yollin (Copyright

2011)

Quantitative Trading Strategies in R

quantstrat-I

41 / 72

Basic strategy backtesting workow for quantstrat


mm 40 60 80 100 120

Initialization

Define strategy

Bar-by-bar processing

Update

Reporting

40
Initialize currency and instruments, and load historic data Initialize portfolio, account, orders, strategy Add indicators, signals, and rules Apply strategy to portfolio Update portfolio, account, equity Generate performance reports and graphs

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 60 100 120 outputs, such as 40 moving averages, bands,80 pricing models or Indicators are applied before signals and rules, and the output of indicators may be used as inputs to construct signals or re rules
40 R Code: The add.indicator function
> 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 80 100 120

add a 10-month simple moving average


R Code:

> strat <- add.indicator(strategy = strat, name = "SMA", arguments = list(x = quote(Cl(mktdata)), n=10), label="SMA10") 40 > summary(strat) Length name 1 assets 0 indicators 1 60 signals 0 rules 1 constraints 0 init 0 wrapup 0 call 2 Class -none-none-none-none-none-none-none-none-noneMode character NULL list list list NULL list list call

80

Guy Yollin (Copyright

2011)

Quantitative Trading Strategies in R

quantstrat-I

44 / 72

The add.signals function


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

120

Main arguments: strategy 80 strategy object name name of the signal (one of the 5 supported signals) arguments arguments to be passed to the indicator function
Guy Yollin (Copyright

2011)

Quantitative Trading Strategies in R

quantstrat-I

45 / 72

Adding signals to a strategy


add signal for crossing above SMA 40 addmm signal for crossing below 60 SMA
R Code:
> strat <- add.signal(strat,name="sigCrossover", arguments = list(columns=c("Close","SMA10"),relationship="gt"), label="Cl.gt.SMA") 40 > strat <- add.signal(strat,name="sigCrossover", arguments = list(columns=c("Close","SMA10"),relationship="lt"), label="Cl.lt.SMA") > summary(strat) Length 601 name assets 0 indicators 1 signals 2 rules 1 constraints 0 800 init wrapup 0 call 2
Guy Yollin (Copyright

80

100

120

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 add.rule adds a rule to a strategy mm 40 60 80
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

100

120

Main arguments: 60 strategy name arguments type


80

strategy object name of the rule (typically ruleSignal) 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
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", 40 "opside", "maker"), portfolio, symbol, ..., ruletype, TxnFees = 0, prefer = NULL, sethold = FALSE) NULL

mm

40

60

80

100

120

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, modied 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 <- add.rule(strat, name='ruleSignal', arguments = list(sigcol="Cl.gt.SMA", sigval=TRUE, orderqty=1000, ordertype='market', orderside='long', pricemethod='market'), type='enter', path.dep=TRUE) > # exit60 when close < MA > strat <- add.rule(strat, name='ruleSignal', arguments = list(sigcol="Cl.lt.SMA", sigval=TRUE, orderqty='all', ordertype='market', orderside='long', pricemethod='market'), type='exit', path.dep=TRUE)

80

Guy Yollin (Copyright

2011)

Quantitative Trading Strategies in R

quantstrat-I

49 / 72

The completed strategy object


The strategy object now contains a complete set of quantitative trading rules ready to be applied to a portfolio of assets. mm 40 60 80 100 120
R Code:
> 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-noneMode character NULL list list list NULL list list call

The strategy object contains: 1 user dened indicator 80 2 user dened signals 2 user dened trading rules
Guy Yollin (Copyright

2011)

Quantitative Trading Strategies in R

quantstrat-I

50 / 72

Basic strategy backtesting workow for quantstrat


mm 40 60 80 100 120

Initialization

Define strategy

Bar-by-bar processing

Update

Reporting

40
Initialize currency and instruments, and load historic data Initialize portfolio, account, orders, strategy Add indicators, signals, and rules Apply strategy to portfolio Update portfolio, account, equity Generate performance reports and graphs

60

80

Guy Yollin (Copyright

2011)

Quantitative Trading Strategies in R

quantstrat-I

51 / 72

The applyStrategy function


mm 60 80 100 120 The applyStrategy 40 function applies the strategy to arbitrary market data
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 parameters


80

a list of portfolios to apply the strategy to named list of parameters to be applied during evaluation of the strategy

Guy Yollin (Copyright

2011)

Quantitative Trading Strategies in R

quantstrat-I

52 / 72

Apply the strategy


mm
R Code:
> out <- applyStrategy(strategy=strat , portfolios=qs.strategy) > names(out)

40

60

80

100

120

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 is40 time series object which contains 100 historic price a the 60 80 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 workow for quantstrat


mm 40 60 80 100 120

Initialization

Define strategy

Bar-by-bar processing

Update

Reporting

40
Initialize currency and instruments, and load historic data Initialize portfolio, account, orders, strategy Add indicators, signals, and rules Apply strategy to portfolio Update portfolio, account, equity Generate performance reports and graphs

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 <- sapply(X=index(SPY),FUN=updateEndEq,Account=qs.strategy)

80

Guy Yollin (Copyright

2011)

Quantitative Trading Strategies in R

quantstrat-I

56 / 72

Basic strategy backtesting workow for quantstrat


mm 40 60 80 100 120

Initialization

Define strategy

Bar-by-bar processing

Update

Reporting

40
Initialize currency and instruments, and load historic data Initialize portfolio, account, orders, strategy Add indicators, signals, and rules Apply strategy to portfolio Update portfolio, account, equity Generate performance reports and graphs

60

80

Guy Yollin (Copyright

2011)

Quantitative Trading Strategies in R

quantstrat-I

57 / 72

Plot performance
mm 40 60 80 100 120

R Code: 40
> 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
140

19980130 / 20110729

mm

40

60

80

100

120
130 120 115

140

130

120

110

110 105

100

100

90

40

95 90 85

80

80 75

70

70

1000 800 600 400 200 0 1e+05

Positionfill 1000

q q

1000 800 600 400 200

60
q q q q q q

0 1e+05 8e+04 6e+04 4e+04

CumPL 81950.02164 8e+04 6e+04 4e+04 2e+04 0e+00 1998 Jan 1998 Jul 1998 Jan 1999 1999 Jul 1999 Jan 2000 2000 Jul 2000 Jan 2001 2001 Jul 2001 Jan 2002 2002 Jul 2002 Jan 2003 2003 Jul 2003 Jan 2004 2004 Jul 2004 Jan 2005 2005 Jul 2005 Jan 2006 2006 Jul 2006 Jan 2007 2007 Jul 2007 Jan 2008 2008 Jul 2008 Jan 2009 2009 Jul 2009 Jan 2010 2010 Jul 2010 2011 Jan 2011 Jul 2011

80

2e+04 0e+00

Guy Yollin (Copyright

2011)

Quantitative Trading Strategies in R

quantstrat-I

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

Guy Yollin (Copyright

2011)

Quantitative Trading Strategies in R

quantstrat-I

60 / 72

Outline
mm 40 60 80 100 120

The blotter package


40

The quantstrat package


60

Performance analytics

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


2000 0.4 0.0 0.4 100000 2005 2010

mm

Long.Value 40

60

80

Short.Value 100

120

Net.Value
100000

Gross.Value

40
Realized.PL

100000

Unrealized.PL
0

0 20000

10000 0 10000 10000 0 10000

Gross.Trading.PL

0.4 0.0 0.440000

Txn.Fees

60
Net.Trading.PL

80
2000 2005 2010

Guy Yollin (Copyright

2011)

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 "Withdrawals" "Realized.PL" "Gross.Trading.PL" "Txn.Fees" "Net.Performance" "End.Eq" "Unrealized.PL" "Net.Trading.PL"

Guy Yollin (Copyright

2011)

Quantitative Trading Strategies in R

quantstrat-I

64 / 72

Trade statistics
mm
R Code:
> (tstats <- tradeStats(Portfolio=b.strategy, Symbol="SPY")) SPY SPY SPY SPY SPY SPY Portfolio Symbol Num.Trades Net.Trading.PL Avg.Trade.PL Med.Trade.PL bFaber SPY 16 98314.97 11638.45 12378.6 40 Largest.Winner Largest.Loser Gross.Profits Gross.Losses Std.Dev.Trade.PL 38313.14 -5599.813 91931.42 -10462.26 15128.19 Percent.Positive Percent.Negative Profit.Factor Avg.Win.Trade Med.Win.Trade 71.42857 28.57143 8.786959 18386.28 16364.95 Avg.Losing.Trade Med.Losing.Trade Avg.Daily.PL Med.Daily.PL Std.Dev.Daily.PL -5231.128 -5231.128 13578.19 15324.13 16919.37 60 maxDrawdown Net.Trading.PL.1 Avg.WinLoss.Ratio Med.WinLoss.Ratio Max.Equity -19594.29 5.017532 3.514784 3.128379 104741.9 Min.Equity Net.Trading.PL.2 0 98314.97

40

60

80

100

120

80

Guy Yollin (Copyright

2011)

Quantitative Trading Strategies in R

quantstrat-I

65 / 72

The PerformanceAnalytics package


mm 40 60 80 100 120 Description The PerformanceAnalytics package is a collection of econometric functions for performance and risk analysis

Key features extensive collection of performance charts extensive collection of performance metrics and ratios extensive collection of risk metrics
60 support for building tables of metrics 40

Authors Peter Carl


80 Brian Peterson

Guy Yollin (Copyright

2011)

Quantitative Trading Strategies in R

quantstrat-I

66 / 72

Plot cumulative return and drawdown


R Code: mm cumulative return and drawdown Plot 40 60
> library(PerformanceAnalytics) > rets <- PortfReturns(Account=b.strategy) > 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 > charts.PerformanceSummary(rets,colorset = bluefocus)

80

100

120

80

Guy Yollin (Copyright

2011)

Quantitative Trading Strategies in R

quantstrat-I

67 / 72

Cumulative return and drawdown


SPY Performance
0.10

mm

40

60

80

100

120

Cumulative Return

0.04

0.06

0.08

40

Monthly Return

0.000 0.005 0.010

0.00

0.02

60
0.000 0.010

Drawdown

0.010

0.020

80
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 <- table.Arbitrary(rets,metrics=c("Return.cumulative", "Return.annualized", "SharpeRatio.annualized", "CalmarRatio"), 40 metricsNames=c("Cumulative Return", "Annualized Return", "Annualized Sharpe Ratio", "Calmar Ratio")) > PA2.tab <- table.Arbitrary(rets, metrics=c("StdDev.annualized", "maxDrawdown", "VaR", "ES"), metricsNames=c("Annualized StdDev", "Max DrawDown", "Value-at-Risk", "Conditional VaR")) > tab1 <- 60 data.frame(rownames(PA1.tab),PA1.tab[,1],rownames(PA2.tab),PA2.tab[,1])

80

Guy Yollin (Copyright

2011)

Quantitative Trading Strategies in R

quantstrat-I

69 / 72

Return statistics
mm 40 60 80 100 120

Cumulative Return 40 Annualized Return Annualized Sharpe Ratio Calmar Ratio


60

0.103 0.007 0.711 0.368

Annualized StdDev Max DrawDown Value-at-Risk Conditional VaR

0.010 0.019 -0.004 -0.005

Table: Faber System Return Statistics

80

Guy Yollin (Copyright

2011)

Quantitative Trading Strategies in R

quantstrat-I

70 / 72

Compute trade statistics


mm
R Code:
> res.tab1 <- cbind(c("Trades","Win Percent","Loss Percent","W/L Ratio"), c((tstats[,"Num.Trades"]-1)/2,tstats[,c("Percent.Positive", "Percent.Negative")], 40 tstats[,"Percent.Positive"]/tstats[,"Percent.Negative"])) > res.tab2 <- cbind(c("Net Profit","Gross Profits","Gross Losses", "Profit Factor"), c(tstats[,c("Net.Trading.PL","Gross.Profits", "Gross.Losses","Profit.Factor")])) > res.tab3 <- cbind(c("Avg Trade","Avg Win","Avg Loss","Avg W/L Ratio"), c(tstats[,c("Avg.Trade.PL","Avg.Win.Trade","Avg.Losing.Trade", 60 "Avg.WinLoss.Ratio")])) > tab2 <- data.frame(res.tab1,res.tab2,res.tab3)

40

60

80

100

120

80

Guy Yollin (Copyright

2011)

Quantitative Trading Strategies in R

quantstrat-I

71 / 72

Trade statistics
mm 40 60 80 100 120

Trades 40 Win Percent Loss Percent W/L Ratio 60

7.50 71.43 28.57 2.50

Net Prot Gross Prots Gross Losses Prot Factor

98314.97 91931.42 -10462.26 8.79

Avg Trade Avg Win Avg Loss Avg W/L Ratio

11638.45 18386.28 -5231.13 3.51

Table: Faber System Trade Statistics

80

Guy Yollin (Copyright

2011)

Quantitative Trading Strategies in R

quantstrat-I

72 / 72

Você também pode gostar