quantitative trading strategies in r part 1 of 3

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

Upload: lycancapital

Post on 28-Apr-2015

1.779 views

Category:

Documents


12 download

DESCRIPTION

Quantitative Trading Strategies in RPart 1 of 3

TRANSCRIPT

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

40 60 80 100 120

40

60

80

mm

Computational Finance and Risk Management

Quantitative Trading Strategies in R

Part 1 of 3

Guy YollinPrincipal Consultant, r-programming.org

Visiting Lecturer, University of Washington

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

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

40 60 80 100 120

40

60

80

mm

Outline

1 The blotter package

2 The quantstrat package

3 Performance analytics

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

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

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-I 3 / 72

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

40 60 80 100 120

40

60

80

mm

About blotter and quantstrat

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

The software is in an alpha/beta stage

some things are not completely implemented (or documented)some things invariably have errorssome implementations will change in the future

Software has been in development for a number of years

blotter: Dec-2008quantstrat: Feb-2010

Software is used everyday by working professions in asset management

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

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

40 60 80 100 120

40

60

80

mm

Lecture references

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

documents and demos for:

blotter packagequantstrat package

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

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

6-part quantstrat example

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

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

40 60 80 100 120

40

60

80

mm

Outline

1 The blotter package

2 The quantstrat package

3 Performance analytics

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

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

40 60 80 100 120

40

60

80

mm

The blotter package

DescriptionTransaction infrastructure for defining instruments, transactions,portfolios and accounts for trading systems and simulation. Providesportfolio 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

Authors

Peter Carl

Brian Peterson

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

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

40 60 80 100 120

40

60

80

mm

Basic strategy backtesting workflow for blotter

Initialize portfolio and

account

Check prices and

indicators to see

if Buy or Sell

triggered

Generate

performance reports

and graphsEnd of Data

Initialize

currency and

instruments, and

load historic data

Update position

and equity

Initialization Bar-by-bar processing Reporting

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

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

40 60 80 100 120

40

60

80

mm

Key blotter functions

Function DescriptionInitialization

initPortf initializes a portfolio objectinitAcct initializes an account object

ProcessinggetEndEq retrieves the most recent value of the capital accountgetPosQty gets position at DateaddTxn add transactions to a portfolioupdatePortf calculate P&L for each symbol for each periodupdateAcct calculate equity from portfolio dataupdateEndEq update ending equity for an account

Analysischart.Posn chart market data, position size, and cumulative P&LPortfReturns calculate portfolio instrument returnsgetAccount get an account object from the .blotter environmentgetPortfolio get a portfolio object from the .blotter environmentgetTxns retrieve transactions from a portfoliotradeStats calculate trade statistics

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

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

40 60 80 100 120

40

60

80

mm

Loading the blotter package

R Code:

> library(blotter)

> search()

[1] ".GlobalEnv" "package:blotter"

[3] "package:FinancialInstrument" "package:quantmod"

[5] "package:TTR" "package:Defaults"

[7] "package:xts" "package:zoo"

[9] "package:stats" "package:graphics"

[11] "package:grDevices" "package:utils"

[13] "package:datasets" "package:methods"

[15] "Autoloads" "package:base"

Loading blotter causes these other libraries to be loaded automatically

FinancialInstrument

quantmod

TTR

FinancialInstrument

xts

zoo

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-I 10 / 72

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

40 60 80 100 120

40

60

80

mm

The .blotter and .instrument environment

The blotter package creates an environment named .blotter forprivate storage of portfolio and account objects

Likewise, the FinancialInstrument package creates an environmentcalled .instrument for private storage of defined instruments (e.g.currency, stock, future, etc.)

R Code:

> ls(all=T)

[1] ".blotter" ".instrument"

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

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

40 60 80 100 120

40

60

80

mm

Basic strategy backtesting workflow for blotter

Initialize portfolio and account

Check prices and indicators to see

if Buy or Sell triggered

Generate performance reports

and graphsEnd of Data

Initialize currency and

