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