Skip to content

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.

Advanced ~12 min8 steps

What runs in CodeSplash

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

Read first

01

What Chronos-2 adds

Read

Chronos-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.

02

On its own

Read
Chronos-2 zero-shot forecast with covariatesRecorded · one engineRecorded 2026-11-25 · 30 values compared
Python

Chronos-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

Forecast of passengersWhere is the series heading, and how uncertain is the forecast?
View data
hi_80hi_95kindlo_80lo_95monthpassengers
——actual——−662,688,000,000112
——actual——−660,009,600,000118
——actual——−657,590,400,000132
——actual——−654,912,000,000129
——actual——−652,320,000,000121
——actual——−649,641,600,000135
——actual——−647,049,600,000148
——actual——−644,371,200,000148
——actual——−641,692,800,000136
——actual——−639,100,800,000119
——actual——−636,422,400,000104
——actual——−633,830,400,000118
——actual——−631,152,000,000115
——actual——−628,473,600,000126
——actual——−626,054,400,000141
——actual——−623,376,000,000135
——actual——−620,784,000,000125
——actual——−618,105,600,000149
——actual——−615,513,600,000170
——actual——−612,835,200,000170
——actual——−610,156,800,000158
——actual——−607,564,800,000133
——actual——−604,886,400,000114
——actual——−602,294,400,000140
——actual——−599,616,000,000145
——actual——−596,937,600,000150
——actual——−594,518,400,000178
——actual——−591,840,000,000163
——actual——−589,248,000,000172
——actual——−586,569,600,000178
——actual——−583,977,600,000199
——actual——−581,299,200,000199
——actual——−578,620,800,000184
——actual——−576,028,800,000162
——actual——−573,350,400,000146
——actual——−570,758,400,000166
——actual——−568,080,000,000171
——actual——−565,401,600,000180
——actual——−562,896,000,000193
——actual——−560,217,600,000181
——actual——−557,625,600,000183
——actual——−554,947,200,000218
——actual——−552,355,200,000230
——actual——−549,676,800,000242
——actual——−546,998,400,000209
——actual——−544,406,400,000191
——actual——−541,728,000,000172
——actual——−539,136,000,000194
——actual——−536,457,600,000196
——actual——−533,779,200,000196
——actual——−531,360,000,000236
——actual——−528,681,600,000235
——actual——−526,089,600,000229
——actual——−523,411,200,000243
——actual——−520,819,200,000264
——actual——−518,140,800,000272
——actual——−515,462,400,000237
——actual——−512,870,400,000211
——actual——−510,192,000,000180
——actual——−507,600,000,000201

First 60 of 156 rows.

Backtest errors by horizonHow does forecast error grow with the horizon, and how stable is it across origins?
View data
errorhorizonorigin
1.85011958-12-01
−0.561921958-12-01
3.66331958-12-01
3.77541958-12-01
19.83651958-12-01
8.95661958-12-01
15.28271958-12-01
30.01481958-12-01
7.99691958-12-01
13.550101958-12-01
22.293111958-12-01
22.450121958-12-01
5.17411959-12-01
−3.60021959-12-01
−36.16431959-12-01
17.22541959-12-01
14.03551959-12-01
−2.12461959-12-01
17.89771959-12-01
−0.298681959-12-01
−8.99491959-12-01
15.023101959-12-01
0.5989111959-12-01
−1.949121959-12-01
Chronos-2 quantiles for passengersWhat range of futures does a probabilistic forecaster expect, step by step?
View data
quantilemonthpassengers
—−378,691,200,000340
—−376,012,800,000318
—−373,593,600,000362
—−370,915,200,000348
—−368,323,200,000363
—−365,644,800,000435
—−363,052,800,000491
—−360,374,400,000505
—−357,696,000,000404
—−355,104,000,000359
—−352,425,600,000310
—−349,833,600,000337
—−347,155,200,000360
—−344,476,800,000342
—−342,057,600,000406
—−339,379,200,000396
—−336,787,200,000420
—−334,108,800,000472
—−331,516,800,000548
—−328,838,400,000559
—−326,160,000,000463
—−323,568,000,000407
—−320,889,600,000362
—−318,297,600,000405
—−315,619,200,000417
—−312,940,800,000391
—−310,435,200,000419
—−307,756,800,000461
—−305,164,800,000472
—−302,486,400,000535
—−299,894,400,000622
—−297,216,000,000606
—−294,537,600,000508
—−291,945,600,000461
—−289,267,200,000390
—−286,675,200,000432
0.0100−283,996,800,000400.18
0.0100−281,318,400,000376.25
0.0100−278,899,200,000448.28
0.0100−276,220,800,000441.76
0.0100−273,628,800,000450.94
0.0100−270,950,400,000503.30
0.0100−268,358,400,000553.82
0.0100−265,680,000,000548.85
0.0100−263,001,600,000475.32
0.0100−260,409,600,000419.85
0.0100−257,731,200,000352.59
0.0100−255,139,200,000400.10
0.0500−283,996,800,000423.38
0.0500−281,318,400,000399.33
0.0500−278,899,200,000474.19
0.0500−276,220,800,000469.45
0.0500−273,628,800,000479.74
0.0500−270,950,400,000536.95
0.0500−268,358,400,000607.85
0.0500−265,680,000,000607.23
0.0500−263,001,600,000514.45
0.0500−260,409,600,000450.21
0.0500−257,731,200,000377.54
0.0500−255,139,200,000430.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)

