VAR(1)滚动窗口(矢量自回归)

时间:2016-05-27 18:25:32

标签: r autoregressive-models

有人可以帮我在R中运行VAR(1)(向量自回归),在多个时间序列上滚动窗口并以某种方式存储Bcoef(系数)和残差?好像我无法找到一种方法一次完成所有工作。

我的代码:(使用包library(vars)进行矢量自动回归

varcoef <- function(x) Bcoef(VAR(x, p=1, type =c("const"), lag.max = NULL))
varr <-  function(x) resid(VAR(x, p=1, type =c("const"), lag.max = NULL))
rolling.var.coef <-  rollapply(eur.var,width=120,varcoef, by.column=FALSE)
var.resids<-as.data.frame(rollapplyr(eur.var,width=120,varr, by.column=FALSE))

这种方法存在两个问题:

  • 我有3000天,输出矩阵rolling.var.coefvar.resids的长度也是3000,而长度必须是7x3000(有7个系数)和119 * 3000(每个回归有119个残差) ),因此它仅计算几天的VAR(1)
  • 最重要的是:如何在一个功能中完成,而不是两个。因为输出是两个矩阵

以下是我的数据的近似视图 - 这样的3000天。

V1    V2    V3    V4    V5    V6   V7
2016-05-10 -0.34 -0.35 -0.37 -0.40 -0.41 -0.30 0.14
2016-05-09 -0.36 -0.35 -0.37 -0.40 -0.41 -0.30 0.15  

1 个答案:

答案 0 :(得分:1)

所以,在这些方面尝试一下(方法是从包frequencyConnectedness的代码中借用的。)

library(vars)

data(Canada)
data <- data.frame(Canada)
window <- 10

# your VAR function, saving both matrices in a list
caller <- function(j) {
  var.2c <- VAR(data[(1:window)+j,],p=1,type = "const")
  B <- Bcoef(var.2c)
  r <- resid(var.2c)
  list(B,r)
}

# Roll the fn over moving windows
out <- pbapply::pblapply(0:(nrow(Canada)-window), caller)

这里的美妙之处在于,您可以使用大型且耗时较长的功能(例如SVAR)parallel

使用linux / mac进行并行计算

例如,在linux / mac系统上,这应该会让您的计算机生活更轻松(Windows的不同故事,请参阅上面的链接以及下面的解决方案):

library(vars)
library(pbapply)

data(Canada)
data <- data.frame(Canada)
window <- 10

caller <- function(j) {
  var.2c <- VAR(data[(1:window)+j,],p=1,type = "const")
  B <- Bcoef(var.2c)
  r <- resid(var.2c)
  list(B,r)
}

# Calculate the number of cores and define cluster
no_cores <- detectCores() - 1
cluster <- makeCluster(no_cores, type ="FORK")

out <- pbapply::pblapply(0:(nrow(Canada)-window), caller, cl = cluster)

stopCluster(cluster)

使用Windows进行并行计算

# Calculate the number of cores and create PSOCK cluster
no_cores <- detectCores() - 1
cluster <- makeCluster(no_cores)

# Export necessary data and functions to the global environment of the cluster workers 
# and necessary packages on the cluster workers
clusterExport(cluster, c("Canada","data","window","caller"), envir=environment())
clusterEvalQ(cluster, library(vars))

#Moving window estimation 
out <- pblapply(0:(nrow(Canada)-window), caller,cl = cluster)

stopCluster(cluster)
相关问题