instruments, and load historic data

Update position and equity

Initialization Bar-by-bar processing Reporting

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-I 12 / 72

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

40 60 80 100 120

40

60

80

mm

Instrument class constructors

The FinancialInstrument package provides the facility to deal withvarying types of instruments and different currencies

R Code: Instrument constructors

> args(currency)

function (primary_id, currency = NULL, multiplier = 1, identifiers = NULL,

...)

NULL

> args(stock)

function (primary_id, currency = NULL, multiplier = 1, tick_size = 0.01,

identifiers = NULL, ...)

NULL

Main arguments:

primary id character string providing a unique ID for the instrumentcurrency string describing the currency IDmultiplier numeric multiplier (multiplier × price = notional values)tick size tick increment of the instrument price

currency instruments must be defined before instruments of othertypes

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

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

40 60 80 100 120

40

60

80

mm

Initialize the currency instrument

R Code:

> currency("USD")

[1] "USD"

> get("USD",envir=.instrument)

$primary_id

[1] "USD"

$currency

[1] "USD"

$multiplier

[1] 1

$tick_size

[1] 0.01

$identifiers

NULL

$type

[1] "currency"

attr(,"class")

[1] "currency" "instrument"Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-I 14 / 72

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

40 60 80 100 120

40

60

80

mm

Initialize the trading instrument

R Code:

> stock("SPY",currency="USD",multiplier=1)

[1] "SPY"

> get("SPY",envir=.instrument)

$primary_id

[1] "SPY"

$currency

[1] "USD"

$multiplier

[1] 1

$tick_size

[1] 0.01

$identifiers

list()

$type

[1] "stock"

attr(,"class")

[1] "stock" "instrument"Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-I 15 / 72

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

40 60 80 100 120

40

60

80

mm

Fetch historic data

R Code:

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

SPY.Open SPY.High SPY.Low SPY.Close SPY.Volume SPY.Adjusted SMA10m

2011-02-28 128.2641 133.4458 128.1849 131.9201 2846131894 131.92 114.9287

2011-03-31 132.3362 132.5031 124.1228 131.9359 4825610492 131.94 117.4512

2011-04-29 132.7519 135.8963 128.8711 135.7570 2826839043 135.76 120.9079

2011-05-31 136.3938 136.5033 130.7319 134.2345 3354154109 134.23 123.5213

2011-06-30 133.8464 134.2544 125.6968 131.9700 4723424476 131.97 126.3944

2011-07-29 132.0900 135.7000 127.9700 129.3300 3840839000 129.33 128.0790

Note conversion from daily data to monthly data using the lasttrading day of the month (xts functionality)

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

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

40 60 80 100 120

40

60

80

mm

Basic strategy backtesting workflow for blotter

Initialize portfolio and account

Check prices and indicators to see

if Buy or Sell triggered

Generate performance reports

and graphsEnd of Data

Initialize currency and

instruments, and load historic data

Update position and equity

Initialization Bar-by-bar processing Reporting

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

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

40 60 80 100 120

40

60

80

mm

The initPortf function

The initPortf function constructs and initializes a portfolio object, whichis used to contain transactions, positions, and aggregate level values.

R Code: The initPortf function

> args(initPortf)

function (name = "default", symbols, initPosQty = 0, initDate = "1950-01-01",

currency = "USD", ...)

NULL

Main arguments:

name name for the resulting portfolio object

symbols list of symbols to be included in the portfolio

initPosQty initial position quantity

initDate date for initial account equity and position (prior to the firstclose price)

currency currency identifier

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

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

40 60 80 100 120

40

60

80

mm

The initAcct function

The initAcct function constructs the data container used to storecalculated account values such as aggregated P&L, equity, etc.

R Code: The initAcct function

> args(initAcct)

function (name = "default", portfolios, initDate = "1950-01-01",

initEq = 0, currency = "USD", ...)

NULL

Main arguments:

name name for the resulting account object

portfolios vector of strings naming portfolios included in this account

