Skip to content

DForecasting · forecast.arimax

ARIMAX (regression with ARIMA errors)

How will the series continue, given its own dynamics and regressors you can supply for the future?

A regression on your regressors with seasonal ARIMA errors, by exact Gaussian maximum likelihood. Orders are chosen by you or by a stepwise AICc search. The outcome and the regressors are differenced explicitly and an ARMA model with regressors is fitted to the differences by statsmodels (Python) or stats::arima (R). Put known future regressor values in rows with an empty value; otherwise the last known values are held. Backtests use the regressors' realized values, so they assume you would have known them in advance.

Verified in Python and R Python and R agree to 6 decimals Also called ARIMAX, SARIMAX, regression with ARIMA errors…

A real result

Example “Seatbelts ar errors”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

ARIMAX (regression with ARIMA errors)Recorded · Python and R agreeRecorded 2026-11-25 · 31 values compared · largest relative difference 2.3e-7
R

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

MAE
12.932
RMSE
17.751
MAPE
0.1146

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
−6.25111983-12-01
−10.98921983-12-01
−17.49831983-12-01
−10.26241983-12-01
−3.89551983-12-01
−4.26361983-12-01
−1.47271983-12-01
3.83381983-12-01
15.42291983-12-01
8.175101983-12-01
27.040111983-12-01
46.086121983-12-01
Residual autocorrelationIs a series (or a model's residuals) autocorrelated, and at which lags?
View data
ACFboundlag
0.00040.14141
0.07420.14142
−0.08020.14143
−0.10000.14144
−0.04810.14145
0.01250.14146
−0.12120.14147
0.06100.14148
0.04700.14149
−0.06240.141410
0.12040.141411
−0.11510.141412
0.20030.141413
−0.06280.141414
0.03870.141415
−0.07540.141416
0.08920.141417
−0.05950.141418
0.03720.141419
−0.05510.141420
−0.07390.141421
−0.03760.141422
0.13290.141423
0.10220.141424

Assumptions

  • Residuals look uncorrelated — Ljung–Box at 24 lags: p = 0.022. The error model has left dynamics unexplained: try more AR or MA terms, or let the search choose them.

Backtest accuracy (1 origin, horizon 12)

MetricValue
MAE12.932
RMSE17.751
MAPE0.1146
sMAPE0.1185
MASE0.7560
WAPE0.1264
Coverage of the 80% interval0.8333
Coverage of the 95% interval0.9167

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

RegressorEstimateSE
petrol−4.3551.947
law−19.5407.538

Forecast

monthForecast80% low80% high95% low95% high
1985-01-01113.7692.005135.5180.490147.03
1985-02-0199.48776.141122.8363.783135.19
1985-03-0193.05369.475116.6356.993129.11
1985-04-0192.85769.244116.4756.744128.97
1985-05-0193.61069.992117.2357.489129.73
1985-06-0194.85771.237118.4858.734130.98
1985-07-0189.29865.678112.9253.175125.42
1985-08-0197.72774.108121.3561.604133.85
1985-09-01110.5586.935134.1774.432146.68
1985-10-01110.0786.447133.6973.943146.19
1985-11-01118.4694.846142.0882.342154.59
1985-12-01126.97103.35150.5990.847163.09
  • Backtest from 1982-12-01 failed: law does not vary in this window, so its effect cannot be estimated
  • Future values of petrol, law are known for 0 of 12 steps; the last known values are held for the rest.
  • 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.
Python

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

MAE
12.932
RMSE
17.751
MAPE
0.1146

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.022. The error model has left dynamics unexplained: try more AR or MA terms, or let the search choose them.

Backtest accuracy (1 origin, horizon 12)

MetricValue
MAE12.932
RMSE17.751
MAPE0.1146
sMAPE0.1185
MASE0.7560
WAPE0.1264
Coverage of the 80% interval0.8333
Coverage of the 95% interval0.9167

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

RegressorEstimateSE
petrol−4.3552.050
law−19.54010.054

Forecast

monthForecast80% low80% high95% low95% high
1985-01-01113.7692.005135.5180.490147.03
1985-02-0199.48776.141122.8363.783135.19
1985-03-0193.05369.475116.6356.993129.11
1985-04-0192.85769.244116.4756.744128.97
1985-05-0193.61069.992117.2357.489129.73
1985-06-0194.85771.237118.4858.734130.98
1985-07-0189.29865.678112.9253.175125.42
1985-08-0197.72774.108121.3561.604133.85
1985-09-01110.5586.935134.1774.432146.68
1985-10-01110.0786.447133.6973.943146.19
1985-11-01118.4694.846142.0882.342154.59
1985-12-01126.97103.35150.5990.847163.09
  • Backtest from 1982-12-01 failed: law does not vary in this window, so its effect cannot be estimated
  • Future values of petrol, law are known for 0 of 12 steps; the last known values are held for the rest.
  • 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.

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Seatbelts ar errorsf7_seatbelts · time: month · value: drivers · xreg: petrol, law
  • Seatbelts airline known futuref7_seatbelts_future · time: month · value: drivers · xreg: petrol, law
  • Seatbelts autof7_seatbelts · time: month · value: drivers · xreg: petrol
  • Seatbelts experiment planf7_seatbelts · time: month · value: drivers · xreg: petrol, law

In the guides

Where it sits in the decision guides

  • Time series (ARIMA, ETS) · DS & ML Decision Guide · Predict — forecast or classify outcomes
  • Probabilistic forecasting (Bayesian, deep ensembles) · DS & ML Decision Guide · Predict — forecast or classify outcomes

What you need

Timetemporal / numeric · 1 column
Dates or evenly spaced numbers; gaps are filled by linear interpolation.
Valuenumeric · 1 column
What to forecast.
Regressorsnumeric · 1–20 columns
Numeric drivers of the value. Rows after the last observed value may carry their known future values.
Seriescategorical · 0–1 column
Optional: one forecast per series (panel data in long format).

Choices you make

model

Ordersdefault auto

Let the AICc search choose the ARIMA orders, or set p, d, q (and seasonal P, D, Q) yourself.

  • Automatic (stepwise AICc search)(default) — Differencing is chosen on the regression's residuals, then the stepwise search picks the orders, as auto.arima does.
  • Set p, d, q (and P, D, Q) — Use the orders below.
AR order pdefault 1

Number of autoregressive terms p (manual orders only).

Differences ddefault 1

Number of ordinary differences d (manual orders only). Usually 0 or 1.

MA order qdefault 1

Number of moving-average terms q (manual orders only).

Seasonal AR order Pdefault 0

Number of seasonal autoregressive terms P (manual orders only).

Seasonal differences Ddefault 0

Number of seasonal differences D (manual orders only). Usually 0 or 1.

Seasonal MA order Qdefault 0

Number of seasonal moving-average terms Q (manual orders only).

Constant (mean or drift)default auto

Automatic includes a mean (no differencing) or drift (one difference) when it lowers AICc, as auto.arima does.

  • Automatic(default) — Allowed with at most one difference in total, kept when it lowers AICc.
  • Include — Always include a mean or drift.
  • Leave out — The differenced series is centered on the regression alone.

options

Horizondefault 12

Steps ahead to forecast.

Interval levels (%)default 80,95

Coverage of the prediction intervals drawn around the forecast, in percent (80% and 95% by default).

Season lengthdefault —

Observations per seasonal cycle (12 monthly, 4 quarterly, 7 daily …); automatic reads the time steps.

validation

Backtest originsdefault 3

Refit on the data up to each origin and forecast the next horizon (0 = no backtest). Automatic orders are chosen once on the whole series.

Origin spacingdefault —

Periods between backtest origins. Leave empty to step by the horizon, so the test windows don't overlap.

Advanced

Train fromdefault —

Leave out rows before this date or number, for example before a structural break. Empty uses every row.

Training windowdefault —

Train each backtest on only this many values before its origin (a sliding window). Empty uses all of them.

Backtest plandefault —

Set by forecast experiments: each origin's distance from the end of the series, shared by all their models.

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • Residuals look uncorrelated

    Ljung–Box test on the one-step residuals: a small p means the error model has left dynamics unexplained.

    • If violated → Let the search choose the orders — The stepwise AICc search can add the AR or MA terms that leftover autocorrelation calls for, on the same regressors.

What it reports

n_obs
How many independent units the analysis used; it sets precision and power.
horizon
How many periods ahead a forecast predicts; uncertainty grows with the horizon.
season
A pattern that repeats at a fixed period — daily, weekly, yearly.
n_series
How many series a run forecast. With a series column in long format, each one gets its own model and its own backtest.
fc_check
A single weighted average of the whole forecast, later steps counting more, so two runs or engines can be compared with one number.
n_origins
How many points in the series a forecaster was refit from and scored against the values that followed.
filled
How many missing steps in the regular time grid were filled before fitting, so the series has no holes.
model_label
The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
freq_label
The spacing of the time grid the forecaster used (daily, weekly, monthly …), as a code and in words.
frequency
The spacing of the time grid the forecaster used (daily, weekly, monthly …), as a code and in words.

Per group, level or term: bt[<metric>], ar<i>, ma<i>, sar<i>, sma<i>, beta_<i>, mean, sigma2, loglik, aicc, lb_p, <fact>[<series>], fc_lo_check, fc_hi_check

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-5). Python uses statsmodels, scipy; R uses stats.

