I have build a cointegration model to select stocks for pairs trading. My problem with it is to refer within a loop to a list of symbols. While the code runs without generating any warnings I get the wrong results:
 
e.g. for the combination BP ~ AMD I get beta=36.45182 and p-value=0.241386 while it should be beta=5.153268 and p-value=0.1557386
 
Thanks for every help to solve the problem.
 
the code is:
 
#Cointegration Combinations
require(quantmod)
require(zoo)
require(quadprog)
require(tseries)
 
setInternet2() 
 
symList <- c('MSN','GOOG','YHOO', 'BA', 'SI', 'BP', 'AMD')
 
xtsStock <- xts()
xtsFinalPrice <- xts()
 
for (i in 1:length(symList)) {
   xtsStock <- getSymbols(symList[i], auto.assign=FALSE)
   xtsFinalPrice <- merge(xtsFinalPrice, xtsStock[,6]) #get the adjusted close price
}
 
colnames(xtsFinalPrice) <- symList
t <- as.data.frame(xtsFinalPrice)
comb <- combn(symList, 2, FUN=NULL, simplify=TRUE)
ergebnis <- cbind(t(comb), 0, 0)
colnames(ergebnis) <- c("St.Y", "St.X", "BETA", "p-value")
 
for (i in 1:((length(symList) * (length(symList)-1)) / 2)) {
   #m <- lm(MSN ~ AMD + 0, data=t)
   m <- lm(paste(comb[1,i],"~",comb[2,i],sep=" ") , data=t)
   beta <- coef(m)[1]
   #sprd <- t$MSN - beta * t$AMD
   sprd <- get(comb[1,i], pos=t) - beta * get(comb[2,i], pos=t)
   ht <- adf.test(sprd, alternative="stationary", k=trunc((length(sprd)-1)^(1/3)))
   ergebnis[i,3] <- as.numeric(beta)
   ergebnis[i,4] <- as.numeric(ht$p.value)
}
 
Josef
 		 	   		  
	[[alternative HTML version deleted]]

