1
$\begingroup$

Many statistical libraries in R offer the possibility to fit a model and then use the results of optimization to predict values some periods ahead. However, many do not have the possibility to backtest the results out-of-sample.

Therefore, I want to build an R function that allows me to (walk forward approach):

  1. Define a training set using a moving window (each looping time, remove oldest observation & add most recent)
  2. Run optimizer thus calibrating the model
  3. Use the calibrated model to generate n step ahead forecast
  4. Store the new forecast in a vector of out-of-sample predicted values (together with the date of forecast)
  5. Loop through 1-4 I tried the following (x is the length of the out-of-sample set, n the fixed length of the training set):
for (j in range (0:x)){
    append <- vector()
    forecast <- vector()
    set <- train [j+1:n+j,]
    fit <- fit(data = set, model) 
    forecast <- predict(fit, ahead = 1) 
    append <- cbind(lubridate::as_date(ts_date[n+j+1]), forecast)
    forc <- rbind(forc, append)
}

However, the matrix forc contains only the first and the last result of the loop.

Can anyone spot a mistake here?

$\endgroup$
  • $\begingroup$ I don’t see anything wrong with it but it’s hard to say without having access to the complete script. $\endgroup$ – Bob Jansen Sep 24 at 19:37
  • $\begingroup$ Also, what does range do? Seems like a pythonism that doesn’t belong. $\endgroup$ – Bob Jansen Sep 24 at 20:58
2
$\begingroup$

You need to remove the call to range. In Python it’s necessary but here it just returns the smallest and largest element of the vector.

$\endgroup$
  • $\begingroup$ It works, great point, thank you so much! $\endgroup$ – Vitomir Sep 24 at 21:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.