我正在对股票数据运行多滚动窗口分位数回归,以便生成的输出是一个 xts 文件,其系数在每个时间点估计。然后从分位数估计最终估计量。然后使用 for 参数将 5 个回归一起循环到我所有的股票中。
我想做什么?我需要循环并存储如下所示的 xts 输出,以列表和唯一名称显示,以便稍后在我的方法的下一步中使用它。
(Intercept) rmrf smb hml rmw cma
2015-05-21 -0.001070362 0.9647046 -0.1206183 -0.05204882 0.01866969 -0.0361021
2015-05-22 -0.001070362 0.9647046 -0.1206183 -0.05204882 0.01866969 -0.0361021
2015-05-26 -0.001070362 0.9647046 -0.1206183 -0.05204882 0.01866969 -0.0361021
2015-05-27 -0.001070362 0.9647046 -0.1206183 -0.05204882 0.01866969 -0.0361021
2015-05-28 -0.001070362 0.9647046 -0.1206183 -0.05204882 0.01866969 -0.0361021
2015-05-29 -0.001070362 0.9647046 -0.1206183 -0.05204882 0.01866969 -0.0361021
当我想将结果存储到列表中时,我的问题最终出现了。发生这种情况是因为我希望数据集的名称与我执行回归的列具有相同的名称。
代码已被简化为只有一个回归。我解决这个问题的最佳尝试如下:
testlist <- list()
for(i in 1:ncol(stocks) {
stock_data <- stocks[,i]
# merge data together
regression_input <- merge(stock_data, rmrf, smb, hml, rmw, cma, rf)
#rename
colnames(regression_input) = c("stock_returns" , "rmrf" , "smb" , "hml" , "rmw" , "cma" , "rf")
quantile005 <- as.xts(
rollapply(zoo(regression_input),
width=200,
FUN = function(Z)
{
t = rq(stock_returns ~ rmrf + smb + hml + rmw + cma, tau=0.05, data = as.data.frame(Z),
method="br", model = TRUE);
return(t$coef)
},
by.column=FALSE, align="right")
)
final_estimators <- # additional calculations are performed with results stored here
#save
name <- paste(rownames(i), sep = "")
testlist[[name]] <- final_estimators
}
此外:即使在循环之外,此命令似乎也不会读取我的行的名称。
> name <- paste(rownames(return_data[,1]), sep = "")
> name
character(0)
>
编辑 W 解决方案
似乎解决方案已经为我准备好了。问题是 colnames 函数仅从数据框对象中检索名称。这是代码的最终版本。
# Create list to store dataframes
testlist <- list()
# Loop over entire regression methodology
for(i in 1:ncol(test_3_stocks)) {
# Get regression input together
stock_data <- test_3_stocks[,i] - ff_data[,7]/100
regression_input <- merge(stock_data, rmrf, smb, hml, rmw, cma, rf)
colnames(regression_input) = c("stock_returns" , "rmrf" , "smb" , "hml" , "rmw" , "cma" , "rf")
#Rolling window regression - Quantile coefficients data
quantile005 <- as.xts(
rollapply(zoo(regression_input),
width=200,
FUN = function(Z)
{
t = rq(stock_returns ~ rmrf + smb + hml + rmw + cma, tau=0.05, data = as.data.frame(Z),
method="br", model = TRUE);
return(t$coef)
},
by.column=FALSE, align="right")
)
print(tail(summary(quantile005)))
tmp <- summary(quantile005)
name <- colnames(as.data.frame(test_3_stocks[,i]))
testlist[[name]] <- tmp
}
最终结果:
> tail(testlist$TEST1)
(Intercept) rmrf smb hml rmw cma
2015-05-21 1255.853 -7.16453 531.4655 1870.740 1422.398 -4034.082
2015-05-22 1256.221 -40.88781 512.3803 1700.796 1569.501 -3830.814
2015-05-26 1256.413 -152.42752 713.5793 1754.086 1452.681 -3771.936
2015-05-27 1256.707 15.39627 451.2127 1568.405 1246.730 -3665.781
2015-05-28 1257.893 -133.72554 705.0280 1816.560 1232.326 -4188.772
2015-05-29 1258.239 -148.11936 624.4424 1837.348 1098.122 -4301.114