initDate date for initial account equity and position (prior to the firstclose price)

initEq initial account equity

currency currency identifier

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

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

40 60 80 100 120

40

60

80

mm

Initialize portfolio and account

R Code:

> b.strategy <- "bFaber"

> initPortf(b.strategy,'SPY', initDate='1997-12-31')

[1] "bFaber"

> initAcct(b.strategy,portfolios=b.strategy, initDate='1997-12-31', initEq=1e6)

[1] "bFaber"

Note that initDate is prior to the start of the data

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

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

40 60 80 100 120

40

60

80

mm

The .blotter and .instrument environment

R Code:

> ls()

[1] "SPY" "b.strategy"

> ls(.blotter)

[1] "account.bFaber" "portfolio.bFaber"

> ls(.instrument)

[1] "SPY" "USD"

various objects (including the historic price xts object) stored in theglobal environment

portfolio and account objects stored in .blotter environment

currency and trading instrument objects stored in the .instrument

environment

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

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

40 60 80 100 120

40

60

80

mm

Basic strategy backtesting workflow for blotter

Initialize portfolio and account

Check prices and indicators to see

if Buy or Sell triggered

Generate performance reports

and graphsEnd of Data

Initialize currency and

instruments, and load historic data

Update position and equity

Initialization Bar-by-bar processing Reporting

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

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

40 60 80 100 120

40

60

80

mm

Plot monthly SPY and 10-month SMA

R Code:

> theme<-chart_theme()

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

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-I 23 / 72

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

40 60 80 100 120

40

60

80

mm

Monthly SPY and 10-month SMA

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

Jan1998

Jul1998

Jan1999

Jul1999

Jan2000

Jul2000

Jan2001

Jul2001

Jan2002

Jul2002

Jan2003

Jul2003

Jan2004

Jul2004

Jan2005

Jul2005

Jan2006

Jul2006

Jan2007

Jul2007

Jan2008

Jul2008

Jan2009

Jul2009

Jan2010

Jul2010

Jan2011

Jul2011

SPY 1998−01−30 / 2011−07−29

70

80

90

100

110

120

130

140

70

80

90

100

110

120

130

140

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

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

40 60 80 100 120

40

60

80

mm

Simple trend-following strategy

Buy-Sell rules:

buy when monthly price > 10-month SMA

sell and move to cash when monthly price < 10-month SMA

Notes:

all entry and exit prices are on the day of the signal at the close

all data series are total return series including dividends, updatedmonthly

commissions and slippage are excluded

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

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

40 60 80 100 120

40

60

80

mm

Apply trading logic

R Code:

> for( i in 1:nrow(SPY) ) {

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

# 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

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)

updateAcct(b.strategy, Dates = CurrentDate)

updateEndEq(b.strategy, Dates = CurrentDate)

} # End dates loop

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

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

40 60 80 100 120

40

60

80

mm

The updatePortf function

The updatePortf function goes through each symbol and calculates thePL for each period prices are available

R Code: The updatePortf function

> args(updatePortf)

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

...)

NULL

Main arguments:

Portfolio portfolio object containing transactions

Symbols character vector of symbols

Dates dates for calculation (these dates must appear in the pricestream)

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-I 27 / 72

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

40 60 80 100 120

40

60

80

mm

The updateAcct function

The updateAcct function performs the equity account calculations fromthe portfolio data and corresponding close prices

R Code: The updateAcct function

> args(updateAcct)

function (name = "default", Dates = NULL)

NULL

Main arguments:

name name of account

Dates dates for calculation

requires that updatePortf has already been run

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

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

40 60 80 100 120

40

60

80

mm

The updateEndEq function

The updateEndEq calculates End.Eq and Net.Performance

R Code: The updateEndEq function

> args(updateEndEq)

function (Account, Dates = NULL)

NULL

Main arguments:

Account name of account

Dates dates for calculation

requires that updateAcct has already been run

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

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

40 60 80 100 120

40

60

80

mm

Basic strategy backtesting workflow for blotter

