Quantitative Trading Strategies in R Part 3 of 3

February 17, 2017 | Author: lycancapital | Category: N/A
Share Embed Donate


Short Description

Download Quantitative Trading Strategies in R Part 3 of 3 ...

Description

Computational Finance and Risk Management mm

40

60

80

100

120

Quantitative Trading Strategies in R 40

Part 3 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-III

1 / 68

Outline mm

40

60

80

1

MACD example

2

MACD example extended to multiple assets

3

Optimizing the MACD trading system

4

RSI example

100

120

40

60 5

Bollinger band example

6

Summary 80

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

2 / 68

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

3 / 68

Quantstrat demos mm

40

name='sigCrossover' name='sigThreshold' ordertype='market' ordertype='stoplimit' type='enter' type='exit'40 type='risk' orderside='long' orderside='short' applyStrategy parameters index.class='Date' 60 index.class='POSIXt' multiasset multicurrency data adjusted updates Account

faber Y N Y N Y Y N Y N N N Y Y N N N

60 maCross Y N Y N Y Y N Y N N Y N N N Y N

bbands 80 Y N Y N Y Y N N N Y Y N N N N N

rsi N Y Y N Y Y N Y Y Y Y N Y N N N

100 macd N Y Y Y Y Y Y Y N Y Y N N N N N

120 faberMC Y N Y N Y Y N Y N N N N Y Y N N

80

demos are located in ∼/R-2.13.1/library/quantstrat/demo Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

4 / 68

Outline mm

40

60

80

1

MACD example

2

MACD example extended to multiple assets

3

Optimizing the MACD trading system

4

RSI example

100

120

40

60 5

Bollinger band example

6

Summary 80

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

5 / 68

MACD (Moving Average Convergence-Divergence) mm

40

60

80

100

120

Trend-following momentum indicator Published by Gerald Appel in the late 1970 40

MACD Calculation MACD = 12-day EMA - 26-day EMA MACD Signal Line = 9-day EMA of MACD MACD histogram = MACD - Signal Line 60

Interpretation Buy/Sell when MACD Signal Line crosses 0 80

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

6 / 68

MACD system in TradeStation mm

40

60

80

100

120

40

60

80

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

7 / 68

MACD code in EasyLanguage mm

40

60

80

100

120

EasyLanguage code inputs : F a s t L e n g t h ( 12 ) , S l o w L e n g t h ( 26 ) , MACDLength ( 9 ) ; v a r i a b l e s : MyMACD( 0 ) , MACDSig ( 0 ) ;

40

MyMACD = MACD( C l o s e , F a s t L e n g t h , S l o w L e n g t h ) ; MACDSig = XAverage ( MyMACD, MACDLength ) ; i f MACDSig c r o s s e s a b o v e 0 t h e n Buy ( ”MacdLE ” ) n e x t b a r a t m a r k e t ;

60

i f MACDSig c r o s s e s b e l o w 0 t h e n S e l l ( ”MacdLX ” ) n e x t b a r a t m a r k e t ;

80

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

8 / 68

MACD indicator from TTR mm

40

60

80

100

120

40

60

80

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

9 / 68

Initialize currency and trading instruments Initialization

Define strategy

mm Initialize currency and instruments, and load historic data

40 Initialize portfolio, account, orders, strategy

60

Add indicators, signals, and rules

Bar-by-bar processing

Update

Apply strategy to portfolio

Update portfolio, account, equity

80

Reporting

100

120 Generate performance reports and graphs

40 R Code: > > > > > > > > >

library(quantstrat) # inz currency and stocks dummy > > >

# inz portfolio, account, orders, strategy strat.name 60 args(sigThreshold) function (label, data = mktdata, column, threshold = 0, relationship = c("gt", "lt", "eq", "gte", "lte"), cross = FALSE) 40 NULL

Main arguments: label text label to apply to the output 60 data data to apply comparison column column name to apply comparison threshold numeric threshold to compare relationship 80 relationship to test (”gt”, ”lt”, ”eq”, ”gte”, ”lte”) cross if TRUE, then signal will be TRUE only for the first observation to cross the threshold Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

13 / 68

Define indicators and signals Initialization mm

Initialize currency and instruments, and load historic data

40

40

Initialize portfolio, account, orders, strategy

