Skip to content

Several seasons, and machine-learning forecasters

Handle several seasonal cycles with MSTL, TBATS and Prophet, then use lag features and recurrent networks, always measured against the same baselines.

Advanced ~15 min13 steps

What runs in CodeSplash

You will be able to

  • Choose MSTL, TBATS or Prophet for several or non-integer seasons
  • Explain lag features, and why tree models need differencing to follow a trend
  • Judge a recurrent network forecast with a backtest rather than a training loss

Read first

01

When one season isn't enough

Read

Hourly load has a daily cycle and a weekly one. Call-center volume may have those plus a yearly one. ETS and seasonal ARIMA handle only one season at a time.

Here are three ways to deal with more than one:

  • MSTLMSTLSplits a series into a trend, one seasonal component per period and a remainder, handling several seasonal cycles at once. peels off each season, then forecasts what's left.
  • TBATSTBATSExponential smoothing with seasonality built from sine and cosine waves, so cycles may be long, several, or a fraction of a step. models each season as a sum of harmonicsHarmonicsPairs of sine and cosine waves that together draw a seasonal shape; more pairs follow sharper shapes and cost more parameters..
  • Prophet fits a trend plus seasonal terms with a regression.
02

MSTL

In the app
MSTL forecastRecorded · Python and R agreeRecorded 2026-11-25 · 29 values compared
R

MSTL(24, 168) + ETS(A,N,N): 24-step forecasts of load (evenly spaced data, 504 observations). Backtest MAE 0.95 over 1 origin.

MAE
0.9498
RMSE
1.193
MAPE
0.0089

Plots

Forecast of loadWhere is the series heading, and how uncertain is the forecast?
View data
hi_80hi_95kindlo_80lo_95hourload
——actual——1102.74
——actual——2105.49
——actual——3107.82
——actual——4107.86
——actual——5106.52
——actual——6106.15
——actual——7107.57
——actual——8106.48
——actual——9106.51
——actual——10106.27
——actual——11105.70
——actual——12103.65
——actual——13103.36
——actual——14100.44
——actual——1596.765
——actual——1694.818
——actual——1792.788
——actual——1892.051
——actual——1991.570
——actual——2095.164
——actual——2197.034
——actual——22100.73
——actual——23104.79
——actual——24108.44
——actual——25109.70
——actual——26109.24
——actual——27110.38
——actual——28110.70
——actual——29110.64
——actual——30110.27
——actual——31112.59
——actual——32110.30
——actual——33109.77
——actual——34111.08
——actual——35110.05
——actual——36108.33
——actual——37106.50
——actual——38103.17
——actual——39100.05
——actual——4096.200
——actual——4194.979
——actual——4295.577
——actual——4396.750
——actual——4499.104
——actual——45100.31
——actual——46103.20
——actual——47105.52
——actual——48107.70
——actual——49111.17
——actual——50110.64
——actual——51112.57
——actual——52111.51
——actual——53110.85
——actual——54109.68
——actual——55111.11
——actual——56112.80
——actual——57111.38
——actual——58110.38
——actual——59108.80
——actual——60107.01

First 60 of 528 rows.

