I am beginner to R and was hoping to have ideas for making a loop.
I would like to automate the following for each observation out of 726 observation making a 5 ahead out-of-sample forecast based on a rolling window of 1000 obsv, storing only the t+5 in the "pred" column and then reset the "VIX.Close" column to his original values.
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"]
I tried this loop but I don't know how to make the last prediction into the "pred" column and reset the "VIX.Close" column.
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)
}
Any ideas?
My understanding is the following:
you first run the loop on each of the five sets of observations, with an IF statement for when you reach the final iteration which goes into the pred
column instead of VIX.close
you keep the reset of VIX.close outside of the for loop, otherwise it would have reset with each iteration
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]
So really all you needed was an IF statement in your loop.