# R code for dickey-fuller test and Johansen cointegration analysis #Random walk shock<-ts(rnorm(140), frequency=4, start=c(1970,1)) RW<-diffinv(shock) ts.plot(RW,ylab="Random walk") RW<-diffinv(shock) RW<-RW+0.2*(1:length(RW)) ts.plot(RW,ylab="Random walk + trend") #install.packages("fpp") library(fpp) ts.plot(usgdp) # regress 100m record on GDP -> spurious record<-ts(c(993,993,993,993,992,992,992,986, 986,986,985,985,984,984,984,979, 979,979,978,978,978,977,977,974, 969,958,958,958,958,958,958), frequency = 1,start=c(1983)) ts.plot(record) year_gdp<-aggregate(usgdp,nfrequency=1) lm1<-lm(record[time(record) %in% c(1983:2005)]~year_gdp[time(year_gdp) %in% c(1983:2005)]) summary(lm1) ts.plot(record) lines(c(1983:2005),fitted.values(lm1),col="red") legend("bottomleft", legend = c("fitted by US_gdp","100m record"), fill = c("red","black")) # Dickey-Fuller test strategy for unit-root install.packages("urca") library(urca) lc<-log(usconsumption[,1]) summary(ur.df(usgdp,type="trend")) summary(ur.df(usgdp,type="drift")) summary(ur.df(usgdp,type="none")) plot(ur.df(usgdp,type="drift")) #cointegration of income and consumption consumption<-diffinv(usconsumption[,1])/sqrt(usgdp) income<-diffinv(usconsumption[,2])/sqrt(usgdp) ts.plot(income,consumption,col = c("red","blue")) legend("topleft", legend = c("income", "consumption"), fill = c("red","blue")) coint=ca.jo(cbind(consumption,income),spec="longrun") summary(coint) #test for cointegration between variables. #compare column test with the levels: #for r<=1 test is larger than 1% level so there is a very significant cointegration relation res= lm(consumption~time(consumption)) summary(res) ts.plot(consumption-1.15*income)