Initialize portfolio and account

Check prices and indicators to see

if Buy or Sell triggered

Generate performance reports

and graphsEnd of Data

Initialize currency and

instruments, and load historic data

Update position and equity

Initialization Bar-by-bar processing Reporting

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

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

40 60 80 100 120

40

60

80

mm

Performance plot

R Code:

> source("chart_Posn.R")

> chart_Posn(b.strategy, Symbol = 'SPY', Dates = '1998::')

> plot(add_SMA(n=10,col=4, on=1, lwd=2))

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

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

40 60 80 100 120

40

60

80

mm

Performance plot

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

Jan1998

Jul1998

Jan1999

Jul1999

Jan2000

Jul2000

Jan2001

Jul2001

Jan2002

Jul2002

Jan2003

Jul2003

Jan2004

Jul2004

Jan2005

Jul2005

Jan2006

Jul2006

Jan2007

Jul2007

Jan2008

Jul2008

Jan2009

Jul2009

Jan2010

Jul2010

Jan2011

Jul2011

SPY 1998−01−30 / 2011−07−29

70

80

90

100

110

120

130

140

70

80

90

100

110

120

130

140

75

80

85

90

95

100

105

110

115

90

100

110

120

130

140

Positionfill 1000

0

200

400

600

800

1000

0

200

400

600

800

1000●

0

200

400

600

800

1000

CumPL 98314.97275

0

20000

40000

60000

80000

100000

120000

0

20000

40000

60000

80000

100000

120000

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

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

40 60 80 100 120

40

60

80

mm

Transactions

R Code:

> getTxns(Portfolio=b.strategy, Symbol="SPY")

Txn.Qty Txn.Price Txn.Fees Txn.Value Txn.Avg.Cost Net.Txn.Realized.PL

1997-12-31 0 0.00000 0 0.00 0.00000 0.000

1998-10-30 1000 89.25095 0 89250.95 89.25095 0.000

1999-09-30 -1000 105.61590 0 -105615.90 105.61590 16364.951

1999-10-29 1000 112.38352 0 112383.52 112.38352 0.000

2000-09-29 -1000 118.98858 0 -118988.58 118.98858 6605.062

2002-03-28 1000 96.28988 0 96289.88 96.28988 0.000

2002-04-30 -1000 90.69007 0 -90690.07 90.69007 -5599.813

2003-04-30 1000 78.59565 0 78595.65 78.59565 0.000

2004-08-31 -1000 96.86532 0 -96865.32 96.86532 18269.669

2004-09-30 1000 97.83755 0 97837.55 97.83755 0.000

2007-12-31 -1000 136.15069 0 -136150.69 136.15069 38313.139

2009-06-30 1000 88.81119 0 88811.19 88.81119 0.000

2010-06-30 -1000 101.18979 0 -101189.79 101.18979 12378.598

2010-07-30 1000 108.10113 0 108101.13 108.10113 0.000

2010-08-31 -1000 103.23868 0 -103238.68 103.23868 -4862.443

2010-09-30 1000 112.48419 0 112484.19 112.48419 0.000

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

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

40 60 80 100 120

40

60

80

mm

Outline

1 The blotter package

2 The quantstrat package

3 Performance analytics

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

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

40 60 80 100 120

40

60

80

mm

The quantstrat package

DescriptionSpecify, build, and back-test quantitative financial trading and portfoliostrategies.

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

Peter Carl

Brian Peterson

Jeffrey Ryan

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

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

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-I 36 / 72

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

40 60 80 100 120

40

60

80

mm

Key quantstrat functions

Function DescriptionInitialization

initOrders initialize order containerstrategy constructor for strategy object

Strategy definitionadd.indicator add an indicator to a strategyadd.signal add a signal to a strategyadd.rule add a rule to a strategy

Default functionssigComparison generate comparison signalsigCrossover generate a crossover signalsigFormula generate a signal from a formulasigPeak signal function for peak/valley signalssigThreshold generate a threshold signalruleSignal default rule to generate a trade order on a signalosNoOp default order sizing function

