0

有人可以帮助我在多个时间序列上使用滚动窗口在 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  
4

1 回答 1

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),您可以并行处理。

使用 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)
于 2017-11-24T20:12:28.913 回答