library(dplyr)
library(parsnip)
library(rsample)
library(timetk)
# Data
m750 <- m4_monthly %>% filter(id == "M750")
m750
# Split Data 80/20
splits <- initial_time_split(m750, prop = 0.8)
# ---- WINDOW FUNCTION -----
# Used to make:
# - Mean/Median forecasts
# - Simple repeating forecasts
# Median Forecast ----
# Model Spec
model_spec <- window_reg(
window_size = 12
) %>%
# Extra parameters passed as: set_engine(...)
set_engine(
engine = "window_function",
window_function = median,
na.rm = TRUE
)
# Fit Spec
model_fit <- model_spec %>%
fit(log(value) ~ date, data = training(splits))
model_fit
# Predict
# - The 12-month median repeats going forward
predict(model_fit, testing(splits))
# ---- PANEL FORECAST - WINDOW FUNCTION ----
# Weighted Average Forecast
model_spec <- window_reg(
# Specify the ID column for Panel Data
id = "id",
window_size = 12
) %>%
set_engine(
engine = "window_function",
# Create a Weighted Average
window_function = ~ sum(tail(.x, 3) * c(0.1, 0.3, 0.6)),
)
# Fit Spec
model_fit <- model_spec %>%
fit(log(value) ~ date + id, data = training(splits))
model_fit
# Predict: The weighted average (scalar) repeats going forward
predict(model_fit, testing(splits))
# ---- BROADCASTING PANELS (REPEATING) ----
# Simulating a Seasonal Naive Forecast by
# broadcasted model the last 12 observations into the future
model_spec <- window_reg(
id = "id",
window_size = Inf
) %>%
set_engine(
engine = "window_function",
window_function = ~ tail(.x, 12),
)
# Fit Spec
model_fit <- model_spec %>%
fit(log(value) ~ date + id, data = training(splits))
model_fit
# Predict: The sequence is broadcasted (repeated) during prediction
predict(model_fit, testing(splits))
Run the code above in your browser using DataLab