Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rolling window option in tsCV() with xreg #715

Open
mkiang opened this issue Jul 3, 2018 · 3 comments
Open

Rolling window option in tsCV() with xreg #715

mkiang opened this issue Jul 3, 2018 · 3 comments
Assignees

Comments

@mkiang
Copy link

mkiang commented Jul 3, 2018

Hi, I may be a bit confused here, but I'm having trouble setting the window option in tsCV() while also using xreg. When not using the xreg, the window seems to scan the data correctly:

far2 <- function(x, h){forecast(Arima(x, order=c(2,0,0)), h=h)}
e <- tsCV(lynx, far2, h=1, window=30)

fit1   <- Arima(lynx[1:30], order = c(2, 0, 0))
fcast1 <- forecast(fit1, h = 1)
lynx[31] - fcast1$mean[1]; e[30]

# [1] -11.41075
# [1] -11.41075

fit2   <- Arima(lynx[2:31], order = c(2, 0, 0))
fcast2 <- forecast(fit2, h = 1)
lynx[32] - fcast1$mean[1]; e[31]

# [1] -578.658
# [1] -578.658

When using the same idea as above, but specifying an xreg, it does not work. Any tips on how to write my forecastfunction such that I can use a rolling window and xreg? It works for the first fit (i.e., before the window starts rolling), but not for other fits.

fc <- function(y, h, xreg)
{
    X <- xreg[1:length(y),]
    if(NROW(xreg) < length(y) + h)
        stop("Not enough xreg data for forecasting")
    newX <- xreg[length(y)+(1:h), ]
    fit <- Arima(y, xreg=X, order = c(1, 0, 0))
    forecast(fit, xreg=newX)
}

set.seed(1)
y <- ts(rnorm(100))
x <- matrix(ts(rnorm(100)),ncol=1)
e <- tsCV(y, fc, xreg=x, window = 20)

fit1   <- Arima(y[1:20], xreg = x[1:20, ], order = c(1, 0, 0))
fcast1 <- forecast(fit1, h = 1, xreg = x[21, ])
y[21] - fcast1$mean[1]; e[20]
# [1] 0.7328816
# [1] 0.7328816

fit2   <- Arima(y[2:21], xreg = x[2:21, ], order = c(1, 0, 0))
fcast2 <- forecast(fit2, h = 1, xreg = x[22, ])
y[22] - fcast2$mean[1]; e[21]
# [1] 0.7791716
# [1] 0.5096576

Thanks for any help!

@robjhyndman
Copy link
Owner

Should be ok now. Fixed in 904028f

@robjhyndman
Copy link
Owner

@mitchelloharawild might be able to make the code a bit neater though.

@anafotina
Copy link

When reproducing the example above, the values between tsCV and manually calculated errors are still different starting from the second step.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants