Skip to content

Instantly share code, notes, and snippets.

@robjhyndman
Last active July 14, 2022 10:00
Show Gist options
  • Save robjhyndman/d9eb5568a78dbc79f7acc49e22553e96 to your computer and use it in GitHub Desktop.
Save robjhyndman/d9eb5568a78dbc79f7acc49e22553e96 to your computer and use it in GitHub Desktop.
tsCV with xreg
library(forecast)
fc <- function(y, h, xreg, newxreg) {
fit <- auto.arima(y, xreg=xreg)
forecast(fit, xreg=newxreg, h=h)
}
y <- ts(rnorm(100))
x <- matrix(ts(rnorm(100)),ncol=1)
tsCV(y, fc, xreg=x, h=1)
@robjhyndman
Copy link
Author

For a linear model, use tslm, not lm.

@Niloojan
Copy link

Niloojan commented Jul 1, 2022

Dear Rob,
I am doing multi step ahead ex-ante forecast with a model with explanatory variables, for instance if its a 7 days ahead forecast of Y, I need to have 1 to 7 days forecast of X to be used recursively in 1 to seven days forecast of Y. I use a modified version of tscv that allows to have xreg_actual and xreg_forecast, then I use these codes:

far <- function(x, h, xreg, newxreg) {
forecast(Arima(x, order=c(0,0,0), xreg=xreg), xreg=newxreg)
}

xreg_actual <- data.frame(X1=X1_actual,)
xreg_forecast <- data.frame(X1=X1_onestep, X1=X1_twostep,....., X1=X7_sevenstep)

So xreg_actual includes the actual values of X1 and xreg_forecast includes X1_onestep to X7_sevenstep, which are forecasted values of X1 for the validation and test period, and are obtained from another tscv forecast. What I expect is that, each of the elements of xreg_forecast dataframe to be used in forecasting y from one to seven step ahead. for example if h=7, the tscv starts from h=1 and then recursively reaches to h=7, and I want X1_onestep to be used in h=1, X2_twostep to be used in h=2 and so on....
So, I made the following loop:

for (i in 1:ncol(xreg_forecast) {
error[[i]]<- data.frame(mytsCV(y, far, h=7, window = 365, initial =10, xreg_actual=xreg_actual,
xreg_forecast=xreg_forecast[[i]]))
}

the loop is generating the errors as it should be, however, I am not sure if the loop is atually doing what I aimed to.
Also Im not sure how can I extend the loop for models with more than one explanatory variables.
Any help is highly appriciated.
Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment