我遇到了一个问题,需要寻找一种计算多列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
该数组被创建用于按时间和因素存储多个变量(残差、系数等)。
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
这个循环的想法是每次将data [,1]
作为因变量(因子)与其他因子之一进行30次观测滚动回归。我必须将这30个残差存储在临时对象中,以便将它们标准化,因为fastLm
不会计算标准化残差。
如果xts对象中的列数(因子)增加到约100,则循环非常缓慢,并且当列数增加到1000时,处理速度就会变得非常缓慢。希望有更高效的代码来创建大型数据集的滚动回归。