滚动回归多列

P. *_*nry 7 r apply linear-regression xts rolling-computation

我有一个问题是找到一种最有效的方法来计算具有多列的xts对象的滚动线性回归.我已经在stackoverflow上搜索并阅读了之前的几个问题.

这个问题和答案很接近,但在我看来还不够,因为我想计算所有回归中因变量不变的多元回归.我试图用随机数据重现一个例子:

require(xts)
require(RcppArmadillo)  # Load libraries

data <- matrix(sample(1:10000, 1500), 1500, 5, byrow = TRUE)  # Random data
data[1000:1500, 2] <- NA  # insert NAs to make it more similar to true data
data <- xts(data, order.by = as.Date(1:1500, origin = "2000-01-01"))

NR <- nrow(data)  # number of observations
NC <- ncol(data)  # number of factors
obs <- 30  # required number of observations for rolling regression analysis
info.names <- c("res", "coef")

info <- array(NA, dim = c(NR, length(info.names), NC))
colnames(info) <- info.names
Run Code Online (Sandbox Code Playgroud)

创建数组是为了随时间和每个因子存储多个变量(残差,系数等).

loop.begin.time <- Sys.time()

for (j in 2:NC) {
  cat(paste("Processing residuals for factor:", j), "\n")
  for (i in obs:NR) {
    regression.temp <- fastLm(data[i:(i-(obs-1)), j] ~ data[i:(i-(obs-1)), 1])
    residuals.temp <- regression.temp$residuals
    info[i, "res", j] <- round(residuals.temp[1] / sd(residuals.temp), 4)
    info[i, "coef", j] <- regression.temp$coefficients[2]
  } 
}

loop.end.time <- Sys.time()
print(loop.end.time - loop.begin.time)  # prints the loop runtime
Run Code Online (Sandbox Code Playgroud)

由于循环显示的想法是data[, 1]每次对其中一个因素运行30个观察滚动回归作为因变量(因子).我必须将30个残差存储在临时对象中,以便将它们标准化,因为fastLm不计算标准化残差.

如果xts对象中的列数(因子)增加到大约100-1,000列,则循环非常慢并且变得麻烦.我希望有一个更高效的代码来创建大型数据集的滚动回归.

Sam*_*eer 10

如果你深入到线性回归的数学水平,它应该很快.如果X是自变量而Y是因变量.系数由下式给出

Beta = inv(t(X) %*% X) %*% (t(X) %*% Y)

我有点困惑你想要哪个变量是依赖的,哪个是独立的,但希望解决下面的类似问题对你也有帮助.

在下面的示例中,我采用1000个变量而不是原始的5个,并且不引入任何NA.

require(xts)

data <- matrix(sample(1:10000, 1500000, replace=T), 1500, 1000, byrow = TRUE)  # Random data
data <- xts(data, order.by = as.Date(1:1500, origin = "2000-01-01"))

NR <- nrow(data)  # number of observations
NC <- ncol(data)  # number of factors
obs <- 30  # required number of observations for rolling regression analysis
Run Code Online (Sandbox Code Playgroud)

现在我们可以使用Joshua的TTR包计算系数.

library(TTR)

loop.begin.time <- Sys.time()

in.dep.var <- data[,1]
xx <- TTR::runSum(in.dep.var*in.dep.var, obs)
coeffs <- do.call(cbind, lapply(data, function(z) {
    xy <- TTR::runSum(z * in.dep.var, obs)
    xy/xx
}))

loop.end.time <- Sys.time()

print(loop.end.time - loop.begin.time)  # prints the loop runtime
Run Code Online (Sandbox Code Playgroud)

时差3.934461秒

res.array = array(NA, dim=c(NC, NR, obs))
for(z in seq(obs)) {
  res.array[,,z] = coredata(data - lag.xts(coeffs, z-1) * as.numeric(in.dep.var))
}
res.sd <- apply(res.array, c(1,2), function(z) z / sd(z))
Run Code Online (Sandbox Code Playgroud)

如果我没有在索引中做出任何错误,res.sd应该给你标准化的残差.请随时修复此解决方案以纠正任何错误.