MetricValue
MAE11.388
RMSE14.951
MAPE0.0252
sMAPE0.0255
MASE0.3875
WAPE0.0252
Coverage of the 80% interval0.9583
Coverage of the 95% interval1

The model's quantiles (the 50% quantile is the forecast)

month1%5%10%20%30%40%50%60%70%80%90%95%99%
1961-01-01400.18423.38432.17442.05447.69451.21455.00459.16463.23469.06476.96484.59503.58
1961-02-01376.25399.33408.76417.78423.40427.20431.38436.17440.23446.70452.26457.48471.80
1961-03-01448.28474.19483.70493.40498.52502.07505.19509.75514.73520.32527.17534.54554.51
1961-04-01441.76469.45478.81488.04494.14498.46503.23506.14510.86516.53525.66535.62557.28
1961-05-01450.94479.74488.36496.52502.95507.99513.08516.72521.72529.13539.54551.83575.89
1961-06-01503.30536.95549.08564.11570.78577.36583.40586.53594.02602.81614.96626.26649.69
1961-07-01553.82607.85624.23637.92647.33653.78662.40667.67677.13687.29702.17715.42743.44
1961-08-01548.85607.23622.85638.06648.93655.28663.36671.87678.67687.66701.98715.35744.59
1961-09-01475.32514.45528.41541.83550.26557.88565.50570.06576.33585.75597.65611.31642.41
1961-10-01419.85450.21461.14471.41477.47482.54486.21492.04496.67505.30519.11531.19561.41
1961-11-01352.59377.54389.13401.61408.08413.22418.71424.03431.15440.01450.18457.89475.87
1961-12-01400.10430.16440.97451.36457.91462.65467.80472.47478.52485.67496.07506.05531.63

Pretrained weights

ItemValue
ModelChronos-2 Small (28M parameters)
Sourcehuggingface.co/autogluon/chronos-2-small
Revisionddec01313e50b6bc58ebaa92ede81bc24a3d9f9a
LicenseApache-2.0
Download size111.8 MB
Related seriesEach forecast alone

Forecast

monthForecast80% low80% high95% low95% high
1961-01-01455.00432.17476.96408.88496.46
1961-02-01431.38408.76452.26384.90466.43
1961-03-01505.19483.70527.17458.00547.02
1961-04-01503.23478.81525.66452.15549.16
1961-05-01513.08488.36539.54461.74566.86
1961-06-01583.40549.08614.96515.92640.90
1961-07-01662.40624.23702.17574.08732.93
1961-08-01663.36622.85701.98570.74733.63
1961-09-01565.50528.41597.65489.99630.75
1961-10-01486.21461.14519.11431.24550.08
1961-11-01418.71389.13450.18361.95469.13
1961-12-01467.80440.97496.07411.37522.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.

03

Two kinds of covariate

Read

A 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.

04

Known-future covariates

Read
Chronos-2 zero-shot forecast with covariatesRecorded · one engineRecorded 2026-11-25 · 30 values compared
Python

Chronos-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

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