Define strategy

Bar-by-bar processing

Update

Add indicators, signals, and rules

Apply strategy to portfolio

Update portfolio, account, equity

60

80

100

Reporting

120

Generate performance reports and graphs

R Code: > # indicators: > strat # signals: > strat strat osPercentEquity

# parameters: fastMA =60 12 slowMA = 26 signalMA = 9 maType="EMA" # apply strategy out dummy if(sum(duplicated(index(getPortfolio(strat.name)$summary)))>0) { tempPortfolio chart_Posn(Portfolio=strat.name,Symbol="XLF") > plot(add_MACD())

80

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

19 / 68

MACD system performance for XLF mm

40

60

80

100

120

40

60

80

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

20 / 68

Outline mm

40

60

80

1

MACD example

2

MACD example extended to multiple assets

3

Optimizing the MACD trading system

4

RSI example

100

120

40

60 5

Bollinger band example

6

Summary 80

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

21 / 68

Quantstrat/Blotter portfolios with multiple assets mm

40

60

80

100

120

While most of the quantstrat demos use a single asset, the real power of the architecture is that it supports multiple assets To use a multiple-asset portfolio, simply supply a symbol list when calling 40 initPortf All functionality should simply work with the entire portfolio of assets applying a strategy via applyStrategy will generate transactions for all assets according to the define trading rules 60 calculating portfolio P&L via updatePortf will accumulate the P&L for all assets

Due to the additional calculations required, working with multi-asset portfolios can be time consuming 80

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

22 / 68

Initialize currency and trading instruments Initialization

Define strategy

mm Initialize currency and instruments, and load historic data

R Code: > > > > > > > > > >

40 Initialize portfolio, account, orders, strategy

60 Add indicators, signals, and rules

Bar-by-bar processing

Apply strategy to portfolio

Reporting

Update

80

100 Update portfolio, account, equity

120 Generate performance reports and graphs

40

# clear out old portfolios and orders try(rm(list=ls(pos=.blotter),pos=.blotter),silent=TRUE) try(rm(list=ls(pos=.strategy),pos=.strategy),silent=TRUE) # inz currency and stocks 60= c("XLF", "XLP", "XLE", "XLY", "XLV", "XLI", "XLB", "XLK", "XLU") stock.str for(symbol in stock.str) stock(symbol, currency="USD",multiplier=1) # download stocks start.data > > > >

# inz portfolio, account, orders, strategy strat.name 60 length(macdPortfolio$symbols) [1] 9

60 > names(macdPortfolio$symbols) [1] "XLF" "XLP" "XLE" "XLY" "XLV" "XLI" "XLB" "XLK" "XLU"

80

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

26 / 68

Define indicators and signals Initialization mm

Initialize currency and instruments, and load historic data

40

40

Initialize portfolio, account, orders, strategy

Define strategy

Bar-by-bar processing

Update

Add indicators, signals, and rules

Apply strategy to portfolio

Update portfolio, account, equity

60

80

100

Reporting

120

Generate performance reports and graphs

R Code: > # indicators: > strat # signals: > strat strat osPercentEquity

# parameters: fastMA =60 12 slowMA = 26 signalMA = 9 maType="EMA" # apply strategy out dummy if(sum(duplicated(index(getPortfolio(strat.name)$summary)))>0) { tempPortfolio > >

Initialize portfolio, account, orders, strategy

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

60

library(PerformanceAnalytics) trading.pl > >

fastMA mm >

# inz portfolio, account, orders, strategy strat.name 60 strat # signals: > strat strat # rules: > strat strat # rules: > strat strat # apply strategy > out dummy if(sum(duplicated(index(getPortfolio(strat.name)$summary)))>0) { tempPortfolio plot(add_RSI()) > trading.pl rets charts.PerformanceSummary(rets,colorset = bluefocus,xlab="")

80

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

52 / 68

AMAT performance for RSI strategy mm

40

60

80

100

120

40

60

80

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

53 / 68

RSI portfolio performance Net.Trading.PL Performance

60

80

100

120

0.5

1.0

1.5

40

40

0.02 0.04 −0.05 0.00

−0.02

60

80 −0.15

Drawdown

Daily Return

0.0

Cumulative Return

mm

1998−12−21

