#R Runs #012008 hac v1.0 #A collection of functions for testing #dependence from Vince's Handbook of Portfolio Mathematics #Expects a P&L vector #count the number of runs in a vector runs<-function(v){ r = 1 wins = 0 for (index in 2:(length(v)-1)) { if ((v[index] > 0 & v[index-1] < 0) | (v[index] < 0 & v[index-1] > 0)) { r<- r + 1 } if (v[index] > 0) { wins<-wins+1 } n<-length(v) x<-2 * wins * (length(v)-wins) a<-(n * (r - .5)) - x b<-(x * (x-n))/(n-1) b<-b^.5 z<-a/b } df<-data.frame(r, wins, a, b, z) return(df) } #count the number of turning points turningpoints<-function(v){ tp<- 0 for (index in 2:(length(v)-1)){ if (v[index] > v[index-1] & v[index] > v[index+1]) { tp<-tp+1 } if (v[index] < v[index-1] & v[index] < v[index+1]) { tp<-tp+1 } } expectedtp<- .67 * (length(v) - 2) sdexp<- (((16 * length(v)) - 29)/90)^.5 z<-(tp - expectedtp)/sdexp df<-data.frame(tp, expectedtp, z) return(df) } #z score for correlation coefficient correlationz<-function(v){ vlag<-c(v[2:length(v)], NA) c<-cor(v, vlag, use='pairwise.complete.obs') return(c) } #allruns #Run all to dependency functions and return their z scores allruns<-function(v){ dfr<-runs(v) dftp<-turningpoints(v) corz<-correlationz(v) df<-data.frame(dfr$z, dftp$z, corz) colnames(df)<-c("runs_z", "turningpoints_z", "correlation_z") return(df) }