First 60 of 204 rows.

Backtest errors by horizonHow does forecast error grow with the horizon, and how stable is it across origins?
View data
errorhorizonorigin
−2.78911983-12-01
3.68221983-12-01
0.756431983-12-01
6.38241983-12-01
5.65051983-12-01
5.97161983-12-01
−6.03971983-12-01
10.71781983-12-01
27.22291983-12-01
9.119101983-12-01
17.244111983-12-01
35.246121983-12-01
Chronos-2 quantiles for driversWhat range of futures does a probabilistic forecaster expect, step by step?
View data
quantilemonthdrivers
—378,691,200,000115
—381,369,600,000104
—383,788,800,000131
—386,467,200,000108
—389,059,200,000103
—391,737,600,000115
—394,329,600,000122
—397,008,000,000122
—399,686,400,000125
—402,278,400,000137
—404,956,800,000138
—407,548,800,000152
—410,227,200,000120
—412,905,600,00095
—415,324,800,000100
—418,003,200,00089
—420,595,200,00082
—423,273,600,00089
—425,865,600,00060
—428,544,000,00084
—431,222,400,000113
—433,814,400,000126
—436,492,800,000122
—439,084,800,000118
—441,763,200,00092
—444,441,600,00086
—446,947,200,00081
—449,625,600,00084
—452,217,600,00087
—454,896,000,00090
—457,488,000,00079
—460,166,400,00096
—462,844,800,000122
—465,436,800,000120
—468,115,200,000137
—470,707,200,000154
0.0100473,385,600,00075.690
0.0100476,064,000,00058.625
0.0100478,483,200,00050.897
0.0100481,161,600,00053.276
0.0100483,753,600,00059.431
0.0100486,432,000,00062.359
0.0100489,024,000,00059.522
0.0100491,702,400,00060.926
0.0100494,380,800,00069.369
0.0100496,972,800,00079.052
0.0100499,651,200,00089.219
0.0100502,243,200,00087.856
0.0500473,385,600,00086.141
0.0500476,064,000,00068.614
0.0500478,483,200,00062.366
0.0500481,161,600,00064.486
0.0500483,753,600,00070.128
0.0500486,432,000,00072.787
0.0500489,024,000,00070.826
0.0500491,702,400,00071.787
0.0500494,380,800,00081.085
0.0500496,972,800,00093.564
0.0500499,651,200,000102.64
0.0500502,243,200,000102.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)

MetricValue
MAE10.902
RMSE14.848
MAPE0.0943
sMAPE0.1010
MASE0.6373
WAPE0.1065
Coverage of the 80% interval0.8333
Coverage of the 95% interval1

The model's quantiles (the 50% quantile is the forecast)

month1%5%10%20%30%40%50%60%70%80%90%95%99%
1985-01-0175.69086.14191.72798.598103.27107.10110.74114.50118.54123.63131.57139.39155.86
1985-02-0158.62568.61473.10778.56182.62285.91489.02692.08195.32599.669106.04112.78126.99
1985-03-0150.89762.36667.77973.86077.83981.09584.17887.42090.72895.022101.26107.84121.46
1985-04-0153.27664.48669.30874.77778.71081.80784.77987.79791.12295.291101.54107.86121.61
1985-05-0159.43170.12874.59779.63983.44486.66189.78793.00396.603100.91107.09113.12125.13
1985-06-0162.35972.78777.35282.83686.50889.87292.92196.08099.517103.98110.30116.32127.94
1985-07-0159.52270.82675.66581.23685.57689.02792.13795.27698.705103.36110.13116.43128.58
1985-08-0160.92671.78776.43682.04286.36690.00893.41196.660100.24104.94111.73118.17130.40
1985-09-0169.36981.08586.31792.44496.947100.83104.43108.07111.95116.91123.90130.77145.39
1985-10-0179.05293.564100.19107.29112.18116.27120.02124.02128.36133.91141.99150.18169.60
1985-11-0189.219102.64109.00116.37121.67126.26130.51135.24140.71147.52156.53165.61190.46
1985-12-0187.856102.29108.83116.70122.29127.08131.56136.10141.05147.42156.70166.58191.35

Covariates the model read

ColumnUsed as
petrolKnown in advance (future values given)
lawKnown in advance (future values given)

