In order to explain what i'm trying to do , i have 73 assets and i'm trying to backtest possible pair trading strategies. So i did test previously all possible pair combinations for cointegration and i stored them in a variable named combos, which is a 2x869 matrix containing in each column the id of both assets that are cointegrated, so if i take the first column of this variable i get (1,25) that means that the asset number 1 and number 25 in my data are cointegrated. The second variable is datats, it an xts objects, it contain the prices of my 73 assets in different dates. Now i'm trying to run a loop on them in order to backtest the pair trading strategy using the PairTrading package in R.
Here is the code using stock.price within the package.
install.packages("PairTrading", repos="http://R-Forge.R-project.org")
install.packages("plyr")
library(PairTrading)
library(plyr)
datats<-stock.price
combos <- combn(ncol(datats),2)
adply(combos, 2, function(x) {
price.pair <- datats[,c(x[1],x[2])]
params <-EstimateParametersHistorically(price.pair, period = 180)
signal <- Simple(params$spread, 0.05)
return.pairtrading <- Return(price.pair, lag(signal), lag(params$hedge.ratio))
returnS<-(100 * cumprod(1 + return.pairtrading))
out <- data.frame("return"=returnS)
return(out)
})
This code works fine, the problem is when i use my own database instead of the one within the package.
So what i'm trying to do is test the strategy aka the function defined previously, with the combination stored in combos, which means for the first execution i want to test the strategy between the asset number 1 and asset number 25, then between 1 and 61 and so on, so i use datats[,c(x[1],x[2])]
to do that, and i store the cumulative return of the strategy returnS<-(100 * cumprod(1 + return.pairtrading))
.
I tested the above function manually and it works perfectly, the problem is when i try to loop it, so my guess is the loop is working fine, but something after breaks the code.
This is the error i get:
Error in apply(merge(signal[, 1], weight.pair[, 1], return.pair[, 1], :
dim(X) must have a positive length
Here is an update, the code works fine even with my data, however it seems to break in certain points, for instance, i managed to run all combinations from 1 to 400 in a single execution, however 408 seems to break the code, and when i use the combination 408 manually, the function works fine, yet in breaks when i try to loop? this error is very confusing and i've been unable to advance today because of it, kindly help if you can.