robjhyndman / forecast

Forecasting Functions for Time Series and Linear Models
http://pkg.robjhyndman.com/forecast
1.1k stars 340 forks source link

Seperating train sample from validate and test samples for exogenous variables in tsCV function #892

Closed Niloojan closed 2 years ago

Niloojan commented 2 years ago

Hi, I hope someone can help me about it,

I am using the tscv function in R to perform a rolling origin forecast of 1 day to 1 year ahead horizons using daily frequency data. Suppose my outcome variable is price, and I have x1, x2 and x3 as exogenous variables.

If I want to use the actual values of x1, x2 and x3 to perform a for instance seven day ahead out of sample forecast, then it would be as:

xreg <- data.frame(x1, x2, x3)

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

e <- tsCV(price, fit, h=7, window=1000, xreg=xreg)

However, the problem is that I want to use the actual values of x1 and x2 for the training sample and their forecasted values for validate and test periods. In the same time, I want to apply the actual value of x3 for the whole period.

So I have forecasted values of x1 and x2, let’s call them f_x1 and f_x2 also. If the first seven day ahead forecast point for price is 1007, then x1, x2 and x3 have to be used for 1 to 1000 to estimate the model, then switch to f_x1 and f_x2 from 1001 to 1007 to perform the forecast, and this have to roll over as the windows roll.

I think a change should occur in xreg, applying a kind of loop that allows the function to switch over variables when the training period ends, right?

I have tried this one: xreg1=contains x1, x2 and x3 xreg2= contains f_x1, f_x2, x3 then: e <tsCV(price, fit, h=7, window =1000, if (length(xreg) < 1001) { xreg=xreg1 } else if (length(xreg) > 1000) { xreg=xreg2 }) But the output shows that it doesnt convert using data from xtreg 1 to xtreg2.

Any help is greatly appreciated,

robjhyndman commented 2 years ago

Answered at https://stats.stackexchange.com/a/547596/159