RamiKrispin / TSstudio

Tools for time series analysis and forecasting
https://ramikrispin.github.io/TSstudio/
Other
421 stars 65 forks source link

Xreg Future values #11

Closed mbanco closed 5 years ago

mbanco commented 5 years ago

Hi, How to include future values ​​in Xreg predictor?

Best regards.

RamiKrispin commented 5 years ago

Hi,

Below is an example of using xreg with the ts_backtesting function:

library(TSstudio)
library(lubridate)

packageVersion("TSstudio") # make sure you are using version 0.1.4

data("USgas")

ts_plot(USgas)

# Creating the data for the auto.arima model xreg argument (train model)
USgas_df <- ts_to_prophet(USgas)

USgas_df$index <- 1:nrow(USgas_df)
USgas_df$seasonal <- factor(month(USgas_df$ds, label = TRUE), ordered = FALSE)

# Set the forecast horizon
h <- 60

# Create the xreg argument for the future prediction 

future_df <- data.frame(ds = seq.Date(from = max(USgas_df$ds) + months(1),
                                        length.out = h,  
                                        by = "month"),
                          index = (max(USgas_df$index) + 1):(max(USgas_df$index) + h))

future_df$seasonal <- factor(month(future_df$ds, label = TRUE), ordered = FALSE)

# Use the USgas_df with the auto.arima xreg argument 
# Use the xreg.h to set the future values of the xreg using the future_df

backtesting_model <- ts_backtesting(ts.obj = USgas,
                                    models = "abehntw",
                                    periods = 6,
                                    error = "MAPE",
                                    window_size = 12,
                                    h = h,
                                    a.arg = list(xreg = cbind(USgas_df$index, USgas_df$seasonal)),
                                    xreg.h = cbind(future_df$index, future_df$seasonal))

Hope this makes sense.

Best, Rami