【问题标题】:VAR(1) rolling window (Vector autoregression)VAR(1) 滚动窗口(向量自回归)
【发布时间】:2016-05-27 18:25:32
【问题描述】:

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

【问题讨论】:

  • 欢迎来到 StackOverflow。请查看有关如何在 R 中创建minimum exampleproducing a good example 上的帖子的提示。另外,您介意在您的问题中包含您正在使用的任何软件包吗?例如,Bcoef 不是基础 R 的一部分。
  • 感谢您的评论!添加了包名..
  • 如链接中所述,包含一个示例数据集(可能小于您的原始数据)也是一个好主意,该数据集可以重现您的问题以供人们使用。查看 R 示例链接的第一个答案,了解如何使用 dput

标签: r autoregressive-models


【解决方案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)

【讨论】:

  • 问题已过时,但已回答以供将来参考
猜你喜欢
  • 2017-11-29
  • 2017-09-16
  • 2013-07-01
  • 1970-01-01
  • 2018-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-25
相关资源
最近更新 更多