ProcessingapplyStrategy apply the strategy to arbitrary market data

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

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

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 processing

Reporting

Update portfolio, account, equity

Define strategy Update

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

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

40 60 80 100 120

40

60

80

mm

Initialize portfolio and account

R Code:

> # inz portfolio, account, and orders

> qs.strategy <- "qsFaber"

> initPortf(qs.strategy,'SPY', initDate='1997-12-31')

[1] "qsFaber"

> initAcct(qs.strategy,portfolios=qs.strategy, initDate='1997-12-31', initEq=1e6)

[1] "qsFaber"

Identical code used earlier

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

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

40 60 80 100 120

40

60

80

mm

Initialize orders and strategy

R Code:

> # initialize orders container

> library(quantstrat)

> initOrders(portfolio=qs.strategy,initDate='1997-12-31')

> # instantiate a new strategy object

> strat<- strategy(qs.strategy)

quantstrat specific initialization

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

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

40 60 80 100 120

40

60

80

mm

The quantstrat strategy object

R Code:

> class(strat)

[1] "strategy"

> summary(strat)

Length Class Mode

name 1 -none- character

assets 0 -none- NULL

indicators 0 -none- list

signals 0 -none- list

rules 1 -none- list

constraints 0 -none- NULL

init 0 -none- list

wrapup 0 -none- list

call 2 -none- call

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

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

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 processing

Reporting

Update portfolio, account, equity

Define strategy Update

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

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

40 60 80 100 120

40

60

80

mm

The add.indicator function

Indicators are typically standard technical or statistical analysisoutputs, such as moving averages, bands, or pricing models

Indicators are applied before signals and rules, and the output ofindicators may be used as inputs to construct signals or fire rules

R Code: The add.indicator function

> args(add.indicator)

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

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

NULL

Main arguments:

strategy strategy object

name name of the indicator (must be an R function)

arguments arguments to be passed to the indicator function

label name to reference the indicatorGuy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-I 43 / 72

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

40 60 80 100 120

40

60

80

mm

Adding an indicator to a strategy

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

> summary(strat)

Length Class Mode

name 1 -none- character

assets 0 -none- NULL

indicators 1 -none- list

signals 0 -none- list

rules 1 -none- list

constraints 0 -none- NULL

init 0 -none- list

wrapup 0 -none- list

call 2 -none- call

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

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

40 60 80 100 120

40

60

80

mm

The add.signals function

quantstrat supports the following signal types:

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

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

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

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

sigFormula signal calculated from a formula

R Code: The add.signals function

> args(add.signal)

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

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

NULL

Main arguments:

strategy strategy object

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

arguments arguments to be passed to the indicator functionGuy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-I 45 / 72

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

40 60 80 100 120

40

60

80

mm

Adding signals to a strategy

add signal for crossing above SMA

add signal for crossing below SMA

R Code:

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

> summary(strat)

Length Class Mode

name 1 -none- character

assets 0 -none- NULL

indicators 1 -none- list

signals 2 -none- list

rules 1 -none- list

constraints 0 -none- NULL

init 0 -none- list

wrapup 0 -none- list

call 2 -none- call

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

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

40 60 80 100 120

40

60

80

mm

The add.rules function

The function add.rule adds a rule to a strategy

R Code: The add.rule function

> args(add.rule)

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

type = c(NULL, "risk", "order", "rebalance", "exit", "enter"),

..., enabled = TRUE, indexnum = NULL, path.dep = TRUE, timespan = NULL,

store = FALSE)

NULL

Main arguments:

strategy strategy object

name name of the rule (typically ruleSignal)

arguments arguments to be passed to the rule function

type type of rule (”risk”,”order”,”rebalance”,”exit”,”enter”)

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-I 47 / 72

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

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-I 48 / 72

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

40 60 80 100 120

40

60

80

mm

Add rules to a strategy

add rule to enter when Cl.gt.SMA is true

add rule to exit when Cl.lt.SMA is true

