rm(list=ls()) set.seed(531) #here's another way to get a random walk w <- rep(0.0,2000) a <- 1 for(i in 2:length(w)){ w[i] <- a*w[i-1] + rnorm(1) } idx <- 1:2000 plot(idx,w,pch=".") lines(idx,w) #how to determine if you have a unit root. #simple regression problem. wt <- w[2:2000] wt_1 <- w[1:1999] aHat <- sum(wt*wt_1)/sum(wt_1*wt_1) aHat e <- wt - aHat*wt_1 plot(e,pch=".") se <- sd(e) se #Dickey-Fuller Test DF <- sum(wt_1*e)/(se*sum(wt_1*wt_1)) DF #cointegration - pairs trading #"drunk and her dog", American Statistician, Feb. 1994, Vol 48 No. 1 #equation for drunk set.seed(531) drunk <- rep(0.0,2000) dog <- rep(0.0,2000) t <- seq(1,2000) #drunk and dog are unrelated for(i in 2:2000){ drunk[i] <- drunk[i-1] + rnorm(1) dog[i] <- dog[i-1] + rnorm(1) } plot(drunk,ylim=c(min(drunk,dog),max(drunk,dog)),pch=".") lines(t,drunk) lines(t,dog,col=2) plot(drunk-dog,pch=".") #drunk is owner of and provider of food and shelter to dog set.seed(531) drunk <- rep(0.0,2000) dog <- rep(0.0,2000) t <- seq(1,2000) alpha <- 0.01 #drunk and dog are unrelated for(i in 2:2000){ drunk[i] <- drunk[i-1] + rnorm(1) dog[i] <- dog[i-1] + alpha*(drunk[i-1] - dog[i-1]) + rnorm(1) } plot(drunk,ylim=c(min(drunk,dog),max(drunk,dog)),pch=".") lines(t,drunk) lines(t,dog,col=2) plot(drunk-dog,pch=".")