2
$\begingroup$

I use now this code from hier Why does the following data fail my cointegration test? with slightly modification of possibility to load something directly from Dropbox file storage .

library(RCurl)
library(zoo)
library(tseries)

x <- getURL("https://dl.dropboxusercontent.com/u/12337149/stat/CBA.csv")
y <- read.csv(text = x)

x1 <- getURL("https://dl.dropboxusercontent.com/u/12337149/stat/WBC.csv")
y1 <- read.csv(text = x1)



##gld <- read.csv("CBA.csv", stringsAsFactors=F)
##gdx <- read.csv("GDX.csv", stringsAsFactors=F)

gld <- y
gdx <- y1

gld <- zoo(gld[,5], as.Date(gld[,1]))
gdx <- zoo(gdx[,5], as.Date(gdx[,1]))

t.zoo <- merge(gld, gdx, all=FALSE)
t <- as.data.frame(t.zoo)

cat("Date range is", format(start(t.zoo)), "to", format(end(t.zoo)), "\n")

m <- lm(gld ~ gdx + 0, data=t)
beta <- coef(m)[1]

cat("Assumed hedge ratio is", beta, "\n")

sprd <- t$gld - beta*t$gdx
ht <- adf.test(sprd, alternative="stationary", k=0)

cat("ADF p-value is", ht$p.value, "\n")

if (ht$p.value < 0.05) {
    cat("The spread is likely mean-reverting\n")
} else {
    cat("The spread is not mean-reverting.\n")
}

How to construct a cointegrating vector using more than 2 price series in R?

$\endgroup$
1
$\begingroup$

Use package "vars" function ca.jo for cointegration analysis (the Johansen procedure) of a multivariate time series. Here is a code snippet from the functions' help file:

data(denmark)
sjd <- denmark[, c("LRM", "LRY", "IBO", "IDE")]
sjd.vecm <- ca.jo(sjd, ecdet = "const", type="eigen", K=2, spec="longrun",
season=4)
summary(sjd.vecm)

It loads a dataset denmark, extracts four times series into a matrix sjd, conducts the Johansen procedure by the function ca.jo and prints its summary.

You can extract the cointegrating vectors by addressing the slot V by @V like sjd.vecm@V. This will be a matrix where each column is a cointegrating vector. You can multiply the original multivariate series (like sjd) to the V matrix to get the error correction terms.

A good introduction is the "vignette" of the "vars" package and Pfaff "Analysis of Integrated and Cointegrated Time Series with R" (a textbook).

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.