## No Cointegration example: checking stationarity and cointegraton 
## properties of consumption and income in the USA

library(strucchange)
data(USIncExp)

USIncExp <- window(USIncExp, start=c(1990,1), end=c(2000,1))

plot(USIncExp[ , "income"])
plot(USIncExp[ , "expenditure"])
plot(USIncExp)
plot(USIncExp, plot.type="single")

library(tseries)
adf.test(USIncExp[ , "income"])
adf.test(USIncExp[ , "expenditure"])

## long-run model
lrmod <- lm(expenditure ~ income, data=USIncExp)
summary(lrmod)
adf.test(resid(lrmod))

lr.resids <- ts(resid(lrmod), start=c(1990,1), freq=12)
plot(lr.resids, col="blue")

#################################################################


## Cointegration example - Motor insurance premiums and claims in
## Germany (dissertation Mila Vujovic)

## read in data
autoDE <- read.table("autoDE.txt", h=T, sep="\t")

## test original data for stationarity
library(tseries)
adf.test(autoDE$premiums)
adf.test(autoDE$claims)

## inspect data by plotting
tsauto <- ts(autoDE[, c("premiums", "claims")], start=autoDE[1,1])
plot(tsauto)
plot(tsauto, plot.type="single", col=c("blue","red"))

## long run model
lrmod <- lm(premiums~claims, data=autoDE)
plot(ts(resid(lrmod), start=autoDE[1,1]), type="l", col="green3")
abline(h=0)

## cointegration test
adf.test(resid(lrmod)) ## should actually use special critical values

## ECM
## lag residuals
lres <- resid(lrmod)[-length(resid(lrmod))]
## estimate ECM
ecmmod <- lm(diff(premiums)~diff(claims)+lres, data=autoDE)
summary(ecmmod)