2000−07−03

Guy Yollin (Copyright

©

2002−01−02

2011)

2003−07−01

2005−01−03

2006−07−03

Quantitative Trading Strategies in R

2008−01−02

2009−07−01

2011−01−03

quantstrat-III

54 / 68

Outline mm

40

60

80

1

MACD example

2

MACD example extended to multiple assets

3

Optimizing the MACD trading system

4

RSI example

100

120

40

60 5

Bollinger band example

6

Summary 80

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

55 / 68

Bollinger bands mm

40

60

80

Bollinger bands are a volatility-sensitive price channel

100

120

Published by John Bollinger in the early 1980s RSI 40 Calculation Calculate a simple moving average (typically 20 days) of the C (either the close or weighted-close) Upper band: MA + N × StdDev(C ) Lower band: MA − N × StdDev(C ) 60 N typically in the range of 2 to 3

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

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

56 / 68

Oil services HOLDR stocks mm

40

60

80

100

120

HOLDRS are ETFs that represent a basket of stocks in a specific industry segment The oil services HOLDR includes companies specifically involved in oil 40 drilling and related services We’ll apply the Bollinger band system to 5 components of the oil services HOLDR ETF SLB - Schlumberger 60 RIG - Transocean HAL - Haliburton BHI - Baker Hughes DO - Diamond Offshore 80

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

57 / 68

Initialize currency and trading instruments Initialization mm

Initialize currency and instruments, and load historic data

40

Initialize portfolio, account, orders, strategy

Define strategy

Bar-by-bar processing

Update

Add indicators, signals, and rules

Apply strategy to portfolio

Update portfolio, account, equity

60

80

100

Reporting

120

Generate performance reports and graphs

40

R Code: > # inz currency and stocks > stock.str = c("SLB","RIG","HAL","BHI","DO") > for(symbol 60 in stock.str) stock(symbol, currency="USD",multiplier=1) > # download stocks > start.data end.data initDate for(symbol in stock.str) getSymbols(symbol,from=start.data,to=end.data,adjust=T) Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

58 / 68

Initialize portfolio, account, and orders object mm Initialization

Initialize currency and instruments, and load historic data

40

40

Initialize portfolio, account, orders, strategy

60

80

100

Define strategy

Bar-by-bar processing

Update

Add indicators, signals, and rules

Apply strategy to portfolio

Update portfolio, account, equity

Reporting

120

Generate performance reports and graphs

R Code: > > > > > >

# inz portfolio, account, orders, strategy strat.name 60 strat # signals: > strat strat strat # rules: > strat strat strat > > > >

# parameters: 60 SD = 2 N = 20 # apply strategy out dummy if(sum(duplicated(index(getPortfolio(strat.name)$summary)))>0) { tempPortfolio plot(add_BBands()) > trading.pl rets charts.PerformanceSummary(rets,colorset = bluefocus,xlab="")

80

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

64 / 68

DO performance for BBands strategy mm

40

60

80

100

120

40

60

80

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

65 / 68

Bollinger bands portfolio performance Net.Trading.PL Performance

60

80

100

120

0.01

0.02

0.03

40

40

0.000 −0.010

60

−0.010

Drawdown

−0.025

Daily Return

0.010

0.00

Cumulative Return

mm

80 1998−12−21

2000−07−03

Guy Yollin (Copyright

©

2002−01−02

2011)

2003−07−01

2005−01−03

2006−07−03

Quantitative Trading Strategies in R

2008−01−02

2009−07−01

2011−01−03

quantstrat-III

66 / 68

Outline mm

40

60

80

1

MACD example

2

MACD example extended to multiple assets

3

Optimizing the MACD trading system

4

RSI example

100

120

40

60 5

Bollinger band example

6

Summary 80

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

67 / 68

Summary of blotter and quantstrat mm

40

60

80

100

120

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. Still40 in heavy development. Despite beta-status, software is used everyday by hearty working professions in asset management Inherent 60 flexibility provided by R allows analysis that is still unavailable in some dedicated commercial packages Although the software is free, be prepared to pay some dues in terms of time and effort to get things working R-SIG-FINANCE is your friend

80

Guy Yollin (Copyright

©

2011)

Quantitative Trading Strategies in R

quantstrat-III

68 / 68

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF