Skip to content

ARIMA and regressors

Read an ARIMA label, choose differences and orders, add known drivers with regression and ARIMA errors, and check what a backtest assumes about the future.

Advanced ~14 min11 steps

What runs in CodeSplash

You will be able to

  • Read ARIMA(p,d,q)(P,D,Q)[m] and say what each part does
  • Use AICc within a fixed amount of differencing, and residual checks after fitting
  • Add regressors with ARIMAX, and say what you must know about their future values

Read first

01

Three parts and a season

Read
ARIMA(p,d,q)(P,D,Q)m\text{ARIMA}(p,d,q)(P,D,Q)_m
  • pp: autoregressive lags, or how the past values matter.
  • dd: ordinary differences, to remove a stochastic trend.
  • qq: moving-average lags, or how the past shocks matter.
  • (P,D,Q)m(P,D,Q)_m: the same three at seasonal lags, with mm the season length.

An ARIMA(0,1,1) is the same as simple exponential smoothing. These families overlap, so they aren't rivals in any strict sense.

02

Read a label

Predict

Predict first

Monthly airline passengers are often fit with ARIMA(0,1,1)(0,1,1)[12]. What does this do?

One ordinary and one seasonal difference, one MA at lag 1 and at lag 12Two ordinary differences, two AR termsTwelve differences
Reveal

One ordinary and one seasonal difference, then an MA term at lag 1 and at lag 12. This is the classic "airline model" of Box and Jenkins. Here, MA(1) = −0.31 and seasonal MA(1) = −0.11.

03

Automatic search

In the app

Orders defaults to a stepwise AICc search. It picks dd and DD first with unit-root rules, then searches the other orders.

ARIMARecorded · Python and R agreeRecorded 2026-11-25 · 26 values compared · largest relative difference 1.7e-7
R

ARIMA(0,1,1)(0,1,0)[4]: 8-step forecasts of gas (quarterly data, 108 observations). Backtest MAE 57.4 over 1 origin.

MAE
57.448
RMSE
68.503
MAPE
0.0904

Plots

Forecast of gasWhere is the series heading, and how uncertain is the forecast?
View data
hi_80hi_95kindlo_80lo_95quartergas
——actual——−315,619,200,000160.10
——actual——−307,756,800,000129.70
——actual——−299,894,400,00084.800
——actual——−291,945,600,000120.10
——actual——−283,996,800,000160.10
——actual——−276,220,800,000124.90
——actual——−268,358,400,00084.800
——actual——−260,409,600,000116.90
——actual——−252,460,800,000169.70
——actual——−244,684,800,000140.90
——actual——−236,822,400,00089.700
——actual——−228,873,600,000123.30
——actual——−220,924,800,000187.30
——actual——−213,148,800,000144.10
——actual——−205,286,400,00092.900
——actual——−197,337,600,000120.10
——actual——−189,388,800,000176.10
——actual——−181,526,400,000147.30
——actual——−173,664,000,00089.700
——actual——−165,715,200,000123.30
——actual——−157,766,400,000185.70
——actual——−149,990,400,000155.30
——actual——−142,128,000,00099.300
——actual——−134,179,200,000131.30
——actual——−126,230,400,000200.10
——actual——−118,454,400,000161.70
——actual——−110,592,000,000102.50
——actual——−102,643,200,000136.10
——actual——−94,694,400,000204.90
——actual——−86,918,400,000176.10
——actual——−79,056,000,000112.10
——actual——−71,107,200,000140.90
——actual——−63,158,400,000227.30
——actual——−55,296,000,000195.30
——actual——−47,433,600,000115.30
——actual——−39,484,800,000142.50
——actual——−31,536,000,000244.90
——actual——−23,760,000,000214.50
——actual——−15,897,600,000118.50
——actual——−7,948,800,000153.70
——actual——0244.90
——actual——7,776,000,000216.10
——actual——15,638,400,000188.90
——actual——23,587,200,000142.50
——actual——31,536,000,000301
——actual——39,312,000,000196.90
——actual——47,174,400,000136.10
——actual——55,123,200,000267.30
——actual——63,072,000,000317
——actual——70,934,400,000230.50
——actual——78,796,800,000152.10
——actual——86,745,600,000336.20
——actual——94,694,400,000371.40
——actual——102,470,400,000240.10
——actual——110,332,800,000158.50
——actual——118,281,600,000355.40
——actual——126,230,400,000449.90
——actual——134,006,400,000286.60
——actual——141,868,800,000179.30
——actual——149,817,600,000403.40

First 60 of 116 rows.

Backtest errors by horizonHow does forecast error grow with the horizon, and how stable is it across origins?
View data
errorhorizonorigin
74.40711984-10-01
34.40721984-10-01
24.90731984-10-01
34.40741984-10-01
128.1151984-10-01
89.61561984-10-01
67.31571984-10-01
6.41581984-10-01
Residual autocorrelationIs a series (or a model's residuals) autocorrelated, and at which lags?
View data
ACFboundlag
−0.11710.19311
−0.19530.19312
0.06890.19313
−0.01550.19314
0.13380.19315
−0.15310.19316
0.05260.19317
0.03880.19318
−0.03280.19319
−0.01700.193110

Backtest accuracy (1 origin, horizon 8)

MetricValue
MAE57.448
RMSE68.503
MAPE0.0904
sMAPE0.0964
MASE2.259
WAPE0.0821
Coverage of the 80% interval0.5000
Coverage of the 95% interval0.7500

Stepwise order search (AICc, lower is better)

ModelAICc
ARIMA(0,1,1)(0,1,0)[4]1030.79
ARIMA(0,1,2)(0,1,0)[4]1031.49
ARIMA(1,1,2)(0,1,0)[4]1032.04
ARIMA(1,1,1)(0,1,0)[4]1032.08
ARIMA(0,1,1)(1,1,0)[4]1032.91
ARIMA(0,1,1)(0,1,1)[4]1032.91
ARIMA(1,1,0)(1,1,0)[4]1079.07
ARIMA(0,1,0)(0,1,0)[4]1099.25
ARIMA(0,1,1)(1,1,1)[4]∞

Forecast

quarterForecast80% low80% high95% low95% high
1987-01-011201.901157.051246.741133.311270.49
1987-04-01651.10606.14696.05582.34719.86
1987-07-01385.40340.33430.47316.47454.32
1987-10-01820.80775.62865.98751.70889.89
1988-01-011239.891173.971305.811139.071340.71
1988-04-01689.09622.87755.31587.81790.37
1988-07-01423.39356.87489.91321.66525.13
1988-10-01858.79791.97925.61756.60960.98
The exact R script · R R version 4.5.1 (2025-06-13)
# ARIMA
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.arima 1.0.0 · spec bd32cb3d922ee427
# 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 <- 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(
  order = "auto",
  p = 1,
  d = 1,
  q = 1,
  sp = 0,
  sd = 0,
  sq = 0,
  constant = "auto"
)
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.arima/auto_seasonal_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
# The series is differenced explicitly ((1 - B)^d (1 - B^m)^D) and an ARMA(p, q)(P, Q)[m] with an
# optional mean is fitted to the differences by stats::arima (exact Gaussian ML); the Python script
# fits the same model with statsmodels. Forecasts are integrated back and their variances come from
# the psi weights of the full model (codesplashr cs_ml_fc_*).
min_train <- function(m) if (m > 1) 2 * m + 6 else 10

arma_fit <- function(w, p, q, P, Q, m, constant) {
  k <- p + q + P + Q + as.integer(constant)
  ctrl <- list(reltol = 1e-14, maxit = 5000)
  if (k > 0) ctrl$ndeps <- rep(1e-6, k)
  one <- function(method) stats::arima(w, order = c(p, 0, q), seasonal = list(order = c(P, 0, Q), period = max(m, 1)),
                                       include.mean = constant, method = method, optim.control = ctrl)
  fit <- tryCatch(one("CSS-ML"), error = function(e) one("ML"))
  cf <- stats::coef(fit)
  pick <- function(prefix, n) { v <- numeric(n); for (i in seq_len(n)) v[i] <- unname(cf[paste0(prefix, i)]); v }
  list(fit = fit, coef = list(ar = pick("ar", p), ma = pick("ma", q), sar = pick("sar", P), sma = pick("sma", Q),
                              mean = if (constant) unname(cf["intercept"]) else 0))
}

prepare_series <- function(y, t, m, freq) {
  seasonal <- m > 1
  if (PARAMS$order == "manual") {
    d <- as.integer(PARAMS$d)
    D <- if (seasonal) as.integer(PARAMS$sd) else 0L
    cc <- PARAMS$constant == "yes" || (PARAMS$constant == "auto" && d + D <= 1)
    return(list(p = as.integer(PARAMS$p), d = d, q = as.integer(PARAMS$q), P = if (seasonal) as.integer(PARAMS$sp) else 0L,
                D = D, Q = if (seasonal) as.integer(PARAMS$sq) else 0L, constant = cc))
  }
  D <- if (seasonal) cs_ml_fc_nsdiffs(y, m) else 0
  d <- cs_ml_fc_ndiffs(cs_ml_fc_difference(y, 0, D, m))
  w <- cs_ml_fc_difference(y, d, D, m)
  allow_c <- PARAMS$constant == "yes" || (PARAMS$constant == "auto" && d + D <= 1)
  score <- function(p, q, P, Q, cc) {
    tryCatch({
      a <- arma_fit(w, p, q, P, Q, m, cc)
      # like auto.arima: reject near-unit roots and non-invertible MA parts
      if (cs_ml_fc_min_root(a$coef$ar, a$coef$ma, a$coef$sar, a$coef$sma, m) < 1.01) Inf else
        cs_ml_fc_aicc(a$fit$loglik, p + q + P + Q + as.integer(cc) + 1, length(w))
    }, error = function(e) Inf)
  }
  sel <- cs_ml_fc_stepwise_orders(score, d, D, m, allow_c)
  aicc <- vapply(sel$table, function(r) if (is.finite(r$aicc)) r$aicc else Inf, numeric(1))
  extra_tables[[length(extra_tables) + 1]] <<- list(
    key = sprintf("selection%d", length(extra_tables) + 1),
    title = paste0("Stepwise order search (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")]
  )
  o <- sel$order
  list(p = o[1], d = d, q = o[2], P = o[3], D = D, Q = o[4], constant = o[5] == 1)
}

fit_forecast <- function(y, t, h, m, levels, spec) {
  w <- cs_ml_fc_difference(y, spec$d, spec$D, m)
  a <- arma_fit(w, spec$p, spec$q, spec$P, spec$Q, m, spec$constant)
  sigma2 <- a$fit$sigma2
  w_fc <- as.numeric(stats::predict(a$fit, n.ahead = h)$pred)
  mean_ <- cs_ml_fc_integrate(y, w_fc, spec$d, spec$D, m)
  psi <- cs_ml_fc_psi_weights(a$coef$ar, a$coef$ma, a$coef$sar, a$coef$sma, spec$d, spec$D, m, h)
  se <- sqrt(sigma2 * cumsum(psi * psi))
  lower <- list(); upper <- list()
  for (level in levels) {
    z <- cs_ml_fc_z(level)
    lower[[as.character(level)]] <- mean_ - z * se
    upper[[as.character(level)]] <- mean_ + z * se
  }
  k0 <- length(y) - length(w)
  fitted <- c(rep(NaN, k0), y[(k0 + 1):length(y)] - as.numeric(stats::residuals(a$fit)))
  facts <- list()
  for (nm in c("ar", "ma", "sar", "sma")) for (i in seq_along(a$coef[[nm]])) facts[[paste0(nm, i)]] <- a$coef[[nm]][i]
  if (spec$constant) facts$mean <- a$coef$mean
  facts$sigma2 <- sigma2
  facts$loglik <- a$fit$loglik
  facts$aicc <- cs_ml_fc_aicc(a$fit$loglik, spec$p + spec$q + spec$P + spec$Q + as.integer(spec$constant) + 1, length(w))
  list(mean = mean_, lower = lower, upper = upper, fitted = fitted,
       label = cs_ml_fc_arima_label(spec$p, spec$d, spec$q, spec$P, spec$D, spec$Q, m, spec$constant), 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 = "ARIMA",
  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

ARIMA(0,1,1)(0,1,0)[4]: 8-step forecasts of gas (quarterly data, 108 observations). Backtest MAE 57.4 over 1 origin.

MAE
57.448
RMSE
68.503
MAPE
0.0904

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

Backtest accuracy (1 origin, horizon 8)

MetricValue
MAE57.448
RMSE68.503
MAPE0.0904
sMAPE0.0964
MASE2.259
WAPE0.0821
Coverage of the 80% interval0.5000
Coverage of the 95% interval0.7500

Stepwise order search (AICc, lower is better)

ModelAICc
ARIMA(0,1,1)(0,1,0)[4]1030.79
ARIMA(0,1,2)(0,1,0)[4]1031.49
ARIMA(1,1,1)(0,1,0)[4]1032.08
ARIMA(0,1,1)(1,1,0)[4]1032.91
ARIMA(0,1,1)(0,1,1)[4]1032.91
ARIMA(1,1,0)(1,1,0)[4]1079.07
ARIMA(0,1,0)(0,1,0)[4]1099.25
ARIMA(0,1,1)(1,1,1)[4]∞
ARIMA(1,1,2)(0,1,0)[4]∞

Forecast

quarterForecast80% low80% high95% low95% high
1987-01-011201.901157.051246.741133.311270.49
1987-04-01651.10606.14696.05582.34719.86
1987-07-01385.40340.33430.47316.47454.32
1987-10-01820.80775.62865.98751.70889.89
1988-01-011239.891173.971305.811139.071340.71
1988-04-01689.09622.87755.31587.81790.37
1988-07-01423.39356.87489.91321.66525.13
1988-10-01858.79791.97925.61756.60960.98
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# ARIMA
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.arima 1.0.0 · spec bd32cb3d922ee427
# 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
import warnings as _warnings

from statsmodels.tsa.arima.model import ARIMA

# %% 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 = 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 = {
    "order": "auto",
    "p": 1,
    "d": 1,
    "q": 1,
    "sp": 0,
    "sd": 0,
    "sq": 0,
    "constant": "auto",
}
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.arima/auto_seasonal_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
# The series is differenced explicitly ((1 − B)^d (1 − B^m)^D, as statsmodels' simple_differencing)
# and an ARMA(p, q)(P, Q)[m] with an optional mean is fitted to the differences by exact Gaussian ML;
# the R script fits the same model with stats::arima. Forecasts are integrated back and their
# variances come from the ψ weights of the full model (codesplash.ml.forecast).


def min_train(m):
    return 2 * m + 6 if m > 1 else 10


def arma_fit(w, p, q, P, Q, m, constant):
    """→ (results, coefficients). Refined L-BFGS → Nelder–Mead → BFGS so the optimum matches R's."""
    seas = (P, 0, Q, m) if m > 1 and (P or Q) else (0, 0, 0, 0)
    mod = ARIMA(np.asarray(w, dtype=np.float64), order=(p, 0, q), seasonal_order=seas, trend="c" if constant else "n", concentrate_scale=True)
    with _warnings.catch_warnings():
        _warnings.simplefilter("ignore")
        if mod.k_params == 0:
            r = mod.filter([])
        else:
            r = mod.fit(method="statespace", method_kwargs={"maxiter": 5000})
            r = mod.fit(start_params=r.params, method="statespace", method_kwargs={"method": "nm", "maxiter": 20000, "xtol": 1e-12, "ftol": 1e-14})
            r = mod.fit(start_params=r.params, method="statespace", method_kwargs={"method": "bfgs", "maxiter": 5000, "gtol": 1e-10})
    coef = {"ar": [0.0] * p, "ma": [0.0] * q, "sar": [0.0] * P, "sma": [0.0] * Q, "mean": 0.0}
    for name, value in zip(mod.param_names, np.atleast_1d(r.params)):
        if name == "const":
            coef["mean"] = float(value)
        elif name.startswith("ar.S.L"):
            coef["sar"][int(name[6:]) // m - 1] = float(value)
        elif name.startswith("ma.S.L"):
            coef["sma"][int(name[6:]) // m - 1] = float(value)
        elif name.startswith("ar.L"):
            coef["ar"][int(name[4:]) - 1] = float(value)
        elif name.startswith("ma.L"):
            coef["ma"][int(name[4:]) - 1] = float(value)
    return r, coef


def prepare_series(y, t, m, freq):
    """(p, d, q, P, D, Q, constant): from the options, or the stepwise AICc search."""
    seasonal = m > 1
    if PARAMS["order"] == "manual":
        d = int(PARAMS["d"])
        D = int(PARAMS["sd"]) if seasonal else 0
        c = PARAMS["constant"] == "yes" or (PARAMS["constant"] == "auto" and d + D <= 1)
        return (int(PARAMS["p"]), d, int(PARAMS["q"]), int(PARAMS["sp"]) if seasonal else 0, D, int(PARAMS["sq"]) if seasonal else 0, c)
    D = fc.nsdiffs(y, m) if seasonal else 0
    d = fc.ndiffs(fc.difference(y, 0, D, m))
    w = fc.difference(y, d, D, m)
    allow_c = PARAMS["constant"] == "yes" or (PARAMS["constant"] == "auto" and d + D <= 1)

    def score(p, q, P, Q, c):
        try:
            r, coef = arma_fit(w, p, q, P, Q, m, c)
            # like auto.arima: reject near-unit roots and non-invertible MA parts
            if fc.min_root(coef["ar"], coef["ma"], coef["sar"], coef["sma"], m) < 1.01:
                return math.inf
            return fc.aicc(float(r.llf), p + q + P + Q + int(bool(c)) + 1, len(w))
        except Exception:
            return math.inf

    best, table = fc.stepwise_orders(score, d, D, m, allow_c)
    extra_tables.append(
        {
            "key": f"selection{len(extra_tables) + 1}",
            "title": "Stepwise order search (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 math.isfinite(r["aicc"]) else float("inf")),
        }
    )
    return (best[0], d, best[1], best[2], D, best[3], bool(best[4]))


def fit_forecast(y, t, h, m, levels, spec):
    p, d, q, P, D, Q, c = spec
    w = fc.difference(y, d, D, m)
    r, coef = arma_fit(w, p, q, P, Q, m, c)
    sigma2 = float(r.scale)
    w_fc = [float(v) for v in np.asarray(r.get_forecast(h).predicted_mean)]
    mean = fc.integrate(y, w_fc, d, D, m)
    psi = fc.psi_weights(coef["ar"], coef["ma"], coef["sar"], coef["sma"], d, D, m, h)
    se = []
    acc = 0.0
    for j in range(h):
        acc += psi[j] * psi[j]
        se.append(math.sqrt(sigma2 * acc))
    lower, upper = {}, {}
    for level in levels:
        z = fc.z_value(level)
        lower[level] = [mean[k] - z * se[k] for k in range(h)]
        upper[level] = [mean[k] + z * se[k] for k in range(h)]
    resid = [float(v) for v in np.asarray(r.resid)]
    k0 = len(y) - len(w)
    fitted = [float("nan")] * k0 + [y[k0 + i] - resid[i] for i in range(len(w))]
    facts = {}
    for name in ("ar", "ma", "sar", "sma"):
        for i, v in enumerate(coef[name]):
            facts[f"{name}{i + 1}"] = v
    if c:
        facts["mean"] = coef["mean"]
    facts["sigma2"] = sigma2
    facts["loglik"] = float(r.llf)
    facts["aicc"] = fc.aicc(float(r.llf), p + q + P + Q + int(bool(c)) + 1, len(w))
    label = fc.arima_label(p, d, q, P, D, Q, m, c)
    return {"mean": mean, "lower": lower, "upper": upper, "fitted": fitted, "label": 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": "ARIMA",
        "engine": cs.engine_info("statsmodels", "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,
    }
)

On quarterly UK gas, it picks ARIMA(0,1,1)(0,1,0)[4], with AICc = 1030.8.

On the Nile, it picks ARIMA(1,1,1). Now open Backtest. How does this compare with the baseline you saw earlier?

04

AICc has a limit

Predict

Predict first

ARIMA(1,0,1) has AICc 1400 and ARIMA(0,1,1) has AICc 1390. Can you say the second is better from these alone?

Yes: lower AICc winsNo: differencing changes the data the likelihood is computed onOnly for seasonal models
Reveal

No. Differencing changes the data that the likelihood is computed on, so AICc only compares models with the same dd and DD. Compare models with different differencing using a backtest.

05

After fitting

Read

Residuals should look like noise. Read the ACF, and run Ljung–Box with Degrees of freedom used by a fitted model set to p+q+P+Qp + q + P + Q.

If a pattern remains, the model has missed something. If it's clean, that shows the model describes the past, and you still need a backtest for the future.

Look at the Ozone model: ARIMA(2,0,0) with mean. Its AR coefficients are 0.58 and 0.11, around a mean of 42.9.

06

Adding regressors

In the app

Road casualties fell after a seatbelt law. ARIMAX fits a regression, and lets its errors follow an ARIMA:

yt=β1x1t+β2x2t+ηt,ηt∼ARIMAy_t = \beta_1 x_{1t} + \beta_2 x_{2t} + \eta_t, \qquad \eta_t \sim \text{ARIMA}
ARIMAX (regression with ARIMA errors)Recorded · Python and R agreeRecorded 2026-11-25 · 30 values compared · largest relative difference 1.1e-7
R

ARIMA(0,1,1)(0,1,1)[12] with regressors: 12-step forecasts of drivers (monthly data, 192 observations). Backtest MAE 7.99 over 1 origin.

MAE
7.992
RMSE
11.243
MAPE
0.0715

Plots

Forecast of driversWhere is the series heading, and how uncertain is the forecast?
View data
hi_80hi_95kindlo_80lo_95monthdrivers
——actual——−31,536,000,000107
——actual——−28,857,600,00097
——actual——−26,438,400,000102
——actual——−23,760,000,00087
——actual——−21,168,000,000119
——actual——−18,489,600,000106
——actual——−15,897,600,000110
——actual——−13,219,200,000106
——actual——−10,540,800,000107
——actual——−7,948,800,000134
——actual——−5,270,400,000147
——actual——−2,678,400,000180
——actual——0125
——actual——2,678,400,000134
——actual——5,097,600,000110
——actual——7,776,000,000102
——actual——10,368,000,000103
——actual——13,046,400,000111
——actual——15,638,400,000120
——actual——18,316,800,000129
——actual——20,995,200,000122
——actual——23,587,200,000183
——actual——26,265,600,000169
——actual——28,857,600,000190
——actual——31,536,000,000134
——actual——34,214,400,000108
——actual——36,633,600,000104
——actual——39,312,000,000117
——actual——41,904,000,000157
——actual——44,582,400,000148
——actual——47,174,400,000130
——actual——49,852,800,000140
——actual——52,531,200,000136
——actual——55,123,200,000140
——actual——57,801,600,000187
——actual——60,393,600,000150
——actual——63,072,000,000159
——actual——65,750,400,000143
——actual——68,256,000,000114
——actual——70,934,400,000127
——actual——73,526,400,000159
——actual——76,204,800,000156
——actual——78,796,800,000138
——actual——81,475,200,000120
——actual——84,153,600,000117
——actual——86,745,600,000170
——actual——89,424,000,000168
——actual——92,016,000,000198
——actual——94,694,400,000144
——actual——97,372,800,000146
——actual——99,792,000,000109
——actual——102,470,400,000131
——actual——105,062,400,000151
——actual——107,740,800,000140
——actual——110,332,800,000153
——actual——113,011,200,000140
——actual——115,689,600,000161
——actual——118,281,600,000168
——actual——120,960,000,000152
——actual——123,552,000,000136

First 60 of 204 rows.

Backtest errors by horizonHow does forecast error grow with the horizon, and how stable is it across origins?
View data
errorhorizonorigin
−2.21011983-12-01
3.04921983-12-01
−7.58331983-12-01
0.159541983-12-01
3.64951983-12-01
−1.78761983-12-01
−12.80871983-12-01
3.54281983-12-01
17.77491983-12-01
1.978101983-12-01
14.488111983-12-01
26.877121983-12-01
Residual autocorrelationIs a series (or a model's residuals) autocorrelated, and at which lags?
View data
ACFboundlag
0.18030.14651
−0.08000.14652
−0.11030.14653
−0.10470.14654
−0.05310.14655
−0.02040.14656
−0.04450.14657
0.11160.14658
0.02690.14659
−0.15290.146510
−0.03050.146511
0.05730.146512
0.07850.146513
−0.07260.146514
0.01370.146515
0.00250.146516
0.11800.146517
0.02440.146518
0.11230.146519
0.07230.146520
−0.03660.146521
−0.07770.146522
0.00800.146523
−0.00100.146524

Assumptions

  • Residuals look uncorrelated — Ljung–Box at 24 lags: p = 0.108.

Backtest accuracy (1 origin, horizon 12)

MetricValue
MAE7.992
RMSE11.243
MAPE0.0715
sMAPE0.0732
MASE0.4672
WAPE0.0781
Coverage of the 80% interval0.9167
Coverage of the 95% interval1

Regression coefficients (on the differenced scale when the model differences)

RegressorEstimateSE
petrol−4.3131.617
law−20.3088.110

Forecast

monthForecast80% low80% high95% low95% high
1985-01-01101.0280.674121.3769.902132.15
1985-02-0189.08668.559109.6157.692120.48
1985-03-0192.55671.852113.2660.892124.22
1985-04-0189.33368.454110.2157.402121.26
1985-05-0189.94668.894111.0057.750122.14
1985-06-0196.96175.737118.1964.502129.42
1985-07-0195.65174.257117.0562.931128.37
1985-08-0197.99976.435119.5665.020130.98
1985-09-01110.8289.092132.5677.588144.06
1985-10-01123.54101.64145.4490.052157.03
1985-11-01130.54108.47152.6096.793164.28
1985-12-01137.40115.17159.63103.40171.39
  • The backtest gave the model the actual future values of petrol, law. A real forecast only knows them when they are planned or fixed in advance (holidays, prices you set), so read the backtest accuracy as a best case.
The exact R script · R R version 4.5.1 (2025-06-13)
# ARIMAX (regression with ARIMA errors)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.arimax 1.0.1 · spec 719025f71e942d5a
# Dataset: f7_seatbelts_future (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 <- "month"
VALUE <- "drivers"
SERIES <- NULL
H <- 12
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 <- c("petrol", "law")
PARAMS <- list(
  order = "manual",
  p = 0,
  d = 1,
  q = 1,
  sp = 0,
  sd = 1,
  sq = 1,
  constant = "auto"
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/f7_seatbelts_future.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.arimax/seatbelts_airline_known_future/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
# Regression with ARIMA errors: y_t = c + x_t'b + n_t with n_t ~ ARIMA(p,d,q)(P,D,Q)[m]. The outcome and the regressors are
# differenced explicitly and an ARMA with regressors is fitted to the differences by stats::arima (exact Gaussian ML); the Python
# script fits the same model with statsmodels. Forecasts are integrated back; their variances come from the psi weights of the error
# model, so they treat the regression coefficients and the future regressors as known, as forecast::Arima does. Refits start from the
# ARMA coefficients of the full series: short windows can have several likelihood optima, and both engines should stay in the same one.
min_train <- function(m) (if (m > 1) 2 * m + 6 else 10) + length(XREG) + 2

arma_fit <- function(w, Xd, p, q, P, Q, m, constant, start = NULL) {
  colnames(Xd) <- sprintf("x%d", seq_len(ncol(Xd)))
  k <- p + q + P + Q + as.integer(constant) + ncol(Xd)
  ctrl <- list(reltol = 1e-14, maxit = 5000, ndeps = rep(1e-6, k))
  one <- function(method, init = NULL) stats::arima(w, order = c(p, 0, q), seasonal = list(order = c(P, 0, Q), period = max(m, 1)), xreg = Xd,
                                                    include.mean = constant, method = method, init = init, optim.control = ctrl)
  cold <- function() tryCatch(one("CSS-ML"), error = function(e) one("ML"))
  # ARMA terms from the full series; the regression terms start from least squares (NA).
  fit <- if (is.null(start)) cold() else tryCatch(one("ML", c(start$ar, start$ma, start$sar, start$sma, rep(NA, as.integer(constant) + ncol(Xd)))), error = function(e) cold())
  cf <- stats::coef(fit)
  pick <- function(prefix, n) { v <- numeric(n); for (i in seq_len(n)) v[i] <- unname(cf[paste0(prefix, i)]); v }
  list(fit = fit, coef = list(ar = pick("ar", p), ma = pick("ma", q), sar = pick("sar", P), sma = pick("sma", Q),
                              mean = if (constant) unname(cf["intercept"]) else 0, beta = pick("x", ncol(Xd))))
}

diff_columns <- function(X, d, D, m) do.call(cbind, lapply(seq_len(ncol(X)), function(j) cs_ml_fc_difference(X[, j], d, D, m)))

# A regressor that does not vary once differenced cannot be estimated.
check_constant <- function(X) {
  for (j in seq_along(XREG)) if (max(X[, j]) - min(X[, j]) == 0) stop(sprintf("%s does not vary in this window, so its effect cannot be estimated", XREG[j]))
}

# The orders plus the full series' coefficients, the starting point of every refit.
with_start <- function(spec, y, m) {
  w <- cs_ml_fc_difference(y, spec$d, spec$D, m)
  Xd <- diff_columns(x_grid, spec$d, spec$D, m)
  check_constant(Xd)
  spec$start <- arma_fit(w, Xd, spec$p, spec$q, spec$P, spec$Q, m, spec$constant)$coef
  spec
}

prepare_series <- function(y, t, m, freq) {
  seasonal <- m > 1
  if (PARAMS$order == "manual") {
    d <- as.integer(PARAMS$d)
    D <- if (seasonal) as.integer(PARAMS$sd) else 0L
    cc <- PARAMS$constant == "yes" || (PARAMS$constant == "auto" && d + D <= 1)
    return(with_start(list(p = as.integer(PARAMS$p), d = d, q = as.integer(PARAMS$q), P = if (seasonal) as.integer(PARAMS$sp) else 0L,
                           D = D, Q = if (seasonal) as.integer(PARAMS$sq) else 0L, constant = cc), y, m))
  }
  # Like auto.arima with xreg: choose the differencing on the residuals of the regression.
  Xc <- cbind(1, x_grid)
  u <- as.numeric(y - Xc %*% solve(crossprod(Xc), crossprod(Xc, y)))
  D <- if (seasonal) cs_ml_fc_nsdiffs(u, m) else 0
  d <- cs_ml_fc_ndiffs(cs_ml_fc_difference(u, 0, D, m))
  w <- cs_ml_fc_difference(y, d, D, m)
  Xd <- diff_columns(x_grid, d, D, m)
  check_constant(Xd)
  allow_c <- PARAMS$constant == "yes" || (PARAMS$constant == "auto" && d + D <= 1)
  score <- function(p, q, P, Q, cc) {
    tryCatch({
      a <- arma_fit(w, Xd, p, q, P, Q, m, cc)
      if (cs_ml_fc_min_root(a$coef$ar, a$coef$ma, a$coef$sar, a$coef$sma, m) < 1.01) Inf else
        cs_ml_fc_aicc(a$fit$loglik, p + q + P + Q + as.integer(cc) + 1 + ncol(Xd), length(w))
    }, error = function(e) Inf)
  }
  sel <- cs_ml_fc_stepwise_orders(score, d, D, m, allow_c)
  aicc <- vapply(sel$table, function(r) if (is.finite(r$aicc)) r$aicc else Inf, numeric(1))
  extra_tables[[length(extra_tables) + 1]] <<- list(
    key = sprintf("selection%d", length(extra_tables) + 1),
    title = paste0("Stepwise order search (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")]
  )
  o <- sel$order
  with_start(list(p = o[1], d = d, q = o[2], P = o[3], D = D, Q = o[4], constant = o[5] == 1), y, m)
}

COEF <- list()
RESID <- list()

fit_forecast <- function(y, t, h, m, levels, spec) {
  w <- cs_ml_fc_difference(y, spec$d, spec$D, m)
  Xall <- diff_columns(rbind(X_TRAIN, X_FUTURE), spec$d, spec$D, m)
  Xd <- Xall[seq_along(w), , drop = FALSE]
  Xf <- Xall[(length(w) + 1):nrow(Xall), , drop = FALSE]
  check_constant(Xd)
  a <- arma_fit(w, Xd, spec$p, spec$q, spec$P, spec$Q, m, spec$constant, spec$start)
  sigma2 <- a$fit$sigma2
  colnames(Xf) <- sprintf("x%d", seq_len(ncol(Xf)))
  w_fc <- as.numeric(stats::predict(a$fit, n.ahead = h, newxreg = Xf)$pred)
  mean_ <- cs_ml_fc_integrate(y, w_fc, spec$d, spec$D, m)
  psi <- cs_ml_fc_psi_weights(a$coef$ar, a$coef$ma, a$coef$sar, a$coef$sma, spec$d, spec$D, m, h)
  se <- sqrt(sigma2 * cumsum(psi * psi))
  lower <- list(); upper <- list()
  for (level in levels) {
    z <- cs_ml_fc_z(level)
    lower[[as.character(level)]] <- mean_ - z * se
    upper[[as.character(level)]] <- mean_ + z * se
  }
  k0 <- length(y) - length(w)
  fitted <- c(rep(NaN, k0), y[(k0 + 1):length(y)] - as.numeric(stats::residuals(a$fit)))
  facts <- list()
  for (nm in c("ar", "ma", "sar", "sma")) for (i in seq_along(a$coef[[nm]])) facts[[paste0(nm, i)]] <- a$coef[[nm]][i]
  if (spec$constant) facts$mean <- a$coef$mean
  for (j in seq_along(a$coef$beta)) facts[[sprintf("beta_%d", j)]] <- a$coef$beta[j]
  facts$sigma2 <- sigma2
  facts$loglik <- a$fit$loglik
  facts$aicc <- cs_ml_fc_aicc(a$fit$loglik, spec$p + spec$q + spec$P + spec$Q + as.integer(spec$constant) + 1 + ncol(Xd), length(w))
  v <- diag(a$fit$var.coef)
  COEF[[if (is.null(current_series)) "_" else current_series]] <<- lapply(seq_len(ncol(Xd)), function(j) {
    list(term = XREG[j], estimate = a$coef$beta[j], se = sqrt(unname(v[sprintf("x%d", j)])))
  })
  RESID[[if (is.null(current_series)) "_" else current_series]] <<- list(z = as.numeric(stats::residuals(a$fit)), fitdf = spec$p + spec$q + spec$P + spec$Q)
  # actual − fitted are these residuals; the check removes the ARMA terms
  DIAG[[if (is.null(current_series)) "_" else current_series]] <<- list(fitdf = spec$p + spec$q + spec$P + spec$Q)
  list(mean = mean_, lower = lower, upper = upper, fitted = fitted,
       label = paste0(cs_ml_fc_arima_label(spec$p, spec$d, spec$q, spec$P, spec$D, spec$Q, m, spec$constant), " with regressors"), 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")
  ))
}

if (n_origins > 0) {
  warnings <- c(warnings, paste0(
    "The backtest gave the model the actual future values of ", paste(XREG, collapse = ", "), ". A real forecast only knows them when",
    " they are planned or fixed in advance (holidays, prices you set), so read the backtest accuracy as a best case."
  ))
}
# %% Regressors
extra_tables[[length(extra_tables) + 1]] <- list(
  key = "regressors",
  title = paste0("Regression coefficients (on the differenced scale when the model differences)", if (!is.null(SERIES)) paste0(" — ", series_keys[1]) else ""),
  columns = list(list(key = "term", label = "Regressor"), list(key = "estimate", label = "Estimate", type = "number"), list(key = "se", label = "SE", type = "number")),
  rows = COEF[[if (is.null(SERIES)) "_" else series_keys[1]]]
)
resid0 <- RESID[[if (is.null(SERIES)) "_" else series_keys[1]]]
check0 <- cs_fcm_residual_check(resid0$z, seasons[1], resid0$fitdf)
if (!is.null(check0)) {
  values$lb_p <- check0$p
  extra_assumptions[[length(extra_assumptions) + 1]] <- cs_fcm_residual_row(check0, "The error model has left dynamics unexplained: try more AR or MA terms, or let the search choose them.", 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 = "ARIMAX (regression with ARIMA errors)",
  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

ARIMA(0,1,1)(0,1,1)[12] with regressors: 12-step forecasts of drivers (monthly data, 192 observations). Backtest MAE 7.99 over 1 origin.

MAE
7.992
RMSE
11.243
MAPE
0.0715

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

Assumptions

  • Residuals look uncorrelated — Ljung–Box at 24 lags: p = 0.108.

Backtest accuracy (1 origin, horizon 12)

MetricValue
MAE7.992
RMSE11.243
MAPE0.0715
sMAPE0.0732
MASE0.4672
WAPE0.0781
Coverage of the 80% interval0.9167
Coverage of the 95% interval1

Regression coefficients (on the differenced scale when the model differences)

RegressorEstimateSE
petrol−4.3131.788
law−20.3089.974

Forecast

monthForecast80% low80% high95% low95% high
1985-01-01101.0280.674121.3769.902132.15
1985-02-0189.08668.559109.6157.692120.48
1985-03-0192.55671.852113.2660.892124.22
1985-04-0189.33368.454110.2157.402121.26
1985-05-0189.94668.894111.0057.750122.14
1985-06-0196.96175.737118.1964.502129.42
1985-07-0195.65174.257117.0562.931128.37
1985-08-0197.99976.435119.5665.020130.98
1985-09-01110.8289.092132.5677.588144.06
1985-10-01123.54101.64145.4490.052157.03
1985-11-01130.54108.47152.6096.793164.28
1985-12-01137.40115.17159.63103.40171.39
  • The backtest gave the model the actual future values of petrol, law. A real forecast only knows them when they are planned or fixed in advance (holidays, prices you set), so read the backtest accuracy as a best case.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# ARIMAX (regression with ARIMA errors)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.arimax 1.0.1 · spec 719025f71e942d5a
# Dataset: f7_seatbelts_future (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
import warnings as _warnings

from statsmodels.tsa.arima.model import ARIMA

from codesplash.ml import forecast_models as fcm

# %% Data
TIME = "month"
VALUE = "drivers"
SERIES = None
H = 12
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 = ["petrol", "law"]
PARAMS = {
    "order": "manual",
    "p": 0,
    "d": 1,
    "q": 1,
    "sp": 0,
    "sd": 1,
    "sq": 1,
    "constant": "auto",
}
df = pd.read_parquet("tests/parity/fixtures/f7_seatbelts_future.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.arimax/seatbelts_airline_known_future/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
# Regression with ARIMA errors: y_t = c + x_t'β + n_t with n_t ~ ARIMA(p,d,q)(P,D,Q)[m]. The outcome and the regressors are
# differenced explicitly and an ARMA with regressors is fitted to the differences by exact Gaussian ML; the R script fits the
# same model with stats::arima. Forecasts are integrated back; their variances come from the ψ weights of the error model, so
# they treat the regression coefficients and the future regressors as known, as forecast::Arima does. Refits start from the ARMA
# coefficients of the full series: short windows can have several likelihood optima, and both engines should stay in the same one.


def min_train(m):
    base = 2 * m + 6 if m > 1 else 10
    return base + len(XREG) + 2


def start_vector(mod, coef, m):
    """The model's parameters in statsmodels' order, from a coefficient dict."""
    out = []
    for name in mod.param_names:
        if name == "const":
            out.append(coef["mean"])
        elif name.startswith("ar.S.L"):
            out.append(coef["sar"][int(name[6:]) // m - 1])
        elif name.startswith("ma.S.L"):
            out.append(coef["sma"][int(name[6:]) // m - 1])
        elif name.startswith("ar.L"):
            out.append(coef["ar"][int(name[4:]) - 1])
        elif name.startswith("ma.L"):
            out.append(coef["ma"][int(name[4:]) - 1])
        else:
            out.append(coef["beta"][int(name[1:]) - 1])
    return np.array(out)


def arma_fit(w, Xd, p, q, P, Q, m, constant, start=None):
    """→ (results, coefficients). Refined L-BFGS → Nelder–Mead → BFGS so the optimum matches R's."""
    seas = (P, 0, Q, m) if m > 1 and (P or Q) else (0, 0, 0, 0)
    mod = ARIMA(np.asarray(w, dtype=np.float64), exog=Xd, order=(p, 0, q), seasonal_order=seas, trend="c" if constant else "n", concentrate_scale=True)
    with _warnings.catch_warnings():
        _warnings.simplefilter("ignore")
        first = start_vector(mod, start, m) if start is not None else mod.fit(method="statespace", method_kwargs={"maxiter": 5000}).params
        r = mod.fit(start_params=first, method="statespace", method_kwargs={"method": "nm", "maxiter": 20000, "xtol": 1e-12, "ftol": 1e-14})
        r = mod.fit(start_params=r.params, method="statespace", method_kwargs={"method": "bfgs", "maxiter": 5000, "gtol": 1e-10})
    coef = {"ar": [0.0] * p, "ma": [0.0] * q, "sar": [0.0] * P, "sma": [0.0] * Q, "mean": 0.0, "beta": [0.0] * Xd.shape[1]}
    for name, value in zip(mod.param_names, np.atleast_1d(r.params)):
        if name == "const":
            coef["mean"] = float(value)
        elif name.startswith("ar.S.L"):
            coef["sar"][int(name[6:]) // m - 1] = float(value)
        elif name.startswith("ma.S.L"):
            coef["sma"][int(name[6:]) // m - 1] = float(value)
        elif name.startswith("ar.L"):
            coef["ar"][int(name[4:]) - 1] = float(value)
        elif name.startswith("ma.L"):
            coef["ma"][int(name[4:]) - 1] = float(value)
        elif name.startswith("x"):
            coef["beta"][int(name[1:]) - 1] = float(value)
    return r, coef


def diff_columns(X, d, D, m):
    return np.column_stack([fc.difference([float(v) for v in X[:, j]], d, D, m) for j in range(X.shape[1])])


def check_constant(X):
    """A regressor that does not vary once differenced cannot be estimated."""
    for j, name in enumerate(XREG):
        if float(np.max(X[:, j]) - np.min(X[:, j])) == 0.0:
            raise ValueError(f"{name} does not vary in this window, so its effect cannot be estimated")


def with_start(spec, y, m):
    """The orders plus the full series' coefficients, the starting point of every refit."""
    p, d, q, P, D, Q, c = spec
    w = fc.difference(y, d, D, m)
    Xd = diff_columns(x_grid, d, D, m)
    check_constant(Xd)
    return (p, d, q, P, D, Q, c, arma_fit(w, Xd, p, q, P, Q, m, c)[1])


def prepare_series(y, t, m, freq):
    """(p, d, q, P, D, Q, constant, start): from the options, or the stepwise AICc search (x_grid: all regressors)."""
    seasonal = m > 1
    if PARAMS["order"] == "manual":
        d = int(PARAMS["d"])
        D = int(PARAMS["sd"]) if seasonal else 0
        c = PARAMS["constant"] == "yes" or (PARAMS["constant"] == "auto" and d + D <= 1)
        return with_start((int(PARAMS["p"]), d, int(PARAMS["q"]), int(PARAMS["sp"]) if seasonal else 0, D, int(PARAMS["sq"]) if seasonal else 0, c), y, m)
    # Like auto.arima with xreg: choose the differencing on the residuals of the regression.
    Xc = np.column_stack([np.ones(len(y)), x_grid])
    u = np.asarray(y, dtype=float) - Xc @ np.linalg.solve(Xc.T @ Xc, Xc.T @ np.asarray(y, dtype=float))
    u = [float(v) for v in u]
    D = fc.nsdiffs(u, m) if seasonal else 0
    d = fc.ndiffs(fc.difference(u, 0, D, m))
    w = fc.difference(y, d, D, m)
    Xd = diff_columns(x_grid, d, D, m)
    check_constant(Xd)
    allow_c = PARAMS["constant"] == "yes" or (PARAMS["constant"] == "auto" and d + D <= 1)

    def score(p, q, P, Q, c):
        try:
            r, coef = arma_fit(w, Xd, p, q, P, Q, m, c)
            if fc.min_root(coef["ar"], coef["ma"], coef["sar"], coef["sma"], m) < 1.01:
                return math.inf
            return fc.aicc(float(r.llf), p + q + P + Q + int(bool(c)) + 1 + Xd.shape[1], len(w))
        except Exception:
            return math.inf

    best, table = fc.stepwise_orders(score, d, D, m, allow_c)
    extra_tables.append(
        {
            "key": f"selection{len(extra_tables) + 1}",
            "title": "Stepwise order search (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 math.isfinite(r["aicc"]) else float("inf")),
        }
    )
    return with_start((best[0], d, best[1], best[2], D, best[3], bool(best[4])), y, m)


COEF = {}
RESID = {}


def fit_forecast(y, t, h, m, levels, spec):
    p, d, q, P, D, Q, c, start = spec
    w = fc.difference(y, d, D, m)
    Xall = diff_columns(np.vstack([X_TRAIN, X_FUTURE]), d, D, m)
    Xd, Xf = Xall[: len(w)], Xall[len(w) :]
    check_constant(Xd)
    r, coef = arma_fit(w, Xd, p, q, P, Q, m, c, start)
    sigma2 = float(r.scale)
    w_fc = [float(v) for v in np.asarray(r.get_forecast(h, exog=Xf).predicted_mean)]
    mean = fc.integrate(y, w_fc, d, D, m)
    psi = fc.psi_weights(coef["ar"], coef["ma"], coef["sar"], coef["sma"], d, D, m, h)
    se = []
    acc = 0.0
    for j in range(h):
        acc += psi[j] * psi[j]
        se.append(math.sqrt(sigma2 * acc))
    lower, upper = {}, {}
    for level in levels:
        z = fc.z_value(level)
        lower[level] = [mean[k] - z * se[k] for k in range(h)]
        upper[level] = [mean[k] + z * se[k] for k in range(h)]
    resid = [float(v) * math.sqrt(sigma2) for v in np.asarray(r.standardized_forecasts_error[0])]  # innovations ÷ √gain, what stats::residuals gives
    k0 = len(y) - len(w)
    fitted = [float("nan")] * k0 + [y[k0 + i] - resid[i] for i in range(len(w))]
    facts = {}
    for name in ("ar", "ma", "sar", "sma"):
        for i, v in enumerate(coef[name]):
            facts[f"{name}{i + 1}"] = v
    if c:
        facts["mean"] = coef["mean"]
    for j, v in enumerate(coef["beta"]):
        facts[f"beta_{j + 1}"] = v
    facts["sigma2"] = sigma2
    facts["loglik"] = float(r.llf)
    facts["aicc"] = fc.aicc(float(r.llf), p + q + P + Q + int(bool(c)) + 1 + Xd.shape[1], len(w))
    names = list(r.model.param_names)
    bse = np.atleast_1d(r.bse)
    COEF[current_series] = [
        {"term": XREG[j], "estimate": coef["beta"][j], "se": float(bse[names.index(f"x{j + 1}")])} for j in range(Xd.shape[1])
    ]
    RESID[current_series] = (resid, p + q + P + Q)
    DIAG[current_series] = {"fitdf": p + q + P + Q}  # actual − fitted are these residuals; the check removes the ARMA terms
    label = fc.arima_label(p, d, q, P, D, Q, m, c) + " with regressors"
    return {"mean": mean, "lower": lower, "upper": upper, "fitted": fitted, "label": 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"),
            },
        )
    )

if n_origins:
    warnings.append(
        f"The backtest gave the model the actual future values of {', '.join(XREG)}. A real forecast only knows them when"
        " they are planned or fixed in advance (holidays, prices you set), so read the backtest accuracy as a best case."
    )
# %% Regressors
rows0 = COEF[series_keys[0]]
extra_tables.append(
    {
        "key": "regressors",
        "title": "Regression coefficients (on the differenced scale when the model differences)" + (f" — {series_keys[0]}" if SERIES else ""),
        "columns": [{"key": "term", "label": "Regressor"}, {"key": "estimate", "label": "Estimate", "type": "number"}, {"key": "se", "label": "SE", "type": "number"}],
        "rows": rows0,
    }
)
resid0, fitdf0 = RESID[series_keys[0]]
check0 = fcm.residual_check(resid0, seasons[0], fitdf0)
if check0 is not None:
    values["lb_p"] = check0["p"]
    extra_assumptions.append(fcm.residual_row(check0, "The error model has left dynamics unexplained: try more AR or MA terms, or let the search choose them.", 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": "ARIMAX (regression with ARIMA errors)",
        "engine": cs.engine_info("statsmodels", "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,
    }
)

For drivers killed per month, the petrol-price coefficient is −4.3, and the law's is −20.3. The Ljung–Box check gives 0.11.

Is this a causal estimate of the law? What would you check?

07

The future regressor

Predict

Predict first

You forecast ice-cream sales using temperature as a regressor. The backtest looks great. What's the catch?

It's fine: the model handles itYou'd need next year's weather; the backtest assumes you already have itWeather can't be a regressor
Reveal

You'd need next year's temperatures to forecast. A backtest uses the realized values of regressors, so it assumes you knew them in advance, and it flatters the model. Use regressors you really know ahead of time, such as holidays or planned prices. Otherwise, CodeSplash holds the last known values, and its intervals don't include the uncertainty in your regressors.

08

Known future values

Reflect

To give future regressors, add rows with the regressors filled in and the value empty. The example above has twelve such months.

With errors of a simpler form, ARIMA(1,0,0)(1,0,0)[12] with mean with regressors, the Ljung–Box check drops to 0.02.

Which drivers of your series do you know ahead of time? Which would you need to forecast too, and what would that add to your uncertainty?

09

Check your understanding

Checkpoint

Check yourself

How many coefficients does an ARIMA(1,1,1)(0,1,1)[12] with no constant estimate, not counting the variance?

Show the answer

Answer: 3

AR(1), MA(1) and seasonal MA(1): three. Differences don't add coefficients.

Check yourself

Which comparison can AICc make safely?

Show the answer

Answer: a

Only the first has the same differencing. Use a backtest for the others.

Check yourself

Ljung–Box on residuals gives p = 0.60. What does this tell you?

Show the answer

Answer: b

Clean residuals describe the fit to the past. Only a backtest speaks about new data.

Check yourself

A law regressor is 0 before the law and 1 after. Its coefficient is −20 on monthly deaths. By how much does the model expect monthly deaths to change when the law starts?

Show the answer

Answer: -20

By 1×(−20)=−201 \times (-20) = -20 per month, holding the other regressor and the error process fixed.

Check yourself

A regressor's future isn't known. What's the honest way to backtest ARIMAX with it?

Show the answer

Answer: b

A backtest with realized regressors answers "if I'd known the future of xx", which isn't what you'll have in production.

Check yourself

Why use ARIMA errors rather than plain regression on a series?

Show the answer

Answer: b

Errors in a series usually carry autocorrelation. Modeling it gives better uncertainty, and often better forecasts.

10

Do it in CodeSplash

In the app

In Forecast, choose ARIMA or ARIMAX (regression with ARIMA errors). Set Orders to Set p, d, q (and P, D, Q) to fix them. The Series lab's hand-off fills in dd and DD.

Python
import pandas as pd
from statsmodels.tsa.arima.model import ARIMA

df = pd.read_csv("seatbelts.csv", parse_dates=["month"], index_col="month").asfreq("MS")
fit = ARIMA(
    df["drivers"],
    exog=df[["petrol", "law"]],
    order=(0, 1, 1),
    seasonal_order=(0, 1, 1, 12),
).fit()
print(fit.summary())
R
# install.packages("forecast")
library(forecast)
sb <- as.data.frame(Seatbelts)
y <- ts(sb$DriversKilled, frequency = 12, start = c(1969, 1))
X <- cbind(petrol = sb$PetrolPrice * 100, law = sb$law)
fit <- Arima(y, order = c(0, 1, 1), seasonal = c(0, 1, 1), xreg = X)
summary(fit)
checkresiduals(fit)
11

Recap

Recap
  • ARIMA's dd and DD handle trends and seasons. The other orders handle what's left.
  • AICc only compares models with the same differencing, and clean residuals aren't a forecast test.
  • ARIMAX adds drivers with autocorrelated errors.
  • Its backtests assume you know the regressors in advance. Check that this is true.

Concepts in this lesson