R Code:

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

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

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

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

40 60 80 100 120

40

60

80

mm

The completed strategy object

The strategy object now contains a complete set of quantitative tradingrules ready to be applied to a portfolio of assets.

R Code:

> summary(strat)

Length Class Mode

name 1 -none- character

assets 0 -none- NULL

indicators 1 -none- list

signals 2 -none- list

rules 3 -none- list

constraints 0 -none- NULL

init 0 -none- list

wrapup 0 -none- list

call 2 -none- call

The strategy object contains:

1 user defined indicator2 user defined signals2 user defined trading rules

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

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

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 processing

Reporting

Update portfolio, account, equity

Define strategy Update

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

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

40 60 80 100 120

40

60

80

mm

The applyStrategy function

The applyStrategy function applies the strategy to arbitrary market data

R Code: The applyStrategy function

> args(applyStrategy)

function (strategy, portfolios, mktdata = NULL, parameters = NULL,

..., verbose = TRUE)

NULL

Main arguments:

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

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

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

40 60 80 100 120

40

60

80

mm

Apply the strategy

R Code:

> out <- applyStrategy(strategy=strat , portfolios=qs.strategy)

> names(out)

[1] "qsFaber"

> names(out$qsFaber)

[1] "SPY"

> names(out$qsFaber$SPY)

[1] "indicators" "signals" "rules"

> class(out$qsFaber$SPY$indicators)

[1] "xts" "zoo"

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

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

40 60 80 100 120

40

60

80

mm

The mktdata object

mktdata is a special variable constructed during the execution ofapplyStrategy. It is a time series object which contains the historic pricedata as well as the calculated indicators, signals, and rules:

R Code:

> tail(mktdata[,-(1:5)],12)

SPY.Adjusted SMA10m SMA10 Cl.gt.SMA Cl.lt.SMA

2010-08-31 103.24 107.7569 107.7569 NA 1

2010-09-30 112.48 108.3360 108.3360 1 NA

2010-10-29 116.78 109.1411 109.1411 NA NA

2010-11-30 116.78 110.3413 110.3413 NA NA

2010-12-31 124.59 111.9953 111.9953 NA NA

2011-01-31 127.49 113.3289 113.3289 NA NA

2011-02-28 131.92 114.9287 114.9287 NA NA

2011-03-31 131.94 117.4512 117.4512 NA NA

2011-04-29 135.76 120.9079 120.9079 NA NA

2011-05-31 134.23 123.5213 123.5213 NA NA

2011-06-30 131.97 126.3944 126.3944 NA NA

2011-07-29 129.33 128.0790 128.0790 NA NA

Inspecting mktdata can be very helpful in understanding strategyprocessing and debugging

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

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

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 processing

Reporting

Update portfolio, account, equity

Define strategy Update

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

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

40 60 80 100 120

40

60

80

mm

update P&L

updates an entire date range at once

functions must be called in order

R Code:

> updatePortf(Portfolio=qs.strategy,Dates=paste('::',as.Date(Sys.time()),sep=''))

[1] "qsFaber"

> updateAcct(name=qs.strategy,Dates=index(SPY))

[1] "qsFaber"

> dummy <- sapply(X=index(SPY),FUN=updateEndEq,Account=qs.strategy)

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

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

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 processing

Reporting

Update portfolio, account, equity

Define strategy Update

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

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

40 60 80 100 120

40

60

80

mm

Plot performance

R Code:

> chart_Posn(qs.strategy, Symbol = 'SPY', Dates = '1998::')

> plot(add_SMA(n=10,col=4, on=1, lwd=2))

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-I 58 / 72

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

40 60 80 100 120

40

60

80

mm

Faber/quanstrat system performance

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

Jan1998

Jul1998

Jan1999

Jul1999

Jan2000

Jul2000

Jan2001

Jul2001

Jan2002

Jul2002

Jan2003

Jul2003

Jan2004

Jul2004

Jan2005

Jul2005

Jan2006

Jul2006

