DForecasting · forecast.arima
ARIMA
How will the series continue, given its autocorrelation, trend and seasonality?
Seasonal ARIMA(p,d,q)(P,D,Q)[m] by exact Gaussian maximum likelihood — orders chosen by you or by a Hyndman–Khandakar stepwise search on AICc (KPSS for d, seasonal strength for D). The series is differenced explicitly and an ARMA model with an optional mean (drift) is fitted to the differences by statsmodels (Python) or stats::arima (R); forecasts are integrated back and their intervals come from the model's ψ weights.
A real result
Example “Airline manual”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
ARIMA(0,1,1)(0,1,1)[12]: 12-step forecasts of passengers (monthly data, 144 observations). Backtest MAE 30.2 over 2 origins.
- MAE
- 30.242
- RMSE
- 35.957
- MAPE
- 0.0699
Plots
View data
| hi_80 | hi_95 | kind | lo_80 | lo_95 | month | passengers |
|---|---|---|---|---|---|---|
| — | — | actual | — | — | −662,688,000,000 | 112 |
| — | — | actual | — | — | −660,009,600,000 | 118 |
| — | — | actual | — | — | −657,590,400,000 | 132 |
| — | — | actual | — | — | −654,912,000,000 | 129 |
| — | — | actual | — | — | −652,320,000,000 | 121 |
| — | — | actual | — | — | −649,641,600,000 | 135 |
| — | — | actual | — | — | −647,049,600,000 | 148 |
| — | — | actual | — | — | −644,371,200,000 | 148 |
| — | — | actual | — | — | −641,692,800,000 | 136 |
| — | — | actual | — | — | −639,100,800,000 | 119 |
| — | — | actual | — | — | −636,422,400,000 | 104 |
| — | — | actual | — | — | −633,830,400,000 | 118 |
| — | — | actual | — | — | −631,152,000,000 | 115 |
| — | — | actual | — | — | −628,473,600,000 | 126 |
| — | — | actual | — | — | −626,054,400,000 | 141 |
| — | — | actual | — | — | −623,376,000,000 | 135 |
| — | — | actual | — | — | −620,784,000,000 | 125 |
| — | — | actual | — | — | −618,105,600,000 | 149 |
| — | — | actual | — | — | −615,513,600,000 | 170 |
| — | — | actual | — | — | −612,835,200,000 | 170 |
| — | — | actual | — | — | −610,156,800,000 | 158 |
| — | — | actual | — | — | −607,564,800,000 | 133 |
| — | — | actual | — | — | −604,886,400,000 | 114 |
| — | — | actual | — | — | −602,294,400,000 | 140 |
| — | — | actual | — | — | −599,616,000,000 | 145 |
| — | — | actual | — | — | −596,937,600,000 | 150 |
| — | — | actual | — | — | −594,518,400,000 | 178 |
| — | — | actual | — | — | −591,840,000,000 | 163 |
| — | — | actual | — | — | −589,248,000,000 | 172 |
| — | — | actual | — | — | −586,569,600,000 | 178 |
| — | — | actual | — | — | −583,977,600,000 | 199 |
| — | — | actual | — | — | −581,299,200,000 | 199 |
| — | — | actual | — | — | −578,620,800,000 | 184 |
| — | — | actual | — | — | −576,028,800,000 | 162 |
| — | — | actual | — | — | −573,350,400,000 | 146 |
| — | — | actual | — | — | −570,758,400,000 | 166 |
| — | — | actual | — | — | −568,080,000,000 | 171 |
| — | — | actual | — | — | −565,401,600,000 | 180 |
| — | — | actual | — | — | −562,896,000,000 | 193 |
| — | — | actual | — | — | −560,217,600,000 | 181 |
| — | — | actual | — | — | −557,625,600,000 | 183 |
| — | — | actual | — | — | −554,947,200,000 | 218 |
| — | — | actual | — | — | −552,355,200,000 | 230 |
| — | — | actual | — | — | −549,676,800,000 | 242 |
| — | — | actual | — | — | −546,998,400,000 | 209 |
| — | — | actual | — | — | −544,406,400,000 | 191 |
| — | — | actual | — | — | −541,728,000,000 | 172 |
| — | — | actual | — | — | −539,136,000,000 | 194 |
| — | — | actual | — | — | −536,457,600,000 | 196 |
| — | — | actual | — | — | −533,779,200,000 | 196 |
| — | — | actual | — | — | −531,360,000,000 | 236 |
| — | — | actual | — | — | −528,681,600,000 | 235 |
| — | — | actual | — | — | −526,089,600,000 | 229 |
| — | — | actual | — | — | −523,411,200,000 | 243 |
| — | — | actual | — | — | −520,819,200,000 | 264 |
| — | — | actual | — | — | −518,140,800,000 | 272 |
| — | — | actual | — | — | −515,462,400,000 | 237 |
| — | — | actual | — | — | −512,870,400,000 | 211 |
| — | — | actual | — | — | −510,192,000,000 | 180 |
| — | — | actual | — | — | −507,600,000,000 | 201 |
First 60 of 156 rows.
View data
| error | horizon | origin |
|---|---|---|
| 17.484 | 1 | 1958-12-01 |
| 21.102 | 2 | 1958-12-01 |
| 40.629 | 3 | 1958-12-01 |
| 44.345 | 4 | 1958-12-01 |
| 53.717 | 5 | 1958-12-01 |
| 33.970 | 6 | 1958-12-01 |
| 54.575 | 7 | 1958-12-01 |
| 52.147 | 8 | 1958-12-01 |
| 55.374 | 9 | 1958-12-01 |
| 44.907 | 10 | 1958-12-01 |
| 48.571 | 11 | 1958-12-01 |
| 64.379 | 12 | 1958-12-01 |
| −5.984 | 1 | 1959-12-01 |
| −13.708 | 2 | 1959-12-01 |
| −48.091 | 3 | 1959-12-01 |
| 4.201 | 4 | 1959-12-01 |
| −7.982 | 5 | 1959-12-01 |
| 1.375 | 6 | 1959-12-01 |
| 14.155 | 7 | 1959-12-01 |
| −13.006 | 8 | 1959-12-01 |
| −14.863 | 9 | 1959-12-01 |
| −6.711 | 10 | 1959-12-01 |
| −32.427 | 11 | 1959-12-01 |
| −32.109 | 12 | 1959-12-01 |
View data
| ACF | bound | lag |
|---|---|---|
| −0.0037 | 0.1712 | 1 |
| 0.0476 | 0.1712 | 2 |
| −0.1044 | 0.1712 | 3 |
| −0.1531 | 0.1712 | 4 |
| 0.0099 | 0.1712 | 5 |
| −0.0220 | 0.1712 | 6 |
| −0.0894 | 0.1712 | 7 |
| −0.0638 | 0.1712 | 8 |
| 0.1262 | 0.1712 | 9 |
| −0.1087 | 0.1712 | 10 |
| 0.0439 | 0.1712 | 11 |
| −0.0231 | 0.1712 | 12 |
| 0.0770 | 0.1712 | 13 |
| 0.0476 | 0.1712 | 14 |
| 0.0208 | 0.1712 | 15 |
| −0.1222 | 0.1712 | 16 |
| −0.0383 | 0.1712 | 17 |
| −0.0187 | 0.1712 | 18 |
| −0.1770 | 0.1712 | 19 |
| −0.1418 | 0.1712 | 20 |
| −0.0236 | 0.1712 | 21 |
| −0.0871 | 0.1712 | 22 |
| 0.2885 | 0.1712 | 23 |
| 0.1417 | 0.1712 | 24 |
Backtest accuracy (2 origins, horizon 12)
| Metric | Value |
|---|---|
| MAE | 30.242 |
| RMSE | 35.957 |
| MAPE | 0.0699 |
| sMAPE | 0.0724 |
| MASE | 1.041 |
| WAPE | 0.0669 |
| Coverage of the 80% interval | 0.4583 |
| Coverage of the 95% interval | 0.6667 |
Forecast
| month | Forecast | 80% low | 80% high | 95% low | 95% high |
|---|---|---|---|---|---|
| 1961-01-01 | 447.05 | 432.14 | 461.97 | 424.24 | 469.86 |
| 1961-02-01 | 421.88 | 403.75 | 440.01 | 394.15 | 449.61 |
| 1961-03-01 | 453.53 | 432.67 | 474.38 | 421.63 | 485.42 |
| 1961-04-01 | 489.90 | 466.63 | 513.17 | 454.32 | 525.48 |
| 1961-05-01 | 502.18 | 476.74 | 527.63 | 463.26 | 541.10 |
| 1961-06-01 | 564.22 | 536.77 | 591.68 | 522.23 | 606.22 |
| 1961-07-01 | 649.80 | 620.47 | 679.12 | 604.94 | 694.65 |
| 1961-08-01 | 636.71 | 605.63 | 667.80 | 589.17 | 684.26 |
| 1961-09-01 | 538.92 | 506.17 | 571.67 | 488.83 | 589.01 |
| 1961-10-01 | 491.07 | 456.73 | 525.41 | 438.55 | 543.58 |
| 1961-11-01 | 422.82 | 386.97 | 458.68 | 367.99 | 477.66 |
| 1961-12-01 | 464.75 | 427.45 | 502.06 | 407.70 | 521.81 |
ARIMA(0,1,1)(0,1,1)[12]: 12-step forecasts of passengers (monthly data, 144 observations). Backtest MAE 30.2 over 2 origins.
- MAE
- 30.242
- RMSE
- 35.957
- MAPE
- 0.0699
To keep this page light, the plots are shown once, under the R tab.
Backtest accuracy (2 origins, horizon 12)
| Metric | Value |
|---|---|
| MAE | 30.242 |
| RMSE | 35.957 |
| MAPE | 0.0699 |
| sMAPE | 0.0724 |
| MASE | 1.041 |
| WAPE | 0.0669 |
| Coverage of the 80% interval | 0.4583 |
| Coverage of the 95% interval | 0.6667 |
Forecast
| month | Forecast | 80% low | 80% high | 95% low | 95% high |
|---|---|---|---|---|---|
| 1961-01-01 | 447.05 | 432.14 | 461.97 | 424.24 | 469.86 |
| 1961-02-01 | 421.88 | 403.75 | 440.01 | 394.15 | 449.61 |
| 1961-03-01 | 453.53 | 432.67 | 474.38 | 421.63 | 485.42 |
| 1961-04-01 | 489.90 | 466.63 | 513.17 | 454.32 | 525.48 |
| 1961-05-01 | 502.18 | 476.74 | 527.63 | 463.26 | 541.10 |
| 1961-06-01 | 564.22 | 536.77 | 591.68 | 522.23 | 606.22 |
| 1961-07-01 | 649.80 | 620.47 | 679.12 | 604.94 | 694.65 |
| 1961-08-01 | 636.71 | 605.63 | 667.80 | 589.17 | 684.26 |
| 1961-09-01 | 538.92 | 506.17 | 571.67 | 488.83 | 589.01 |
| 1961-10-01 | 491.07 | 456.73 | 525.41 | 438.55 | 543.58 |
| 1961-11-01 | 422.82 | 386.97 | 458.68 | 367.99 | 477.66 |
| 1961-12-01 | 464.75 | 427.45 | 502.06 | 407.70 | 521.81 |
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
- Airline manualml_airpassengers · time: month · value: passengers
- Auto annualml_nile · time: year · value: flow
- Drift manualml_deaths · series: sex · time: month · value: deaths
- Daily ar with meanml_airquality · time: date · value: Ozone
- Auto seasonal quarterlyml_ukgas · time: quarter · value: gas
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.
- 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) — Searches the orders by AICc; the usual choice and a good start.
- Set p, d, q (and P, D, Q) — Fits the orders you enter; pick it when ACF plots or theory point to a specific model.
- 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) — Lets the search decide whether to include a constant or drift; the usual choice.
- Include — Keeps a constant, which acts as drift when the series is differenced; pick it when you expect a steady trend.
- Leave out — Leaves the constant out; pick it when the series has no steady trend after differencing.
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.
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>, mean, sigma2, loglik, aicc, <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: statsmodels ARIMA (L-BFGS, then Nelder–Mead and BFGS refinement) versus stats::arima (CSS-ML, BFGS with reltol 1e-14 and 1e-6 gradient steps). Coefficients, forecasts and interval bounds agree to about 1e-7 relative.
- Differencing is explicit (the likelihood conditions on the first d + D·m values, like statsmodels' simple_differencing); stats::arima's own diffuse prior (kappa = 1e6) gives slightly different estimates, so the R code differences the series first too.
- Automatic orders follow auto.arima's stepwise rules, but D uses a classical-decomposition seasonal strength (> 0.64) in place of STL, and d a KPSS level test (5%: 0.463) with the 'short' Newey–West lag.
The exact script CodeSplash ran for example “Airline manual” · 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 e8693b375bf4f208
# Dataset: ml_airpassengers (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 = "month"
VALUE = "passengers"
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 = []
PARAMS = {
"order": "manual",
"p": 0,
"d": 1,
"q": 1,
"sp": 0,
"sd": 1,
"sq": 1,
"constant": "auto",
}
df = pd.read_parquet("tests/parity/fixtures/ml_airpassengers.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/airline_manual/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,
}
)
The exact script CodeSplash ran for example “Airline manual” · 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 e8693b375bf4f208
# Dataset: ml_airpassengers (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 <- "passengers"
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 <- character(0)
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/ml_airpassengers.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/airline_manual/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
))
Sources
- Box GEP, Jenkins GM, Reinsel GC, Ljung GM (2015). Time Series Analysis: Forecasting and Control, 5th ed. Wiley.
- Hyndman RJ, Khandakar Y (2008). Automatic time series forecasting: the forecast package for R. Journal of Statistical Software 27(3).
From the CodeSplash method registry · forecast.arima v1.0.0.