使用 xreg 和重新估计进行滚动预测

Rolling forecast with xreg and re-estimation

我尝试通过重新估计将 xreg 实施到我的滚动预测中。 不幸的是,我遇到了 xreg 长度的问题。

# sample data  
sample <- ts(rnorm(100, mean = 1000, sd=7), start = c(2012,1), end = c(2019,12), frequency = 12)
external <- ts(mtcars, start = c(2012,1), end = c(2019,12), frequency = 12)

#Define h --> One-step ahead (for a start, later to be increased)
h <- 1
#specify length to forecast
test  <- window(sample, start = c(2018,01), end = c(2019,12), frequency = 12)
n <- length(test) - h + 1
#provide total length of regressors available
total_xreg <- ts(external[,c(1,2,3)], start = c(2012,1), end= c(2019,12), frequency = 12)

#create empty matrix
fcmatx <- matrix(0, nrow=n, ncol=h)

# create loop
for(i in 1:n)
{  
# x is the target variable, provide training data 
  x <- window(sample, end= c(2017,12) + (i-1)/12)
# provide xregs for training data
  xregs <- window(total_xreg, end = c(2017,12) + (i-1)/12)
# provide new xregs for forecasting, assuming that xreg is available for the forecasting period
  xregs2 <- window(total_xreg, start = c(2018,1) + (i-1)/12
# limit xregs2 to show only the first line since we are only forecasting 1 step in advance
 xregs3 <- xregs2[1,]
# create auto.arima model
  refit.multirex <- auto.arima(x, xreg = xregs)
# forecast using regressors
  fcmatx[i,] <- forecast(refit.multirex, 
                         h=h, 
                         xreg = xregs3
                         )$mean
}
fcmattsx <- ts(fcmatx, start = c(2018,1), frequency = 12)

这会导致以下错误:

Error in forecast.forecast_ARIMA(refit.multirex, h = h, xreg = xregs3) : 
  Number of regressors does not match fitted model

h 的长度为 1,xregs 的长度为 3,因为我填入了 3 个变量,但它们都只用于一个时间段。我尝试了各种调整,但无法正确调整。

下面一行

xregs3 <- xregs2[1,]

return是向量而不是矩阵。当您从矩阵中提取单个列或行时,这是 R 中的默认行为。改成

xregs3 <- xregs2[1,,drop=FALSE]

保持矩阵结构(1x3)。那么forecast()函数就不会return报错了。

i=23 时你会得到一个不同的错误,因为在创建 xregs2 时你在 end 之后有 start