Stocks: “ABX” “NEM” “GG” “AEM” “RGLD” “KGC” “GFI” “PVG” “HMY” “RIC”

“GORO”

Before we get to the actual code, the idea is simple. It’s to calculate the past 100 day correlations of the stocks and do pairs trading on the stock with the maximum correlation and the portfolio with a holding period of 4 days (which gives a Sharpe versus S&P 500 of > 18.0 estimated roughly by dividing sum(strategy return)-sum(SP500 return) by sigma(strategy return)*sqrt(254). More useful is the graph. These types of strategies (with good returns) are actually not extremely hard to construct in backtests although they are unstable and finicky. In this case, if you used past correlations much more or less than 100 will make the performance much worse and almost unusable. So there is the question of whether there are fundamental laws governing such things. If there are, they are not connected to concepts of daily correlations.

symbols = c("ABX" "NEM" "GG" "AEM" "RGLD" "KGC" "GFI" "PVG" "HMY" "RIC" "GORO","SPY") getSymbols(symbols) rets = merge(lapply(symbols, function(s){ dailyReturn(eval(parse(text=s))) }) cstrat<-function(thresh,days,corrdays){ meanport<-rowMeans(rets) meanport[is.na(meanport)]<-0 N<-nrow(rets) v<-rep(0,N) dirs<-rep(0,N) for (a in (corrdays+1):(N-days-1)){ m<-mean(meanport[(a-10):a]) if (is.nan(m)){m=0} # choose the stock with the highest correlation # in the past 20 days #C<-cor(rets[(a-21):a,]) #C[is.na(C)]<-0 #diag(C)<-0 #idx<-which(C==max(C),arr.ind=TRUE)[1] CC<-rep(0,ncol(rets)) for (bb in 1:ncol(rets)){ CC[bb]<-cor( meanport[(a-corrdays):a],rets[(a-corrdays):a,bb]) } #mb<-median(CC) #CD<-abs(CC-mb) b<-which.max(CC) print(paste(b,CC[b])) R<-mean(rets[(a-10):a,b]) if (abs(R-m)>thresh){ direction<- -sign(R-m) if (v[a]< 0 && v[a-1]<0 && v[a-2]<0 && dirs[a] == dirs[a-1] && dirs[a-2]==dirs[a-1]){ direction<- -dirs[a] } dirs[a+1]<-direction v[a+1]<- direction*mean(meanport[a+1:days]-rets[a+1:days,b]) } } print(paste('SD=',sd(v),'mean=',mean(v),'av sd=', sd(meanport),'av mean=',mean(meanport))) plot(cumsum(v)) (sum(v)-sum(X[,12]))/max(0.0001,sd(v)*sqrt(254)) }