SCM

SCM Repository

[blotter] Annotation of /pkg/quantstrat/demo/pair_trade.R
ViewVC logotype

Annotation of /pkg/quantstrat/demo/pair_trade.R

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1020 - (view) (download)

1 : braverock 1020 #Kindly contributed to quantstrat by Garrett See
2 :     #code borrowed heavily from existing quantstrat demos
3 :    
4 :     #This is a simple pairs trading example intended to illustrate how you can extend
5 :     #existing quantstrat functionality. It uses addPosLimits to specify levels and
6 :     #position limits, and shows how to pass a custom order sizing function to osFUN
7 :    
8 :     #Note that it would be easier to build a spread first and treat it as a single instrument
9 :     #instead of dealing with a portfolio of stocks.
10 :    
11 :     ## given 2 stocks, calculate the ratio of their notional values. If the ratio falls below it's
12 :     # 2 stdev band, then when it crosses back above it, buy stock 1 and sell stock 2.
13 :     # If the ratio rises above it's 2 stdev band, then when it crosses back below
14 :     # it, sell stock 1 and buy stock 2. If the ratio crosses it's moving average,
15 :     # then flatten any open positions.
16 :    
17 :     # The Qty of Stock A that it buys (sells) = MaxPos / lvls
18 :     # The Qty of Stock B that is sells (buys) = MaxPos * Ratio / lvls
19 :    
20 :     suppressWarnings(rm("order_book.pair1",pos=.strategy))
21 :     suppressWarnings(rm("account.pairs", "portfolio.pair1", pos=.blotter))
22 :     suppressWarnings(rm("initDate", "endDate", "startDate", "initEq", "SD", "N", "symb1", "symb2",
23 :     "portfolio1.st", "account.st", "pairStrat", "out1"))
24 :    
25 :     require(quantstrat)
26 :     initDate = '2009-01-01'
27 :     endDate = '2011-05-01'
28 :     startDate = '2009-01-02'
29 :     initEq = 100000
30 :     SD = 2
31 :     N = 20
32 :    
33 :     MaxPos = 1500 #max position in stockA;
34 :     #max position in stock B will be max * ratio, i.e. no hard position limit in Stock B
35 :     lvls = 3 #how many times to fade; Each order's qty will = MaxPos/lvls
36 :    
37 :     symb1 <- 'SPY' #change these to try other pairs
38 :     symb2 <- 'DIA' #if you change them, make sure position limits still make sense
39 :    
40 :     portfolio1.st <- 'pair1'
41 :     account.st <- 'pairs'
42 :    
43 :     getSymbols(c(symb1, symb2), from=startDate, to=endDate, adjust=TRUE)
44 :    
45 :     #generic used to make sure the timestamps of all symbols are the same
46 :     #deletes rows where one of the stocks is missing data
47 :     alignSymbols <- function(symbols, env=.GlobalEnv) {
48 :     if (length(symbols) < 2)
49 :     stop("Must provide at least 2 symbols")
50 :     if (any(!is.character(symbols)))
51 :     stop("Symbols must be vector of character strings.")
52 :     ff <- get(symbols[1],env=env)
53 :     for (sym in symbols[-1]) {
54 :     tmp.sym <- get(sym,env=env)
55 :     ff <- merge(ff,tmp.sym,all=FALSE)
56 :     }
57 :     for (sym in symbols) {
58 :     assign(sym,ff[,grep(sym,colnames(ff))],env=env)
59 :     }
60 :     symbols
61 :     }
62 :     alignSymbols(c(symb1,symb2))
63 :    
64 :     #Define Instruments
65 :     currency("USD")
66 :     stock(symb1, currency="USD", multiplier=1)
67 :     stock(symb2, currency="USD", multiplier=1)
68 :    
69 :     #Initialize Portfolio, Account, and Orders
70 :     initPortf(name=portfolio1.st, c(symb1,symb2), initDate=initDate)
71 :     initAcct(account.st, portfolios=portfolio1.st, initDate=initDate, initEq=initEq)
72 :     initOrders(portfolio=portfolio1.st,initDate=initDate)
73 :    
74 :     #osFUN will need to know which symbol is leg 1 and which is leg 2 as well as what the
75 :     #values are for MaxPos and lvls. So, create a slot in portfolio to hold this info.
76 :     pair <- c(1,2,MaxPos,lvls)
77 :     names(pair) <- c(symb1,symb2,"MaxPos","lvls")
78 :     .blotter[[paste('portfolio',portfolio1.st,sep='.')]]$pair <- pair
79 :    
80 :     # Create initial position limits and levels by symbol
81 :     # allow 3 entries for long and short if lvls=3.
82 :     addPosLimit(portfolio=portfolio1.st, timestamp=initDate, symbol=symb1, maxpos=MaxPos, longlevels=lvls, minpos=-MaxPos, shortlevels=lvls)
83 :     addPosLimit(portfolio=portfolio1.st, timestamp=initDate, symbol=symb2, maxpos=MaxPos, longlevels=lvls, minpos=-MaxPos, shortlevels=lvls)
84 :    
85 :     # Create a strategy object
86 :     pairStrat <- strategy('pairStrat')
87 :    
88 :     # Indicator function
89 :     calcRatio <- function(x) { #returns the ratio of notional close prices for 2 symbols
90 :     x1 <- get(x[1])
91 :     x2 <- get(x[2])
92 :     mult1 <- getInstrument(x[1])$multiplier
93 :     mult2 <- getInstrument(x[2])$multiplier
94 :     rat <- (mult1 * Cl(x1)) / (mult2 * Cl(x2))
95 :     colnames(rat) <- 'Ratio'
96 :     rat
97 :     }
98 :     Ratio <- calcRatio(c(symb1[1],symb2[1])) #Indicator used for determining entry/exits
99 :    
100 :     #Put a slot in portfolio to hold hedge ratio so that it's available for order sizing function.
101 :     #In this example, the hedge ratio happens to be the same as the Ratio indicator.
102 :     .blotter[[paste('portfolio',portfolio1.st,sep='.')]]$HedgeRatio <- Ratio
103 :     #and make a function to get the most recent HedgeRatio
104 :     getHedgeRatio <- function(portfolio, timestamp) {
105 :     portf <- getPortfolio(portfolio)
106 :     timestamp <- format(timestamp,"%Y-%m-%d %H:%M:%S") #ensures you don't get last value of next day if using intraday data and timestamp=midnight
107 :     toDate <- paste("::", timestamp, sep="")
108 :     Ratio <- last(portf$HedgeRatio[toDate])
109 :     as.numeric(Ratio)
110 :     }
111 :    
112 :     # Create an indicator - BBands on the Ratio
113 :     pairStrat <- add.indicator(strategy = pairStrat, name = "calcRatio", arguments = list(x=c(symb1,symb2)))
114 :     pairStrat <- add.indicator(strategy = pairStrat, name = "BBands", arguments = list(HLC=quote(Ratio), sd=SD, n=N, maType='SMA'))
115 :    
116 :     #applyIndicators(strategy=pairStrat,mktdata=get(symb1[1])) #for debugging
117 :    
118 :     # Create signals - buy when crossing lower band from below, sell when crossing upper band from above, flatten when crossing mavg from above or from below
119 :     pairStrat <- add.signal(strategy = pairStrat, name = "sigCrossover", arguments= list(columns=c("Ratio","up"), relationship="lt"), label="cross.up")
120 :     pairStrat <- add.signal(strategy = pairStrat, name = "sigCrossover", arguments= list(columns=c("Ratio","dn"), relationship="gt"), label="cross.dn")
121 :     pairStrat <- add.signal(strategy = pairStrat, name = "sigCrossover", arguments= list(columns=c("Ratio","mavg"), relationship="lt"), label="cross.mid.fa")
122 :     pairStrat <- add.signal(strategy = pairStrat, name = "sigCrossover", arguments= list(columns=c("Ratio","mavg"), relationship="gt"), label="cross.mid.fb")
123 :    
124 :     #make an order sizing function
125 :     #######################_ORDER SIZING FUNCTION_##########################################################
126 :     #check to see which stock it is. If it's the second stock, reverse orderqty and orderside
127 :     osSpreadMaxPos <- function (data, timestamp, orderqty, ordertype, orderside, portfolio, symbol, ruletype, ..., orderprice)
128 :     {
129 :     portf <- getPortfolio(portfolio)
130 :     #check to make sure pair slot has the things needed for this function
131 :     if (!any(portf$pair == 1) && !(any(portf$pair == 2))) stop('pair must contain both values 1 and 2')
132 :     if (!any(names(portf$pair) == "MaxPos") || !any(names(portf$pair) == "lvls")) stop('pair must contain MaxPos and lvls')
133 :    
134 :     if (portf$pair[symbol] == 1) legside <- "long"
135 :     if (portf$pair[symbol] == 2) legside <- "short"
136 :     MaxPos <- portf$pair["MaxPos"]
137 :     lvls <- portf$pair["lvls"]
138 :     ratio <- getHedgeRatio(portfolio, timestamp)
139 :     pos <- getPosQty(portfolio, symbol, timestamp)
140 :     PosLimit <- getPosLimit(portfolio, symbol, timestamp)
141 :     qty <- orderqty
142 :     if (legside == "short") {#symbol is 2nd leg
143 :     ## Comment out next line to use equal ordersizes for each stock.
144 :     addPosLimit(portfolio=portfolio, timestamp=timestamp, symbol=symbol, maxpos=round(MaxPos*ratio,0), longlevels=lvls, minpos=round(-MaxPos*ratio,0), shortlevels=lvls)
145 :     ##
146 :     qty <- -orderqty #switch orderqty for Stock B
147 :     }
148 :    
149 :     if (qty > 0) orderside = 'long'
150 :     if (qty < 0) orderside = 'short'
151 :    
152 :     orderqty <- osMaxPos(data=data,timestamp=timestamp,orderqty=qty,ordertype=ordertype,
153 :     orderside=orderside,portfolio=portfolio,symbol=symbol,ruletype=ruletype, ...)
154 :    
155 :     #Add the order here instead of in the ruleSignal function
156 :     if (!is.null(orderqty) & !orderqty == 0 & !is.null(orderprice)) {
157 :     addOrder(portfolio = portfolio, symbol = symbol,
158 :     timestamp = timestamp, qty = orderqty, price = as.numeric(orderprice),
159 :     ordertype = ordertype, side = orderside, replace = FALSE,
160 :     status = "open", ... = ...)
161 :     }
162 :     return(0) #so that ruleSignal function doesn't also try to place an order
163 :     }
164 :     ########################################################################################################
165 :    
166 :     # Create entry and exit rules for longs and for shorts. Both symbols will get the same buy/sell signals, but osMaxPos will reverse those for the second symbol.
167 :     # orderqty's are bigger than PosLimits allow. osMaxPos will adjust the orderqty down to 1/3 the max allowed. (1/3 is because we are using 3 levels in PosLimit)
168 :     pairStrat <- add.rule(strategy = pairStrat, name='ruleSignal', arguments = list(sigcol="cross.dn", sigval=TRUE, orderqty=1e6, ordertype='market', orderside=NULL, osFUN='osSpreadMaxPos'), type='enter' )
169 :     pairStrat <- add.rule(strategy = pairStrat, name='ruleSignal', arguments = list(sigcol="cross.up", sigval=TRUE, orderqty=-1e6, ordertype='market', orderside=NULL, osFUN='osSpreadMaxPos'), type='enter')
170 :     pairStrat <- add.rule(strategy = pairStrat, name='ruleSignal', arguments = list(sigcol="cross.mid.fb", sigval=TRUE, orderqty='all', ordertype='market', orderside=NULL), type='exit')
171 :     pairStrat <- add.rule(strategy = pairStrat, name='ruleSignal', arguments = list(sigcol="cross.mid.fa", sigval=TRUE, orderqty='all', ordertype='market', orderside=NULL), type='exit')
172 :    
173 :     #applySignals(strategy=pairStrat, mktdata=applyIndicators(strategy=pairStrat,mktdata=get(symb1))) #for debugging
174 :    
175 :     out1<-applyStrategy(strategy=pairStrat, portfolios=portfolio1.st)
176 :    
177 :     updatePortf(Portfolio=portfolio1.st,Dates=paste("::",as.Date(Sys.time()),sep=''))
178 :     updateAcct(account.st,Dates=paste(startDate,endDate,sep="::"))
179 :     updateEndEq(account.st,Dates=paste(startDate,endDate,sep="::"))
180 :     getEndEq(account.st,Sys.time())
181 :    
182 :     dev.new()
183 :     chart.Posn(Portfolio=portfolio1.st,Symbol=symb1)
184 :     dev.new()
185 :     chart.Posn(Portfolio=portfolio1.st,Symbol=symb2)
186 :     dev.new()
187 :     chartSeries(Cl(get(symb1))/Cl(get(symb2)),TA="addBBands(n=N,sd=SD)")
188 :    
189 :     ret1 <- PortfReturns(account.st)
190 :     ret1$total <- rowSums(ret1)
191 :     #ret1
192 :    
193 :     if("package:PerformanceAnalytics" %in% search() || require("PerformanceAnalytics",quietly=TRUE)) {
194 :     # getSymbols("SPY", from='1999-01-01')
195 :     # SPY.ret <- Return.calculate(SPY$SPY.Close)
196 :     # tmp <- merge(SPY.ret,ret1$total,all=FALSE)
197 :     dev.new()
198 :     charts.PerformanceSummary(ret1$total,geometric=FALSE,wealth.index=TRUE)
199 :     }
200 :    
201 :    
202 :     ###############################################################################
203 :     # R (http://r-project.org/) Quantitative Strategy Model Framework
204 :     #
205 :     # Package Copyright (c) 2009-2010
206 :     # Peter Carl, Dirk Eddelbuettel, Brian G. Peterson, Jeffrey Ryan, and Joshua Ulrich
207 :     #
208 :     # This library is distributed under the terms of the GNU Public License (GPL)
209 :     # for full details see the file COPYING
210 :     #
211 :     # $Id$
212 :     #
213 :     ###############################################################################

root@r-forge.r-project.org
ViewVC Help
Powered by ViewVC 1.0.0  
Thanks to:
Vienna University of Economics and Business Powered By FusionForge