# 17 Cointegration Tests and Modelling Cointegrated Systems library(fUnitRoots) library (readxl) library(vars) library(tseries) library(urca) SandPhedge <- read_excel("D:/Programming Guide/data/SandPhedge.xls", col_types = c("date","numeric","numeric")) View(SandPhedge) #head(SandPhedge) # Log prices SandPhedge$lspot = log(SandPhedge$Spot) SandPhedge$lfutures = log(SandPhedge$Futures) # Apply Phillips-Ouliaris test for cointegration dat <- cbind(SandPhedge$lspot,SandPhedge$lfutures) po.test(dat) # H0: no cointegration is rejected # Log returns SandPhedge$rspot = c(NA,100*diff(log(SandPhedge$Spot))) SandPhedge$rfutures = c(NA,100*diff(log(SandPhedge$Futures))) log_lm <- lm(SandPhedge$lspot ~ SandPhedge$lfutures) summary(log_lm) par(lwd =2,cex.axis = 2) #par(mar = c(1,1,1,1)) # Changing area margins plot(SandPhedge$Date,SandPhedge$lspot,type = "l",xlab = "",ylab = "",col ="red") lines(SandPhedge$Date,log_lm$fitted.values) par(new=T) plot(SandPhedge$Date,log_lm$residuals,col="blue",axes=F,type ="l") axis(side=4, at = pretty(range(log_lm$residuals))) legend ("bottomleft",legend=c("Actual","Fitted"),col =c("black","red"),lty=1) legend ("bottomright",legend=c("Resid"),col=c("blue"),lty = 1) # Unitroot test applied to residuals urersTest(log_lm$residuals,doplot=F,type="DF-GLS",model="trend",lag.max=12)@test$test@teststat urersTest(log_lm$residuals,doplot=F,type="DF-GLS",model="trend",lag.max=12)@test$test@cval # Unit root in the residuals cannot be tejected -> no cointegration summary(lm(SandPhedge$rspot[-1] ~ SandPhedge$rfutures[-1]+log_lm$residuals[-247])) # ECM is statisrically significant -> cointegration ### Johansen's method fred <- read_excel("D:/Programming Guide/data/fred.xls", col_types = c("date",rep("numeric",6))) View(fred) head(fred) summary(fred[c("GS3M","GS6M","GS1","GS3","GS5","GS10")]) plot (fred$Date,fred$GS3M, type ="l",xlab ="",ylab ="") lines(fred$Date,fred$GS6M,col="red") lines(fred$Date,fred$GS1,col="blue") lines(fred$Date,fred$GS3,col="brown") lines(fred$Date,fred$GS5,col="orange") lines(fred$Date,fred$GS10,col="darkgreen") # Select lags in the VAR model VARselect(fred[c("GS3M","GS6M","GS1","GS3","GS5","GS10")],lag.max=12) # Johansen's test summary(ca.jo(fred[c("GS3M","GS6M","GS1","GS3","GS5","GS10")],K=2,ecdet="const",type="trace")) # At most 3 cointegrating vectors at the 1% significance level # Estimate VECM vecm <- (ca.jo(fred[c("GS3M","GS6M","GS1","GS3","GS5","GS10")],K=2,ecdet="const",type="trace")) cajorls(vecm,r=3)