Default traps between the two languages

  • Different optimizers reach the same likelihood optimum, as for forecast.arima (statsmodels' state-space ML against stats::arima with reltol 1e-14), with refits started from the full series' ARMA coefficients so both stay in the same optimum. Coefficients and forecasts agree to about 1e-6 relative. Standard errors in the coefficient table come from each library's own numerical Hessian and differ more; they are not part of the parity check.
  • Forecast variances treat the coefficients and the future regressors as known, as stats::predict.Arima and forecast::Arima do, so intervals are too narrow when the future regressors are themselves uncertain.
Python

The exact script CodeSplash ran for example “Seatbelts ar errors” · 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 6c30b4aede693d4b
# Dataset: f7_seatbelts (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 = 2
STEP = None  # None = the horizon
OFFSETS = None  # the host's BacktestPlan: distance of each origin from the end of the series; None = windows and step
TRAIN_WINDOW = None  # None = train on all values before each origin
TRAIN_START = None  # rows before this time are left out (for example, before a structural break)
SEED = 42
XREG = ["petrol", "law"]
PARAMS = {
    "order": "manual",
    "p": 1,
    "d": 0,
    "q": 0,
    "sp": 1,
    "sd": 0,
    "sq": 0,
    "constant": "yes",
}
df = pd.read_parquet("tests/parity/fixtures/f7_seatbelts.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_ar_errors/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,
    }
)
R

The exact script CodeSplash ran for example “Seatbelts ar errors” · 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 6c30b4aede693d4b
# Dataset: f7_seatbelts (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 <- 2
STEP <- NULL  # NULL = the horizon
OFFSETS <- NULL  # the host's BacktestPlan: distance of each origin from the end of the series; NULL = windows and step
TRAIN_WINDOW <- NULL  # NULL = train on all values before each origin
TRAIN_START <- NULL  # rows before this time are left out (for example, before a structural break)
SEED <- 42
XREG <- c("petrol", "law")
PARAMS <- list(
  order = "manual",
  p = 1,
  d = 0,
  q = 0,
  sp = 1,
  sd = 0,
  sq = 0,
  constant = "yes"
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/f7_seatbelts.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_ar_errors/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
))

Sources

  • Box GEP, Jenkins GM, Reinsel GC, Ljung GM (2015). Time Series Analysis: Forecasting and Control, 5th ed. Wiley.
  • Hyndman RJ, Athanasopoulos G (2021). Forecasting: Principles and Practice, 3rd ed., ch. 10 (dynamic regression). OTexts.

From the CodeSplash method registry · forecast.arimax v1.0.1.