Jan2007

Jul2007

Jan2008

Jul2008

Jan2009

Jul2009

Jan2010

Jul2010

Jan2011

Jul2011

SPY 1998−01−30 / 2011−07−29

70

80

90

100

110

120

130

140

70

80

90

100

110

120

130

140

75

80

85

90

95

100

105

110

115

90

100

110

120

130

140

Positionfill 1000

0

200

400

600

800

1000

0

200

400

600

800

1000●

0

200

400

600

800

1000

CumPL 81950.02164

0e+00

2e+04

4e+04

6e+04

8e+04

1e+05

0e+00

2e+04

4e+04

6e+04

8e+04

1e+05

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

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

40 60 80 100 120

40

60

80

mm

Transactions

R Code:

> getTxns(Portfolio=qs.strategy, Symbol="SPY")

Txn.Qty Txn.Price Txn.Fees Txn.Value Txn.Avg.Cost Net.Txn.Realized.PL

1997-12-31 0 0.00000 0 0.00 0.00000 0.000

1999-10-29 1000 112.38352 0 112383.52 112.38352 0.000

2000-09-29 -1000 118.98858 0 -118988.58 118.98858 6605.062

2002-03-28 1000 96.28988 0 96289.88 96.28988 0.000

2002-04-30 -1000 90.69007 0 -90690.07 90.69007 -5599.813

2003-04-30 1000 78.59565 0 78595.65 78.59565 0.000

2004-08-31 -1000 96.86532 0 -96865.32 96.86532 18269.669

2004-09-30 1000 97.83755 0 97837.55 97.83755 0.000

2007-12-31 -1000 136.15069 0 -136150.69 136.15069 38313.139

2009-06-30 1000 88.81119 0 88811.19 88.81119 0.000

2010-06-30 -1000 101.18979 0 -101189.79 101.18979 12378.598

2010-07-30 1000 108.10113 0 108101.13 108.10113 0.000

2010-08-31 -1000 103.23868 0 -103238.68 103.23868 -4862.443

2010-09-30 1000 112.48419 0 112484.19 112.48419 0.000

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-I 60 / 72

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

40 60 80 100 120

40

60

80

mm

Outline

1 The blotter package

2 The quantstrat package

3 Performance analytics

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

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

40 60 80 100 120

40

60

80

mm

The blotter portfolio object

R Code:

> thePortfolio = getPortfolio(b.strategy)

> names(thePortfolio)

[1] "symbols" "summary"

> names(thePortfolio$symbols)

[1] "SPY"

> names(thePortfolio$symbols$SPY)

[1] "txn" "posPL" "posPL.USD"

> names(thePortfolio$summary)

[1] "Long.Value" "Short.Value" "Net.Value" "Gross.Value"

[5] "Realized.PL" "Unrealized.PL" "Gross.Trading.PL" "Txn.Fees"

[9] "Net.Trading.PL"

> library(lattice)

> plot(xyplot(thePortfolio$summary,xlab="",type="h",col=4))

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

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

40 60 80 100 120

40

60

80

mm

Plot of portfolio summary time series object0

1000

00

Long.Value

2000 2005 2010

−0.

40.

00.

4

Short.Value

010

0000

Net.Value

010

0000

Gross.Value

020

000

Realized.PL

−40

000

0

Unrealized.PL

−10

000

010

000 Gross.Trading.PL

−0.

40.

00.

4

Txn.Fees

−10

000

010

000

2000 2005 2010

Net.Trading.PL

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

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

40 60 80 100 120

40

60

80

mm

The blotter account object

R Code:

> theAccount = getAccount(b.strategy)

> names(theAccount)

[1] "portfolios" "summary"

> names(theAccount$portfolios)

[1] "bFaber"

> names(theAccount$portfolios$bFaber)

[1] "Long.Value" "Short.Value" "Net.Value" "Gross.Value"

[5] "Realized.PL" "Unrealized.PL" "Gross.Trading.PL" "Txn.Fees"

[9] "Net.Trading.PL"

