有人能帮我在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))这种方法的两个问题是:
rolling.var.coef和var.resids也是3000长,而长度必须是7x3000 (有7个系数)和119*3000 (每个回归有119个残差),所以它只计算前几天的变量(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 发布于 2017-11-24 20:12:28
所以,在这些行中尝试一些东西(方法是从包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)https://stackoverflow.com/questions/37490102
复制相似问题