如何为样本外预测做一个循环

How to make a loop for out-of-sample forecast

我是 R 的初学者,希望有制作循环的想法。

我想为 726 个观察中的每个观察自动执行以下操作,基于 1000 obsv 的滚动 window 进行 5 提前样本外预测,仅将 t+5 存储在“pred”列,然后将“VIX.Close”列重置为其原始值。

require(highfrequency)
require(quantmod)
require(xts)

getSymbols("^VIX")

VIX_fcst_test <- VIX[, "VIX.Close"]
VIX_fcst_test$pred <- NA

VIX_fcst_test$VIX.Close[3000] <- predict(HARmodel(data = VIX_fcst_test$VIX.Close[2000:2999], periods = c(1, 5 , 22), type = "HAR", inputType = "RM"))
VIX_fcst_test$VIX.Close[3001] <- predict(HARmodel(data = VIX_fcst_test$VIX.Close[2001:3000], periods = c(1, 5 , 22), type = "HAR", inputType = "RM"))
VIX_fcst_test$VIX.Close[3002] <- predict(HARmodel(data = VIX_fcst_test$VIX.Close[2002:3001], periods = c(1, 5 , 22), type = "HAR", inputType = "RM"))
VIX_fcst_test$VIX.Close[3003] <- predict(HARmodel(data = VIX_fcst_test$VIX.Close[2003:3002], periods = c(1, 5 , 22), type = "HAR", inputType = "RM"))
VIX_fcst_test$pred[3004] <- predict(HARmodel(data = VIX_fcst_test$VIX.Close[2004:3003], periods = c(1, 5 , 22), type = "HAR", inputType = "RM"))

VIX_fcst_test$VIX.Close <- VIX[, "VIX.Close"]

我尝试了这个循环,但我不知道如何将最后一个预测放入“pred”列并重置“VIX.Close”列。

for (i in 2000:2004) {
  HAREstimated <- HARmodel(data = VIX_fcst_test[i: (i+ 999), "VIX.Close"], periods = c(1, 5 , 22), type = "HAR", inputType = "RM")
  VIX_fcst_test$VIX.Close[i + 1000] <- predict(HAREstimated)
}

有什么想法吗?

我的理解是这样的:

  • 你首先 运行 五组观察中每组的循环,当你到达最终迭代时使用 IF 语句进入 pred 列共 VIX.close

  • 您将 VIX.close 的重置保留在 for 循环之外,否则每次迭代都会重置

    for (i in 2000:2004) {
      if (i != 2004) {
        HAREstimated <- HARmodel(data = VIX_fcst_test[i:(i+999), "VIX.Close"], periods = c(1, 5 , 22), type = "HAR", inputType = "RM")
        VIX_fcst_test$VIX.Close[i + 1000] <- predict(HAREstimated)
      } else {
        HAREstimated <- HARmodel(data = VIX_fcst_test[i:(i+999), "VIX.Close"], periods = c(1, 5 , 22), type = "HAR", inputType = "RM")
        VIX_fcst_test$pred[i + 1000] <- predict(HAREstimated)
      }
    }
    
    VIX_fcst_test$VIX.Close <- VIX[, "VIX.Close"]
    
    # final prediction
    VIX_fcst_test$pred[3004]
    

所以您真正需要的只是循环中的 IF 语句。