> names(theAccount$summary)

[1] "Additions" "Withdrawals" "Realized.PL" "Unrealized.PL"

[5] "Int.Income" "Gross.Trading.PL" "Txn.Fees" "Net.Trading.PL"

[9] "Advisory.Fees" "Net.Performance" "End.Eq"

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

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

40 60 80 100 120

40

60

80

mm

Trade statistics

R Code:

> (tstats <- tradeStats(Portfolio=b.strategy, Symbol="SPY"))

Portfolio Symbol Num.Trades Net.Trading.PL Avg.Trade.PL Med.Trade.PL

SPY bFaber SPY 16 98314.97 11638.45 12378.6

Largest.Winner Largest.Loser Gross.Profits Gross.Losses Std.Dev.Trade.PL

SPY 38313.14 -5599.813 91931.42 -10462.26 15128.19

Percent.Positive Percent.Negative Profit.Factor Avg.Win.Trade Med.Win.Trade

SPY 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

SPY -5231.128 -5231.128 13578.19 15324.13 16919.37

maxDrawdown Net.Trading.PL.1 Avg.WinLoss.Ratio Med.WinLoss.Ratio Max.Equity

SPY -19594.29 5.017532 3.514784 3.128379 104741.9

Min.Equity Net.Trading.PL.2

SPY 0 98314.97

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

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

40 60 80 100 120

40

60

80

mm

The PerformanceAnalytics package

DescriptionThe PerformanceAnalytics package is a collection of econometricfunctions for performance and risk analysis

Key features

extensive collection of performance charts

extensive collection of performance metrics and ratios

extensive collection of risk metrics

support for building tables of metrics

Authors

Peter Carl

Brian Peterson

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

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

40 60 80 100 120

40

60

80

mm

Plot cumulative return and drawdown

R Code: Plot cumulative return and drawdown

> library(PerformanceAnalytics)

> rets <- PortfReturns(Account=b.strategy)

> tail(rets,12)

SPY

2010-08-31 -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-28 4.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)

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

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

40 60 80 100 120

40

60

80

mm

Cumulative return and drawdown0.

000.

020.

040.

060.

080.

10

Cum

ulat

ive

Ret

urn

SPY Performance

−0.

010

0.00

00.

005

0.01

0

Mon

thly

Ret

urn

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

−0.

020

−0.

010

0.00

0

Dra

wdo

wn

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

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

40 60 80 100 120

40

60

80

mm

Compute return statistics

R Code:

> PA1.tab <- table.Arbitrary(rets,metrics=c("Return.cumulative",

"Return.annualized", "SharpeRatio.annualized", "CalmarRatio"),

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 <- data.frame(rownames(PA1.tab),PA1.tab[,1],rownames(PA2.tab),PA2.tab[,1])

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-I 69 / 72

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

40 60 80 100 120

40

60

80

mm

Return statistics

Cumulative Return 0.103 Annualized StdDev 0.010Annualized Return 0.007 Max DrawDown 0.019Annualized Sharpe Ratio 0.711 Value-at-Risk -0.004Calmar Ratio 0.368 Conditional VaR -0.005

Table: Faber System Return Statistics

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-I 70 / 72

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

40 60 80 100 120

40

60

80

mm

Compute trade statistics

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

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

"Avg.WinLoss.Ratio")]))

> tab2 <- data.frame(res.tab1,res.tab2,res.tab3)

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-I 71 / 72

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

40 60 80 100 120

40

60

80

mm

Trade statistics

Trades 7.50 Net Profit 98314.97 Avg Trade 11638.45Win Percent 71.43 Gross Profits 91931.42 Avg Win 18386.28Loss Percent 28.57 Gross Losses -10462.26 Avg Loss -5231.13

W/L Ratio 2.50 Profit Factor 8.79 Avg W/L Ratio 3.51

Table: Faber System Trade Statistics

Guy Yollin (Copyright© 2011) Quantitative Trading Strategies in R quantstrat-I 72 / 72