Pretrained weights

ItemValue
ModelChronos-2 Small (28M parameters)
Sourcehuggingface.co/autogluon/chronos-2-small
Revisionddec01313e50b6bc58ebaa92ede81bc24a3d9f9a
LicenseApache-2.0
Download size111.8 MB
Related seriesEach forecast alone

Forecast

monthForecast80% low80% high95% low95% high
1985-01-01110.7491.727131.5779.609149.68
1985-02-0189.02673.107106.0462.371121.66
1985-03-0184.17867.779101.2655.198116.35
1985-04-0184.77969.308101.5457.480116.45
1985-05-0189.78774.597107.0963.442120.62
1985-06-0192.92177.352110.3066.269123.58
1985-07-0192.13775.665110.1363.761124.02
1985-08-0193.41176.436111.7364.999125.81
1985-09-01104.4386.317123.9073.763139.91
1985-10-01120.02100.19141.9984.494162.31
1985-11-01130.51109.00156.5394.253181.14
1985-12-01131.56108.83156.7093.268182.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.

05

Past and future together

Read
Chronos-2 zero-shot forecast with covariatesRecorded · one engineRecorded 2026-11-25 · 30 values compared
Python

Chronos-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

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

First 60 of 198 rows.

Backtest errors by horizonHow does forecast error grow with the horizon, and how stable is it across origins?
View data
errorhorizonorigin
1.26111983-12-01
6.25121983-12-01
3.45531983-12-01
9.46841983-12-01
8.84251983-12-01
8.11961983-12-01
−9.00411984-06-01
8.02621984-06-01
27.20531984-06-01
7.53641984-06-01
13.91651984-06-01
32.15261984-06-01
Chronos-2 quantiles for driversWhat range of futures does a probabilistic forecaster expect, step by step?
View data
quantilemonthdrivers
—410,227,200,000120
—412,905,600,00095
—415,324,800,000100
—418,003,200,00089
—420,595,200,00082
—423,273,600,00089
—425,865,600,00060
—428,544,000,00084
—431,222,400,000113
—433,814,400,000126
—436,492,800,000122
—439,084,800,000118
—441,763,200,00092
—444,441,600,00086
—446,947,200,00081
—449,625,600,00084
—452,217,600,00087
—454,896,000,00090
—457,488,000,00079
—460,166,400,00096
—462,844,800,000122
—465,436,800,000120
—468,115,200,000137
—470,707,200,000154
0.0100473,385,600,00078.735
0.0100476,064,000,00061.903
0.0100478,483,200,00052.977
0.0100481,161,600,00053.157
0.0100483,753,600,00060.191
0.0100486,432,000,00063.949
0.0500473,385,600,00088.960
0.0500476,064,000,00071.626
0.0500478,483,200,00064.543
0.0500481,161,600,00064.801
0.0500483,753,600,00071.000
0.0500486,432,000,00074.856
0.1000473,385,600,00094.187
0.1000476,064,000,00075.915
0.1000478,483,200,00069.892
0.1000481,161,600,00069.820
0.1000483,753,600,00075.523
0.1000486,432,000,00079.690
0.2000473,385,600,000100.42
0.2000476,064,000,00081.083
0.2000478,483,200,00075.809
0.2000481,161,600,00075.430
0.2000483,753,600,00080.738
0.2000486,432,000,00085.447
0.3000473,385,600,000104.62
0.3000476,064,000,00084.927
0.3000478,483,200,00079.647
0.3000481,161,600,00079.464
0.3000483,753,600,00084.743
0.3000486,432,000,00089.353
0.4000473,385,600,000107.99
0.4000476,064,000,00088.169
0.4000478,483,200,00082.876
0.4000481,161,600,00082.686
0.4000483,753,600,00088.159
0.4000486,432,000,00092.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)

MetricValue
MAE11.270
RMSE14.307
MAPE0.1023
sMAPE0.1087
MASE0.6645
WAPE0.1101
Coverage of the 80% interval0.7500
Coverage of the 95% interval0.9167

The model's quantiles (the 50% quantile is the forecast)

