[R-SIG-Finance] How to test pairs trading strategy

Daniel Cegiełka daniel.cegielka at gmail.com
Sun May 29 13:43:33 CEST 2011


> Why I am not getting any plot?.

I have chart.. but eq_* == 1

> How to test pairs trading strategy?

Try quantstrat package - this is a high-quality backtester. In demo
you have a pair trading script... so install and run demo.

https://r-forge.r-project.org/scm/viewvc.php/pkg/quantstrat/demo/pair_trade.R?view=markup&revision=605&root=blotter

https://r-forge.r-project.org/R/?group_id=316

Best regards,
Daniel


2011/5/29 Velappan Periasamy <veepsirtt at gmail.com>:
> How to test pairs trading strategy?
>
> Why I am not getting any plot?.
> Kindly help me
> with regards
> veepsirtt
>
> # We will need the quantmod package for charting and pulling data
> # You can install packages via: install.packages("packageName")
> # install.packages(c("quantmod","TTR"))
> library(quantmod)
>
> # Pull "KO", "PEP" stock data from Yahoo! Finance
> tckr1<-"KO"
> tckr2<-"PEP"
> start<-Sys.Date()-500
> end<- format(Sys.Date(),"%Y-%m-%d") # yyyy-mm-dd
> getSymbols(tckr1, from=start, to=end)
> getSymbols(tckr2, from=start, to=end)
>
> #Calculate the pair ratio
> ra <- Cl(KO)/Cl(PEP)
>
> #Create a long (up) signal
> #if the current ratio is less than 2.7*STD from mean.
> sigup <- ifelse(ra < mean(ra)-2.7*sd(ra) , 1, 0)
>
> # Create the short (dn) signals
> #if the current ratio is more  than 0.5*STD from mean.
> sigdn <- ifelse(ra > mean(ra)-0.5*sd(ra) -1, 0)
>
> sigup[is.na(sigup)] <- 0
> sigdn[is.na(sigdn)] <- 0
>
> # Lag signals to align with days in market,
> # not days signals were generated
> #sigup <- Lag(sigup,1) # Use lag() to avoid Toby's error
> #sigdn <- Lag(sigdn,1) # Use lag() to avoid Toby's error
> sigup <- lag(sigup,1) # Note k=1 implies a move *forward*
> sigdn <- lag(sigdn,1) # Note k=1 implies a move *forward*
>
> # Replace missing signals with no position
> # (generally just at beginning of series)
> sigup[is.na(sigup)] <- 0
> sigdn[is.na(sigdn)] <- 0
>
> # Combine both signals into one vector
> sig <- sigup + sigdn
>
> # Calculate Close-to-Close returns
> ret <- ROC(Cl(KO))
> ret[1] <- 0
>
> # Calculate equity curves
> eq_up <- cumprod(1+ret*sigup)
> eq_dn <- cumprod(1+ret*sigdn*-1)
> eq_all <- cumprod(1+ret*sig)
>
> # Replicate Michael's nice chart
> plot.zoo( cbind(eq_up, eq_dn),
> ylab=c("Long","Short"), col=c("green","red"),
> main="Simple Pair Trading Strategy")
> # Wait a few seconds before making next chart...
>
>        [[alternative HTML version deleted]]
>
> _______________________________________________
> R-SIG-Finance at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-sig-finance
> -- Subscriber-posting only. If you want to post, subscribe first.
> -- Also note that this is not the r-help list where general R questions should go.
>



More information about the R-SIG-Finance mailing list