Exponential smoothing and Theta
Read the ETS naming scheme, see what the smoothing parameters mean, damp a trend you don't trust, and meet Theta, a simple method that has done well in competitions.
What runs in CodeSplash
- Exponential smoothing (ETS) Verified in Python and R
- Theta method Verified in Python and R
You will be able to
- Read an ETS label and say what each of its letters means
- Interpret smoothing parameters, and say why damping helps
- Say what Theta does, and compare methods with a backtest
Read first
Weighted memory
ReadSimple exponential smoothing forecasts with a level that updates after each value:
near 1 means the level follows the latest values, like the naive rule. near 0 means long memory, like the mean. This one parameter spans the two baselines.
On the Nile's flow, = 0.25 in the model ETS(A,N,N). Old years still count a lot.
Read a label
PredictPredict first
The name ETS comes from Error, Trend and Season. Each letter is N (none), A (additive), M (multiplicative), or Ad (additive damped).
What does ETS(A,Ad,A) mean?
Reveal
Additive errors, additive damped trend, additive season. This one, fit to AirPassengers, has = 0.96. Each future step's trend shrinks by that factor.
What the parameters say
In the appHere, ETS chooses its own form by AICc on quarterly UK gas consumption:
ETS(M,A,M): 8-step forecasts of gas (quarterly data, 108 observations). Backtest MAE 41.7 over 2 origins.
- MAE
- 41.742
- RMSE
- 57.712
- MAPE
- 0.0699
Plots
View data
| hi_80 | hi_95 | kind | lo_80 | lo_95 | quarter | gas |
|---|---|---|---|---|---|---|
| — | — | actual | — | — | −315,619,200,000 | 160.10 |
| — | — | actual | — | — | −307,756,800,000 | 129.70 |
| — | — | actual | — | — | −299,894,400,000 | 84.800 |
| — | — | actual | — | — | −291,945,600,000 | 120.10 |
| — | — | actual | — | — | −283,996,800,000 | 160.10 |
| — | — | actual | — | — | −276,220,800,000 | 124.90 |
| — | — | actual | — | — | −268,358,400,000 | 84.800 |
| — | — | actual | — | — | −260,409,600,000 | 116.90 |
| — | — | actual | — | — | −252,460,800,000 | 169.70 |
| — | — | actual | — | — | −244,684,800,000 | 140.90 |
| — | — | actual | — | — | −236,822,400,000 | 89.700 |
| — | — | actual | — | — | −228,873,600,000 | 123.30 |
| — | — | actual | — | — | −220,924,800,000 | 187.30 |
| — | — | actual | — | — | −213,148,800,000 | 144.10 |
| — | — | actual | — | — | −205,286,400,000 | 92.900 |
| — | — | actual | — | — | −197,337,600,000 | 120.10 |
| — | — | actual | — | — | −189,388,800,000 | 176.10 |
| — | — | actual | — | — | −181,526,400,000 | 147.30 |
| — | — | actual | — | — | −173,664,000,000 | 89.700 |
| — | — | actual | — | — | −165,715,200,000 | 123.30 |
| — | — | actual | — | — | −157,766,400,000 | 185.70 |
| — | — | actual | — | — | −149,990,400,000 | 155.30 |
| — | — | actual | — | — | −142,128,000,000 | 99.300 |
| — | — | actual | — | — | −134,179,200,000 | 131.30 |
| — | — | actual | — | — | −126,230,400,000 | 200.10 |
| — | — | actual | — | — | −118,454,400,000 | 161.70 |
| — | — | actual | — | — | −110,592,000,000 | 102.50 |
| — | — | actual | — | — | −102,643,200,000 | 136.10 |
| — | — | actual | — | — | −94,694,400,000 | 204.90 |
| — | — | actual | — | — | −86,918,400,000 | 176.10 |
| — | — | actual | — | — | −79,056,000,000 | 112.10 |
| — | — | actual | — | — | −71,107,200,000 | 140.90 |
| — | — | actual | — | — | −63,158,400,000 | 227.30 |
| — | — | actual | — | — | −55,296,000,000 | 195.30 |
| — | — | actual | — | — | −47,433,600,000 | 115.30 |
| — | — | actual | — | — | −39,484,800,000 | 142.50 |
| — | — | actual | — | — | −31,536,000,000 | 244.90 |
| — | — | actual | — | — | −23,760,000,000 | 214.50 |
| — | — | actual | — | — | −15,897,600,000 | 118.50 |
| — | — | actual | — | — | −7,948,800,000 | 153.70 |
| — | — | actual | — | — | 0 | 244.90 |
| — | — | actual | — | — | 7,776,000,000 | 216.10 |
| — | — | actual | — | — | 15,638,400,000 | 188.90 |
| — | — | actual | — | — | 23,587,200,000 | 142.50 |
| — | — | actual | — | — | 31,536,000,000 | 301 |
| — | — | actual | — | — | 39,312,000,000 | 196.90 |
| — | — | actual | — | — | 47,174,400,000 | 136.10 |
| — | — | actual | — | — | 55,123,200,000 | 267.30 |
| — | — | actual | — | — | 63,072,000,000 | 317 |
| — | — | actual | — | — | 70,934,400,000 | 230.50 |
| — | — | actual | — | — | 78,796,800,000 | 152.10 |
| — | — | actual | — | — | 86,745,600,000 | 336.20 |
| — | — | actual | — | — | 94,694,400,000 | 371.40 |
| — | — | actual | — | — | 102,470,400,000 | 240.10 |
| — | — | actual | — | — | 110,332,800,000 | 158.50 |
| — | — | actual | — | — | 118,281,600,000 | 355.40 |
| — | — | actual | — | — | 126,230,400,000 | 449.90 |
| — | — | actual | — | — | 134,006,400,000 | 286.60 |
| — | — | actual | — | — | 141,868,800,000 | 179.30 |
| — | — | actual | — | — | 149,817,600,000 | 403.40 |
First 60 of 116 rows.
View data
| error | horizon | origin |
|---|---|---|
| −25.852 | 1 | 1982-10-01 |
| 51.238 | 2 | 1982-10-01 |
| −0.8087 | 3 | 1982-10-01 |
| −17.148 | 4 | 1982-10-01 |
| 22.312 | 5 | 1982-10-01 |
| 1.130 | 6 | 1982-10-01 |
| 3.155 | 7 | 1982-10-01 |
| 0.3214 | 8 | 1982-10-01 |
| 83.898 | 1 | 1984-10-01 |
| 30.887 | 2 | 1984-10-01 |
| 42.661 | 3 | 1984-10-01 |
| 40.752 | 4 | 1984-10-01 |
| 133.77 | 5 | 1984-10-01 |
| 95.803 | 6 | 1984-10-01 |
| 101.90 | 7 | 1984-10-01 |
| 16.227 | 8 | 1984-10-01 |
View data
| ACF | bound | lag |
|---|---|---|
| −0.1001 | 0.1886 | 1 |
| −0.1828 | 0.1886 | 2 |
| 0.0130 | 0.1886 | 3 |
| 0.0838 | 0.1886 | 4 |
| 0.0752 | 0.1886 | 5 |
| −0.0920 | 0.1886 | 6 |
| 0.0189 | 0.1886 | 7 |
| −0.0924 | 0.1886 | 8 |
| −0.0003 | 0.1886 | 9 |
| 0.0367 | 0.1886 | 10 |
Backtest accuracy (2 origins, horizon 8)
| Metric | Value |
|---|---|
| MAE | 41.742 |
| RMSE | 57.712 |
| MAPE | 0.0699 |
| sMAPE | 0.0758 |
| MASE | 1.649 |
| WAPE | 0.0643 |
| Coverage of the 80% interval | 0.8750 |
| Coverage of the 95% interval | 0.9375 |
Model selection (AICc, lower is better)
| Model | AICc |
|---|---|
| ETS(M,A,M) | 1255.94 |
| ETS(M,Ad,M) | 1260.32 |
| ETS(M,A,A) | 1268.71 |
| ETS(M,Ad,A) | 1270.94 |
| ETS(M,N,M) | 1286.54 |
| ETS(A,A,A) | 1286.96 |
| ETS(M,N,A) | 1287.13 |
| ETS(A,Ad,A) | 1291.87 |
| ETS(A,N,A) | 1311.11 |
| ETS(M,A,N) | 1510.40 |
| ETS(M,Ad,N) | 1514.84 |
| ETS(M,N,N) | 1532.31 |
| ETS(A,A,N) | 1619.96 |
| ETS(A,Ad,N) | 1622.46 |
| ETS(A,N,N) | 1631.96 |
Forecast
| quarter | Forecast | 80% low | 80% high | 95% low | 95% high |
|---|---|---|---|---|---|
| 1987-01-01 | 1259.33 | 1077.89 | 1449.35 | 984.47 | 1552.13 |
| 1987-04-01 | 652.89 | 555.81 | 752.87 | 502.63 | 807.55 |
| 1987-07-01 | 357.36 | 302.03 | 412.98 | 274.52 | 441.56 |
| 1987-10-01 | 879.26 | 747.30 | 1014.49 | 680.94 | 1087.67 |
| 1988-01-01 | 1369.75 | 1118.78 | 1642.03 | 996.73 | 1798.44 |
| 1988-04-01 | 708.91 | 578.20 | 848.84 | 515.07 | 931.35 |
| 1988-07-01 | 387.37 | 312.10 | 466.94 | 278.71 | 510.96 |
| 1988-10-01 | 951.60 | 765.18 | 1141.85 | 687.85 | 1256.01 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Exponential smoothing (ETS)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.ets 1.0.0 · spec c8de979d5469155c
# Dataset: ml_ukgas (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 <- "quarter"
VALUE <- "gas"
SERIES <- NULL
H <- 8
LEVELS <- as.numeric(c(80, 95))
SEASON <- NULL # NULL = from the time steps (12 monthly, 4 quarterly, 7 daily …)
WINDOWS <- 2
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(
error = "auto",
trend = "auto",
damped = "auto",
season_type = "auto",
npaths = 5000
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_ukgas.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.ets/auto_quarterly/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
# ETS by the
# codesplashr twin — the Python script runs the same algorithm, so both engines agree to the last digits.
min_train <- function(m) if (m > 1) 2 * m + 2 else 10
prepare_series <- function(y, t, m, freq) {
cands <- cs_ml_fc_ets_candidates(y, m, damped = PARAMS$damped)
if (PARAMS$error != "auto") cands <- Filter(function(c) c$error == PARAMS$error, cands)
if (PARAMS$trend != "auto") cands <- Filter(function(c) c$trend == PARAMS$trend, cands)
if (PARAMS$season_type != "auto") cands <- Filter(function(c) c$season == PARAMS$season_type, cands)
if (!length(cands)) {
stop("No ETS model matches these choices for this series (multiplicative terms need positive values; seasonal terms need a season length above 1 and more than one cycle)")
}
if (length(cands) == 1) return(cands[[1]])
sel <- cs_ml_fc_ets_auto(y, m, cands)
aicc <- vapply(sel$table, function(r) if (is.nan(r$aicc)) Inf else r$aicc, numeric(1))
extra_tables[[length(extra_tables) + 1]] <<- list(
key = sprintf("selection%d", length(extra_tables) + 1), title = paste0("Model selection (AICc, lower is better)", if (!is.null(current_series)) paste0(" — ", current_series) else ""),
columns = list(list(key = "model", label = "Model"), list(key = "aicc", label = "AICc", type = "number")),
rows = sel$table[order(aicc, method = "radix")]
)
b <- sel$fit
list(error = b$error, trend = b$trend, damped = b$damped, season = b$season)
}
fit_forecast <- function(y, t, h, m, levels, spec) {
fit <- cs_ml_fc_ets_fit(y, m, spec$error, spec$trend, spec$damped, spec$season)
f <- cs_ml_fc_ets_forecast(fit, h, levels, seed = SEED, npaths = as.integer(PARAMS$npaths))
facts <- list(alpha = fit$alpha, aicc = fit$aicc, sigma2 = fit$sigma2, loglik = fit$loglik)
if (spec$trend != "N") facts$beta <- fit$beta
if (spec$season != "N") facts$gamma <- fit$gamma
if (spec$damped) facts$phi <- fit$phi
list(mean = f$mean, lower = f$lower, upper = f$upper, fitted = fit$fitted, label = fit$label, facts = facts)
}
# %% 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")
))
}
# %% 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 = "Exponential smoothing (ETS)",
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
))
ETS(M,A,M): 8-step forecasts of gas (quarterly data, 108 observations). Backtest MAE 41.7 over 2 origins.
- MAE
- 41.742
- RMSE
- 57.712
- MAPE
- 0.0699
To keep this page light, the plots are shown once, under the R tab.
Backtest accuracy (2 origins, horizon 8)
| Metric | Value |
|---|---|
| MAE | 41.742 |
| RMSE | 57.712 |
| MAPE | 0.0699 |
| sMAPE | 0.0758 |
| MASE | 1.649 |
| WAPE | 0.0643 |
| Coverage of the 80% interval | 0.8750 |
| Coverage of the 95% interval | 0.9375 |
Model selection (AICc, lower is better)
| Model | AICc |
|---|---|
| ETS(M,A,M) | 1255.94 |
| ETS(M,Ad,M) | 1260.32 |
| ETS(M,A,A) | 1268.71 |
| ETS(M,Ad,A) | 1270.94 |
| ETS(M,N,M) | 1286.54 |
| ETS(A,A,A) | 1286.96 |
| ETS(M,N,A) | 1287.13 |
| ETS(A,Ad,A) | 1291.87 |
| ETS(A,N,A) | 1311.11 |
| ETS(M,A,N) | 1510.40 |
| ETS(M,Ad,N) | 1514.84 |
| ETS(M,N,N) | 1532.31 |
| ETS(A,A,N) | 1619.96 |
| ETS(A,Ad,N) | 1622.46 |
| ETS(A,N,N) | 1631.96 |
Forecast
| quarter | Forecast | 80% low | 80% high | 95% low | 95% high |
|---|---|---|---|---|---|
| 1987-01-01 | 1259.33 | 1077.89 | 1449.35 | 984.47 | 1552.13 |
| 1987-04-01 | 652.89 | 555.81 | 752.87 | 502.63 | 807.55 |
| 1987-07-01 | 357.36 | 302.03 | 412.98 | 274.52 | 441.56 |
| 1987-10-01 | 879.26 | 747.30 | 1014.49 | 680.94 | 1087.67 |
| 1988-01-01 | 1369.75 | 1118.78 | 1642.03 | 996.73 | 1798.44 |
| 1988-04-01 | 708.91 | 578.20 | 848.84 | 515.07 | 931.35 |
| 1988-07-01 | 387.37 | 312.10 | 466.94 | 278.71 | 510.96 |
| 1988-10-01 | 951.60 | 765.18 | 1141.85 | 687.85 | 1256.01 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Exponential smoothing (ETS)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.ets 1.0.0 · spec c8de979d5469155c
# Dataset: ml_ukgas (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
# %% Data
TIME = "quarter"
VALUE = "gas"
SERIES = None
H = 8
LEVELS = [float(v) for v in [80, 95]]
SEASON = None # None = from the time steps (12 monthly, 4 quarterly, 7 daily …)
WINDOWS = 2
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 = {
"error": "auto",
"trend": "auto",
"damped": "auto",
"season_type": "auto",
"npaths": 5000,
}
df = pd.read_parquet("tests/parity/fixtures/ml_ukgas.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.ets/auto_quarterly/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
# ETS by the
# codesplash twin — the R script runs the same algorithm, so both engines agree to the last digits.
def min_train(m):
return 2 * m + 2 if m > 1 else 10
def prepare_series(y, t, m, freq):
"""The model form: fixed by the options, else the smallest AICc on the whole series."""
cands = fc.ets_candidates(y, m, damped=PARAMS["damped"])
if PARAMS["error"] != "auto":
cands = [c for c in cands if c[0] == PARAMS["error"]]
if PARAMS["trend"] != "auto":
cands = [c for c in cands if c[1] == PARAMS["trend"]]
if PARAMS["season_type"] != "auto":
cands = [c for c in cands if c[3] == PARAMS["season_type"]]
if not cands:
raise ValueError(
"No ETS model matches these choices for this series (multiplicative terms need positive values; "
"seasonal terms need a season length above 1 and more than one cycle)"
)
if len(cands) == 1:
return cands[0]
best, table = fc.ets_auto(y, m, cands)
extra_tables.append(
{
"key": f"selection{len(extra_tables) + 1}",
"title": "Model selection (AICc, lower is better)" + (f" — {current_series}" if current_series else ""),
"columns": [{"key": "model", "label": "Model"}, {"key": "aicc", "label": "AICc", "type": "number"}],
"rows": sorted(table, key=lambda r: r["aicc"] if r["aicc"] == r["aicc"] else float("inf")),
}
)
return (best["error"], best["trend"], best["damped"], best["season"])
def fit_forecast(y, t, h, m, levels, spec):
error, trend, damped, season = spec
fit = fc.ets_fit(y, m, error, trend, damped, season)
f = fc.ets_forecast(fit, h, levels, seed=SEED, npaths=int(PARAMS["npaths"]))
facts = {"alpha": fit["alpha"], "aicc": fit["aicc"], "sigma2": fit["sigma2"], "loglik": fit["loglik"]}
if trend != "N":
facts["beta"] = fit["beta"]
if season != "N":
facts["gamma"] = fit["gamma"]
if damped:
facts["phi"] = fit["phi"]
return {**f, "fitted": fit["fitted"], "label": fit["label"], "facts": facts}
# %% 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"),
},
)
)
# %% 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": "Exponential smoothing (ETS)",
"engine": cs.engine_info("numpy", "scipy", "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,
}
)
It chooses ETS(M,A,M), with = 0.03, = 0.03 and = 0.62.
The season updates fast, while the level and trend update slowly. Why might multiplicative make sense for a series like this? Then read the Backtest table. Is the MASE below 1 on this series? It's 1.65, so no: over the backtest, ETS misses by more than a naive forecast did one step ahead in-sample. That isn't a head-to-head with the naive forecast, though. To see whether ETS beats the seasonal naive forecast on the same origins, compare the two in a forecast experiment.
Damping
PredictPredict first
A linear trend grows without limit. What do damped trends do at long horizons?
Reveal
They flatten it, since each step multiplies the trend by . This has held up well empirically: extrapolating a trend forever is usually optimistic (Gardner & McKenzie, 1985). Damped trend on Automatic lets AICc decide.
Theta
ReadThe Theta method won the M3 forecasting competition with very little machinery. It decomposes the series into long-run drift and short-run curvature, and combines their forecasts. Hyndman & Billah (2003) showed that its standard form is equivalent to simple exponential smoothing with drift.
On monthly passengers, = 0.84 and the drift is 1.32 per month. It first removes seasonality, then adds it back.
There's nothing to tune, so it makes a good second benchmark after the baselines.
Simple versus flexible
ReflectETS searches among many forms. Theta has nearly no options. Yet on the Nile, Theta's fit is close to ETS's: = 0.25, against 0.25, plus a small drift.
How would you decide between them? AICc compares models within a family, fit to the same data. What would a backtest let you do that AICc doesn't?
Check your understanding
CheckpointCheck yourself
, the current level is 100, and the new value is 120. What is the new level?
Show the answer
Answer: 104
.
Check yourself
Seasonal swings grow with the level. Which label fits best?
Show the answer
Answer: c
Multiplicative season and errors scale with the level. Additive parts stay the same size.
Check yourself
An ETS model has near 1. What does that imply?
Show the answer
Answer: a
With , the level is the latest value.
Check yourself
What makes Theta a useful benchmark?
Show the answer
Answer: b
No method wins everywhere. Theta sets a bar that a complicated method should clear.
Check yourself
Hyndman and Billah showed that the standard Theta method is equivalent to which model?
Show the answer
Answer: b
That's why it needs so few parameters: a smoothing parameter and a drift.
Check yourself
On a seasonal monthly series, what does Theta do first in CodeSplash?
Show the answer
Answer: a
Seasonal adjustment happens before the smoothing step, and the card shows if it was used.
Do it in CodeSplash
In the appIn Forecast, choose Exponential smoothing (ETS) or Theta method from the methods in the rail. Compare methods fits your chosen methods on the same windows.
import pandas as pd
from statsmodels.tsa.exponential_smoothing.ets import ETSModel
from statsmodels.tsa.forecasting.theta import ThetaModel
y = pd.read_csv("airpassengers.csv", parse_dates=["month"], index_col="month")["passengers"].asfreq("MS")
ets = ETSModel(y, error="add", trend="add", damped_trend=True, seasonal="add", seasonal_periods=12).fit(disp=False)
print(ets.forecast(12))
print(ThetaModel(y, period=12).fit().forecast(12))# install.packages("forecast")
library(forecast)
fit <- ets(AirPassengers, model = "AAA", damped = TRUE)
forecast(fit, h = 12)
thetaf(AirPassengers, h = 12)Recap
Recap- sets how fast the level follows new data. ETS adds a trend and a season in the same way.
- Labels read Error, Trend, Season, with damping marked by a "d".
- Damped trends are usually safer than straight-line extrapolation.
- Theta is a strong, simple benchmark. Compare by backtest.