month1%5%10%20%30%40%50%60%70%80%90%95%99%
1985-01-0178.73588.96094.187100.42104.62107.99111.02114.14117.57121.72127.47132.94145.17
1985-02-0161.90371.62675.91581.08384.92788.16991.22594.26597.505101.67107.37113.07124.69
1985-03-0152.97764.54369.89275.80979.64782.87685.91989.08792.33696.502102.33108.21120.13
1985-04-0153.15764.80169.82075.43079.46482.68685.69588.69091.99496.132102.14108.01121.03
1985-05-0160.19171.00075.52380.73884.74388.15991.42694.73998.384102.73108.76114.56126.14
1985-06-0163.94974.85679.69085.44789.35392.88996.06599.314102.74107.19113.34119.06130.11

Covariates the model read

ColumnUsed as
lawKnown in advance (future values given)
petrolPast only

Pretrained weights

ItemValue
ModelChronos-2 Small (28M parameters)
Sourcehuggingface.co/autogluon/chronos-2-small
Revisionddec01313e50b6bc58ebaa92ede81bc24a3d9f9a
LicenseApache-2.0
Download size111.8 MB
Related seriesEach forecast alone

Forecast

monthForecast80% low80% high95% low95% high
1985-01-01111.0294.187127.4782.569140.58
1985-02-0191.22575.915107.3765.549120.34
1985-03-0185.91969.892102.3357.314115.66
1985-04-0185.69569.820102.1457.523116.15
1985-05-0191.42675.523108.7664.244121.80
1985-06-0196.06579.690113.3468.039125.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.

06

Which kind?

Predict

Predict 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?

Known-futurePast-only
Reveal

Known-future: you know next month's promotions when you forecast, so put them in the rows after the last observed day.

07

Related series together

Read
Chronos-2 zero-shot forecast with covariatesRecorded · one engineRecorded 2026-11-25 · 30 values compared
Python

2 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

Forecast of deathsWhere is the series heading, and how uncertain is the forecast?
View data
kindsexmonthdeaths
actualfemale126,230,400,000901
actualfemale128,908,800,000689
actualfemale131,328,000,000827
actualfemale134,006,400,000677
actualfemale136,598,400,000522
actualfemale139,276,800,000406
actualfemale141,868,800,000441
actualfemale144,547,200,000393
actualfemale147,225,600,000387
actualfemale149,817,600,000582
actualfemale152,496,000,000578
actualfemale155,088,000,000666
actualfemale157,766,400,000830
actualfemale160,444,800,000752
actualfemale162,864,000,000785
actualfemale165,542,400,000664
actualfemale168,134,400,000467
actualfemale170,812,800,000438
actualfemale173,404,800,000421
actualfemale176,083,200,000412
actualfemale178,761,600,000343
actualfemale181,353,600,000440
actualfemale184,032,000,000531
actualfemale186,624,000,000771
actualfemale189,302,400,000767
actualfemale191,980,800,0001,141
actualfemale194,486,400,000896
actualfemale197,164,800,000532
actualfemale199,756,800,000447
actualfemale202,435,200,000420
actualfemale205,027,200,000376
actualfemale207,705,600,000330
actualfemale210,384,000,000357
actualfemale212,976,000,000445
actualfemale215,654,400,000546
actualfemale218,246,400,000764
actualfemale220,924,800,000862
actualfemale223,603,200,000660
actualfemale226,022,400,000663
actualfemale228,700,800,000643
actualfemale231,292,800,000502
actualfemale233,971,200,000392
actualfemale236,563,200,000411
actualfemale239,241,600,000348
actualfemale241,920,000,000387
actualfemale244,512,000,000385
actualfemale247,190,400,000411
actualfemale249,782,400,000638
actualfemale252,460,800,000796
actualfemale255,139,200,000853
actualfemale257,558,400,000737
actualfemale260,236,800,000546
actualfemale262,828,800,000530
actualfemale265,507,200,000446
actualfemale268,099,200,000431
actualfemale270,777,600,000362
actualfemale273,456,000,000387
actualfemale276,048,000,000430
actualfemale278,726,400,000425
actualfemale281,318,400,000679

First 60 of 156 rows.

