Chronos-2: a pretrained forecaster that reads covariates
Give a pretrained forecaster the drivers you know about, tell past-only covariates from known-future ones, forecast related series together, and judge all of it on the same backtest as the baselines.
What runs in CodeSplash
- Chronos-2 zero-shot forecast with covariates Experimental
You will be able to
- Say what Chronos-2 adds to Chronos-Bolt
- Tell a past-only covariate from a known-future one, and where each goes in the data
- Explain why a backtest with known-future covariates is a best case
- Decide when to forecast related series together
What Chronos-2 adds
ReadChronos-2Chronos-2Amazon's pretrained forecaster that reads past-only and known-future covariates and related series, and predicts 13 quantiles. is a pretrained forecaster like Chronos-Bolt: nothing is trained on your data, and it predicts quantiles of the next steps directly. It adds two things:
- Covariates. It can read other columns alongside the series, such as a price, a law change or a holiday flag.
- Related series together. The series of a panel can attend to each other, so a short series borrows patterns from its neighbors.
It also reads much longer histories and predicts 13 quantiles, from 1% to 99%. The weights are a download the app asks about first; it states the size before anything is fetched, and Small is the lighter one.
On its own
ReadChronos-2 Small (zero-shot): 12-step forecasts of passengers (monthly data, 144 observations). Backtest MAE 11.4 over 2 origins.
- MAE
- 11.388
- RMSE
- 14.951
- MAPE
- 0.0252
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 |
|---|---|---|
| 1.850 | 1 | 1958-12-01 |
| −0.5619 | 2 | 1958-12-01 |
| 3.663 | 3 | 1958-12-01 |
| 3.775 | 4 | 1958-12-01 |
| 19.836 | 5 | 1958-12-01 |
| 8.956 | 6 | 1958-12-01 |
| 15.282 | 7 | 1958-12-01 |
| 30.014 | 8 | 1958-12-01 |
| 7.996 | 9 | 1958-12-01 |
| 13.550 | 10 | 1958-12-01 |
| 22.293 | 11 | 1958-12-01 |
| 22.450 | 12 | 1958-12-01 |
| 5.174 | 1 | 1959-12-01 |
| −3.600 | 2 | 1959-12-01 |
| −36.164 | 3 | 1959-12-01 |
| 17.225 | 4 | 1959-12-01 |
| 14.035 | 5 | 1959-12-01 |
| −2.124 | 6 | 1959-12-01 |
| 17.897 | 7 | 1959-12-01 |
| −0.2986 | 8 | 1959-12-01 |
| −8.994 | 9 | 1959-12-01 |
| 15.023 | 10 | 1959-12-01 |
| 0.5989 | 11 | 1959-12-01 |
| −1.949 | 12 | 1959-12-01 |
View data
| quantile | month | passengers |
|---|---|---|
| — | −378,691,200,000 | 340 |
| — | −376,012,800,000 | 318 |
| — | −373,593,600,000 | 362 |
| — | −370,915,200,000 | 348 |
| — | −368,323,200,000 | 363 |
| — | −365,644,800,000 | 435 |
| — | −363,052,800,000 | 491 |
| — | −360,374,400,000 | 505 |
| — | −357,696,000,000 | 404 |
| — | −355,104,000,000 | 359 |
| — | −352,425,600,000 | 310 |
| — | −349,833,600,000 | 337 |
| — | −347,155,200,000 | 360 |
| — | −344,476,800,000 | 342 |
| — | −342,057,600,000 | 406 |
| — | −339,379,200,000 | 396 |
| — | −336,787,200,000 | 420 |
| — | −334,108,800,000 | 472 |
| — | −331,516,800,000 | 548 |
| — | −328,838,400,000 | 559 |
| — | −326,160,000,000 | 463 |
| — | −323,568,000,000 | 407 |
| — | −320,889,600,000 | 362 |
| — | −318,297,600,000 | 405 |
| — | −315,619,200,000 | 417 |
| — | −312,940,800,000 | 391 |
| — | −310,435,200,000 | 419 |
| — | −307,756,800,000 | 461 |
| — | −305,164,800,000 | 472 |
| — | −302,486,400,000 | 535 |
| — | −299,894,400,000 | 622 |
| — | −297,216,000,000 | 606 |
| — | −294,537,600,000 | 508 |
| — | −291,945,600,000 | 461 |
| — | −289,267,200,000 | 390 |
| — | −286,675,200,000 | 432 |
| 0.0100 | −283,996,800,000 | 400.18 |
| 0.0100 | −281,318,400,000 | 376.25 |
| 0.0100 | −278,899,200,000 | 448.28 |
| 0.0100 | −276,220,800,000 | 441.76 |
| 0.0100 | −273,628,800,000 | 450.94 |
| 0.0100 | −270,950,400,000 | 503.30 |
| 0.0100 | −268,358,400,000 | 553.82 |
| 0.0100 | −265,680,000,000 | 548.85 |
| 0.0100 | −263,001,600,000 | 475.32 |
| 0.0100 | −260,409,600,000 | 419.85 |
| 0.0100 | −257,731,200,000 | 352.59 |
| 0.0100 | −255,139,200,000 | 400.10 |
| 0.0500 | −283,996,800,000 | 423.38 |
| 0.0500 | −281,318,400,000 | 399.33 |
| 0.0500 | −278,899,200,000 | 474.19 |
| 0.0500 | −276,220,800,000 | 469.45 |
| 0.0500 | −273,628,800,000 | 479.74 |
| 0.0500 | −270,950,400,000 | 536.95 |
| 0.0500 | −268,358,400,000 | 607.85 |
| 0.0500 | −265,680,000,000 | 607.23 |
| 0.0500 | −263,001,600,000 | 514.45 |
| 0.0500 | −260,409,600,000 | 450.21 |
| 0.0500 | −257,731,200,000 | 377.54 |
| 0.0500 | −255,139,200,000 | 430.16 |
First 60 of 192 rows.
Assumptions
- Horizon within the model's training — Horizon 12; Chronos-2 predicts up to 1024 steps at once.
- Enough history for the model — The model read 144 values.
- Beats the seasonal naive forecast — Backtest MAE is 0.24 times the seasonal naive forecast's from the same origins.
Backtest accuracy (2 origins, horizon 12)
| Metric | Value |
|---|---|
| MAE | 11.388 |
| RMSE | 14.951 |
| MAPE | 0.0252 |
| sMAPE | 0.0255 |
| MASE | 0.3875 |
| WAPE | 0.0252 |
| Coverage of the 80% interval | 0.9583 |
| Coverage of the 95% interval | 1 |
The model's quantiles (the 50% quantile is the forecast)
| month | 1% | 5% | 10% | 20% | 30% | 40% | 50% | 60% | 70% | 80% | 90% | 95% | 99% |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 1961-01-01 | 400.18 | 423.38 | 432.17 | 442.05 | 447.69 | 451.21 | 455.00 | 459.16 | 463.23 | 469.06 | 476.96 | 484.59 | 503.58 |
| 1961-02-01 | 376.25 | 399.33 | 408.76 | 417.78 | 423.40 | 427.20 | 431.38 | 436.17 | 440.23 | 446.70 | 452.26 | 457.48 | 471.80 |
| 1961-03-01 | 448.28 | 474.19 | 483.70 | 493.40 | 498.52 | 502.07 | 505.19 | 509.75 | 514.73 | 520.32 | 527.17 | 534.54 | 554.51 |
| 1961-04-01 | 441.76 | 469.45 | 478.81 | 488.04 | 494.14 | 498.46 | 503.23 | 506.14 | 510.86 | 516.53 | 525.66 | 535.62 | 557.28 |
| 1961-05-01 | 450.94 | 479.74 | 488.36 | 496.52 | 502.95 | 507.99 | 513.08 | 516.72 | 521.72 | 529.13 | 539.54 | 551.83 | 575.89 |
| 1961-06-01 | 503.30 | 536.95 | 549.08 | 564.11 | 570.78 | 577.36 | 583.40 | 586.53 | 594.02 | 602.81 | 614.96 | 626.26 | 649.69 |
| 1961-07-01 | 553.82 | 607.85 | 624.23 | 637.92 | 647.33 | 653.78 | 662.40 | 667.67 | 677.13 | 687.29 | 702.17 | 715.42 | 743.44 |
| 1961-08-01 | 548.85 | 607.23 | 622.85 | 638.06 | 648.93 | 655.28 | 663.36 | 671.87 | 678.67 | 687.66 | 701.98 | 715.35 | 744.59 |
| 1961-09-01 | 475.32 | 514.45 | 528.41 | 541.83 | 550.26 | 557.88 | 565.50 | 570.06 | 576.33 | 585.75 | 597.65 | 611.31 | 642.41 |
| 1961-10-01 | 419.85 | 450.21 | 461.14 | 471.41 | 477.47 | 482.54 | 486.21 | 492.04 | 496.67 | 505.30 | 519.11 | 531.19 | 561.41 |
| 1961-11-01 | 352.59 | 377.54 | 389.13 | 401.61 | 408.08 | 413.22 | 418.71 | 424.03 | 431.15 | 440.01 | 450.18 | 457.89 | 475.87 |
| 1961-12-01 | 400.10 | 430.16 | 440.97 | 451.36 | 457.91 | 462.65 | 467.80 | 472.47 | 478.52 | 485.67 | 496.07 | 506.05 | 531.63 |
Pretrained weights
| Item | Value |
|---|---|
| Model | Chronos-2 Small (28M parameters) |
| Source | huggingface.co/autogluon/chronos-2-small |
| Revision | ddec01313e50b6bc58ebaa92ede81bc24a3d9f9a |
| License | Apache-2.0 |
| Download size | 111.8 MB |
| Related series | Each forecast alone |
Forecast
| month | Forecast | 80% low | 80% high | 95% low | 95% high |
|---|---|---|---|---|---|
| 1961-01-01 | 455.00 | 432.17 | 476.96 | 408.88 | 496.46 |
| 1961-02-01 | 431.38 | 408.76 | 452.26 | 384.90 | 466.43 |
| 1961-03-01 | 505.19 | 483.70 | 527.17 | 458.00 | 547.02 |
| 1961-04-01 | 503.23 | 478.81 | 525.66 | 452.15 | 549.16 |
| 1961-05-01 | 513.08 | 488.36 | 539.54 | 461.74 | 566.86 |
| 1961-06-01 | 583.40 | 549.08 | 614.96 | 515.92 | 640.90 |
| 1961-07-01 | 662.40 | 624.23 | 702.17 | 574.08 | 732.93 |
| 1961-08-01 | 663.36 | 622.85 | 701.98 | 570.74 | 733.63 |
| 1961-09-01 | 565.50 | 528.41 | 597.65 | 489.99 | 630.75 |
| 1961-10-01 | 486.21 | 461.14 | 519.11 | 431.24 | 550.08 |
| 1961-11-01 | 418.71 | 389.13 | 450.18 | 361.95 | 469.13 |
| 1961-12-01 | 467.80 | 440.97 | 496.07 | 411.37 | 522.04 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Chronos-2 zero-shot forecast with covariates
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.chronos2 1.0.0 · spec ca1b85fd721ded3f
# 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
from codesplash.deep import chronos2 as c2 # pretrained weights, looked up locally only (never downloaded here)
# %% 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
FUTURE_COV = [] # known-future covariates: their future values sit in rows after the last observed value
PAST_COV = [] # past-only covariates: observed up to now, not ahead
XREG = FUTURE_COV + [c for c in PAST_COV if c not in FUTURE_COV]
PARAMS = {
"model": "chronos2_small",
"context": None,
"related": "independent",
}
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.chronos2/small_monthly/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
# Chronos-2 (Ansari et al. 2025) is pretrained: it reads the recent history (and any covariates) and predicts 13
# quantiles of the next steps without training on this data. Python only — the weights run through the
# chronos-forecasting package. The weights must already be on this computer (the app downloads them only after you
# confirm the size).
MODEL = PARAMS["model"]
CONTEXT = PARAMS["context"]
TOGETHER = bool(SERIES) and PARAMS["related"] == "together" # forecast the series jointly (cross-learning)
FINAL = {}
WEIGHTS = c2.locate(MODEL) # stops with CS_WEIGHTS_MISSING and the download size when absent
def min_train(m):
return 8
def prepare_series(y, t, m, freq):
return None
def covariates(x_train, x_future):
"""Past values of every covariate (aligned with y) and the h future values of the known-future ones."""
if not XREG:
return None, None
past = {c: x_train[:, j] for j, c in enumerate(XREG)}
future = {c: x_future[:, XREG.index(c)] for c in FUTURE_COV} if FUTURE_COV else None
return past, future
# Related series together: every series on the same time grid as the driver builds it (same regularization), so
# a forecast from one origin can include all series that have a value at that origin's time.
GRID = {}
if TOGETHER:
for key in series_keys:
sel = ~np.isnan(times_all) & (keys_all.astype(str) == key)
t_raw, y_raw = times_all[sel], values_all[sel]
x_raw, x_later = None, None
if XREG:
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]
if int(np.sum(~np.isnan(y_raw))) < 3:
continue # the driver stops on this series itself
freq_k = fc.detect_frequency(np.sort(t_raw), TEMPORAL)
t_k, y_k, _ = fc.regularize(t_raw, y_raw, freq_k)
x_k = np.column_stack([fc.regularize(t_raw, x_raw[:, j], freq_k)[1] for j in range(x_raw.shape[1])]) if XREG else None
GRID[key] = (np.asarray(t_k, dtype=np.float64), [float(v) for v in y_k], x_k, x_later)
JOINT = {} # origin time → {series: (training length, quantile levels, quantiles, context used)}
def joint(t_last):
"""Forecast every series that has a value at time t_last from that origin, all in one call."""
if t_last in JOINT:
return JOINT[t_last]
items, keys, lens = [], [], []
for key, (ts, ys, xg, xl) in GRID.items():
o = int(np.searchsorted(ts, t_last + 1e-9, side="right"))
if o < min_train(1) or abs(ts[o - 1] - t_last) > 1e-6:
continue # no value at this time: this series is forecast from its own origins
start = max(0, o - int(TRAIN_WINDOW)) if TRAIN_WINDOW else 0
past, future = None, None
if XREG:
if o + H <= len(ts):
xf = xg[o:o + H]
elif o == len(ts):
xf = fc.future_regressors(xg, xl, H)
else:
xf = np.vstack([xg[o:]] + [xg[-1:]] * (o + H - len(ts)))
past, future = covariates(xg[start:o], xf)
items.append((ys[start:o], past, future))
keys.append(key)
lens.append(o - start)
outs = c2.native_quantiles_many(MODEL, items, H, CONTEXT, together=True) if items else []
JOINT[t_last] = {k: (n_k, lq, q, used) for k, n_k, (lq, q, used) in zip(keys, lens, outs, strict=True)}
return JOINT[t_last]
def fit_forecast(y, t, h, m, levels, spec):
past, future = covariates(X_TRAIN, X_FUTURE)
res = None
if TOGETHER:
entry = joint(float(t[-1])).get(current_series)
if entry is not None and entry[0] == len(y):
n_k, lq, q, used = entry
res = c2.result_from_quantiles(lq, q, used, levels, MODEL, len(XREG))
if res is None:
res = c2.fit_forecast(y, h, levels, model=MODEL, context=CONTEXT, past=past, future=future)
FINAL[current_series] = (res, [float(v) for v in t])
return res
# %% 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"),
},
)
)
# %% Quantiles and checks
res0, t0 = FINAL[series_keys[0]]
spec0 = c2.MODELS[MODEL]
freq0 = fc.detect_frequency(np.array(t0), TEMPORAL)
times0 = [fc.format_time(v, TEMPORAL) for v in fc.future_times(t0[-1], freq0, H)]
lq0, q0 = res0["quantile_levels"], res0["quantiles"]
wq = [(j + 1.0) * (k + 1.0) for j in range(len(lq0)) for k in range(H)]
values["q_check"] = fc._sum([wq[j * H + k] * float(q0[j, k]) for j in range(len(lq0)) for k in range(H)]) / fc._sum(wq)
values["weights_label"] = spec0["label"]
values["n_covariates"] = len(XREG)
values["n_future_covariates"] = len(FUTURE_COV)
values["together"] = 1 if TOGETHER else 0
if SERIES and len(series_keys) > 1:
values["model_label"] = f"{len(series_keys)} series, " + ("forecast together" if TOGETHER else "each forecast alone")
suffix0 = f" — {series_keys[0]}" if SERIES else ""
hist0 = min(len(t0), max(3 * H, 24))
y0 = [r["mean"] for r in fc_rows if r["series"] == series_keys[0] and r["kind"] == "actual"][-hist0:]
th0 = [r["time"] for r in fc_rows if r["series"] == series_keys[0] and r["kind"] == "actual"][-hist0:]
charts.append(
cs.chart(
"quantiles",
"quantile-fan",
f"Chronos-2 quantiles for {VALUE}" + suffix0,
{
"time": cs.col(TIME, th0 + [times0[k] for j in range(len(lq0)) for k in range(H)], kind="temporal" if TEMPORAL else "numeric"),
"value": cs.col(VALUE, y0 + [float(q0[j, k]) for j in range(len(lq0)) for k in range(H)], kind="numeric"),
"quantile": cs.col("quantile", [None] * len(y0) + [lq0[j] for j in range(len(lq0)) for k in range(H)], kind="numeric"),
},
)
)
extra_tables.append(
{
"key": "quantiles",
"title": "The model's quantiles (the 50% quantile is the forecast)" + suffix0,
"columns": [{"key": "time", "label": TIME}] + [{"key": f"q{round(p * 100):g}", "label": f"{p * 100:g}%", "type": "number"} for p in lq0],
"rows": [dict({"time": times0[k]}, **{f"q{round(p * 100):g}": float(q0[j, k]) for j, p in enumerate(lq0)}) for k in range(H)],
}
)
if XREG:
extra_tables.append(
{
"key": "covariates",
"title": "Covariates the model read",
"columns": [{"key": "column", "label": "Column"}, {"key": "use", "label": "Used as"}],
"rows": [{"column": c, "use": "Known in advance (future values given)" if c in FUTURE_COV else "Past only"} for c in XREG],
}
)
extra_tables.append(
{
"key": "weights",
"title": "Pretrained weights",
"columns": [{"key": "item", "label": "Item"}, {"key": "value", "label": "Value"}],
"rows": [
{"item": "Model", "value": f"{spec0['label']} ({spec0['params']} parameters)"},
{"item": "Source", "value": f"huggingface.co/{spec0['repo']}"},
{"item": "Revision", "value": spec0["revision"]},
{"item": "License", "value": "Apache-2.0"},
{"item": "Download size", "value": c2.size_text(spec0["bytes"])},
{"item": "Related series", "value": "Forecast together (cross-learning)" if TOGETHER else "Each forecast alone"},
],
}
)
extra_assumptions.append(
{
"key": "horizon_trained",
"label": "Horizon within the model's training",
"status": "pass" if H <= c2.TRAINED_HORIZON else "warn",
"statistic": float(H),
"detail": f"Horizon {H}; Chronos-2 predicts up to {c2.TRAINED_HORIZON} steps at once." + ("" if H <= c2.TRAINED_HORIZON else " Later steps feed the model's own forecasts back, so they can drift."),
}
)
ctx0 = int(res0["facts"]["context"])
extra_assumptions.append(
{
"key": "context_length",
"label": "Enough history for the model",
"status": "pass" if ctx0 >= 64 else "warn",
"statistic": float(ctx0),
"detail": f"The model read {ctx0} values." + ("" if ctx0 >= 64 else " Fewer than 64 (four patches of 16) leaves little pattern to recognize."),
}
)
rel0 = fc.naive_relative_mae(bt_rows) # not MASE < 1: MASE scales by the in-sample one-step naive error
if math.isfinite(rel0):
values["bt[rel_mae]"] = rel0
beats0 = rel0 < 1
extra_assumptions.append(
{
"key": "beats_naive",
"label": "Beats the seasonal naive forecast",
"status": "pass" if beats0 else "warn",
"statistic": rel0,
"detail": f"Backtest MAE is {rel0:.2f} times the seasonal naive forecast's from the same origins." + ("" if beats0 else " Repeating the last season forecast these origins at least as well."),
}
)
# The driver's held-regressor note names every covariate; only known-future ones need future values.
warnings[:] = [w for w in warnings if not w.startswith("Future values of ")]
if FUTURE_COV:
later_counts = []
for key in series_keys:
sel = ~np.isnan(times_all) & ((keys_all.astype(str) == key) if SERIES else True)
y_k, t_k = values_all[sel], times_all[sel]
last_k = np.nanmax(np.where(np.isnan(y_k), np.nan, t_k))
later_counts.append(int(np.sum(t_k > last_k)))
if min(later_counts) < H:
warnings.append(f"Future values of {', '.join(FUTURE_COV)} are known for {min(later_counts)} of {H} steps; the last known values are held for the rest.")
if n_origins and FUTURE_COV:
warnings.append(
f"The backtest gave the model the actual future values of {', '.join(FUTURE_COV)}. 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."
)
if H > c2.TRAINED_HORIZON:
warnings.append(f"Chronos-2 predicts up to {c2.TRAINED_HORIZON} steps at once; steps beyond that are rolled forward from its own forecasts.")
# %% 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": "Chronos-2 zero-shot forecast with covariates",
"engine": cs.engine_info("chronos-forecasting", "torch", "codesplash", "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,
}
)
With no covariates it is a plain zero-shot forecast. Chronos-2 Small (zero-shot) read 144 months, and its backtest MASE is 0.39.
Two kinds of covariate
ReadA covariate is known-future when you know its values ahead: holidays, a price you set, a law that takes effect on a date. Put those future values in rows after the last observed value, with the value left empty.
A covariate is past-only when you see it only as it happens: another sensor, a competitor's sales. The model reads its history and needs no future values.
Known-future covariates
ReadChronos-2 Small (zero-shot, with covariates): 12-step forecasts of drivers (monthly data, 192 observations). Backtest MAE 10.9 over 1 origin.
- MAE
- 10.902
- RMSE
- 14.848
- MAPE
- 0.0943
Plots
View data
| hi_80 | hi_95 | kind | lo_80 | lo_95 | month | drivers |
|---|---|---|---|---|---|---|
| — | — | actual | — | — | −31,536,000,000 | 107 |
| — | — | actual | — | — | −28,857,600,000 | 97 |
| — | — | actual | — | — | −26,438,400,000 | 102 |
| — | — | actual | — | — | −23,760,000,000 | 87 |
| — | — | actual | — | — | −21,168,000,000 | 119 |
| — | — | actual | — | — | −18,489,600,000 | 106 |
| — | — | actual | — | — | −15,897,600,000 | 110 |
| — | — | actual | — | — | −13,219,200,000 | 106 |
| — | — | actual | — | — | −10,540,800,000 | 107 |
| — | — | actual | — | — | −7,948,800,000 | 134 |
| — | — | actual | — | — | −5,270,400,000 | 147 |
| — | — | actual | — | — | −2,678,400,000 | 180 |
| — | — | actual | — | — | 0 | 125 |
| — | — | actual | — | — | 2,678,400,000 | 134 |
| — | — | actual | — | — | 5,097,600,000 | 110 |
| — | — | actual | — | — | 7,776,000,000 | 102 |
| — | — | actual | — | — | 10,368,000,000 | 103 |
| — | — | actual | — | — | 13,046,400,000 | 111 |
| — | — | actual | — | — | 15,638,400,000 | 120 |
| — | — | actual | — | — | 18,316,800,000 | 129 |
| — | — | actual | — | — | 20,995,200,000 | 122 |
| — | — | actual | — | — | 23,587,200,000 | 183 |
| — | — | actual | — | — | 26,265,600,000 | 169 |
| — | — | actual | — | — | 28,857,600,000 | 190 |
| — | — | actual | — | — | 31,536,000,000 | 134 |
| — | — | actual | — | — | 34,214,400,000 | 108 |
| — | — | actual | — | — | 36,633,600,000 | 104 |
| — | — | actual | — | — | 39,312,000,000 | 117 |
| — | — | actual | — | — | 41,904,000,000 | 157 |
| — | — | actual | — | — | 44,582,400,000 | 148 |
| — | — | actual | — | — | 47,174,400,000 | 130 |
| — | — | actual | — | — | 49,852,800,000 | 140 |
| — | — | actual | — | — | 52,531,200,000 | 136 |
| — | — | actual | — | — | 55,123,200,000 | 140 |
| — | — | actual | — | — | 57,801,600,000 | 187 |
| — | — | actual | — | — | 60,393,600,000 | 150 |
| — | — | actual | — | — | 63,072,000,000 | 159 |
| — | — | actual | — | — | 65,750,400,000 | 143 |
| — | — | actual | — | — | 68,256,000,000 | 114 |
| — | — | actual | — | — | 70,934,400,000 | 127 |
| — | — | actual | — | — | 73,526,400,000 | 159 |
| — | — | actual | — | — | 76,204,800,000 | 156 |
| — | — | actual | — | — | 78,796,800,000 | 138 |
| — | — | actual | — | — | 81,475,200,000 | 120 |
| — | — | actual | — | — | 84,153,600,000 | 117 |
| — | — | actual | — | — | 86,745,600,000 | 170 |
| — | — | actual | — | — | 89,424,000,000 | 168 |
| — | — | actual | — | — | 92,016,000,000 | 198 |
| — | — | actual | — | — | 94,694,400,000 | 144 |
| — | — | actual | — | — | 97,372,800,000 | 146 |
| — | — | actual | — | — | 99,792,000,000 | 109 |
| — | — | actual | — | — | 102,470,400,000 | 131 |
| — | — | actual | — | — | 105,062,400,000 | 151 |
| — | — | actual | — | — | 107,740,800,000 | 140 |
| — | — | actual | — | — | 110,332,800,000 | 153 |
| — | — | actual | — | — | 113,011,200,000 | 140 |
| — | — | actual | — | — | 115,689,600,000 | 161 |
| — | — | actual | — | — | 118,281,600,000 | 168 |
| — | — | actual | — | — | 120,960,000,000 | 152 |
| — | — | actual | — | — | 123,552,000,000 | 136 |
First 60 of 204 rows.
View data
| error | horizon | origin |
|---|---|---|
| −2.789 | 1 | 1983-12-01 |
| 3.682 | 2 | 1983-12-01 |
| 0.7564 | 3 | 1983-12-01 |
| 6.382 | 4 | 1983-12-01 |
| 5.650 | 5 | 1983-12-01 |
| 5.971 | 6 | 1983-12-01 |
| −6.039 | 7 | 1983-12-01 |
| 10.717 | 8 | 1983-12-01 |
| 27.222 | 9 | 1983-12-01 |
| 9.119 | 10 | 1983-12-01 |
| 17.244 | 11 | 1983-12-01 |
| 35.246 | 12 | 1983-12-01 |
View data
| quantile | month | drivers |
|---|---|---|
| — | 378,691,200,000 | 115 |
| — | 381,369,600,000 | 104 |
| — | 383,788,800,000 | 131 |
| — | 386,467,200,000 | 108 |
| — | 389,059,200,000 | 103 |
| — | 391,737,600,000 | 115 |
| — | 394,329,600,000 | 122 |
| — | 397,008,000,000 | 122 |
| — | 399,686,400,000 | 125 |
| — | 402,278,400,000 | 137 |
| — | 404,956,800,000 | 138 |
| — | 407,548,800,000 | 152 |
| — | 410,227,200,000 | 120 |
| — | 412,905,600,000 | 95 |
| — | 415,324,800,000 | 100 |
| — | 418,003,200,000 | 89 |
| — | 420,595,200,000 | 82 |
| — | 423,273,600,000 | 89 |
| — | 425,865,600,000 | 60 |
| — | 428,544,000,000 | 84 |
| — | 431,222,400,000 | 113 |
| — | 433,814,400,000 | 126 |
| — | 436,492,800,000 | 122 |
| — | 439,084,800,000 | 118 |
| — | 441,763,200,000 | 92 |
| — | 444,441,600,000 | 86 |
| — | 446,947,200,000 | 81 |
| — | 449,625,600,000 | 84 |
| — | 452,217,600,000 | 87 |
| — | 454,896,000,000 | 90 |
| — | 457,488,000,000 | 79 |
| — | 460,166,400,000 | 96 |
| — | 462,844,800,000 | 122 |
| — | 465,436,800,000 | 120 |
| — | 468,115,200,000 | 137 |
| — | 470,707,200,000 | 154 |
| 0.0100 | 473,385,600,000 | 75.690 |
| 0.0100 | 476,064,000,000 | 58.625 |
| 0.0100 | 478,483,200,000 | 50.897 |
| 0.0100 | 481,161,600,000 | 53.276 |
| 0.0100 | 483,753,600,000 | 59.431 |
| 0.0100 | 486,432,000,000 | 62.359 |
| 0.0100 | 489,024,000,000 | 59.522 |
| 0.0100 | 491,702,400,000 | 60.926 |
| 0.0100 | 494,380,800,000 | 69.369 |
| 0.0100 | 496,972,800,000 | 79.052 |
| 0.0100 | 499,651,200,000 | 89.219 |
| 0.0100 | 502,243,200,000 | 87.856 |
| 0.0500 | 473,385,600,000 | 86.141 |
| 0.0500 | 476,064,000,000 | 68.614 |
| 0.0500 | 478,483,200,000 | 62.366 |
| 0.0500 | 481,161,600,000 | 64.486 |
| 0.0500 | 483,753,600,000 | 70.128 |
| 0.0500 | 486,432,000,000 | 72.787 |
| 0.0500 | 489,024,000,000 | 70.826 |
| 0.0500 | 491,702,400,000 | 71.787 |
| 0.0500 | 494,380,800,000 | 81.085 |
| 0.0500 | 496,972,800,000 | 93.564 |
| 0.0500 | 499,651,200,000 | 102.64 |
| 0.0500 | 502,243,200,000 | 102.29 |
First 60 of 192 rows.
Assumptions
- Horizon within the model's training — Horizon 12; Chronos-2 predicts up to 1024 steps at once.
- Enough history for the model — The model read 192 values.
- Beats the seasonal naive forecast — Backtest MAE is 0.80 times the seasonal naive forecast's from the same origins.
Backtest accuracy (1 origin, horizon 12)
| Metric | Value |
|---|---|
| MAE | 10.902 |
| RMSE | 14.848 |
| MAPE | 0.0943 |
| sMAPE | 0.1010 |
| MASE | 0.6373 |
| WAPE | 0.1065 |
| Coverage of the 80% interval | 0.8333 |
| Coverage of the 95% interval | 1 |
The model's quantiles (the 50% quantile is the forecast)
| month | 1% | 5% | 10% | 20% | 30% | 40% | 50% | 60% | 70% | 80% | 90% | 95% | 99% |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 1985-01-01 | 75.690 | 86.141 | 91.727 | 98.598 | 103.27 | 107.10 | 110.74 | 114.50 | 118.54 | 123.63 | 131.57 | 139.39 | 155.86 |
| 1985-02-01 | 58.625 | 68.614 | 73.107 | 78.561 | 82.622 | 85.914 | 89.026 | 92.081 | 95.325 | 99.669 | 106.04 | 112.78 | 126.99 |
| 1985-03-01 | 50.897 | 62.366 | 67.779 | 73.860 | 77.839 | 81.095 | 84.178 | 87.420 | 90.728 | 95.022 | 101.26 | 107.84 | 121.46 |
| 1985-04-01 | 53.276 | 64.486 | 69.308 | 74.777 | 78.710 | 81.807 | 84.779 | 87.797 | 91.122 | 95.291 | 101.54 | 107.86 | 121.61 |
| 1985-05-01 | 59.431 | 70.128 | 74.597 | 79.639 | 83.444 | 86.661 | 89.787 | 93.003 | 96.603 | 100.91 | 107.09 | 113.12 | 125.13 |
| 1985-06-01 | 62.359 | 72.787 | 77.352 | 82.836 | 86.508 | 89.872 | 92.921 | 96.080 | 99.517 | 103.98 | 110.30 | 116.32 | 127.94 |
| 1985-07-01 | 59.522 | 70.826 | 75.665 | 81.236 | 85.576 | 89.027 | 92.137 | 95.276 | 98.705 | 103.36 | 110.13 | 116.43 | 128.58 |
| 1985-08-01 | 60.926 | 71.787 | 76.436 | 82.042 | 86.366 | 90.008 | 93.411 | 96.660 | 100.24 | 104.94 | 111.73 | 118.17 | 130.40 |
| 1985-09-01 | 69.369 | 81.085 | 86.317 | 92.444 | 96.947 | 100.83 | 104.43 | 108.07 | 111.95 | 116.91 | 123.90 | 130.77 | 145.39 |
| 1985-10-01 | 79.052 | 93.564 | 100.19 | 107.29 | 112.18 | 116.27 | 120.02 | 124.02 | 128.36 | 133.91 | 141.99 | 150.18 | 169.60 |
| 1985-11-01 | 89.219 | 102.64 | 109.00 | 116.37 | 121.67 | 126.26 | 130.51 | 135.24 | 140.71 | 147.52 | 156.53 | 165.61 | 190.46 |
| 1985-12-01 | 87.856 | 102.29 | 108.83 | 116.70 | 122.29 | 127.08 | 131.56 | 136.10 | 141.05 | 147.42 | 156.70 | 166.58 | 191.35 |
Covariates the model read
| Column | Used as |
|---|---|
| petrol | Known in advance (future values given) |
| law | Known in advance (future values given) |
Pretrained weights
| Item | Value |
|---|---|
| Model | Chronos-2 Small (28M parameters) |
| Source | huggingface.co/autogluon/chronos-2-small |
| Revision | ddec01313e50b6bc58ebaa92ede81bc24a3d9f9a |
| License | Apache-2.0 |
| Download size | 111.8 MB |
| Related series | Each forecast alone |
Forecast
| month | Forecast | 80% low | 80% high | 95% low | 95% high |
|---|---|---|---|---|---|
| 1985-01-01 | 110.74 | 91.727 | 131.57 | 79.609 | 149.68 |
| 1985-02-01 | 89.026 | 73.107 | 106.04 | 62.371 | 121.66 |
| 1985-03-01 | 84.178 | 67.779 | 101.26 | 55.198 | 116.35 |
| 1985-04-01 | 84.779 | 69.308 | 101.54 | 57.480 | 116.45 |
| 1985-05-01 | 89.787 | 74.597 | 107.09 | 63.442 | 120.62 |
| 1985-06-01 | 92.921 | 77.352 | 110.30 | 66.269 | 123.58 |
| 1985-07-01 | 92.137 | 75.665 | 110.13 | 63.761 | 124.02 |
| 1985-08-01 | 93.411 | 76.436 | 111.73 | 64.999 | 125.81 |
| 1985-09-01 | 104.43 | 86.317 | 123.90 | 73.763 | 139.91 |
| 1985-10-01 | 120.02 | 100.19 | 141.99 | 84.494 | 162.31 |
| 1985-11-01 | 130.51 | 109.00 | 156.53 | 94.253 | 181.14 |
| 1985-12-01 | 131.56 | 108.83 | 156.70 | 93.268 | 182.06 |
- The backtest gave the model the actual future values of petrol, law. A real forecast only knows them when they are planned or fixed in advance (holidays, prices you set), so read the backtest accuracy as a best case.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Chronos-2 zero-shot forecast with covariates
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.chronos2 1.0.0 · spec bd120e895eee11d1
# Dataset: f7_seatbelts_future (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import forecast as fc
from codesplash.deep import chronos2 as c2 # pretrained weights, looked up locally only (never downloaded here)
# %% Data
TIME = "month"
VALUE = "drivers"
SERIES = None
H = 12
LEVELS = [float(v) for v in [80, 95]]
SEASON = None # None = from the time steps (12 monthly, 4 quarterly, 7 daily …)
WINDOWS = 1
STEP = None # None = the horizon
OFFSETS = None # the host's BacktestPlan: distance of each origin from the end of the series; None = windows and step
TRAIN_WINDOW = None # None = train on all values before each origin
TRAIN_START = None # rows before this time are left out (for example, before a structural break)
SEED = 42
FUTURE_COV = ["petrol", "law"] # known-future covariates: their future values sit in rows after the last observed value
PAST_COV = [] # past-only covariates: observed up to now, not ahead
XREG = FUTURE_COV + [c for c in PAST_COV if c not in FUTURE_COV]
PARAMS = {
"model": "chronos2_small",
"context": None,
"related": "independent",
}
df = pd.read_parquet("tests/parity/fixtures/f7_seatbelts_future.parquet", columns=list(dict.fromkeys([c for c in (TIME, VALUE, SERIES) if c] + list(XREG))))
cs.check_finite_columns(df, [TIME, VALUE] + list(XREG)) # infinite values stop with CS_E_NOT_FINITE, naming the column
if len(df) == 0:
cs.cs_error("CS_E_NO_ROWS")
warnings = []
times_all, TEMPORAL = fc.to_days(df[TIME])
values_all = pd.to_numeric(df[VALUE], errors="coerce").to_numpy(dtype=np.float64)
x_all = np.column_stack([pd.to_numeric(df[c], errors="coerce").to_numpy(dtype=np.float64) for c in XREG]) if XREG else None
if TRAIN_START is not None:
cut = fc.parse_time(TRAIN_START, TEMPORAL)
early = np.nan_to_num(times_all, nan=np.inf) < cut
if early.any():
warnings.append(f"{int(early.sum())} rows before {TRAIN_START} were left out of training.")
times_all = np.where(early, np.nan, times_all)
keys_all = df[SERIES].astype("object").to_numpy() if SERIES else np.array([None] * len(df), dtype=object)
dropped = int(np.isnan(times_all).sum()) - (int(early.sum()) if TRAIN_START is not None else 0)
if dropped:
warnings.append(f"{dropped} rows without a time were left out.")
series_keys = sorted({str(k) for k in keys_all if not pd.isna(k)}) if SERIES else [None] # None, NaN, pd.NA: no name
if SERIES and any(pd.isna(k) for k in keys_all):
warnings.append("Rows without a series name were left out.")
# Degenerate inputs stop with catalog codes, in the same order as the R driver.
if bool(np.isnan(values_all).all()):
cs.cs_error("CS_E_ALL_MISSING", column=VALUE)
if not bool((~np.isnan(times_all) & ~np.isnan(values_all)).any()):
cs.cs_error("CS_E_NO_ROWS")
out = csml.out_dir("target/academy-parity/run-8142/forecast.chronos2/small_known_future_covariates/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
# Chronos-2 (Ansari et al. 2025) is pretrained: it reads the recent history (and any covariates) and predicts 13
# quantiles of the next steps without training on this data. Python only — the weights run through the
# chronos-forecasting package. The weights must already be on this computer (the app downloads them only after you
# confirm the size).
MODEL = PARAMS["model"]
CONTEXT = PARAMS["context"]
TOGETHER = bool(SERIES) and PARAMS["related"] == "together" # forecast the series jointly (cross-learning)
FINAL = {}
WEIGHTS = c2.locate(MODEL) # stops with CS_WEIGHTS_MISSING and the download size when absent
def min_train(m):
return 8
def prepare_series(y, t, m, freq):
return None
def covariates(x_train, x_future):
"""Past values of every covariate (aligned with y) and the h future values of the known-future ones."""
if not XREG:
return None, None
past = {c: x_train[:, j] for j, c in enumerate(XREG)}
future = {c: x_future[:, XREG.index(c)] for c in FUTURE_COV} if FUTURE_COV else None
return past, future
# Related series together: every series on the same time grid as the driver builds it (same regularization), so
# a forecast from one origin can include all series that have a value at that origin's time.
GRID = {}
if TOGETHER:
for key in series_keys:
sel = ~np.isnan(times_all) & (keys_all.astype(str) == key)
t_raw, y_raw = times_all[sel], values_all[sel]
x_raw, x_later = None, None
if XREG:
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]
if int(np.sum(~np.isnan(y_raw))) < 3:
continue # the driver stops on this series itself
freq_k = fc.detect_frequency(np.sort(t_raw), TEMPORAL)
t_k, y_k, _ = fc.regularize(t_raw, y_raw, freq_k)
x_k = np.column_stack([fc.regularize(t_raw, x_raw[:, j], freq_k)[1] for j in range(x_raw.shape[1])]) if XREG else None
GRID[key] = (np.asarray(t_k, dtype=np.float64), [float(v) for v in y_k], x_k, x_later)
JOINT = {} # origin time → {series: (training length, quantile levels, quantiles, context used)}
def joint(t_last):
"""Forecast every series that has a value at time t_last from that origin, all in one call."""
if t_last in JOINT:
return JOINT[t_last]
items, keys, lens = [], [], []
for key, (ts, ys, xg, xl) in GRID.items():
o = int(np.searchsorted(ts, t_last + 1e-9, side="right"))
if o < min_train(1) or abs(ts[o - 1] - t_last) > 1e-6:
continue # no value at this time: this series is forecast from its own origins
start = max(0, o - int(TRAIN_WINDOW)) if TRAIN_WINDOW else 0
past, future = None, None
if XREG:
if o + H <= len(ts):
xf = xg[o:o + H]
elif o == len(ts):
xf = fc.future_regressors(xg, xl, H)
else:
xf = np.vstack([xg[o:]] + [xg[-1:]] * (o + H - len(ts)))
past, future = covariates(xg[start:o], xf)
items.append((ys[start:o], past, future))
keys.append(key)
lens.append(o - start)
outs = c2.native_quantiles_many(MODEL, items, H, CONTEXT, together=True) if items else []
JOINT[t_last] = {k: (n_k, lq, q, used) for k, n_k, (lq, q, used) in zip(keys, lens, outs, strict=True)}
return JOINT[t_last]
def fit_forecast(y, t, h, m, levels, spec):
past, future = covariates(X_TRAIN, X_FUTURE)
res = None
if TOGETHER:
entry = joint(float(t[-1])).get(current_series)
if entry is not None and entry[0] == len(y):
n_k, lq, q, used = entry
res = c2.result_from_quantiles(lq, q, used, levels, MODEL, len(XREG))
if res is None:
res = c2.fit_forecast(y, h, levels, model=MODEL, context=CONTEXT, past=past, future=future)
FINAL[current_series] = (res, [float(v) for v in t])
return res
# %% 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"),
},
)
)
# %% Quantiles and checks
res0, t0 = FINAL[series_keys[0]]
spec0 = c2.MODELS[MODEL]
freq0 = fc.detect_frequency(np.array(t0), TEMPORAL)
times0 = [fc.format_time(v, TEMPORAL) for v in fc.future_times(t0[-1], freq0, H)]
lq0, q0 = res0["quantile_levels"], res0["quantiles"]
wq = [(j + 1.0) * (k + 1.0) for j in range(len(lq0)) for k in range(H)]
values["q_check"] = fc._sum([wq[j * H + k] * float(q0[j, k]) for j in range(len(lq0)) for k in range(H)]) / fc._sum(wq)
values["weights_label"] = spec0["label"]
values["n_covariates"] = len(XREG)
values["n_future_covariates"] = len(FUTURE_COV)
values["together"] = 1 if TOGETHER else 0
if SERIES and len(series_keys) > 1:
values["model_label"] = f"{len(series_keys)} series, " + ("forecast together" if TOGETHER else "each forecast alone")
suffix0 = f" — {series_keys[0]}" if SERIES else ""
hist0 = min(len(t0), max(3 * H, 24))
y0 = [r["mean"] for r in fc_rows if r["series"] == series_keys[0] and r["kind"] == "actual"][-hist0:]
th0 = [r["time"] for r in fc_rows if r["series"] == series_keys[0] and r["kind"] == "actual"][-hist0:]
charts.append(
cs.chart(
"quantiles",
"quantile-fan",
f"Chronos-2 quantiles for {VALUE}" + suffix0,
{
"time": cs.col(TIME, th0 + [times0[k] for j in range(len(lq0)) for k in range(H)], kind="temporal" if TEMPORAL else "numeric"),
"value": cs.col(VALUE, y0 + [float(q0[j, k]) for j in range(len(lq0)) for k in range(H)], kind="numeric"),
"quantile": cs.col("quantile", [None] * len(y0) + [lq0[j] for j in range(len(lq0)) for k in range(H)], kind="numeric"),
},
)
)
extra_tables.append(
{
"key": "quantiles",
"title": "The model's quantiles (the 50% quantile is the forecast)" + suffix0,
"columns": [{"key": "time", "label": TIME}] + [{"key": f"q{round(p * 100):g}", "label": f"{p * 100:g}%", "type": "number"} for p in lq0],
"rows": [dict({"time": times0[k]}, **{f"q{round(p * 100):g}": float(q0[j, k]) for j, p in enumerate(lq0)}) for k in range(H)],
}
)
if XREG:
extra_tables.append(
{
"key": "covariates",
"title": "Covariates the model read",
"columns": [{"key": "column", "label": "Column"}, {"key": "use", "label": "Used as"}],
"rows": [{"column": c, "use": "Known in advance (future values given)" if c in FUTURE_COV else "Past only"} for c in XREG],
}
)
extra_tables.append(
{
"key": "weights",
"title": "Pretrained weights",
"columns": [{"key": "item", "label": "Item"}, {"key": "value", "label": "Value"}],
"rows": [
{"item": "Model", "value": f"{spec0['label']} ({spec0['params']} parameters)"},
{"item": "Source", "value": f"huggingface.co/{spec0['repo']}"},
{"item": "Revision", "value": spec0["revision"]},
{"item": "License", "value": "Apache-2.0"},
{"item": "Download size", "value": c2.size_text(spec0["bytes"])},
{"item": "Related series", "value": "Forecast together (cross-learning)" if TOGETHER else "Each forecast alone"},
],
}
)
extra_assumptions.append(
{
"key": "horizon_trained",
"label": "Horizon within the model's training",
"status": "pass" if H <= c2.TRAINED_HORIZON else "warn",
"statistic": float(H),
"detail": f"Horizon {H}; Chronos-2 predicts up to {c2.TRAINED_HORIZON} steps at once." + ("" if H <= c2.TRAINED_HORIZON else " Later steps feed the model's own forecasts back, so they can drift."),
}
)
ctx0 = int(res0["facts"]["context"])
extra_assumptions.append(
{
"key": "context_length",
"label": "Enough history for the model",
"status": "pass" if ctx0 >= 64 else "warn",
"statistic": float(ctx0),
"detail": f"The model read {ctx0} values." + ("" if ctx0 >= 64 else " Fewer than 64 (four patches of 16) leaves little pattern to recognize."),
}
)
rel0 = fc.naive_relative_mae(bt_rows) # not MASE < 1: MASE scales by the in-sample one-step naive error
if math.isfinite(rel0):
values["bt[rel_mae]"] = rel0
beats0 = rel0 < 1
extra_assumptions.append(
{
"key": "beats_naive",
"label": "Beats the seasonal naive forecast",
"status": "pass" if beats0 else "warn",
"statistic": rel0,
"detail": f"Backtest MAE is {rel0:.2f} times the seasonal naive forecast's from the same origins." + ("" if beats0 else " Repeating the last season forecast these origins at least as well."),
}
)
# The driver's held-regressor note names every covariate; only known-future ones need future values.
warnings[:] = [w for w in warnings if not w.startswith("Future values of ")]
if FUTURE_COV:
later_counts = []
for key in series_keys:
sel = ~np.isnan(times_all) & ((keys_all.astype(str) == key) if SERIES else True)
y_k, t_k = values_all[sel], times_all[sel]
last_k = np.nanmax(np.where(np.isnan(y_k), np.nan, t_k))
later_counts.append(int(np.sum(t_k > last_k)))
if min(later_counts) < H:
warnings.append(f"Future values of {', '.join(FUTURE_COV)} are known for {min(later_counts)} of {H} steps; the last known values are held for the rest.")
if n_origins and FUTURE_COV:
warnings.append(
f"The backtest gave the model the actual future values of {', '.join(FUTURE_COV)}. 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."
)
if H > c2.TRAINED_HORIZON:
warnings.append(f"Chronos-2 predicts up to {c2.TRAINED_HORIZON} steps at once; steps beyond that are rolled forward from its own forecasts.")
# %% 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": "Chronos-2 zero-shot forecast with covariates",
"engine": cs.engine_info("chronos-forecasting", "torch", "codesplash", "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,
}
)
Here the petrol price and the 1983 seat-belt law are given for the next 12 months. The model read 2 known-future covariates, and its backtest MAE is 10.9.
Read the warning on the card. In the backtest the model was given the values that actually happened. A real forecast knows them only if they are truly planned, so read this accuracy as a best case.
Past and future together
ReadChronos-2 Small (zero-shot, with covariates): 6-step forecasts of drivers (monthly data, 192 observations). Backtest MAE 11.3 over 2 origins.
- MAE
- 11.270
- RMSE
- 14.307
- MAPE
- 0.1023
Plots
View data
| hi_80 | hi_95 | kind | lo_80 | lo_95 | month | drivers |
|---|---|---|---|---|---|---|
| — | — | actual | — | — | −31,536,000,000 | 107 |
| — | — | actual | — | — | −28,857,600,000 | 97 |
| — | — | actual | — | — | −26,438,400,000 | 102 |
| — | — | actual | — | — | −23,760,000,000 | 87 |
| — | — | actual | — | — | −21,168,000,000 | 119 |
| — | — | actual | — | — | −18,489,600,000 | 106 |
| — | — | actual | — | — | −15,897,600,000 | 110 |
| — | — | actual | — | — | −13,219,200,000 | 106 |
| — | — | actual | — | — | −10,540,800,000 | 107 |
| — | — | actual | — | — | −7,948,800,000 | 134 |
| — | — | actual | — | — | −5,270,400,000 | 147 |
| — | — | actual | — | — | −2,678,400,000 | 180 |
| — | — | actual | — | — | 0 | 125 |
| — | — | actual | — | — | 2,678,400,000 | 134 |
| — | — | actual | — | — | 5,097,600,000 | 110 |
| — | — | actual | — | — | 7,776,000,000 | 102 |
| — | — | actual | — | — | 10,368,000,000 | 103 |
| — | — | actual | — | — | 13,046,400,000 | 111 |
| — | — | actual | — | — | 15,638,400,000 | 120 |
| — | — | actual | — | — | 18,316,800,000 | 129 |
| — | — | actual | — | — | 20,995,200,000 | 122 |
| — | — | actual | — | — | 23,587,200,000 | 183 |
| — | — | actual | — | — | 26,265,600,000 | 169 |
| — | — | actual | — | — | 28,857,600,000 | 190 |
| — | — | actual | — | — | 31,536,000,000 | 134 |
| — | — | actual | — | — | 34,214,400,000 | 108 |
| — | — | actual | — | — | 36,633,600,000 | 104 |
| — | — | actual | — | — | 39,312,000,000 | 117 |
| — | — | actual | — | — | 41,904,000,000 | 157 |
| — | — | actual | — | — | 44,582,400,000 | 148 |
| — | — | actual | — | — | 47,174,400,000 | 130 |
| — | — | actual | — | — | 49,852,800,000 | 140 |
| — | — | actual | — | — | 52,531,200,000 | 136 |
| — | — | actual | — | — | 55,123,200,000 | 140 |
| — | — | actual | — | — | 57,801,600,000 | 187 |
| — | — | actual | — | — | 60,393,600,000 | 150 |
| — | — | actual | — | — | 63,072,000,000 | 159 |
| — | — | actual | — | — | 65,750,400,000 | 143 |
| — | — | actual | — | — | 68,256,000,000 | 114 |
| — | — | actual | — | — | 70,934,400,000 | 127 |
| — | — | actual | — | — | 73,526,400,000 | 159 |
| — | — | actual | — | — | 76,204,800,000 | 156 |
| — | — | actual | — | — | 78,796,800,000 | 138 |
| — | — | actual | — | — | 81,475,200,000 | 120 |
| — | — | actual | — | — | 84,153,600,000 | 117 |
| — | — | actual | — | — | 86,745,600,000 | 170 |
| — | — | actual | — | — | 89,424,000,000 | 168 |
| — | — | actual | — | — | 92,016,000,000 | 198 |
| — | — | actual | — | — | 94,694,400,000 | 144 |
| — | — | actual | — | — | 97,372,800,000 | 146 |
| — | — | actual | — | — | 99,792,000,000 | 109 |
| — | — | actual | — | — | 102,470,400,000 | 131 |
| — | — | actual | — | — | 105,062,400,000 | 151 |
| — | — | actual | — | — | 107,740,800,000 | 140 |
| — | — | actual | — | — | 110,332,800,000 | 153 |
| — | — | actual | — | — | 113,011,200,000 | 140 |
| — | — | actual | — | — | 115,689,600,000 | 161 |
| — | — | actual | — | — | 118,281,600,000 | 168 |
| — | — | actual | — | — | 120,960,000,000 | 152 |
| — | — | actual | — | — | 123,552,000,000 | 136 |
First 60 of 198 rows.
View data
| error | horizon | origin |
|---|---|---|
| 1.261 | 1 | 1983-12-01 |
| 6.251 | 2 | 1983-12-01 |
| 3.455 | 3 | 1983-12-01 |
| 9.468 | 4 | 1983-12-01 |
| 8.842 | 5 | 1983-12-01 |
| 8.119 | 6 | 1983-12-01 |
| −9.004 | 1 | 1984-06-01 |
| 8.026 | 2 | 1984-06-01 |
| 27.205 | 3 | 1984-06-01 |
| 7.536 | 4 | 1984-06-01 |
| 13.916 | 5 | 1984-06-01 |
| 32.152 | 6 | 1984-06-01 |
View data
| quantile | month | drivers |
|---|---|---|
| — | 410,227,200,000 | 120 |
| — | 412,905,600,000 | 95 |
| — | 415,324,800,000 | 100 |
| — | 418,003,200,000 | 89 |
| — | 420,595,200,000 | 82 |
| — | 423,273,600,000 | 89 |
| — | 425,865,600,000 | 60 |
| — | 428,544,000,000 | 84 |
| — | 431,222,400,000 | 113 |
| — | 433,814,400,000 | 126 |
| — | 436,492,800,000 | 122 |
| — | 439,084,800,000 | 118 |
| — | 441,763,200,000 | 92 |
| — | 444,441,600,000 | 86 |
| — | 446,947,200,000 | 81 |
| — | 449,625,600,000 | 84 |
| — | 452,217,600,000 | 87 |
| — | 454,896,000,000 | 90 |
| — | 457,488,000,000 | 79 |
| — | 460,166,400,000 | 96 |
| — | 462,844,800,000 | 122 |
| — | 465,436,800,000 | 120 |
| — | 468,115,200,000 | 137 |
| — | 470,707,200,000 | 154 |
| 0.0100 | 473,385,600,000 | 78.735 |
| 0.0100 | 476,064,000,000 | 61.903 |
| 0.0100 | 478,483,200,000 | 52.977 |
| 0.0100 | 481,161,600,000 | 53.157 |
| 0.0100 | 483,753,600,000 | 60.191 |
| 0.0100 | 486,432,000,000 | 63.949 |
| 0.0500 | 473,385,600,000 | 88.960 |
| 0.0500 | 476,064,000,000 | 71.626 |
| 0.0500 | 478,483,200,000 | 64.543 |
| 0.0500 | 481,161,600,000 | 64.801 |
| 0.0500 | 483,753,600,000 | 71.000 |
| 0.0500 | 486,432,000,000 | 74.856 |
| 0.1000 | 473,385,600,000 | 94.187 |
| 0.1000 | 476,064,000,000 | 75.915 |
| 0.1000 | 478,483,200,000 | 69.892 |
| 0.1000 | 481,161,600,000 | 69.820 |
| 0.1000 | 483,753,600,000 | 75.523 |
| 0.1000 | 486,432,000,000 | 79.690 |
| 0.2000 | 473,385,600,000 | 100.42 |
| 0.2000 | 476,064,000,000 | 81.083 |
| 0.2000 | 478,483,200,000 | 75.809 |
| 0.2000 | 481,161,600,000 | 75.430 |
| 0.2000 | 483,753,600,000 | 80.738 |
| 0.2000 | 486,432,000,000 | 85.447 |
| 0.3000 | 473,385,600,000 | 104.62 |
| 0.3000 | 476,064,000,000 | 84.927 |
| 0.3000 | 478,483,200,000 | 79.647 |
| 0.3000 | 481,161,600,000 | 79.464 |
| 0.3000 | 483,753,600,000 | 84.743 |
| 0.3000 | 486,432,000,000 | 89.353 |
| 0.4000 | 473,385,600,000 | 107.99 |
| 0.4000 | 476,064,000,000 | 88.169 |
| 0.4000 | 478,483,200,000 | 82.876 |
| 0.4000 | 481,161,600,000 | 82.686 |
| 0.4000 | 483,753,600,000 | 88.159 |
| 0.4000 | 486,432,000,000 | 92.889 |
First 60 of 102 rows.
Assumptions
- Horizon within the model's training — Horizon 6; Chronos-2 predicts up to 1024 steps at once.
- Enough history for the model — The model read 192 values.
- Beats the seasonal naive forecast — Backtest MAE is 0.82 times the seasonal naive forecast's from the same origins.
Backtest accuracy (2 origins, horizon 6)
| Metric | Value |
|---|---|
| MAE | 11.270 |
| RMSE | 14.307 |
| MAPE | 0.1023 |
| sMAPE | 0.1087 |
| MASE | 0.6645 |
| WAPE | 0.1101 |
| Coverage of the 80% interval | 0.7500 |
| Coverage of the 95% interval | 0.9167 |
The model's quantiles (the 50% quantile is the forecast)
| month | 1% | 5% | 10% | 20% | 30% | 40% | 50% | 60% | 70% | 80% | 90% | 95% | 99% |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 1985-01-01 | 78.735 | 88.960 | 94.187 | 100.42 | 104.62 | 107.99 | 111.02 | 114.14 | 117.57 | 121.72 | 127.47 | 132.94 | 145.17 |
| 1985-02-01 | 61.903 | 71.626 | 75.915 | 81.083 | 84.927 | 88.169 | 91.225 | 94.265 | 97.505 | 101.67 | 107.37 | 113.07 | 124.69 |
| 1985-03-01 | 52.977 | 64.543 | 69.892 | 75.809 | 79.647 | 82.876 | 85.919 | 89.087 | 92.336 | 96.502 | 102.33 | 108.21 | 120.13 |
| 1985-04-01 | 53.157 | 64.801 | 69.820 | 75.430 | 79.464 | 82.686 | 85.695 | 88.690 | 91.994 | 96.132 | 102.14 | 108.01 | 121.03 |
| 1985-05-01 | 60.191 | 71.000 | 75.523 | 80.738 | 84.743 | 88.159 | 91.426 | 94.739 | 98.384 | 102.73 | 108.76 | 114.56 | 126.14 |
| 1985-06-01 | 63.949 | 74.856 | 79.690 | 85.447 | 89.353 | 92.889 | 96.065 | 99.314 | 102.74 | 107.19 | 113.34 | 119.06 | 130.11 |
Covariates the model read
| Column | Used as |
|---|---|
| law | Known in advance (future values given) |
| petrol | Past only |
Pretrained weights
| Item | Value |
|---|---|
| Model | Chronos-2 Small (28M parameters) |
| Source | huggingface.co/autogluon/chronos-2-small |
| Revision | ddec01313e50b6bc58ebaa92ede81bc24a3d9f9a |
| License | Apache-2.0 |
| Download size | 111.8 MB |
| Related series | Each forecast alone |
Forecast
| month | Forecast | 80% low | 80% high | 95% low | 95% high |
|---|---|---|---|---|---|
| 1985-01-01 | 111.02 | 94.187 | 127.47 | 82.569 | 140.58 |
| 1985-02-01 | 91.225 | 75.915 | 107.37 | 65.549 | 120.34 |
| 1985-03-01 | 85.919 | 69.892 | 102.33 | 57.314 | 115.66 |
| 1985-04-01 | 85.695 | 69.820 | 102.14 | 57.523 | 116.15 |
| 1985-05-01 | 91.426 | 75.523 | 108.76 | 64.244 | 121.80 |
| 1985-06-01 | 96.065 | 79.690 | 113.34 | 68.039 | 125.97 |
- Future values of law are known for 0 of 6 steps; the last known values are held for the rest.
- The backtest gave the model the actual future values of law. A real forecast only knows them when they are planned or fixed in advance (holidays, prices you set), so read the backtest accuracy as a best case.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Chronos-2 zero-shot forecast with covariates
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.chronos2 1.0.0 · spec 0bc0f1ceae0fd222
# 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
from codesplash.deep import chronos2 as c2 # pretrained weights, looked up locally only (never downloaded here)
# %% Data
TIME = "month"
VALUE = "drivers"
SERIES = None
H = 6
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
FUTURE_COV = ["law"] # known-future covariates: their future values sit in rows after the last observed value
PAST_COV = ["petrol"] # past-only covariates: observed up to now, not ahead
XREG = FUTURE_COV + [c for c in PAST_COV if c not in FUTURE_COV]
PARAMS = {
"model": "chronos2_small",
"context": None,
"related": "independent",
}
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.chronos2/small_past_and_future_covariates/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
# Chronos-2 (Ansari et al. 2025) is pretrained: it reads the recent history (and any covariates) and predicts 13
# quantiles of the next steps without training on this data. Python only — the weights run through the
# chronos-forecasting package. The weights must already be on this computer (the app downloads them only after you
# confirm the size).
MODEL = PARAMS["model"]
CONTEXT = PARAMS["context"]
TOGETHER = bool(SERIES) and PARAMS["related"] == "together" # forecast the series jointly (cross-learning)
FINAL = {}
WEIGHTS = c2.locate(MODEL) # stops with CS_WEIGHTS_MISSING and the download size when absent
def min_train(m):
return 8
def prepare_series(y, t, m, freq):
return None
def covariates(x_train, x_future):
"""Past values of every covariate (aligned with y) and the h future values of the known-future ones."""
if not XREG:
return None, None
past = {c: x_train[:, j] for j, c in enumerate(XREG)}
future = {c: x_future[:, XREG.index(c)] for c in FUTURE_COV} if FUTURE_COV else None
return past, future
# Related series together: every series on the same time grid as the driver builds it (same regularization), so
# a forecast from one origin can include all series that have a value at that origin's time.
GRID = {}
if TOGETHER:
for key in series_keys:
sel = ~np.isnan(times_all) & (keys_all.astype(str) == key)
t_raw, y_raw = times_all[sel], values_all[sel]
x_raw, x_later = None, None
if XREG:
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]
if int(np.sum(~np.isnan(y_raw))) < 3:
continue # the driver stops on this series itself
freq_k = fc.detect_frequency(np.sort(t_raw), TEMPORAL)
t_k, y_k, _ = fc.regularize(t_raw, y_raw, freq_k)
x_k = np.column_stack([fc.regularize(t_raw, x_raw[:, j], freq_k)[1] for j in range(x_raw.shape[1])]) if XREG else None
GRID[key] = (np.asarray(t_k, dtype=np.float64), [float(v) for v in y_k], x_k, x_later)
JOINT = {} # origin time → {series: (training length, quantile levels, quantiles, context used)}
def joint(t_last):
"""Forecast every series that has a value at time t_last from that origin, all in one call."""
if t_last in JOINT:
return JOINT[t_last]
items, keys, lens = [], [], []
for key, (ts, ys, xg, xl) in GRID.items():
o = int(np.searchsorted(ts, t_last + 1e-9, side="right"))
if o < min_train(1) or abs(ts[o - 1] - t_last) > 1e-6:
continue # no value at this time: this series is forecast from its own origins
start = max(0, o - int(TRAIN_WINDOW)) if TRAIN_WINDOW else 0
past, future = None, None
if XREG:
if o + H <= len(ts):
xf = xg[o:o + H]
elif o == len(ts):
xf = fc.future_regressors(xg, xl, H)
else:
xf = np.vstack([xg[o:]] + [xg[-1:]] * (o + H - len(ts)))
past, future = covariates(xg[start:o], xf)
items.append((ys[start:o], past, future))
keys.append(key)
lens.append(o - start)
outs = c2.native_quantiles_many(MODEL, items, H, CONTEXT, together=True) if items else []
JOINT[t_last] = {k: (n_k, lq, q, used) for k, n_k, (lq, q, used) in zip(keys, lens, outs, strict=True)}
return JOINT[t_last]
def fit_forecast(y, t, h, m, levels, spec):
past, future = covariates(X_TRAIN, X_FUTURE)
res = None
if TOGETHER:
entry = joint(float(t[-1])).get(current_series)
if entry is not None and entry[0] == len(y):
n_k, lq, q, used = entry
res = c2.result_from_quantiles(lq, q, used, levels, MODEL, len(XREG))
if res is None:
res = c2.fit_forecast(y, h, levels, model=MODEL, context=CONTEXT, past=past, future=future)
FINAL[current_series] = (res, [float(v) for v in t])
return res
# %% 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"),
},
)
)
# %% Quantiles and checks
res0, t0 = FINAL[series_keys[0]]
spec0 = c2.MODELS[MODEL]
freq0 = fc.detect_frequency(np.array(t0), TEMPORAL)
times0 = [fc.format_time(v, TEMPORAL) for v in fc.future_times(t0[-1], freq0, H)]
lq0, q0 = res0["quantile_levels"], res0["quantiles"]
wq = [(j + 1.0) * (k + 1.0) for j in range(len(lq0)) for k in range(H)]
values["q_check"] = fc._sum([wq[j * H + k] * float(q0[j, k]) for j in range(len(lq0)) for k in range(H)]) / fc._sum(wq)
values["weights_label"] = spec0["label"]
values["n_covariates"] = len(XREG)
values["n_future_covariates"] = len(FUTURE_COV)
values["together"] = 1 if TOGETHER else 0
if SERIES and len(series_keys) > 1:
values["model_label"] = f"{len(series_keys)} series, " + ("forecast together" if TOGETHER else "each forecast alone")
suffix0 = f" — {series_keys[0]}" if SERIES else ""
hist0 = min(len(t0), max(3 * H, 24))
y0 = [r["mean"] for r in fc_rows if r["series"] == series_keys[0] and r["kind"] == "actual"][-hist0:]
th0 = [r["time"] for r in fc_rows if r["series"] == series_keys[0] and r["kind"] == "actual"][-hist0:]
charts.append(
cs.chart(
"quantiles",
"quantile-fan",
f"Chronos-2 quantiles for {VALUE}" + suffix0,
{
"time": cs.col(TIME, th0 + [times0[k] for j in range(len(lq0)) for k in range(H)], kind="temporal" if TEMPORAL else "numeric"),
"value": cs.col(VALUE, y0 + [float(q0[j, k]) for j in range(len(lq0)) for k in range(H)], kind="numeric"),
"quantile": cs.col("quantile", [None] * len(y0) + [lq0[j] for j in range(len(lq0)) for k in range(H)], kind="numeric"),
},
)
)
extra_tables.append(
{
"key": "quantiles",
"title": "The model's quantiles (the 50% quantile is the forecast)" + suffix0,
"columns": [{"key": "time", "label": TIME}] + [{"key": f"q{round(p * 100):g}", "label": f"{p * 100:g}%", "type": "number"} for p in lq0],
"rows": [dict({"time": times0[k]}, **{f"q{round(p * 100):g}": float(q0[j, k]) for j, p in enumerate(lq0)}) for k in range(H)],
}
)
if XREG:
extra_tables.append(
{
"key": "covariates",
"title": "Covariates the model read",
"columns": [{"key": "column", "label": "Column"}, {"key": "use", "label": "Used as"}],
"rows": [{"column": c, "use": "Known in advance (future values given)" if c in FUTURE_COV else "Past only"} for c in XREG],
}
)
extra_tables.append(
{
"key": "weights",
"title": "Pretrained weights",
"columns": [{"key": "item", "label": "Item"}, {"key": "value", "label": "Value"}],
"rows": [
{"item": "Model", "value": f"{spec0['label']} ({spec0['params']} parameters)"},
{"item": "Source", "value": f"huggingface.co/{spec0['repo']}"},
{"item": "Revision", "value": spec0["revision"]},
{"item": "License", "value": "Apache-2.0"},
{"item": "Download size", "value": c2.size_text(spec0["bytes"])},
{"item": "Related series", "value": "Forecast together (cross-learning)" if TOGETHER else "Each forecast alone"},
],
}
)
extra_assumptions.append(
{
"key": "horizon_trained",
"label": "Horizon within the model's training",
"status": "pass" if H <= c2.TRAINED_HORIZON else "warn",
"statistic": float(H),
"detail": f"Horizon {H}; Chronos-2 predicts up to {c2.TRAINED_HORIZON} steps at once." + ("" if H <= c2.TRAINED_HORIZON else " Later steps feed the model's own forecasts back, so they can drift."),
}
)
ctx0 = int(res0["facts"]["context"])
extra_assumptions.append(
{
"key": "context_length",
"label": "Enough history for the model",
"status": "pass" if ctx0 >= 64 else "warn",
"statistic": float(ctx0),
"detail": f"The model read {ctx0} values." + ("" if ctx0 >= 64 else " Fewer than 64 (four patches of 16) leaves little pattern to recognize."),
}
)
rel0 = fc.naive_relative_mae(bt_rows) # not MASE < 1: MASE scales by the in-sample one-step naive error
if math.isfinite(rel0):
values["bt[rel_mae]"] = rel0
beats0 = rel0 < 1
extra_assumptions.append(
{
"key": "beats_naive",
"label": "Beats the seasonal naive forecast",
"status": "pass" if beats0 else "warn",
"statistic": rel0,
"detail": f"Backtest MAE is {rel0:.2f} times the seasonal naive forecast's from the same origins." + ("" if beats0 else " Repeating the last season forecast these origins at least as well."),
}
)
# The driver's held-regressor note names every covariate; only known-future ones need future values.
warnings[:] = [w for w in warnings if not w.startswith("Future values of ")]
if FUTURE_COV:
later_counts = []
for key in series_keys:
sel = ~np.isnan(times_all) & ((keys_all.astype(str) == key) if SERIES else True)
y_k, t_k = values_all[sel], times_all[sel]
last_k = np.nanmax(np.where(np.isnan(y_k), np.nan, t_k))
later_counts.append(int(np.sum(t_k > last_k)))
if min(later_counts) < H:
warnings.append(f"Future values of {', '.join(FUTURE_COV)} are known for {min(later_counts)} of {H} steps; the last known values are held for the rest.")
if n_origins and FUTURE_COV:
warnings.append(
f"The backtest gave the model the actual future values of {', '.join(FUTURE_COV)}. 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."
)
if H > c2.TRAINED_HORIZON:
warnings.append(f"Chronos-2 predicts up to {c2.TRAINED_HORIZON} steps at once; steps beyond that are rolled forward from its own forecasts.")
# %% 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": "Chronos-2 zero-shot forecast with covariates",
"engine": cs.engine_info("chronos-forecasting", "torch", "codesplash", "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,
}
)
Now the law is known ahead but the petrol price is past-only: the model reads its history and nothing beyond. The Covariates table on the card says how each column was used.
Which kind?
PredictPredict first
You forecast daily store visits. The column promo says whether a promotion runs that day, and promotions are planned a month ahead. Which kind of covariate is it?
Reveal
Known-future: you know next month's promotions when you forecast, so put them in the rows after the last observed day.
Related series together
Read2 series, forecast together: 6-step forecasts of deaths (monthly data, 144 observations). Backtest MAE 62 over 2 origins.
- MAE
- 61.969
- RMSE
- 93.408
- MAPE
- 0.0701
Plots
View data
| kind | sex | month | deaths |
|---|---|---|---|
| actual | female | 126,230,400,000 | 901 |
| actual | female | 128,908,800,000 | 689 |
| actual | female | 131,328,000,000 | 827 |
| actual | female | 134,006,400,000 | 677 |
| actual | female | 136,598,400,000 | 522 |
| actual | female | 139,276,800,000 | 406 |
| actual | female | 141,868,800,000 | 441 |
| actual | female | 144,547,200,000 | 393 |
| actual | female | 147,225,600,000 | 387 |
| actual | female | 149,817,600,000 | 582 |
| actual | female | 152,496,000,000 | 578 |
| actual | female | 155,088,000,000 | 666 |
| actual | female | 157,766,400,000 | 830 |
| actual | female | 160,444,800,000 | 752 |
| actual | female | 162,864,000,000 | 785 |
| actual | female | 165,542,400,000 | 664 |
| actual | female | 168,134,400,000 | 467 |
| actual | female | 170,812,800,000 | 438 |
| actual | female | 173,404,800,000 | 421 |
| actual | female | 176,083,200,000 | 412 |
| actual | female | 178,761,600,000 | 343 |
| actual | female | 181,353,600,000 | 440 |
| actual | female | 184,032,000,000 | 531 |
| actual | female | 186,624,000,000 | 771 |
| actual | female | 189,302,400,000 | 767 |
| actual | female | 191,980,800,000 | 1,141 |
| actual | female | 194,486,400,000 | 896 |
| actual | female | 197,164,800,000 | 532 |
| actual | female | 199,756,800,000 | 447 |
| actual | female | 202,435,200,000 | 420 |
| actual | female | 205,027,200,000 | 376 |
| actual | female | 207,705,600,000 | 330 |
| actual | female | 210,384,000,000 | 357 |
| actual | female | 212,976,000,000 | 445 |
| actual | female | 215,654,400,000 | 546 |
| actual | female | 218,246,400,000 | 764 |
| actual | female | 220,924,800,000 | 862 |
| actual | female | 223,603,200,000 | 660 |
| actual | female | 226,022,400,000 | 663 |
| actual | female | 228,700,800,000 | 643 |
| actual | female | 231,292,800,000 | 502 |
| actual | female | 233,971,200,000 | 392 |
| actual | female | 236,563,200,000 | 411 |
| actual | female | 239,241,600,000 | 348 |
| actual | female | 241,920,000,000 | 387 |
| actual | female | 244,512,000,000 | 385 |
| actual | female | 247,190,400,000 | 411 |
| actual | female | 249,782,400,000 | 638 |
| actual | female | 252,460,800,000 | 796 |
| actual | female | 255,139,200,000 | 853 |
| actual | female | 257,558,400,000 | 737 |
| actual | female | 260,236,800,000 | 546 |
| actual | female | 262,828,800,000 | 530 |
| actual | female | 265,507,200,000 | 446 |
| actual | female | 268,099,200,000 | 431 |
| actual | female | 270,777,600,000 | 362 |
| actual | female | 273,456,000,000 | 387 |
| actual | female | 276,048,000,000 | 430 |
| actual | female | 278,726,400,000 | 425 |
| actual | female | 281,318,400,000 | 679 |
First 60 of 156 rows.
View data
| error | horizon | origin |
|---|---|---|
| 15.331 | 1 | 1979-06-01 |
| −1.682 | 2 | 1979-06-01 |
| 17.791 | 3 | 1979-06-01 |
| 23.233 | 4 | 1979-06-01 |
| 60.964 | 5 | 1979-06-01 |
| −47.026 | 6 | 1979-06-01 |
| 3.153 | 1 | 1979-06-01 |
| −68.066 | 2 | 1979-06-01 |
| −102.04 | 3 | 1979-06-01 |
| 23.573 | 4 | 1979-06-01 |
| 121.19 | 5 | 1979-06-01 |
| −259.58 | 6 | 1979-06-01 |
View data
| quantile | month | deaths |
|---|---|---|
| — | 252,460,800,000 | 796 |
| — | 255,139,200,000 | 853 |
| — | 257,558,400,000 | 737 |
| — | 260,236,800,000 | 546 |
| — | 262,828,800,000 | 530 |
| — | 265,507,200,000 | 446 |
| — | 268,099,200,000 | 431 |
| — | 270,777,600,000 | 362 |
| — | 273,456,000,000 | 387 |
| — | 276,048,000,000 | 430 |
| — | 278,726,400,000 | 425 |
| — | 281,318,400,000 | 679 |
| — | 283,996,800,000 | 821 |
| — | 286,675,200,000 | 785 |
| — | 289,094,400,000 | 727 |
| — | 291,772,800,000 | 612 |
| — | 294,364,800,000 | 478 |
| — | 297,043,200,000 | 429 |
| — | 299,635,200,000 | 405 |
| — | 302,313,600,000 | 379 |
| — | 304,992,000,000 | 393 |
| — | 307,584,000,000 | 411 |
| — | 310,262,400,000 | 487 |
| — | 312,854,400,000 | 574 |
| 0.0100 | 315,532,800,000 | 612.79 |
| 0.0100 | 318,211,200,000 | 637.10 |
| 0.0100 | 320,716,800,000 | 565.59 |
| 0.0100 | 323,395,200,000 | 442.78 |
| 0.0100 | 325,987,200,000 | 357.23 |
| 0.0100 | 328,665,600,000 | 342.28 |
| 0.0500 | 315,532,800,000 | 678.36 |
| 0.0500 | 318,211,200,000 | 718.70 |
| 0.0500 | 320,716,800,000 | 623.69 |
| 0.0500 | 323,395,200,000 | 488.10 |
| 0.0500 | 325,987,200,000 | 397.25 |
| 0.0500 | 328,665,600,000 | 372.50 |
| 0.1000 | 315,532,800,000 | 704.42 |
| 0.1000 | 318,211,200,000 | 750.63 |
| 0.1000 | 320,716,800,000 | 650.97 |
| 0.1000 | 323,395,200,000 | 508.22 |
| 0.1000 | 325,987,200,000 | 413.19 |
| 0.1000 | 328,665,600,000 | 381.55 |
| 0.2000 | 315,532,800,000 | 732.04 |
| 0.2000 | 318,211,200,000 | 782.29 |
| 0.2000 | 320,716,800,000 | 681.87 |
| 0.2000 | 323,395,200,000 | 532.38 |
| 0.2000 | 325,987,200,000 | 429.52 |
| 0.2000 | 328,665,600,000 | 391.64 |
| 0.3000 | 315,532,800,000 | 750.02 |
| 0.3000 | 318,211,200,000 | 803.65 |
| 0.3000 | 320,716,800,000 | 704.23 |
| 0.3000 | 323,395,200,000 | 550.29 |
| 0.3000 | 325,987,200,000 | 441.67 |
| 0.3000 | 328,665,600,000 | 400.08 |
| 0.4000 | 315,532,800,000 | 765.46 |
| 0.4000 | 318,211,200,000 | 822.17 |
| 0.4000 | 320,716,800,000 | 721.64 |
| 0.4000 | 323,395,200,000 | 564.38 |
| 0.4000 | 325,987,200,000 | 452.41 |
| 0.4000 | 328,665,600,000 | 409.17 |
First 60 of 102 rows.
Assumptions
- Horizon within the model's training — Horizon 6; Chronos-2 predicts up to 1024 steps at once.
- Enough history for the model — The model read 72 values.
- Beats the seasonal naive forecast — Backtest MAE is 0.71 times the seasonal naive forecast's from the same origins.
Backtest accuracy (2 origins, horizon 6)
| Metric | Value |
|---|---|
| MAE | 61.969 |
| RMSE | 93.408 |
| MAPE | 0.0701 |
| sMAPE | 0.0692 |
| MASE | 0.4644 |
| WAPE | 0.0797 |
| Coverage of the 90% interval | 0.9167 |
The model's quantiles (the 50% quantile is the forecast) — female
| month | 1% | 5% | 10% | 20% | 30% | 40% | 50% | 60% | 70% | 80% | 90% | 95% | 99% |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 1980-01-01 | 612.79 | 678.36 | 704.42 | 732.04 | 750.02 | 765.46 | 779.90 | 794.66 | 810.66 | 831.95 | 864.73 | 904.75 | 1044.86 |
| 1980-02-01 | 637.10 | 718.70 | 750.63 | 782.29 | 803.65 | 822.17 | 839.54 | 858.38 | 879.06 | 908.64 | 951.17 | 1003.33 | 1175.04 |
| 1980-03-01 | 565.59 | 623.69 | 650.97 | 681.87 | 704.23 | 721.64 | 737.38 | 753.22 | 769.09 | 790.18 | 824.61 | 864.68 | 995.60 |
| 1980-04-01 | 442.78 | 488.10 | 508.22 | 532.38 | 550.29 | 564.38 | 576.19 | 587.44 | 600.16 | 618.85 | 650.71 | 686.39 | 788.54 |
| 1980-05-01 | 357.23 | 397.25 | 413.19 | 429.52 | 441.67 | 452.41 | 463.34 | 476.46 | 491.38 | 512.17 | 545.05 | 577.07 | 653.27 |
| 1980-06-01 | 342.28 | 372.50 | 381.55 | 391.64 | 400.08 | 409.17 | 418.72 | 430.46 | 443.05 | 460.10 | 486.84 | 515.39 | 590.71 |
Pretrained weights
| Item | Value |
|---|---|
| Model | Chronos-2 Small (28M parameters) |
| Source | huggingface.co/autogluon/chronos-2-small |
| Revision | ddec01313e50b6bc58ebaa92ede81bc24a3d9f9a |
| License | Apache-2.0 |
| Download size | 111.8 MB |
| Related series | Forecast together (cross-learning) |
Forecast
| Series | month | Forecast | 90% low | 90% high |
|---|---|---|---|---|
| female | 1980-01-01 | 779.90 | 678.36 | 904.75 |
| female | 1980-02-01 | 839.54 | 718.70 | 1003.33 |
| female | 1980-03-01 | 737.38 | 623.69 | 864.68 |
| female | 1980-04-01 | 576.19 | 488.10 | 686.39 |
| female | 1980-05-01 | 463.34 | 397.25 | 577.07 |
| female | 1980-06-01 | 418.72 | 372.50 | 515.39 |
| male | 1980-01-01 | 1938.00 | 1670.65 | 2204.94 |
| male | 1980-02-01 | 2049.03 | 1772.23 | 2374.70 |
| male | 1980-03-01 | 1831.99 | 1557.06 | 2116.46 |
| male | 1980-04-01 | 1427.00 | 1212.38 | 1677.02 |
| male | 1980-05-01 | 1112.66 | 1001.18 | 1345.19 |
| male | 1980-06-01 | 1051.32 | 974.07 | 1273.97 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Chronos-2 zero-shot forecast with covariates
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.chronos2 1.0.0 · spec df3dbbf61f414ecd
# Dataset: ml_deaths (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import forecast as fc
from codesplash.deep import chronos2 as c2 # pretrained weights, looked up locally only (never downloaded here)
# %% Data
TIME = "month"
VALUE = "deaths"
SERIES = "sex"
H = 6
LEVELS = [float(v) for v in [90]]
SEASON = None # None = from the time steps (12 monthly, 4 quarterly, 7 daily …)
WINDOWS = 1
STEP = None # None = the horizon
OFFSETS = None # the host's BacktestPlan: distance of each origin from the end of the series; None = windows and step
TRAIN_WINDOW = None # None = train on all values before each origin
TRAIN_START = None # rows before this time are left out (for example, before a structural break)
SEED = 42
FUTURE_COV = [] # known-future covariates: their future values sit in rows after the last observed value
PAST_COV = [] # past-only covariates: observed up to now, not ahead
XREG = FUTURE_COV + [c for c in PAST_COV if c not in FUTURE_COV]
PARAMS = {
"model": "chronos2_small",
"context": None,
"related": "together",
}
df = pd.read_parquet("tests/parity/fixtures/ml_deaths.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.chronos2/small_panel_together/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
# Chronos-2 (Ansari et al. 2025) is pretrained: it reads the recent history (and any covariates) and predicts 13
# quantiles of the next steps without training on this data. Python only — the weights run through the
# chronos-forecasting package. The weights must already be on this computer (the app downloads them only after you
# confirm the size).
MODEL = PARAMS["model"]
CONTEXT = PARAMS["context"]
TOGETHER = bool(SERIES) and PARAMS["related"] == "together" # forecast the series jointly (cross-learning)
FINAL = {}
WEIGHTS = c2.locate(MODEL) # stops with CS_WEIGHTS_MISSING and the download size when absent
def min_train(m):
return 8
def prepare_series(y, t, m, freq):
return None
def covariates(x_train, x_future):
"""Past values of every covariate (aligned with y) and the h future values of the known-future ones."""
if not XREG:
return None, None
past = {c: x_train[:, j] for j, c in enumerate(XREG)}
future = {c: x_future[:, XREG.index(c)] for c in FUTURE_COV} if FUTURE_COV else None
return past, future
# Related series together: every series on the same time grid as the driver builds it (same regularization), so
# a forecast from one origin can include all series that have a value at that origin's time.
GRID = {}
if TOGETHER:
for key in series_keys:
sel = ~np.isnan(times_all) & (keys_all.astype(str) == key)
t_raw, y_raw = times_all[sel], values_all[sel]
x_raw, x_later = None, None
if XREG:
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]
if int(np.sum(~np.isnan(y_raw))) < 3:
continue # the driver stops on this series itself
freq_k = fc.detect_frequency(np.sort(t_raw), TEMPORAL)
t_k, y_k, _ = fc.regularize(t_raw, y_raw, freq_k)
x_k = np.column_stack([fc.regularize(t_raw, x_raw[:, j], freq_k)[1] for j in range(x_raw.shape[1])]) if XREG else None
GRID[key] = (np.asarray(t_k, dtype=np.float64), [float(v) for v in y_k], x_k, x_later)
JOINT = {} # origin time → {series: (training length, quantile levels, quantiles, context used)}
def joint(t_last):
"""Forecast every series that has a value at time t_last from that origin, all in one call."""
if t_last in JOINT:
return JOINT[t_last]
items, keys, lens = [], [], []
for key, (ts, ys, xg, xl) in GRID.items():
o = int(np.searchsorted(ts, t_last + 1e-9, side="right"))
if o < min_train(1) or abs(ts[o - 1] - t_last) > 1e-6:
continue # no value at this time: this series is forecast from its own origins
start = max(0, o - int(TRAIN_WINDOW)) if TRAIN_WINDOW else 0
past, future = None, None
if XREG:
if o + H <= len(ts):
xf = xg[o:o + H]
elif o == len(ts):
xf = fc.future_regressors(xg, xl, H)
else:
xf = np.vstack([xg[o:]] + [xg[-1:]] * (o + H - len(ts)))
past, future = covariates(xg[start:o], xf)
items.append((ys[start:o], past, future))
keys.append(key)
lens.append(o - start)
outs = c2.native_quantiles_many(MODEL, items, H, CONTEXT, together=True) if items else []
JOINT[t_last] = {k: (n_k, lq, q, used) for k, n_k, (lq, q, used) in zip(keys, lens, outs, strict=True)}
return JOINT[t_last]
def fit_forecast(y, t, h, m, levels, spec):
past, future = covariates(X_TRAIN, X_FUTURE)
res = None
if TOGETHER:
entry = joint(float(t[-1])).get(current_series)
if entry is not None and entry[0] == len(y):
n_k, lq, q, used = entry
res = c2.result_from_quantiles(lq, q, used, levels, MODEL, len(XREG))
if res is None:
res = c2.fit_forecast(y, h, levels, model=MODEL, context=CONTEXT, past=past, future=future)
FINAL[current_series] = (res, [float(v) for v in t])
return res
# %% 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"),
},
)
)
# %% Quantiles and checks
res0, t0 = FINAL[series_keys[0]]
spec0 = c2.MODELS[MODEL]
freq0 = fc.detect_frequency(np.array(t0), TEMPORAL)
times0 = [fc.format_time(v, TEMPORAL) for v in fc.future_times(t0[-1], freq0, H)]
lq0, q0 = res0["quantile_levels"], res0["quantiles"]
wq = [(j + 1.0) * (k + 1.0) for j in range(len(lq0)) for k in range(H)]
values["q_check"] = fc._sum([wq[j * H + k] * float(q0[j, k]) for j in range(len(lq0)) for k in range(H)]) / fc._sum(wq)
values["weights_label"] = spec0["label"]
values["n_covariates"] = len(XREG)
values["n_future_covariates"] = len(FUTURE_COV)
values["together"] = 1 if TOGETHER else 0
if SERIES and len(series_keys) > 1:
values["model_label"] = f"{len(series_keys)} series, " + ("forecast together" if TOGETHER else "each forecast alone")
suffix0 = f" — {series_keys[0]}" if SERIES else ""
hist0 = min(len(t0), max(3 * H, 24))
y0 = [r["mean"] for r in fc_rows if r["series"] == series_keys[0] and r["kind"] == "actual"][-hist0:]
th0 = [r["time"] for r in fc_rows if r["series"] == series_keys[0] and r["kind"] == "actual"][-hist0:]
charts.append(
cs.chart(
"quantiles",
"quantile-fan",
f"Chronos-2 quantiles for {VALUE}" + suffix0,
{
"time": cs.col(TIME, th0 + [times0[k] for j in range(len(lq0)) for k in range(H)], kind="temporal" if TEMPORAL else "numeric"),
"value": cs.col(VALUE, y0 + [float(q0[j, k]) for j in range(len(lq0)) for k in range(H)], kind="numeric"),
"quantile": cs.col("quantile", [None] * len(y0) + [lq0[j] for j in range(len(lq0)) for k in range(H)], kind="numeric"),
},
)
)
extra_tables.append(
{
"key": "quantiles",
"title": "The model's quantiles (the 50% quantile is the forecast)" + suffix0,
"columns": [{"key": "time", "label": TIME}] + [{"key": f"q{round(p * 100):g}", "label": f"{p * 100:g}%", "type": "number"} for p in lq0],
"rows": [dict({"time": times0[k]}, **{f"q{round(p * 100):g}": float(q0[j, k]) for j, p in enumerate(lq0)}) for k in range(H)],
}
)
if XREG:
extra_tables.append(
{
"key": "covariates",
"title": "Covariates the model read",
"columns": [{"key": "column", "label": "Column"}, {"key": "use", "label": "Used as"}],
"rows": [{"column": c, "use": "Known in advance (future values given)" if c in FUTURE_COV else "Past only"} for c in XREG],
}
)
extra_tables.append(
{
"key": "weights",
"title": "Pretrained weights",
"columns": [{"key": "item", "label": "Item"}, {"key": "value", "label": "Value"}],
"rows": [
{"item": "Model", "value": f"{spec0['label']} ({spec0['params']} parameters)"},
{"item": "Source", "value": f"huggingface.co/{spec0['repo']}"},
{"item": "Revision", "value": spec0["revision"]},
{"item": "License", "value": "Apache-2.0"},
{"item": "Download size", "value": c2.size_text(spec0["bytes"])},
{"item": "Related series", "value": "Forecast together (cross-learning)" if TOGETHER else "Each forecast alone"},
],
}
)
extra_assumptions.append(
{
"key": "horizon_trained",
"label": "Horizon within the model's training",
"status": "pass" if H <= c2.TRAINED_HORIZON else "warn",
"statistic": float(H),
"detail": f"Horizon {H}; Chronos-2 predicts up to {c2.TRAINED_HORIZON} steps at once." + ("" if H <= c2.TRAINED_HORIZON else " Later steps feed the model's own forecasts back, so they can drift."),
}
)
ctx0 = int(res0["facts"]["context"])
extra_assumptions.append(
{
"key": "context_length",
"label": "Enough history for the model",
"status": "pass" if ctx0 >= 64 else "warn",
"statistic": float(ctx0),
"detail": f"The model read {ctx0} values." + ("" if ctx0 >= 64 else " Fewer than 64 (four patches of 16) leaves little pattern to recognize."),
}
)
rel0 = fc.naive_relative_mae(bt_rows) # not MASE < 1: MASE scales by the in-sample one-step naive error
if math.isfinite(rel0):
values["bt[rel_mae]"] = rel0
beats0 = rel0 < 1
extra_assumptions.append(
{
"key": "beats_naive",
"label": "Beats the seasonal naive forecast",
"status": "pass" if beats0 else "warn",
"statistic": rel0,
"detail": f"Backtest MAE is {rel0:.2f} times the seasonal naive forecast's from the same origins." + ("" if beats0 else " Repeating the last season forecast these origins at least as well."),
}
)
# The driver's held-regressor note names every covariate; only known-future ones need future values.
warnings[:] = [w for w in warnings if not w.startswith("Future values of ")]
if FUTURE_COV:
later_counts = []
for key in series_keys:
sel = ~np.isnan(times_all) & ((keys_all.astype(str) == key) if SERIES else True)
y_k, t_k = values_all[sel], times_all[sel]
last_k = np.nanmax(np.where(np.isnan(y_k), np.nan, t_k))
later_counts.append(int(np.sum(t_k > last_k)))
if min(later_counts) < H:
warnings.append(f"Future values of {', '.join(FUTURE_COV)} are known for {min(later_counts)} of {H} steps; the last known values are held for the rest.")
if n_origins and FUTURE_COV:
warnings.append(
f"The backtest gave the model the actual future values of {', '.join(FUTURE_COV)}. 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."
)
if H > c2.TRAINED_HORIZON:
warnings.append(f"Chronos-2 predicts up to {c2.TRAINED_HORIZON} steps at once; steps beyond that are rolled forward from its own forecasts.")
# %% 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": "Chronos-2 zero-shot forecast with covariates",
"engine": cs.engine_info("chronos-forecasting", "torch", "codesplash", "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,
}
)
With a Series column, Related series can be "Forecast each alone" (the default) or "Forecast together". Together, every series with a value at the same time goes into one call and they attend to each other. This is the same idea as a global modelGlobal forecasting modelOne model fitted to many related series together instead of one model per series, so short series borrow patterns., without any training.
It does not always help, and each series' forecast then depends on which others are in the panel. Run both settings in one forecast experiment and compare them on common windows.
Check: Chronos-2
CheckpointCheck yourself
What can Chronos-2 do that Chronos-Bolt can't?
Show the answer
Answer: a
Both are pretrained and zero-shot. Chronos-2 adds covariates and joint forecasts of related series.
Check yourself
Where do the future values of a known-future covariate go?
Show the answer
Answer: a
The forecast driver reads rows after the last observed value as known future values of the covariates.
Check yourself
A backtest with a known-future covariate looks much better than one without. Why might real forecasts not be as good?
Show the answer
Answer: a
Unless the driver is genuinely known ahead (calendar, planned prices), the backtest gave the model information a real forecast won't have.
Check yourself
When is "Forecast together" most likely to help?
Show the answer
Answer: a
Joint forecasts help most when each series has little history of its own. Check it in a backtest.
Concepts in this lesson