Backtest errors by horizonHow does forecast error grow with the horizon, and how stable is it across origins?
View data
errorhorizonorigin
1.5941480
1.6482480
0.33243480
1.2164480
−0.74535480
−1.9696480
−0.21687480
0.07028480
1.9879480
0.932410480
−0.339011480
0.569612480
1.19113480
1.03614480
2.41015480
0.598116480
−1.84917480
−1.55818480
0.084119480
−1.67520480
0.005221480
−0.337122480
−0.404023480
−0.027224480
Residual autocorrelationIs a series (or a model's residuals) autocorrelated, and at which lags?
View data
ACFboundlag
0.18260.08731
−0.09780.08732
−0.17500.08733
−0.17520.08734
−0.12170.08735
0.01230.08736
0.01250.08737
−0.03390.08738
−0.04300.08739
−0.03760.087310

Assumptions

  • Residuals look uncorrelated — Ljung–Box at 10 lags: p = 0.000. Dynamics remain beyond the seasonal cycles and the adjusted series' model: try TBATS with ARMA errors.

Backtest accuracy (1 origin, horizon 24)

MetricValue
MAE0.9498
RMSE1.193
MAPE0.0089
sMAPE0.0089
MASE0.5405
WAPE0.0088
Coverage of the 80% interval0.7083
Coverage of the 95% interval0.8750

Forecast

hourForecast80% low80% high95% low95% high
505113.27112.33114.21111.83114.70
506115.29114.29116.30113.76116.83
507114.66113.60115.72113.04116.28
508115.53114.41116.65113.82117.24
509114.69113.52115.86112.90116.47
510115.37114.15116.59113.51117.24
511115.92114.65117.19113.98117.86
512115.71114.40117.03113.70117.72
513116.12114.76117.48114.03118.20
514115.10113.70116.51112.95117.25
515115.28113.83116.73113.07117.49
516114.39112.91115.88112.12116.67
517112.54111.01114.07110.20114.87
518108.98107.41110.55106.58111.38
519107.71106.10109.31105.25110.16
520104.12102.48105.76101.61106.63
521102.45100.77104.1399.886105.02
522101.1699.447102.8898.540103.78
523101.7299.967103.4799.041104.39
524102.88101.09104.66100.15105.60
525106.43104.61108.24103.65109.21
526110.42108.57112.27107.59113.25
527112.84110.96114.72109.96115.72
528115.96114.05117.88113.03118.89
  • One-step 95% intervals missed about 10% of future values in simulation (96 monthly values): they treat the seasonal part as known, so read them as a lower bound on the uncertainty.
The exact R script · R R version 4.5.1 (2025-06-13)
# MSTL forecast
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.mstl 1.0.1 · spec fa765bbb191a2bb2
# Dataset: f7_two_seasons (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
TIME <- "hour"
VALUE <- "load"
SERIES <- NULL
H <- 24
LEVELS <- as.numeric(c(80, 95))
SEASON <- NULL  # NULL = from the time steps (12 monthly, 4 quarterly, 7 daily …)
WINDOWS <- 1
STEP <- NULL  # NULL = the horizon
OFFSETS <- NULL  # the host's BacktestPlan: distance of each origin from the end of the series; NULL = windows and step
TRAIN_WINDOW <- NULL  # NULL = train on all values before each origin
TRAIN_START <- NULL  # rows before this time are left out (for example, before a structural break)
SEED <- 42
XREG <- character(0)
PARAMS <- list(
  periods = c(24, 168),
  adjusted_method = "ets",
  log_transform = FALSE
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/f7_two_seasons.parquet", col_select = unique(c(TIME, VALUE, SERIES, XREG))))
cs_check_finite_columns(df, c(TIME, VALUE, XREG))  # infinite values stop with CS_E_NOT_FINITE, naming the column
if (nrow(df) == 0) cs_error("CS_E_NO_ROWS")
warnings <- list()
td <- cs_ml_fc_to_days(df[[TIME]])
times_all <- td$values
TEMPORAL <- td$temporal
values_all <- suppressWarnings(as.numeric(df[[VALUE]]))
x_all <- if (length(XREG)) do.call(cbind, lapply(XREG, function(c) suppressWarnings(as.numeric(df[[c]])))) else NULL
n_early <- 0L
if (!is.null(TRAIN_START)) {
  cut <- cs_ml_fc_parse_time(TRAIN_START, TEMPORAL)
  early <- !is.na(times_all) & times_all < cut
  n_early <- sum(early)
  if (n_early > 0) {
    warnings <- c(warnings, sprintf("%d rows before %s were left out of training.", n_early, as.character(TRAIN_START)))
    times_all[early] <- NA
  }
}
keys_all <- if (!is.null(SERIES)) as.character(df[[SERIES]]) else rep(NA_character_, nrow(df))
dropped <- sum(is.na(times_all)) - n_early
if (dropped > 0) warnings <- c(warnings, sprintf("%d rows without a time were left out.", dropped))
series_keys <- if (!is.null(SERIES)) sort(unique(keys_all[!is.na(keys_all)]), method = "radix") else list(NULL)
if (!is.null(SERIES) && anyNA(keys_all)) warnings <- c(warnings, "Rows without a series name were left out.")
# Degenerate inputs stop with catalog codes, in the same order as the Python driver.
if (all(is.na(values_all))) cs_error("CS_E_ALL_MISSING", column = VALUE)
if (!any(!is.na(times_all) & !is.na(values_all))) cs_error("CS_E_NO_ROWS")
out <- cs_ml_out_dir("target/academy-parity/run-8142/forecast.mstl/two_seasons_ets/out-r")
extra_tables <- list()  # model blocks may add result tables (assign with <<-)
extra_assumptions <- list()  # … and assumption rows
current_series <- NULL
X_TRAIN <- NULL  # regressors while fit_forecast runs: rows × regressors, aligned with its y
X_FUTURE <- NULL  # … and h × regressors for the steps it forecasts
# Model blocks may set DIAG[[current_series, or "_"]] <<- list(resid = ..., fitdf = k, lags = L) from each fit (the final fit's
# entry is kept): the residuals their own check tests when that is not actual − fitted (GARCH: standardized; ARIMAX:
# the ARMA errors), the ARMA terms they were filtered with, and the Ljung–Box lags when the method's rule differs from
# min(2m, n/5). They go to forecast.parquet so the host's Residuals tab tests the same thing.
DIAG <- list()

# %% Model
# MSTL splits the series into a trend, one seasonal component per period and a remainder. The seasonally adjusted
# series is forecast on its own and each component's last cycle is added back (the Python script runs the same code).
periods_for <- function(m) {
  chosen <- as.integer(unlist(PARAMS$periods))
  chosen <- chosen[chosen >= 2]
  if (length(chosen)) chosen else if (m > 1) as.integer(m) else integer(0)
}
min_train <- function(m) {
  periods <- periods_for(m)
  if (length(periods)) 2L * max(periods) + 2L else 10L
}
prepare_series <- function(y, t, m, freq) {
  periods <- periods_for(m)
  if (!length(periods)) stop("This series has no seasonal cycle to remove: set the seasonal periods or use another forecaster.")
  periods
}
fit_forecast <- function(y, t, h, m, levels, spec) {
  cs_fcm_mstl_forecast(y, spec, h, levels, PARAMS$adjusted_method, isTRUE(PARAMS$log_transform), SEED)
}

# %% Backtests and forecasts
lv <- function(level) if (level == floor(level)) as.character(as.integer(level)) else gsub(".", "_", as.character(level), fixed = TRUE)
bt_rows <- list()
fc_rows <- list()
facts <- list()
labels <- list()
freq_label <- ""
freq_alias <- ""
seasons <- integer(0)
n_obs <- 0
n_origins <- 0
filled <- 0
residuals_first <- NULL
for (key in series_keys) {
  current_series <- key  # model blocks may read it (e.g. table titles)
  sel <- !is.na(times_all) & (if (!is.null(SERIES)) (!is.na(keys_all) & keys_all == key) else TRUE)
  t_raw <- times_all[sel]; y_raw <- values_all[sel]
  if (sum(!is.na(y_raw)) < 3) {  # too few values to read the time step from
    cs_error("CS_E_TOO_FEW_ROWS", what = if (is.null(key)) "Forecasting" else paste("Series", key), min = min_train(1) + 1, n = sum(!is.na(y_raw)))
  }
  x_later <- NULL
  if (length(XREG)) {  # rows after the last observed value carry known future regressors
    x_raw <- x_all[sel, , drop = FALSE]
    last_y <- max(t_raw[!is.na(y_raw)])
    later <- t_raw > last_y
    x_later <- x_raw[later, , drop = FALSE][order(t_raw[later]), , drop = FALSE]
    t_raw <- t_raw[!later]; y_raw <- y_raw[!later]; x_raw <- x_raw[!later, , drop = FALSE]
  }
  freq <- cs_ml_fc_detect_frequency(sort(t_raw), TEMPORAL)
  reg <- cs_ml_fc_regularize(t_raw, y_raw, freq)
  t <- reg$t; y <- reg$y
  x_grid <- if (length(XREG)) do.call(cbind, lapply(seq_len(ncol(x_raw)), function(j) cs_ml_fc_regularize(t_raw, x_raw[, j], freq)$y)) else NULL
  filled <- filled + reg$filled
  freq_label <- freq$label
  freq_alias <- cs_ml_fc_alias(freq$unit)
  m <- if (!is.null(SEASON)) as.integer(SEASON) else as.integer(freq$season)
  seasons <- c(seasons, m)
  n <- length(y)
  n_obs <- n_obs + n
  if (n < min_train(m) + 1) cs_error("CS_E_TOO_FEW_ROWS", what = if (is.null(key)) "Forecasting" else paste("Series", key), min = min_train(m) + 1, n = n)
  spec <- prepare_series(y, t, m, freq)
  step <- if (!is.null(STEP)) as.integer(STEP) else H
  if (!is.null(OFFSETS)) {
    origins <- cs_ml_fc_plan_origins(n, H, as.integer(OFFSETS), min_train(m))
    if (length(origins) < length(OFFSETS)) {
      warnings <- c(warnings, sprintf("%d of %d backtest origins were skipped for %s: too few values before them.", length(OFFSETS) - length(origins), length(OFFSETS), if (is.null(key)) VALUE else key))
    }
  } else {
    origins <- cs_ml_fc_backtest_origins(n, H, WINDOWS, step, min_train(m))
  }
  for (o in origins) {
    start <- if (!is.null(TRAIN_WINDOW)) max(1L, o - as.integer(TRAIN_WINDOW) + 1L) else 1L
    if (length(XREG)) {
      X_TRAIN <- x_grid[start:o, , drop = FALSE]
      X_FUTURE <- x_grid[(o + 1):(o + H), , drop = FALSE]
    }
    res <- tryCatch(fit_forecast(y[start:o], t[start:o], H, m, LEVELS, spec), error = function(e) e)
    if (inherits(res, "error")) {
      warnings <- c(warnings, sprintf("Backtest from %s failed: %s", cs_ml_fc_format_time(t[o], TEMPORAL), conditionMessage(res)))
      next
    }
    n_origins <- n_origins + 1
    scale <- cs_ml_fc_mase_scale(y[1:o], m)
    scale2 <- cs_ml_fc_rmsse_scale(y[1:o], m)
    lag <- if (m > 1 && o > m) m else 1  # the seasonal naive forecast from this origin (MASE's lag rule)
    for (k in seq_len(H)) {
      row <- list(series = if (is.null(key)) NA_character_ else key, origin = cs_ml_fc_format_time(t[o], TEMPORAL),
                  time = cs_ml_fc_format_time(t[o + k], TEMPORAL), h = k, actual = y[o + k],
                  mean = res$mean[k], scale = scale, scale2 = scale2, last = y[o],
                  snaive = y[o - lag + (k - 1) %% lag + 1])
      for (level in LEVELS) {
        row[[paste0("lo_", lv(level))]] <- res$lower[[as.character(level)]][k]
        row[[paste0("hi_", lv(level))]] <- res$upper[[as.character(level)]][k]
      }
      bt_rows[[length(bt_rows) + 1]] <- row
    }
  }
  if (length(XREG)) {
    X_TRAIN <- x_grid
    X_FUTURE <- cs_ml_fc_future_regressors(x_grid, x_later, H)
    if (nrow(x_later) < H) {
      warnings <- c(warnings, sprintf("Future values of %s are known for %d of %d steps; the last known values are held for the rest.", paste(XREG, collapse = ", "), nrow(x_later), H))
    }
  }
  final <- fit_forecast(y, t, H, m, LEVELS, spec)
  labels[[length(labels) + 1]] <- final$label
  for (name in names(final$facts)) facts[[if (is.null(SERIES)) name else sprintf("%s[%s]", name, key)]] <- final$facts[[name]]
  fitted <- final$fitted
  diag <- DIAG[[if (is.null(key)) "_" else key]]
  resid <- diag$resid
  if (is.null(residuals_first) && !is.null(resid)) {
    residuals_first <- as.numeric(resid)
  } else if (is.null(residuals_first) && !is.null(fitted)) {
    ok <- !is.na(fitted)
    residuals_first <- (y - fitted)[ok]
  }
  skey <- if (is.null(key)) NA_character_ else key
  for (i in seq_len(n)) {
    row <- list(series = skey, time = cs_ml_fc_format_time(t[i], TEMPORAL), t = t[i], kind = "actual", mean = y[i])
    if (!is.null(resid) && i > n - length(resid)) row$resid <- resid[i - (n - length(resid))]  # the last length(resid) times
    if (!is.null(diag$fitdf)) row$lb_fitdf <- as.numeric(diag$fitdf)
    if (!is.null(diag$lags)) row$lb_lags <- as.numeric(diag$lags)
    fc_rows[[length(fc_rows) + 1]] <- row
    if (!is.null(fitted) && !is.na(fitted[i])) {
      fc_rows[[length(fc_rows) + 1]] <- list(series = skey, time = cs_ml_fc_format_time(t[i], TEMPORAL), t = t[i], kind = "fitted", mean = fitted[i])
    }
  }
  future <- cs_ml_fc_future_times(t[n], freq, H)
  for (k in seq_len(H)) {
    row <- list(series = skey, time = cs_ml_fc_format_time(future[k], TEMPORAL), t = future[k], kind = "forecast", mean = final$mean[k])
    for (level in LEVELS) {
      row[[paste0("lo_", lv(level))]] <- final$lower[[as.character(level)]][k]
      row[[paste0("hi_", lv(level))]] <- final$upper[[as.character(level)]][k]
    }
    fc_rows[[length(fc_rows) + 1]] <- row
  }
}
if (filled > 0) warnings <- c(warnings, sprintf("%d missing time steps or values were filled by linear interpolation.", filled))

as_frame <- function(rows) {
  cols <- unique(unlist(lapply(rows, names)))
  as.data.frame(stats::setNames(lapply(cols, function(cn) {
    v <- lapply(rows, function(r) if (is.null(r[[cn]])) NA else r[[cn]])
    unlist(v)
  }), cols), stringsAsFactors = FALSE, check.names = FALSE)
}

# %% Accuracy
bt <- if (length(bt_rows)) as_frame(bt_rows) else data.frame()
accuracy <- if (nrow(bt)) cs_ml_fc_accuracy(bt, LEVELS) else list()
fc_df <- as_frame(fc_rows)
forecasts <- fc_df[fc_df$kind == "forecast", , drop = FALSE]
weights <- seq_len(nrow(forecasts))
top <- if (length(LEVELS)) lv(max(LEVELS)) else NULL
wsum <- function(xs) sum(weights * xs) / sum(weights)
values <- list(
  n_series = length(series_keys), n_obs = n_obs, horizon = H, season = seasons[1], n_origins = n_origins,
  filled = filled, fc_check = wsum(forecasts$mean),
  model_label = if (length(series_keys) == 1) labels[[1]] else sprintf("%d series, one model each", length(series_keys)),
  freq_label = freq_label, frequency = freq_alias
)
if (!is.null(top)) {
  values$fc_lo_check <- wsum(forecasts[[paste0("lo_", top)]])
  values$fc_hi_check <- wsum(forecasts[[paste0("hi_", top)]])
}
for (k in names(accuracy)) values[[sprintf("bt[%s]", k)]] <- accuracy[[k]]
values <- c(values, facts)

nanoparquet::write_parquet(fc_df, file.path(out, "forecast.parquet"))
artifacts <- list(list(key = "forecast", path = file.path(out, "forecast.parquet"), format = "parquet"))
if (nrow(bt)) {
  nanoparquet::write_parquet(bt, file.path(out, "backtest.parquet"))
  artifacts[[2]] <- list(key = "backtest", path = file.path(out, "backtest.parquet"), format = "parquet")
}

# %% Charts
charts <- list()
shown <- if (!is.null(SERIES)) utils::head(series_keys, 8) else NULL
fan <- fc_df[fc_df$kind != "fitted" & (if (!is.null(SERIES)) fc_df$series %in% shown else TRUE), , drop = FALSE]
roles <- list(
  time = cs_col(TIME, fan$time, kind = if (TEMPORAL) "temporal" else "numeric"),
  value = cs_col(VALUE, fan$mean, kind = "numeric"),
  kind = cs_col("kind", fan$kind, kind = "categorical", levels = c("actual", "forecast"))
)
for (level in c(80, 95)) {
  if (level %in% LEVELS) {
    roles[[paste0("lo_", lv(level))]] <- cs_col(paste0("lo_", lv(level)), fan[[paste0("lo_", lv(level))]], kind = "numeric")
    roles[[paste0("hi_", lv(level))]] <- cs_col(paste0("hi_", lv(level)), fan[[paste0("hi_", lv(level))]], kind = "numeric")
  }
}
if (!is.null(SERIES)) roles$series <- cs_col(SERIES, fan$series, kind = "categorical", levels = shown)
charts[[1]] <- cs_chart("forecast", "forecast-fan", sprintf("Forecast of %s", VALUE), roles)
if (nrow(bt)) {
  charts[[length(charts) + 1]] <- cs_chart("backtest", "backtest-errors", "Backtest errors by horizon", list(
    h = cs_col("horizon", bt$h, kind = "numeric"),
    error = cs_col("error", bt$actual - bt$mean, kind = "numeric"),
    origin = cs_col("origin", bt$origin, kind = "categorical")
  ))
}
if (length(residuals_first) > 4) {
  lags <- min(max(2 * seasons[1], 10), length(residuals_first) - 1, 48)
  r_acf <- cs_ml_fc_acf(residuals_first, lags)
  bound <- 1.959963984540054 / sqrt(length(residuals_first))
  charts[[length(charts) + 1]] <- cs_chart("acf", "acf-plot", "Residual autocorrelation", list(
    lag = cs_col("lag", seq_len(lags), kind = "numeric"),
    acf = cs_col("ACF", r_acf, kind = "numeric"),
    bound = cs_col("bound", rep(bound, lags), kind = "numeric")
  ))
}

warnings <- c(warnings, "One-step 95% intervals missed about 10% of future values in simulation (96 monthly values): they treat the seasonal part as known, so read them as a lower bound on the uncertainty.")
# %% Residual check
check0 <- cs_fcm_residual_check(residuals_first, seasons[1])
if (!is.null(check0)) {
  values$lb_p <- check0$p
  extra_assumptions[[length(extra_assumptions) + 1]] <- cs_fcm_residual_row(check0, "Dynamics remain beyond the seasonal cycles and the adjusted series' model: try TBATS with ARMA errors.", if (!is.null(SERIES)) series_keys[1])
}
# %% Result
show <- intersect(c("mae", "rmse", "mape", "smape", "mase", "wape"), names(accuracy))
tables <- list()
if (length(accuracy)) {
  rows <- lapply(show, function(k) list(metric = if (k == "smape") "sMAPE" else toupper(k), value = accuracy[[k]]))
  for (level in LEVELS) {
    ck <- paste0("coverage_", lv(level))
    if (!is.null(accuracy[[ck]])) rows[[length(rows) + 1]] <- list(metric = sprintf("Coverage of the %s%% interval", lv(level)), value = accuracy[[ck]])
  }
  tables[[1]] <- list(key = "accuracy", title = sprintf("Backtest accuracy (%d origin%s, horizon %d)", n_origins, if (n_origins != 1) "s" else "", H),
                      columns = list(list(key = "metric", label = "Metric"), list(key = "value", label = "Value", type = "number")), rows = rows)
}
fc_cols <- c(if (!is.null(SERIES)) list(list(key = "series", label = "Series")),
             list(list(key = "time", label = TIME), list(key = "mean", label = "Forecast", type = "number")))
for (level in LEVELS) {
  fc_cols <- c(fc_cols, list(list(key = paste0("lo_", lv(level)), label = sprintf("%s%% low", lv(level)), type = "number"),
                             list(key = paste0("hi_", lv(level)), label = sprintf("%s%% high", lv(level)), type = "number")))
}
tables <- c(tables, extra_tables)
keep <- setdiff(names(forecasts), c("t", "kind", if (is.null(SERIES)) "series"))
tables[[length(tables) + 1]] <- list(key = "forecast", title = "Forecast", columns = fc_cols,
  rows = lapply(seq_len(min(200, nrow(forecasts))), function(i) as.list(forecasts[i, keep, drop = FALSE])))
summary <- sprintf("%s: %d-step forecasts of %s (%s data, %d observations).", values$model_label, H, VALUE, freq_label, n_obs)
if (!is.null(accuracy$mae)) summary <- paste0(summary, sprintf(" Backtest MAE %s over %d origin%s.", format(signif(accuracy$mae, 3)), n_origins, if (n_origins != 1) "s" else ""))
cs_publish(list(
  title = "MSTL forecast",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n_obs,
  summary = summary,
  statistics = lapply(utils::head(show, 3), function(k) list(key = k, label = toupper(k), value = accuracy[[k]])),
  tables = tables,
  values = values,
  assumptions = extra_assumptions,
  warnings = warnings,
  notes = list(),
  charts = charts,
  artifacts = artifacts
))
Python

MSTL(24, 168) + ETS(A,N,N): 24-step forecasts of load (evenly spaced data, 504 observations). Backtest MAE 0.95 over 1 origin.

MAE
0.9498
RMSE
1.193
MAPE
0.0089

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Residuals look uncorrelated — Ljung–Box at 10 lags: p = 0.000. Dynamics remain beyond the seasonal cycles and the adjusted series' model: try TBATS with ARMA errors.

Backtest accuracy (1 origin, horizon 24)

MetricValue
MAE0.9498
RMSE1.193
MAPE0.0089
sMAPE0.0089
MASE0.5405
WAPE0.0088
Coverage of the 80% interval0.7083
Coverage of the 95% interval0.8750

Forecast

hourForecast80% low80% high95% low95% high
505113.27112.33114.21111.83114.70
506115.29114.29116.30113.76116.83
507114.66113.60115.72113.04116.28
508115.53114.41116.65113.82117.24
509114.69113.52115.86112.90116.47
510115.37114.15116.59113.51117.24
511115.92114.65117.19113.98117.86
512115.71114.40117.03113.70117.72
513116.12114.76117.48114.03118.20
514115.10113.70116.51112.95117.25
515115.28113.83116.73113.07117.49
516114.39112.91115.88112.12116.67
517112.54111.01114.07110.20114.87
518108.98107.41110.55106.58111.38
519107.71106.10109.31105.25110.16
520104.12102.48105.76101.61106.63
521102.45100.77104.1399.886105.02
522101.1699.447102.8898.540103.78
523101.7299.967103.4799.041104.39
524102.88101.09104.66100.15105.60
525106.43104.61108.24103.65109.21
526110.42108.57112.27107.59113.25
527112.84110.96114.72109.96115.72
528115.96114.05117.88113.03118.89
  • One-step 95% intervals missed about 10% of future values in simulation (96 monthly values): they treat the seasonal part as known, so read them as a lower bound on the uncertainty.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# MSTL forecast
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.mstl 1.0.1 · spec fa765bbb191a2bb2
# Dataset: f7_two_seasons (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import forecast as fc
from codesplash.ml import forecast_models as fcm

# %% Data
TIME = "hour"
VALUE = "load"
SERIES = None
H = 24
LEVELS = [float(v) for v in [80, 95]]
SEASON = None  # None = from the time steps (12 monthly, 4 quarterly, 7 daily …)
WINDOWS = 1
STEP = None  # None = the horizon
OFFSETS = None  # the host's BacktestPlan: distance of each origin from the end of the series; None = windows and step
TRAIN_WINDOW = None  # None = train on all values before each origin
TRAIN_START = None  # rows before this time are left out (for example, before a structural break)
SEED = 42
XREG = []
PARAMS = {
    "periods": [24, 168],
    "adjusted_method": "ets",
    "log_transform": False,
}
df = pd.read_parquet("tests/parity/fixtures/f7_two_seasons.parquet", columns=list(dict.fromkeys([c for c in (TIME, VALUE, SERIES) if c] + list(XREG))))
cs.check_finite_columns(df, [TIME, VALUE] + list(XREG))  # infinite values stop with CS_E_NOT_FINITE, naming the column
if len(df) == 0:
    cs.cs_error("CS_E_NO_ROWS")
warnings = []
times_all, TEMPORAL = fc.to_days(df[TIME])
values_all = pd.to_numeric(df[VALUE], errors="coerce").to_numpy(dtype=np.float64)
x_all = np.column_stack([pd.to_numeric(df[c], errors="coerce").to_numpy(dtype=np.float64) for c in XREG]) if XREG else None
if TRAIN_START is not None:
    cut = fc.parse_time(TRAIN_START, TEMPORAL)
    early = np.nan_to_num(times_all, nan=np.inf) < cut
    if early.any():
        warnings.append(f"{int(early.sum())} rows before {TRAIN_START} were left out of training.")
        times_all = np.where(early, np.nan, times_all)
keys_all = df[SERIES].astype("object").to_numpy() if SERIES else np.array([None] * len(df), dtype=object)
dropped = int(np.isnan(times_all).sum()) - (int(early.sum()) if TRAIN_START is not None else 0)
if dropped:
    warnings.append(f"{dropped} rows without a time were left out.")
series_keys = sorted({str(k) for k in keys_all if not pd.isna(k)}) if SERIES else [None]  # None, NaN, pd.NA: no name
if SERIES and any(pd.isna(k) for k in keys_all):
    warnings.append("Rows without a series name were left out.")
# Degenerate inputs stop with catalog codes, in the same order as the R driver.
if bool(np.isnan(values_all).all()):
    cs.cs_error("CS_E_ALL_MISSING", column=VALUE)
if not bool((~np.isnan(times_all) & ~np.isnan(values_all)).any()):
    cs.cs_error("CS_E_NO_ROWS")
out = csml.out_dir("target/academy-parity/run-8142/forecast.mstl/two_seasons_ets/out-python")
extra_tables = []  # model blocks may add result tables (e.g. automatic selection)
extra_assumptions = []  # … and assumption rows
current_series = None
X_TRAIN = None  # regressors while fit_forecast runs: rows × regressors, aligned with its y
X_FUTURE = None  # … and h × regressors for the steps it forecasts
# Model blocks may set DIAG[current_series] = {"resid": [...], "fitdf": k, "lags": L} from each fit (the final fit's
# entry is kept): the residuals their own check tests when that is not actual − fitted (GARCH: standardized; ARIMAX:
# the ARMA errors), the ARMA terms they were filtered with, and the Ljung–Box lags when the method's rule differs from
# min(2m, n/5). They go to forecast.parquet so the host's Residuals tab tests the same thing.
DIAG = {}


# %% Model
# MSTL splits the series into a trend, one seasonal component per period and a remainder. The seasonally adjusted
# series is forecast on its own and each component's last cycle is added back (the R script runs the same code).


def periods_for(m):
    chosen = [int(p) for p in (PARAMS["periods"] or []) if int(p) >= 2]
    return chosen or ([m] if m > 1 else [])


def min_train(m):
    periods = periods_for(m)
    return 2 * max(periods) + 2 if periods else 10


def prepare_series(y, t, m, freq):
    periods = periods_for(m)
    if not periods:
        raise ValueError("This series has no seasonal cycle to remove: set the seasonal periods or use another forecaster.")
    return periods


def fit_forecast(y, t, h, m, levels, spec):
    return fcm.mstl_forecast(y, spec, h, levels, PARAMS["adjusted_method"], bool(PARAMS["log_transform"]), SEED)


# %% Backtests and forecasts
def lv(level):
    return str(int(level)) if float(level).is_integer() else str(level).replace(".", "_")


bt_rows = []
fc_rows = []
facts = {}
labels = {}
freq_label = ""
freq_alias = ""
seasons = []
n_obs = 0
n_origins = 0
filled = 0
residuals_first = None
for key in series_keys:
    current_series = key  # model blocks may read it (e.g. table titles)
    sel = ~np.isnan(times_all) & ((keys_all.astype(str) == key) if SERIES else True)
    t_raw, y_raw = times_all[sel], values_all[sel]
    if int(np.sum(~np.isnan(y_raw))) < 3:  # too few values to read the time step from
        cs.cs_error("CS_E_TOO_FEW_ROWS", what=("Forecasting" if key is None else f"Series {key}"), min=min_train(1) + 1, n=int(np.sum(~np.isnan(y_raw))))
    x_later = None
    if XREG:  # rows after the last observed value carry known future regressors
        x_raw = x_all[sel]
        last_y = np.nanmax(np.where(np.isnan(y_raw), np.nan, t_raw))
        later = t_raw > last_y
        order_later = np.argsort(t_raw[later], kind="stable")
        x_later = x_raw[later][order_later]
        t_raw, y_raw, x_raw = t_raw[~later], y_raw[~later], x_raw[~later]
    freq = fc.detect_frequency(np.sort(t_raw), TEMPORAL)
    t, y, nfill = fc.regularize(t_raw, y_raw, freq)
    x_grid = np.column_stack([fc.regularize(t_raw, x_raw[:, j], freq)[1] for j in range(x_raw.shape[1])]) if XREG else None
    filled += nfill
    freq_label = freq["label"]
    freq_alias = fc.ALIASES.get(freq["unit"], "")
    m = int(SEASON) if SEASON else int(freq["season"])
    seasons.append(m)
    y = [float(v) for v in y]
    n = len(y)
    n_obs += n
    if n < min_train(m) + 1:
        cs.cs_error("CS_E_TOO_FEW_ROWS", what=("Forecasting" if key is None else f"Series {key}"), min=min_train(m) + 1, n=n)
    spec = prepare_series(y, t, m, freq)
    step = int(STEP) if STEP else H
    if OFFSETS is not None:
        origins = fc.plan_origins(n, H, [int(v) for v in OFFSETS], min_train(m))
        if len(origins) < len(OFFSETS):
            warnings.append(f"{len(OFFSETS) - len(origins)} of {len(OFFSETS)} backtest origins were skipped for {key or VALUE}: too few values before them.")
    else:
        origins = fc.backtest_origins(n, H, WINDOWS, step, min_train(m))
    for o in origins:
        start = max(0, o - int(TRAIN_WINDOW)) if TRAIN_WINDOW else 0
        if XREG:
            X_TRAIN, X_FUTURE = x_grid[start:o], x_grid[o:o + H]
        try:
            res = fit_forecast(y[start:o], t[start:o], H, m, LEVELS, spec)
        except Exception as e:  # a failed origin is skipped, not fatal
            warnings.append(f"Backtest from {fc.format_time(t[o - 1], TEMPORAL)} failed: {e}")
            continue
        n_origins += 1
        scale = fc.mase_scale(y[:o], m)
        scale2 = fc.rmsse_scale(y[:o], m)
        lag = m if (m > 1 and o > m) else 1  # the seasonal naive forecast from this origin (MASE's lag rule)
        for k in range(H):
            row = {
                "series": key,
                "origin": fc.format_time(t[o - 1], TEMPORAL),
                "time": fc.format_time(t[o + k], TEMPORAL),
                "h": k + 1,
                "actual": y[o + k],
                "mean": float(res["mean"][k]),
                "scale": scale,
                "scale2": scale2,
                "last": y[o - 1],
                "snaive": y[o - lag + k % lag],
            }
            for level in LEVELS:
                row[f"lo_{lv(level)}"] = float(res["lower"][level][k])
                row[f"hi_{lv(level)}"] = float(res["upper"][level][k])
            bt_rows.append(row)
    if XREG:
        X_TRAIN = x_grid
        X_FUTURE = fc.future_regressors(x_grid, x_later, H)
        if len(x_later) < H:
            warnings.append(f"Future values of {', '.join(XREG)} are known for {len(x_later)} of {H} steps; the last known values are held for the rest.")
    final = fit_forecast(y, t, H, m, LEVELS, spec)
    labels[key] = final["label"]
    for name, value in final["facts"].items():
        facts[name if not SERIES else f"{name}[{key}]"] = value
    fitted = final.get("fitted")
    diag = DIAG.get(key) or {}
    resid = diag.get("resid")
    if residuals_first is None and resid is not None:
        residuals_first = [float(v) for v in resid]
    elif residuals_first is None and fitted is not None:
        residuals_first = [y[i] - fitted[i] for i in range(n) if fitted[i] is not None and not math.isnan(fitted[i])]
    for i in range(n):
        row = {"series": key, "time": fc.format_time(t[i], TEMPORAL), "t": float(t[i]), "kind": "actual", "mean": y[i]}
        if resid is not None and i >= n - len(resid):  # the last len(resid) times (differencing drops early ones)
            row["resid"] = float(resid[i - (n - len(resid))])
        if "fitdf" in diag:
            row["lb_fitdf"] = float(diag["fitdf"])
        if "lags" in diag:
            row["lb_lags"] = float(diag["lags"])
        fc_rows.append(row)
        if fitted is not None and not math.isnan(fitted[i]):
            fc_rows.append({"series": key, "time": fc.format_time(t[i], TEMPORAL), "t": float(t[i]), "kind": "fitted", "mean": float(fitted[i])})
    future = fc.future_times(t[-1], freq, H)
    for k in range(H):
        row = {"series": key, "time": fc.format_time(future[k], TEMPORAL), "t": float(future[k]), "kind": "forecast", "mean": float(final["mean"][k])}
        for level in LEVELS:
            row[f"lo_{lv(level)}"] = float(final["lower"][level][k])
            row[f"hi_{lv(level)}"] = float(final["upper"][level][k])
        fc_rows.append(row)
if filled:
    warnings.append(f"{filled} missing time steps or values were filled by linear interpolation.")

# %% Accuracy
accuracy = fc.accuracy(bt_rows, LEVELS)
forecasts = [r for r in fc_rows if r["kind"] == "forecast"]
weights = [i + 1.0 for i in range(len(forecasts))]
top = lv(max(LEVELS)) if LEVELS else None


def wsum(xs):
    return fc._sum([weights[i] * xs[i] for i in range(len(xs))]) / fc._sum(weights)


values = {
    "n_series": len(series_keys),
    "n_obs": n_obs,
    "horizon": H,
    "season": seasons[0],
    "n_origins": n_origins,
    "filled": filled,
    "fc_check": wsum([r["mean"] for r in forecasts]),
    "model_label": labels[series_keys[0]] if len(series_keys) == 1 else f"{len(series_keys)} series, one model each",
    "freq_label": freq_label,
    "frequency": freq_alias,
}
if top:
    values["fc_lo_check"] = wsum([r[f"lo_{top}"] for r in forecasts])
    values["fc_hi_check"] = wsum([r[f"hi_{top}"] for r in forecasts])
for k, v in accuracy.items():
    values[f"bt[{k}]"] = v
values.update(facts)

pd.DataFrame(fc_rows).to_parquet(os.path.join(out, "forecast.parquet"), index=False)
artifacts = [{"key": "forecast", "path": os.path.join(out, "forecast.parquet"), "format": "parquet"}]
if bt_rows:
    pd.DataFrame(bt_rows).to_parquet(os.path.join(out, "backtest.parquet"), index=False)
    artifacts.append({"key": "backtest", "path": os.path.join(out, "backtest.parquet"), "format": "parquet"})

# %% Charts
charts = []
shown = series_keys[:8]
fan = [r for r in fc_rows if r["series"] in shown and r["kind"] != "fitted"]
kind = "temporal" if TEMPORAL else "numeric"
roles = {
    "time": cs.col(TIME, [r["time"] for r in fan], kind=kind),
    "value": cs.col(VALUE, [r["mean"] for r in fan], kind="numeric"),
    "kind": cs.col("kind", [r["kind"] for r in fan], kind="categorical", levels=["actual", "forecast"]),
}
for level in (80.0, 95.0):
    if level in LEVELS:
        roles[f"lo_{lv(level)}"] = cs.col(f"lo_{lv(level)}", [r.get(f"lo_{lv(level)}") for r in fan], kind="numeric")
        roles[f"hi_{lv(level)}"] = cs.col(f"hi_{lv(level)}", [r.get(f"hi_{lv(level)}") for r in fan], kind="numeric")
if SERIES:
    roles["series"] = cs.col(SERIES, [r["series"] for r in fan], kind="categorical", levels=shown)
charts.append(cs.chart("forecast", "forecast-fan", f"Forecast of {VALUE}", roles))
if bt_rows:
    charts.append(
        cs.chart(
            "backtest",
            "backtest-errors",
            "Backtest errors by horizon",
            {
                "h": cs.col("horizon", [r["h"] for r in bt_rows], kind="numeric"),
                "error": cs.col("error", [r["actual"] - r["mean"] for r in bt_rows], kind="numeric"),
                "origin": cs.col("origin", [r["origin"] for r in bt_rows], kind="categorical"),
            },
        )
    )
if residuals_first and len(residuals_first) > 4:
    lags = min(max(2 * seasons[0], 10), len(residuals_first) - 1, 48)
    r_acf = fc.acf(residuals_first, lags)
    bound = 1.959963984540054 / math.sqrt(len(residuals_first))
    charts.append(
        cs.chart(
            "acf",
            "acf-plot",
            "Residual autocorrelation",
            {
                "lag": cs.col("lag", list(range(1, lags + 1)), kind="numeric"),
                "acf": cs.col("ACF", r_acf, kind="numeric"),
                "bound": cs.col("bound", [bound] * lags, kind="numeric"),
            },
        )
    )

warnings.append("One-step 95% intervals missed about 10% of future values in simulation (96 monthly values): they treat the seasonal part as known, so read them as a lower bound on the uncertainty.")
# %% Residual check
check0 = fcm.residual_check(residuals_first, seasons[0])
if check0 is not None:
    values["lb_p"] = check0["p"]
    extra_assumptions.append(fcm.residual_row(check0, "Dynamics remain beyond the seasonal cycles and the adjusted series' model: try TBATS with ARMA errors.", series_keys[0]))
# %% Result
show = [m for m in ("mae", "rmse", "mape", "smape", "mase", "wape") if m in accuracy]
tables = []
if accuracy:
    tables.append(
        {
            "key": "accuracy",
            "title": f"Backtest accuracy ({n_origins} origin{'s' if n_origins != 1 else ''}, horizon {H})",
            "columns": [{"key": "metric", "label": "Metric"}, {"key": "value", "label": "Value", "type": "number"}],
            "rows": [{"metric": k.upper() if k != "smape" else "sMAPE", "value": accuracy[k]} for k in show]
            + [{"metric": f"Coverage of the {lv(level)}% interval", "value": accuracy.get(f"coverage_{lv(level)}")} for level in LEVELS if f"coverage_{lv(level)}" in accuracy],
        }
    )
tables.extend(extra_tables)
tables.append(
    {
        "key": "forecast",
        "title": "Forecast",
        "columns": ([{"key": "series", "label": "Series"}] if SERIES else [])
        + [{"key": "time", "label": TIME}, {"key": "mean", "label": "Forecast", "type": "number"}]
        + [c for level in LEVELS for c in ({"key": f"lo_{lv(level)}", "label": f"{lv(level)}% low", "type": "number"}, {"key": f"hi_{lv(level)}", "label": f"{lv(level)}% high", "type": "number"})],
        "rows": [{k: v for k, v in r.items() if k not in ("t", "kind") and (SERIES or k != "series")} for r in forecasts[:200]],
    }
)
summary = f"{values['model_label']}: {H}-step forecasts of {VALUE} ({freq_label} data, {n_obs} observations)."
if "mae" in accuracy:
    summary += f" Backtest MAE {accuracy['mae']:.3g} over {n_origins} origin{'s' if n_origins != 1 else ''}."
cs.publish(
    {
        "title": "MSTL forecast",
        "engine": cs.engine_info("statsmodels", "numpy", "numpy", "pandas"),
        "n": n_obs,
        "summary": summary,
        "statistics": [{"key": k, "label": k.upper(), "value": accuracy[k]} for k in show[:3]],
        "tables": tables,
        "values": values,
        "assumptions": extra_assumptions,
        "warnings": warnings,
        "notes": [],
        "charts": charts,
        "artifacts": artifacts,
    }
)

MSTL(24, 168) + ETS(A,N,N) finds strengths of 0.98 at 24 hours and 0.95 at 168.

Forecast the adjusted series with picks the model for the remainder, and the seasonal parts repeat on top. Its residual check gives a tiny p-value: p < .001. What would you try next, knowing a pattern remains?

Work on logs suits swings that grow with the level. On AirPassengers, that gives MSTL(12) + ETS(A,A,N) on logs.

03

TBATS

Read

TBATS is short for its parts: Trigonometric seasonality, Box–Cox, ARMA errors, Trend, Seasonal. Its label reads the same way.

  • TBATS(-, {0,0}, -, {<24,2>, <168,1>}): two seasons, with 2 and 1 harmonics.
  • TBATS(0.000, {0,0}, 1, {<12,5>}): AirPassengers, with a Box–Cox λ\lambda near 0, or logs, and ARMA errors.

It takes longer to fit, and it searches its own options by AIC.

04

Non-integer seasons

Predict

Predict first

Weekly data have a yearly cycle of about 52.1852.18 weeks. Which method can represent that period directly?

ETS(A,N,A) with m = 52Seasonal naive, m = 52TBATS with a period of about 52.18
Reveal

TBATS. Harmonics don't need a whole number of steps per cycle. This simulated series has a period of 24.524.5, and it gets TBATS(-, {0,0}, 0.994, {<24.5,1>}).

05

Prophet

Read

Prophet fits a piecewise-linear trend with Potential changepoints, plus seasonal terms and holidays. It's designed for daily business data with gaps, and it needs little tuning.

On AirPassengers with multiplicative seasonality, it uses 25 potential changepoints. Its point forecasts backtest well here, with a MASE of 0.65. But check 80% coverage: it comes out at 33%. Don't trust its default intervals without checking them.

06

Lag features

Predict

Predict first

You train a boosted tree on lags of the raw values of a rising series. What does its forecast do above anything it saw in training?

They follow it upwardThey stay flat at about the highest level seenThey fall back to the mean
Reveal

It stays flat at about the highest level seen. Trees can't predict beyond the range of their training targets. That's why Model the defaults to Changes: the model learns the step, and the host adds it up. Here, LightGBM on lags of changes uses 7 features.

07

Choosing lags

Reflect

Lags and Rolling-mean windows decide what the model sees. Include the season length. Leaving out lag 12 on monthly data means the model can't see last year.

A ridge model on seasonal changes, Ridge on lags of seasonal changes, uses 6 features, and it's fast. Why might ridge beat a boosted tree on a short series?

These features use only past values. Could any of your candidate features use information that wouldn't be known at forecast time?

08

Recurrent networks

Read

A GRU or LSTM reads a window of past values, keeps a memory, and predicts the next change. This monthly model uses a window of 12, trained for 150 epochs, to a final loss of 0.10.

A low training loss isn't evidence of a good forecast. With 144 points and many weights, networks need the backtest more than other methods do. Check it, and compare it with seasonal naive, before you spend any more time.

09

Compare honestly

In the app

The same backtest applies to all of these. In Compare methods, use a common set of windows.

Which would you pick if a simple method came close to the best: the best score, or the simpler model? What does each cost to maintain?

10

Check: several seasons

Checkpoint

Check yourself

A forecast needs daily and weekly seasonality, and you want something fast and easy to explain. Which should you try first?

Show the answer

Answer: a

MSTL is quick, and you can inspect each season.

Check yourself

What does Work on logs do for MSTL?

Show the answer

Answer: a

Logs turn "percent of level" into "fixed amount", which additive decomposition can handle.

Check yourself

An MSTL fit shows a tiny Ljung–Box p-value on its residuals. What does that mean?

Show the answer

Answer: b

Pattern left in the residuals means there's something for another model to pick up.

Check yourself

What does the "T" in TBATS give you that a seasonal ARIMA doesn't?

Show the answer

Answer: a

Harmonics need few parameters even for a very long period.

Check yourself

In TBATS(-, {0,0}, -, {<24,2>, <168,1>}), how many harmonics does the 24-hour season have?

Show the answer

Answer: 2

<24,2> means a period of 24 with 2 harmonics.

Check yourself

A TBATS label starts with 0.000 in place of "-". What does that mean?

Show the answer

Answer: a

The first slot is the Box–Cox parameter, and "-" means none is used.

Check yourself

Prophet's point forecast backtests well, but its 80% interval covers only a third of actuals. What should you do?

Show the answer

Answer: b

Point accuracy and interval calibration are separate questions.

Check yourself

What does Prophet's Trend flexibility control?

Show the answer

Answer: a

Higher values let the trend bend more, which risks overfitting.

Check yourself

When is Prophet a reasonable first try?

Show the answer

Answer: a

It was built for that setting. Compare it with the baselines all the same.

11

Check: learners

Checkpoint

Check yourself

A boosted tree on raw lags gives a flat forecast above the training range. What's the standard fix?

Show the answer

Answer: b

The model then learns the step, and adding those steps can carry the forecast beyond past levels.

Check yourself

You add a 7-day rolling mean feature. How should it be computed at forecast time?

Show the answer

Answer: a

A centered or future-including window is leakage. It flatters the backtest, and you can't reproduce it in production.

Check yourself

For monthly data with a yearly cycle, which lag is the most important to include?

Show the answer

Answer: b

Lag 12 lets the model see the same month last year.

Check yourself

A GRU's final training loss is very low, but its backtest MASE is above 1. Which do you believe?

Show the answer

Answer: b

A backtest scores what was unseen. A training loss can fall by memorizing the past.

Check yourself

Which situation favors a recurrent network?

Show the answer

Answer: a

Deep models need data. On a single short series, simple methods usually do as well or better.

Check yourself

Why does Model the default to changes for an RNN, as well as for lag models?

Show the answer

Answer: a

Scale and trend are easier to handle when you model differences.

12

In code

Read
Python
import pandas as pd
from statsmodels.tsa.seasonal import MSTL

y = pd.read_csv("load.csv")["load"]
fit = MSTL(y, periods=[24, 168]).fit()
print(fit.seasonal.head(), fit.trend.tail())
R
# install.packages("forecast")
library(forecast)
y <- msts(read.csv("load.csv")$load, seasonal.periods = c(24, 168))
forecast(mstl(y), h = 24)
forecast(tbats(y), h = 24)
13

Recap

Recap
  • MSTL, TBATS and Prophet handle several seasons, and TBATS handles non-integer periods too.
  • Trees can't extrapolate levels, so model changes.
  • A low training loss isn't evidence of a good forecast. Backtests decide.
  • Check interval coverage separately from point accuracy.

Concepts in this lesson