Backtest errors by horizonHow does forecast error grow with the horizon, and how stable is it across origins?
View data
errorhorizonorigin
15.33111979-06-01
−1.68221979-06-01
17.79131979-06-01
23.23341979-06-01
60.96451979-06-01
−47.02661979-06-01
3.15311979-06-01
−68.06621979-06-01
−102.0431979-06-01
23.57341979-06-01
121.1951979-06-01
−259.5861979-06-01
Chronos-2 quantiles for deaths — femaleWhat range of futures does a probabilistic forecaster expect, step by step?
View data
quantilemonthdeaths
—252,460,800,000796
—255,139,200,000853
—257,558,400,000737
—260,236,800,000546
—262,828,800,000530
—265,507,200,000446
—268,099,200,000431
—270,777,600,000362
—273,456,000,000387
—276,048,000,000430
—278,726,400,000425
—281,318,400,000679
—283,996,800,000821
—286,675,200,000785
—289,094,400,000727
—291,772,800,000612
—294,364,800,000478
—297,043,200,000429
—299,635,200,000405
—302,313,600,000379
—304,992,000,000393
—307,584,000,000411
—310,262,400,000487
—312,854,400,000574
0.0100315,532,800,000612.79
0.0100318,211,200,000637.10
0.0100320,716,800,000565.59
0.0100323,395,200,000442.78
0.0100325,987,200,000357.23
0.0100328,665,600,000342.28
0.0500315,532,800,000678.36
0.0500318,211,200,000718.70
0.0500320,716,800,000623.69
0.0500323,395,200,000488.10
0.0500325,987,200,000397.25
0.0500328,665,600,000372.50
0.1000315,532,800,000704.42
0.1000318,211,200,000750.63
0.1000320,716,800,000650.97
0.1000323,395,200,000508.22
0.1000325,987,200,000413.19
0.1000328,665,600,000381.55
0.2000315,532,800,000732.04
0.2000318,211,200,000782.29
0.2000320,716,800,000681.87
0.2000323,395,200,000532.38
0.2000325,987,200,000429.52
0.2000328,665,600,000391.64
0.3000315,532,800,000750.02
0.3000318,211,200,000803.65
0.3000320,716,800,000704.23
0.3000323,395,200,000550.29
0.3000325,987,200,000441.67
0.3000328,665,600,000400.08
0.4000315,532,800,000765.46
0.4000318,211,200,000822.17
0.4000320,716,800,000721.64
0.4000323,395,200,000564.38
0.4000325,987,200,000452.41
0.4000328,665,600,000409.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)

MetricValue
MAE61.969
RMSE93.408
MAPE0.0701
sMAPE0.0692
MASE0.4644
WAPE0.0797
Coverage of the 90% interval0.9167

The model's quantiles (the 50% quantile is the forecast) — female

month1%5%10%20%30%40%50%60%70%80%90%95%99%
1980-01-01612.79678.36704.42732.04750.02765.46779.90794.66810.66831.95864.73904.751044.86
1980-02-01637.10718.70750.63782.29803.65822.17839.54858.38879.06908.64951.171003.331175.04
1980-03-01565.59623.69650.97681.87704.23721.64737.38753.22769.09790.18824.61864.68995.60
1980-04-01442.78488.10508.22532.38550.29564.38576.19587.44600.16618.85650.71686.39788.54
1980-05-01357.23397.25413.19429.52441.67452.41463.34476.46491.38512.17545.05577.07653.27
1980-06-01342.28372.50381.55391.64400.08409.17418.72430.46443.05460.10486.84515.39590.71

Pretrained weights

ItemValue
ModelChronos-2 Small (28M parameters)
Sourcehuggingface.co/autogluon/chronos-2-small
Revisionddec01313e50b6bc58ebaa92ede81bc24a3d9f9a
LicenseApache-2.0
Download size111.8 MB
Related seriesForecast together (cross-learning)

Forecast

SeriesmonthForecast90% low90% high
female1980-01-01779.90678.36904.75
female1980-02-01839.54718.701003.33
female1980-03-01737.38623.69864.68
female1980-04-01576.19488.10686.39
female1980-05-01463.34397.25577.07
female1980-06-01418.72372.50515.39
male1980-01-011938.001670.652204.94
male1980-02-012049.031772.232374.70
male1980-03-011831.991557.062116.46
male1980-04-011427.001212.381677.02
male1980-05-011112.661001.181345.19
male1980-06-011051.32974.071273.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.

08

Check: Chronos-2

Checkpoint

Check 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