Skip to content

DForecasting · forecast.hierarchical

Hierarchical forecast (reconciliation)

How do I forecast a total and every region, store or product under it so the numbers add up?

Forecasts every series of a hierarchy — the total, each level (e.g. regions) and the bottom series (e.g. stores) — with a base model, then reconciles them so that every level adds up: bottom-up, top-down by historical proportions, or the optimal combinations (OLS, WLS, MinT with shrinkage) that use every level's information. Backtests compare base and reconciled accuracy at each level.

Verified in Python and R Python and R agree to 6 decimals

A real result

Example “Mint ets two levels”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Hierarchical forecast (reconciliation)Recorded · Python and R agreeRecorded 2026-11-25 · 37 values compared
R

ETS(A,A,A) base forecasts reconciled by MinT (shrinkage): 6-step forecasts of sales for 8 series (5 at the bottom, monthly data, 48 periods). Backtest MASE 0.65 reconciled vs 0.649 base.

MAE
5.692
RMSE
8.533
MASE
0.6497

Plots

Reconciled forecasts of salesWhere is the series heading, and how uncertain is the forecast?
View data
hi_80hi_95kindlo_80lo_95seriesmonthsales
——actual——Total1,609,459,200,000371.10
——actual——Total1,612,137,600,000393.20
——actual——Total1,614,556,800,000397.40
——actual——Total1,617,235,200,000407.40
——actual——Total1,619,827,200,000397.50
——actual——Total1,622,505,600,000422.20
——actual——Total1,625,097,600,000383.50
——actual——Total1,627,776,000,000357.30
——actual——Total1,630,454,400,000312.10
——actual——Total1,633,046,400,000300.20
——actual——Total1,635,724,800,000316
——actual——Total1,638,316,800,000349.50
——actual——Total1,640,995,200,000386.30
——actual——Total1,643,673,600,000411.70
——actual——Total1,646,092,800,000419
——actual——Total1,648,771,200,000415.60
——actual——Total1,651,363,200,000432.90
——actual——Total1,654,041,600,000430.70
——actual——Total1,656,633,600,000397
——actual——Total1,659,312,000,000375.50
——actual——Total1,661,990,400,000327.70
——actual——Total1,664,582,400,000324.70
——actual——Total1,667,260,800,000324.50
——actual——Total1,669,852,800,000378.40
——actual——Total1,672,531,200,000409.80
——actual——Total1,675,209,600,000437.60
——actual——Total1,677,628,800,000434.30
——actual——Total1,680,307,200,000432
——actual——Total1,682,899,200,000451.70
——actual——Total1,685,577,600,000456.50
——actual——Total1,688,169,600,000419.90
——actual——Total1,690,848,000,000391.70
——actual——Total1,693,526,400,000340
——actual——Total1,696,118,400,000332.10
——actual——Total1,698,796,800,000351.90
——actual——Total1,701,388,800,000405.20
——actual——Total1,704,067,200,000442.60
——actual——Total1,706,745,600,000452.90
——actual——Total1,709,251,200,000472.10
——actual——Total1,711,929,600,000473.70
——actual——Total1,714,521,600,000481.70
——actual——Total1,717,200,000,000468.30
——actual——Total1,719,792,000,000458.20
——actual——Total1,722,470,400,000412.30
——actual——Total1,725,148,800,000368.40
——actual——Total1,727,740,800,000332.80
——actual——Total1,730,419,200,000351.10
——actual——Total1,733,011,200,000430.60
464.43470.31forecast442.19436.30Total1,735,689,600,000453.31
485.83491.72forecast463.59457.70Total1,738,368,000,000474.71
492.68498.57forecast470.43464.54Total1,740,787,200,000481.56
494.17500.06forecast471.91466.02Total1,743,465,600,000483.04
502.94508.83forecast480.68474.78Total1,746,057,600,000491.81
506.42512.32forecast484.15478.25Total1,748,736,000,000495.28
——actual——region=north1,609,459,200,000214
——actual——region=north1,612,137,600,000225.60
——actual——region=north1,614,556,800,000230.30
——actual——region=north1,617,235,200,000233
——actual——region=north1,619,827,200,000226.50
——actual——region=north1,622,505,600,000244.40

First 60 of 432 rows.

Backtest errors of the total by horizonHow does forecast error grow with the horizon, and how stable is it across origins?
View data
errorhorizonorigin
15.45212023-12-01
0.652322023-12-01
17.11732023-12-01
17.28442023-12-01
16.25152023-12-01
−6.25062023-12-01
15.72812024-06-01
−4.87022024-06-01
−0.538032024-06-01
−28.54142024-06-01
−22.04052024-06-01
10.56362024-06-01

Backtest accuracy by level — base vs reconciled (2 origins, horizon 6)

LevelSeriesMAE (base)MAE (reconciled)MASE (base)MASE (reconciled)
Total112.97912.9400.65200.6500
region27.0117.0120.66120.6612
store53.7113.7150.64380.6450

Reconciled forecast

SeriesmonthBaseReconciled80% low80% high95% low95% high
Total2025-01-01453.51453.31442.19464.43436.30470.31
Total2025-02-01474.92474.71463.59485.83457.70491.72
Total2025-03-01481.76481.56470.43492.68464.54498.57
Total2025-04-01483.24483.04471.91494.17466.02500.06
Total2025-05-01492.01491.81480.68502.94474.78508.83
Total2025-06-01495.49495.28484.15506.42478.25512.32
region=north2025-01-01263.83263.75254.02273.47248.87278.62
region=north2025-02-01275.41275.33265.60285.05260.45290.20
region=north2025-03-01278.81278.73269.00288.45263.86293.59
region=north2025-04-01279.04278.95269.23288.67264.09293.82
region=north2025-05-01285.98285.90276.18295.62271.03300.76
region=north2025-06-01285.81285.72276.01295.44270.86300.59
region=south2025-01-01189.75189.56183.83195.28180.80198.32
region=south2025-02-01199.57199.38193.64205.13190.60208.17
region=south2025-03-01203.02202.83197.07208.60194.01211.65
region=south2025-04-01204.28204.08198.30209.87195.24212.93
region=south2025-05-01206.10205.91200.11211.72197.03214.79
region=south2025-06-01209.75209.56203.74215.38200.65218.47
region=north / store=N12025-01-01169.13169.08162.13176.03158.46179.71
region=north / store=N12025-02-01172.85172.81165.86179.76162.19183.44
region=north / store=N12025-03-01172.68172.64165.69179.58162.01183.26
region=north / store=N12025-04-01173.53173.49166.54180.43162.87184.11
region=north / store=N12025-05-01181.73181.68174.74188.62171.07192.30
region=north / store=N12025-06-01180.60180.56173.62187.50169.95191.17
region=north / store=N22025-01-0194.61994.66488.254101.0784.861104.47
region=north / store=N22025-02-01102.47102.5296.105108.9392.711112.32
region=north / store=N22025-03-01106.05106.0999.678112.5096.284115.90
region=north / store=N22025-04-01105.42105.4799.053111.8895.658115.27
region=north / store=N22025-05-01104.17104.2297.801110.6394.406114.02
region=north / store=N22025-06-01105.12105.1798.752111.5895.356114.98
region=south / store=S12025-01-0182.96383.07979.61786.54077.78588.372
region=south / store=S12025-02-0188.91389.02985.51792.54183.65894.400
region=south / store=S12025-03-0190.23790.35386.79193.91584.90695.800
region=south / store=S12025-04-0193.91294.02990.41897.64088.50799.551
region=south / store=S12025-05-0193.53793.65489.99597.31388.05899.250
region=south / store=S12025-06-0195.13795.25591.54998.96189.587100.92
region=south / store=S22025-01-0145.27945.35041.97648.72440.19050.510
region=south / store=S22025-02-0144.55644.62641.25348.00039.46749.786
region=south / store=S22025-03-0145.78045.85042.47749.22440.69151.010
region=south / store=S22025-04-0143.73043.80140.42747.17438.64248.960

First 40 of 48 rows.

  • Missing periods of a series count as zero (no row = no sales). Reconciled intervals combine the base forecasts' standard errors with the shrunk correlation of the in-sample residuals.
Python

ETS(A,A,A) base forecasts reconciled by MinT (shrinkage): 6-step forecasts of sales for 8 series (5 at the bottom, monthly data, 48 periods). Backtest MASE 0.65 reconciled vs 0.649 base.

MAE
5.692
RMSE
8.533
MASE
0.6497

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

Backtest accuracy by level — base vs reconciled (2 origins, horizon 6)

LevelSeriesMAE (base)MAE (reconciled)MASE (base)MASE (reconciled)
Total112.97912.9400.65200.6500
region27.0117.0120.66120.6612
store53.7113.7150.64380.6450

Reconciled forecast

SeriesmonthBaseReconciled80% low80% high95% low95% high
Total2025-01-01453.51453.31442.19464.43436.30470.31
Total2025-02-01474.92474.71463.59485.83457.70491.72
Total2025-03-01481.76481.56470.43492.68464.54498.57
Total2025-04-01483.24483.04471.91494.17466.02500.06
Total2025-05-01492.01491.81480.68502.94474.78508.83
Total2025-06-01495.49495.28484.15506.42478.25512.32
region=north2025-01-01263.83263.75254.02273.47248.87278.62
region=north2025-02-01275.41275.33265.60285.05260.45290.20
region=north2025-03-01278.81278.73269.00288.45263.86293.59
region=north2025-04-01279.04278.95269.23288.67264.09293.82
region=north2025-05-01285.98285.90276.18295.62271.03300.76
region=north2025-06-01285.81285.72276.01295.44270.86300.59
region=south2025-01-01189.75189.56183.83195.28180.80198.32
region=south2025-02-01199.57199.38193.64205.13190.60208.17
region=south2025-03-01203.02202.83197.07208.60194.01211.65
region=south2025-04-01204.28204.08198.30209.87195.24212.93
region=south2025-05-01206.10205.91200.11211.72197.03214.79
region=south2025-06-01209.75209.56203.74215.38200.65218.47
region=north / store=N12025-01-01169.13169.08162.13176.03158.46179.71
region=north / store=N12025-02-01172.85172.81165.86179.76162.19183.44
region=north / store=N12025-03-01172.68172.64165.69179.58162.01183.26
region=north / store=N12025-04-01173.53173.49166.54180.43162.87184.11
region=north / store=N12025-05-01181.73181.68174.74188.62171.07192.30
region=north / store=N12025-06-01180.60180.56173.62187.50169.95191.17
region=north / store=N22025-01-0194.61994.66488.254101.0784.861104.47
region=north / store=N22025-02-01102.47102.5296.105108.9392.711112.32
region=north / store=N22025-03-01106.05106.0999.678112.5096.284115.90
region=north / store=N22025-04-01105.42105.4799.053111.8895.658115.27
region=north / store=N22025-05-01104.17104.2297.801110.6394.406114.02
region=north / store=N22025-06-01105.12105.1798.752111.5895.356114.98
region=south / store=S12025-01-0182.96383.07979.61786.54077.78588.372
region=south / store=S12025-02-0188.91389.02985.51792.54183.65894.400
region=south / store=S12025-03-0190.23790.35386.79193.91584.90695.800
region=south / store=S12025-04-0193.91294.02990.41897.64088.50799.551
region=south / store=S12025-05-0193.53793.65489.99597.31388.05899.250
region=south / store=S12025-06-0195.13795.25591.54998.96189.587100.92
region=south / store=S22025-01-0145.27945.35041.97648.72440.19050.510
region=south / store=S22025-02-0144.55644.62641.25348.00039.46749.786
region=south / store=S22025-03-0145.78045.85042.47749.22440.69151.010
region=south / store=S22025-04-0143.73043.80140.42747.17438.64248.960

First 40 of 48 rows.

  • Missing periods of a series count as zero (no row = no sales). Reconciled intervals combine the base forecasts' standard errors with the shrunk correlation of the in-sample residuals.

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

Worked examples in the app

  • Mint ets two levelsl3_stores · hierarchy: region, store · time: month · value: sales
  • Bottom up snaivel3_stores · hierarchy: region, store · time: month · value: sales
  • Top down drift one levell3_stores · hierarchy: store · time: month · value: sales
  • Wls and olsl3_stores · hierarchy: region, store · time: month · value: sales
  • Wls var meanl3_stores · hierarchy: region, store · time: month · value: sales

In the guides

Where it sits in the decision guides

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

What you need

Timetemporal / numeric · 1 column
Dates or evenly spaced numbers.
Valuenumeric · 1 column
The quantity at the bottom level (rows are summed up the hierarchy).
Hierarchy levelscategorical · 1–3 columns
Top level first, e.g. region then store. Each bottom series is one combination of these columns.

Choices you make

model

Reconciliationdefault mint_shrink

MinT (shrinkage) usually forecasts best at every level; bottom-up ignores the upper levels' own forecasts; top-down splits the total by historical shares.

  • MinT with shrinkage (Wickramasuriya et al.)(default) — Reconciles using shrunken residual covariances; the usual choice with enough history.
  • WLS with structural weights — Weights by how many bottom series feed each node; pick it when residuals are short or missing.
  • WLS with residual variances — Weights by each series' residual variance; pick it when accuracy differs a lot between series.
  • OLS — Treats all series alike; a plain choice when they share one scale.
  • Bottom-up — Forecasts the lowest level and adds up; keeps the detail, but low levels can be noisy.
  • Top-down (average historical proportions) — Forecasts the top and splits by historical shares; pick it for noisy bottom series, though local patterns are lost.
Base forecastsdefault ets

Model fitted to every series before reconciliation; ETS forms are chosen per series by AICc (additive errors).

  • ETS (automatic)(default) — Forecasts each series with automatic ETS before reconciling; a strong general choice.
  • Seasonal naive — Repeats each series' value from the same season last cycle; a quick baseline for strongly seasonal data.
  • Naive — Repeats each series' last value; a baseline for series that wander without a pattern.
  • Random walk with drift — Extends the line from each series' first to last value; a baseline for series with a steady trend.
  • Mean — Forecasts each series' historical average; a baseline for series that hover around a level.

options

Horizondefault 12

Steps ahead to forecast.

Interval levels (%)default 80,95

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

Season lengthdefault —

Length of the seasonal cycle in periods. Leave empty to detect it from the dates.

validation

Backtest originsdefault 3

Refit every base model and reconcile at each origin (0 = no backtest). The model forms are chosen once on the whole history.

Origin spacingdefault —

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

What it reports

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

Per group, level or term: bt[<metric>], bt_base[<metric>], bt_level[mase][<level>], lambda

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-7). Python uses numpy; R uses forecast.

Default traps between the two languages

  • Reconciliation (summing matrix, shrinkage covariance as hts::shrink.estim, G matrices, reconciled variances) is a twin in both engines (codesplash.ml.forecast_adv ↔ codesplashr::cs_fc_reconcile); hts and fabletools::reconcile are the classic R equivalents. Base ETS forecasts use the F1 ETS twins and base naive/drift/mean forecasts use forecast::naive/snaive/rwf/meanf in R and the same closed forms in Python, so base forecasts agree to the ETS twin's optimizer tolerance.
  • coherence (the largest gap between a node's reconciled forecast and the sum of its bottom series) is floating-point noise near 1e-13 in both engines; its exact value is not compared (absolute tolerance only).
  • Reconciled intervals are mean ± z · sd with sd² = diag(S G Σ_h Gᵀ Sᵀ), Σ_h from the base standard errors and the shrunk residual correlation — an approximation for multiplicative or simulated base intervals; additive ETS is used for the base models.
Python

The exact script CodeSplash ran for example “Mint ets two levels” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Hierarchical forecast (reconciliation)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.hierarchical 1.0.1 · spec 4f5f4c8bf5f828be
# Dataset: l3_stores (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.ml import forecast_adv as fca

# %% Data
# Hierarchical forecasting (Phase 9, stream L3): base forecasts for every node of the hierarchy
# (total → each level → bottom series), then reconciliation so the forecasts add up. Twins:
# codesplash.ml.forecast_adv ↔ codesplashr::cs_fc_reconcile (hts / fabletools::reconcile are the
# classic equivalents).
TIME = "month"
VALUE = "sales"
LEVEL_COLS = ["region", "store"]  # top level first
H = 6
LEVELS = [float(v) for v in [80, 95]]
SEASON = None
WINDOWS = 2
STEP = None
BASE = "ets"
METHOD = "mint_shrink"
SEED = 42
df = pd.read_parquet("tests/parity/fixtures/l3_stores.parquet", columns=list(dict.fromkeys([TIME, VALUE] + LEVEL_COLS)))
warnings = []
notes = []
times_all, TEMPORAL = fc.to_days(df[TIME])
values_all = pd.to_numeric(df[VALUE], errors="coerce").to_numpy(dtype=np.float64)
keys_df = df[LEVEL_COLS].astype("object")
ok = ~np.isnan(times_all) & keys_df.notna().all(axis=1).to_numpy()
if (~ok).sum():
    warnings.append(f"{int((~ok).sum())} rows without a time or a hierarchy value were left out.")
missing_values = int(np.isnan(values_all[ok]).sum())
if missing_values:
    warnings.append(f"{missing_values} missing values were counted as zero.")
times = times_all[ok]
vals = np.nan_to_num(values_all[ok], nan=0.0)
keys = [tuple(str(v) for v in row) for row in keys_df.to_numpy()[ok]]
out = csml.out_dir("target/academy-parity/run-8142/forecast.hierarchical/mint_ets_two_levels/out-python")

# %% The hierarchy on one time grid (a missing period of a series counts as zero)
tu = np.unique(times)
freq = fc.detect_frequency(tu, TEMPORAL)
pos_u = fc.grid_position(tu, freq)
if np.any(np.abs(pos_u - np.round(pos_u)) > 1e-6):
    raise ValueError("The time steps are irregular — forecasting needs evenly spaced times")
n = int(round(pos_u[-1])) + 1
grid_t = np.concatenate([[tu[0]], fc.future_times(tu[0], freq, n - 1)]) if n > 1 else np.array([tu[0]])
pos_of = {float(t): int(round(p)) for t, p in zip(tu, pos_u)}
labels, depths, S = fca.hierarchy_nodes(keys, LEVEL_COLS)
bottom = sorted(set(keys))
col_of = {b: j for j, b in enumerate(bottom)}
Yb = np.zeros((n, len(bottom)))
for t, k, v in zip(times, keys, vals):
    Yb[pos_of[float(t)], col_of[k]] += v
Y = Yb @ S.T  # n × nodes
n_nodes = len(labels)
m = int(SEASON) if SEASON else int(freq["season"])
ref = 95.0 if 95.0 in LEVELS else (max(LEVELS) if LEVELS else 95.0)
z_ref = fc.z_value(ref)


def min_train(m):
    return 2 * m + 2 if (BASE == "ets" and m > 1) else (m + 2 if BASE == "snaive" and m > 1 else 6)


if n < min_train(m) + 1:
    raise ValueError(f"The series have {n} periods — too few to forecast (needs more than {min_train(m)})")


# %% Base models: the model form is chosen once per node on its whole history
def choose(y):
    if BASE != "ets":
        return None
    cands = fc.ets_candidates(list(y), m, allow_multiplicative=False)
    if len(cands) == 1:
        return cands[0]
    best, _ = fc.ets_auto(list(y), m, cands)
    return (best["error"], best["trend"], best["damped"], best["season"])


def base_forecast(y, spec, h):
    """Mean, standard error and one-step fitted values of one node's base forecast."""
    y = [float(v) for v in y]
    if BASE == "ets":
        fit = fc.ets_fit(y, m, *spec)
        f = fc.ets_forecast(fit, h, [ref], seed=SEED)
        fitted = fit["fitted"]
        label = fit["label"]
    else:
        f = fc.baseline(y, BASE, m, h, [ref])
        fitted = f["fitted"]
        label = {"naive": "Naive", "snaive": "Seasonal naive", "drift": "Drift", "mean": "Mean"}[BASE]
    mean = np.array(f["mean"], dtype=float)
    sd = (np.array(f["upper"][ref]) - np.array(f["lower"][ref])) / (2.0 * z_ref)
    return mean, sd, np.array([float("nan") if v is None else float(v) for v in fitted]), label


specs = [choose(Y[:, i]) for i in range(n_nodes)]


def forecast_all(o, h):
    """Base and reconciled forecasts from the first `o` periods."""
    bm = np.empty((n_nodes, h))
    bs = np.empty((n_nodes, h))
    res = np.empty((o, n_nodes))
    names = []
    for i in range(n_nodes):
        mean, sd, fitted, label = base_forecast(Y[:o, i], specs[i], h)
        bm[i], bs[i] = mean, sd
        res[:, i] = Y[:o, i] - fitted
        names.append(label)
    rec = fca.reconcile(S, METHOD, bm, bs, res, Yb[:o])
    return bm, bs, rec, names


def lv(level):
    return str(int(level)) if float(level).is_integer() else str(level).replace(".", "_")


# %% Backtests
step = int(STEP) if STEP else H
bt_rows, bt_base = [], []
n_origins = 0
for o in fc.backtest_origins(n, H, WINDOWS, step, min_train(m)):
    try:
        bm, bs, rec, _ = forecast_all(o, H)
    except Exception as e:  # a failed origin is skipped, not fatal
        warnings.append(f"Backtest from {fc.format_time(grid_t[o - 1], TEMPORAL)} failed: {e}")
        continue
    n_origins += 1
    lag = m if (m > 1 and o > m) else 1  # the seasonal naive forecast from this origin (MASE's lag rule)
    for i in range(n_nodes):
        scale = fc.mase_scale(list(Y[:o, i]), m)
        scale2 = fc.rmsse_scale(list(Y[:o, i]), m)
        for k in range(H):
            # The columns the host's backtest reader expects (cs-data forecastio.rs), like the shared driver's.
            common = {
                "series": labels[i],
                "level": depths[i],
                "origin": fc.format_time(grid_t[o - 1], TEMPORAL),
                "time": fc.format_time(grid_t[o + k], TEMPORAL),
                "h": k + 1,
                "actual": float(Y[o + k, i]),
                "scale": scale,
                "scale2": scale2,
                "last": float(Y[o - 1, i]),
                "snaive": float(Y[o - lag + k % lag, i]),
            }
            row = {**common, "mean": float(rec["mean"][i, k])}
            brow = {**common, "mean": float(bm[i, k])}
            for level in LEVELS:
                zq = fc.z_value(level)
                row[f"lo_{lv(level)}"] = row["mean"] - zq * float(rec["sd"][i, k])
                row[f"hi_{lv(level)}"] = row["mean"] + zq * float(rec["sd"][i, k])
                brow[f"lo_{lv(level)}"] = brow["mean"] - zq * float(bs[i, k])
                brow[f"hi_{lv(level)}"] = brow["mean"] + zq * float(bs[i, k])
            bt_rows.append(row)
            bt_base.append(brow)

# %% Final forecasts
bm, bs, rec, base_labels = forecast_all(n, H)
future = fc.future_times(grid_t[-1], freq, H)
fc_rows = []
for i in range(n_nodes):
    for j in range(n):
        fc_rows.append({"series": labels[i], "level": depths[i], "time": fc.format_time(grid_t[j], TEMPORAL), "t": float(grid_t[j]), "kind": "actual", "mean": float(Y[j, i])})
    for k in range(H):
        row = {"series": labels[i], "level": depths[i], "time": fc.format_time(future[k], TEMPORAL), "t": float(future[k]), "kind": "forecast", "mean": float(rec["mean"][i, k]), "base": float(bm[i, k])}
        for level in LEVELS:
            zq = fc.z_value(level)
            row[f"lo_{lv(level)}"] = row["mean"] - zq * float(rec["sd"][i, k])
            row[f"hi_{lv(level)}"] = row["mean"] + zq * float(rec["sd"][i, k])
        fc_rows.append(row)
coherence = float(np.max(np.abs(S @ rec["mean"][n_nodes - len(bottom) :] - rec["mean"])))

# %% Accuracy (reconciled vs base, overall and by level)
accuracy = fc.accuracy(bt_rows, LEVELS)
base_acc = fc.accuracy(bt_base, LEVELS)
level_names = ["Total"] + LEVEL_COLS
forecasts = [r for r in fc_rows if r["kind"] == "forecast"]
weights = [i + 1.0 for i in range(len(forecasts))]


def wsum(xs):
    return fc._sum([weights[i] * xs[i] for i in range(len(xs))]) / fc._sum(weights)


METHOD_LABEL = {
    "bottom_up": "bottom-up",
    "top_down": "top-down (average historical proportions)",
    "ols": "OLS",
    "wls_struct": "WLS (structural weights)",
    "wls_var": "WLS (residual variances)",
    "mint_shrink": "MinT (shrinkage)",
}[METHOD]
values = {
    "n_series": len(bottom),
    "n_nodes": n_nodes,
    "n_levels": len(LEVEL_COLS) + 1,
    "n_obs": n,
    "horizon": H,
    "season": m,
    "n_origins": n_origins,
    "fc_check": wsum([r["mean"] for r in forecasts]),
    "coherence": coherence,
    "model_label": f"{base_labels[0]} base forecasts reconciled by {METHOD_LABEL}",
    "method_label": METHOD_LABEL,
    "freq_label": freq["label"],
    "frequency": fc.ALIASES.get(freq["unit"], ""),
}
if rec["lambda"] == rec["lambda"] and METHOD in ("mint_shrink", "wls_var"):
    values["lambda"] = rec["lambda"]
for k, v in accuracy.items():
    values[f"bt[{k}]"] = v
for k, v in base_acc.items():
    values[f"bt_base[{k}]"] = v
by_level = []
for d, name in enumerate(level_names):
    rr = [r for r in bt_rows if r["level"] == d]
    bb = [r for r in bt_base if r["level"] == d]
    a, b = fc.accuracy(rr, []), fc.accuracy(bb, [])
    by_level.append({"level": name, "nodes": int(sum(1 for x in depths if x == d)), "mae_base": b.get("mae"), "mae": a.get("mae"), "mase_base": b.get("mase"), "mase": a.get("mase")})
    if a.get("mase") is not None:
        values[f"bt_level[mase][{name}]"] = a["mase"]

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 = labels[: min(n_nodes, 8)]
fan = [r for r in fc_rows if r["series"] in shown]
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"]),
    "series": cs.col("series", [r["series"] for r in fan], kind="categorical", levels=shown),
}
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")
charts.append(cs.chart("forecast", "forecast-fan", f"Reconciled forecasts of {VALUE}", roles))
if bt_rows:
    errs = [r for r in bt_rows if r["level"] == 0]
    charts.append(
        cs.chart(
            "backtest",
            "backtest-errors",
            "Backtest errors of the total by horizon",
            {
                "h": cs.col("horizon", [r["h"] for r in errs], kind="numeric"),
                "error": cs.col("error", [r["actual"] - r["mean"] for r in errs], kind="numeric"),
                "origin": cs.col("origin", [r["origin"] for r in errs], kind="categorical"),
            },
        )
    )

# %% Result
tables = []
if bt_rows:
    tables.append(
        {
            "key": "levels",
            "title": f"Backtest accuracy by level — base vs reconciled ({n_origins} origin{'s' if n_origins != 1 else ''}, horizon {H})",
            "columns": [
                {"key": "level", "label": "Level"},
                {"key": "nodes", "label": "Series", "type": "number"},
                {"key": "mae_base", "label": "MAE (base)", "type": "number"},
                {"key": "mae", "label": "MAE (reconciled)", "type": "number"},
                {"key": "mase_base", "label": "MASE (base)", "type": "number"},
                {"key": "mase", "label": "MASE (reconciled)", "type": "number"},
            ],
            "rows": by_level,
        }
    )
tables.append(
    {
        "key": "forecast",
        "title": "Reconciled forecast",
        "columns": [{"key": "series", "label": "Series"}, {"key": "time", "label": TIME}, {"key": "base", "label": "Base", "type": "number"}, {"key": "mean", "label": "Reconciled", "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", "level")} for r in forecasts[:300]],
    }
)
notes.append("Missing periods of a series count as zero (no row = no sales). Reconciled intervals combine the base forecasts' standard errors with the shrunk correlation of the in-sample residuals.")
summary = f"{values['model_label']}: {H}-step forecasts of {VALUE} for {n_nodes} series ({len(bottom)} at the bottom, {freq['label']} data, {n} periods)."
if "mase" in accuracy and "mase" in base_acc:
    summary += f" Backtest MASE {accuracy['mase']:.3g} reconciled vs {base_acc['mase']:.3g} base."
cs.publish(
    {
        "title": "Hierarchical forecast (reconciliation)",
        "engine": cs.engine_info("numpy", "pandas"),
        "n": int(len(times)),
        "summary": summary,
        "statistics": [{"key": k, "label": k.upper(), "value": accuracy[k]} for k in ("mae", "rmse", "mase") if k in accuracy],
        "tables": tables,
        "values": values,
        "warnings": warnings,
        "notes": notes,
        "charts": charts,
        "artifacts": artifacts,
    }
)
R

The exact script CodeSplash ran for example “Mint ets two levels” · R version 4.5.1 (2025-06-13)

# Hierarchical forecast (reconciliation)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.hierarchical 1.0.1 · spec 4f5f4c8bf5f828be
# Dataset: l3_stores (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)
suppressPackageStartupMessages(library(forecast))

# %% Data
# Hierarchical forecasting (Phase 9, stream L3): base forecasts for every node of the hierarchy
# (total → each level → bottom series), then reconciliation so the forecasts add up. Twins:
# codesplashr::cs_fc_reconcile ↔ codesplash.ml.forecast_adv (hts / fabletools::reconcile are the
# classic equivalents).
TIME <- "month"
VALUE <- "sales"
LEVEL_COLS <- c("region", "store")  # top level first
H <- 6
LEVELS <- as.numeric(c(80, 95))
SEASON <- NULL
WINDOWS <- 2
STEP <- NULL
BASE <- "ets"
METHOD <- "mint_shrink"
SEED <- 42
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/l3_stores.parquet", col_select = unique(c(TIME, VALUE, LEVEL_COLS))))
warnings <- list()
notes <- list()
td <- cs_ml_fc_to_days(df[[TIME]])
times_all <- td$values
TEMPORAL <- td$temporal
values_all <- suppressWarnings(as.numeric(df[[VALUE]]))
keys_df <- as.data.frame(lapply(df[LEVEL_COLS], as.character), stringsAsFactors = FALSE)
ok <- !is.na(times_all) & stats::complete.cases(keys_df)
if (sum(!ok)) warnings <- c(warnings, sprintf("%d rows without a time or a hierarchy value were left out.", sum(!ok)))
missing_values <- sum(is.na(values_all[ok]))
if (missing_values) warnings <- c(warnings, sprintf("%d missing values were counted as zero.", missing_values))
times <- times_all[ok]
vals <- values_all[ok]
vals[is.na(vals)] <- 0
keys <- as.matrix(keys_df[ok, , drop = FALSE])
out <- cs_ml_out_dir("target/academy-parity/run-8142/forecast.hierarchical/mint_ets_two_levels/out-r")

# %% The hierarchy on one time grid (a missing period of a series counts as zero)
tu <- sort(unique(times))
freq <- cs_ml_fc_detect_frequency(tu, TEMPORAL)
pos_u <- cs_fc_grid_position(tu, freq)
if (any(abs(pos_u - round(pos_u)) > 1e-6)) stop("The time steps are irregular — forecasting needs evenly spaced times")
n <- as.integer(round(pos_u[length(pos_u)])) + 1L
grid_t <- if (n > 1) c(tu[1], cs_ml_fc_future_times(tu[1], freq, n - 1)) else tu[1]
pos <- as.integer(round(pos_u[match(times, tu)])) + 1L
hn <- cs_fc_hierarchy_nodes(keys, LEVEL_COLS)
labels <- hn$labels
depths <- hn$depth
S <- hn$S
bottom <- hn$bottom
bkey <- function(mat) apply(mat, 1, function(r) paste(r, collapse = "\x1f"))
col_of <- match(bkey(keys), bkey(bottom))
Yb <- matrix(0, n, nrow(bottom))
for (i in seq_along(vals)) Yb[pos[i], col_of[i]] <- Yb[pos[i], col_of[i]] + vals[i]
Y <- Yb %*% t(S)  # n x nodes
n_nodes <- length(labels)
m <- if (!is.null(SEASON)) as.integer(SEASON) else as.integer(freq$season)
ref <- if (95 %in% LEVELS) 95 else if (length(LEVELS)) max(LEVELS) else 95
z_ref <- cs_ml_fc_z(ref)
min_train <- function(m) if (BASE == "ets" && m > 1) 2 * m + 2 else if (BASE == "snaive" && m > 1) m + 2 else 6
if (n < min_train(m) + 1) stop(sprintf("The series have %d periods — too few to forecast (needs more than %d)", n, min_train(m)))

# %% Base models: the model form is chosen once per node on its whole history
choose <- function(y) {
  if (BASE != "ets") return(NULL)
  cands <- cs_ml_fc_ets_candidates(as.numeric(y), m, allow_multiplicative = FALSE)
  if (length(cands) == 1) return(cands[[1]])
  best <- cs_ml_fc_ets_auto(as.numeric(y), m, cands)$fit
  list(error = best$error, trend = best$trend, damped = best$damped, season = best$season)
}
base_forecast <- function(y, spec, h) {
  y <- as.numeric(y)
  if (BASE == "ets") {
    fit <- cs_ml_fc_ets_fit(y, m, spec$error, spec$trend, spec$damped, spec$season)
    f <- cs_ml_fc_ets_forecast(fit, h, ref, seed = SEED)
    fitted <- fit$fitted
    label <- fit$label
    lo <- f$lower[[as.character(ref)]]; hi <- f$upper[[as.character(ref)]]; mean_ <- f$mean
  } else {
    yt <- stats::ts(y, frequency = max(m, 1))
    f <- switch(BASE,
      naive = forecast::naive(yt, h = h, level = ref),
      snaive = forecast::snaive(yt, h = h, level = ref),
      drift = forecast::rwf(yt, h = h, drift = TRUE, level = ref),
      mean = forecast::meanf(yt, h = h, level = ref)
    )
    fitted <- as.numeric(f$fitted)
    label <- c(naive = "Naive", snaive = "Seasonal naive", drift = "Drift", mean = "Mean")[[BASE]]
    lo <- as.numeric(f$lower[, 1]); hi <- as.numeric(f$upper[, 1]); mean_ <- as.numeric(f$mean)
  }
  list(mean = as.numeric(mean_), sd = (hi - lo) / (2 * z_ref), fitted = as.numeric(fitted), label = label)
}
specs <- lapply(seq_len(n_nodes), function(i) choose(Y[, i]))
forecast_all <- function(o, h) {
  bm <- matrix(0, n_nodes, h); bs <- matrix(0, n_nodes, h); res <- matrix(0, o, n_nodes); names_ <- character(n_nodes)
  for (i in seq_len(n_nodes)) {
    b <- base_forecast(Y[seq_len(o), i], specs[[i]], h)
    bm[i, ] <- b$mean; bs[i, ] <- b$sd
    res[, i] <- Y[seq_len(o), i] - b$fitted
    names_[i] <- b$label
  }
  rec <- cs_fc_reconcile(S, METHOD, bm, bs, res, Yb[seq_len(o), , drop = FALSE])
  list(bm = bm, bs = bs, rec = rec, names = names_)
}
lv <- function(level) if (level == floor(level)) as.character(as.integer(level)) else gsub(".", "_", as.character(level), fixed = TRUE)

# %% Backtests
step <- if (!is.null(STEP)) as.integer(STEP) else H
bt_rows <- list(); bt_base <- list()
n_origins <- 0
for (o in cs_ml_fc_backtest_origins(n, H, WINDOWS, step, min_train(m))) {
  fa <- tryCatch(forecast_all(o, H), error = function(e) e)
  if (inherits(fa, "error")) {
    warnings <- c(warnings, sprintf("Backtest from %s failed: %s", cs_ml_fc_format_time(grid_t[o], TEMPORAL), conditionMessage(fa)))
    next
  }
  n_origins <- n_origins + 1
  lag <- if (m > 1 && o > m) m else 1  # the seasonal naive forecast from this origin (MASE's lag rule)
  for (i in seq_len(n_nodes)) {
    scale <- cs_ml_fc_mase_scale(Y[seq_len(o), i], m)
    scale2 <- cs_ml_fc_rmsse_scale(Y[seq_len(o), i], m)
    for (k in seq_len(H)) {
      # The columns the host's backtest reader expects (cs-data forecastio.rs), like the shared driver's.
      common <- list(series = labels[i], level = depths[i], origin = cs_ml_fc_format_time(grid_t[o], TEMPORAL),
                     time = cs_ml_fc_format_time(grid_t[o + k], TEMPORAL), h = k, actual = Y[o + k, i], scale = scale,
                     scale2 = scale2, last = Y[o, i], snaive = Y[o - lag + (k - 1) %% lag + 1, i])
      row <- c(common, list(mean = fa$rec$mean[i, k]))
      brow <- c(common, list(mean = fa$bm[i, k]))
      for (level in LEVELS) {
        zq <- cs_ml_fc_z(level)
        row[[paste0("lo_", lv(level))]] <- row$mean - zq * fa$rec$sd[i, k]
        row[[paste0("hi_", lv(level))]] <- row$mean + zq * fa$rec$sd[i, k]
        brow[[paste0("lo_", lv(level))]] <- brow$mean - zq * fa$bs[i, k]
        brow[[paste0("hi_", lv(level))]] <- brow$mean + zq * fa$bs[i, k]
      }
      bt_rows[[length(bt_rows) + 1]] <- row
      bt_base[[length(bt_base) + 1]] <- brow
    }
  }
}

# %% Final forecasts
fa <- forecast_all(n, H)
future <- cs_ml_fc_future_times(grid_t[n], freq, H)
fc_rows <- list()
for (i in seq_len(n_nodes)) {
  for (j in seq_len(n)) {
    fc_rows[[length(fc_rows) + 1]] <- list(series = labels[i], level = depths[i], time = cs_ml_fc_format_time(grid_t[j], TEMPORAL),
                                           t = grid_t[j], kind = "actual", mean = Y[j, i])
  }
  for (k in seq_len(H)) {
    row <- list(series = labels[i], level = depths[i], time = cs_ml_fc_format_time(future[k], TEMPORAL), t = future[k],
                kind = "forecast", mean = fa$rec$mean[i, k], base = fa$bm[i, k])
    for (level in LEVELS) {
      zq <- cs_ml_fc_z(level)
      row[[paste0("lo_", lv(level))]] <- row$mean - zq * fa$rec$sd[i, k]
      row[[paste0("hi_", lv(level))]] <- row$mean + zq * fa$rec$sd[i, k]
    }
    fc_rows[[length(fc_rows) + 1]] <- row
  }
}
nb <- nrow(bottom)
coherence <- max(abs(S %*% fa$rec$mean[(n_nodes - nb + 1):n_nodes, , drop = FALSE] - fa$rec$mean))

as_frame <- function(rows) {
  cols <- unique(unlist(lapply(rows, names)))
  as.data.frame(stats::setNames(lapply(cols, function(cn) unlist(lapply(rows, function(r) if (is.null(r[[cn]])) NA else r[[cn]]))), cols),
                stringsAsFactors = FALSE, check.names = FALSE)
}

# %% Accuracy (reconciled vs base, overall and by level)
bt <- if (length(bt_rows)) as_frame(bt_rows) else data.frame()
btb <- if (length(bt_base)) as_frame(bt_base) else data.frame()
accuracy <- if (nrow(bt)) cs_ml_fc_accuracy(bt, LEVELS) else list()
base_acc <- if (nrow(btb)) cs_ml_fc_accuracy(btb, LEVELS) else list()
level_names <- c("Total", LEVEL_COLS)
fc_df <- as_frame(fc_rows)
forecasts <- fc_df[fc_df$kind == "forecast", , drop = FALSE]
weights <- seq_len(nrow(forecasts))
wsum <- function(xs) sum(weights * xs) / sum(weights)
METHOD_LABEL <- c(bottom_up = "bottom-up", top_down = "top-down (average historical proportions)", ols = "OLS",
                  wls_struct = "WLS (structural weights)", wls_var = "WLS (residual variances)", mint_shrink = "MinT (shrinkage)")[[METHOD]]
values <- list(
  n_series = nb, n_nodes = n_nodes, n_levels = length(LEVEL_COLS) + 1, n_obs = n, horizon = H, season = m,
  n_origins = n_origins, fc_check = wsum(forecasts$mean), coherence = coherence,
  model_label = sprintf("%s base forecasts reconciled by %s", fa$names[1], METHOD_LABEL), method_label = METHOD_LABEL,
  freq_label = freq$label, frequency = cs_ml_fc_alias(freq$unit)
)
if (!is.nan(fa$rec$lambda) && METHOD %in% c("mint_shrink", "wls_var")) values$lambda <- fa$rec$lambda
for (k in names(accuracy)) values[[sprintf("bt[%s]", k)]] <- accuracy[[k]]
for (k in names(base_acc)) values[[sprintf("bt_base[%s]", k)]] <- base_acc[[k]]
by_level <- list()
for (d in seq_along(level_names) - 1L) {
  a <- if (nrow(bt)) cs_ml_fc_accuracy(bt[bt$level == d, , drop = FALSE], numeric(0)) else list()
  b <- if (nrow(btb)) cs_ml_fc_accuracy(btb[btb$level == d, , drop = FALSE], numeric(0)) else list()
  nm <- level_names[d + 1]
  by_level[[length(by_level) + 1]] <- list(level = nm, nodes = sum(depths == d), mae_base = b$mae, mae = a$mae, mase_base = b$mase, mase = a$mase)
  if (!is.null(a$mase)) values[[sprintf("bt_level[mase][%s]", nm)]] <- a$mase
}

nanoparquet::write_parquet(fc_df, file.path(out, "forecast.parquet"))
artifacts <- list(list(key = "forecast", path = file.path(out, "forecast.parquet"), format = "parquet"))
if (nrow(bt)) {
  nanoparquet::write_parquet(bt, file.path(out, "backtest.parquet"))
  artifacts[[2]] <- list(key = "backtest", path = file.path(out, "backtest.parquet"), format = "parquet")
}

# %% Charts
charts <- list()
shown <- utils::head(labels, 8)
fan <- fc_df[fc_df$series %in% shown, , drop = FALSE]
roles <- list(
  time = cs_col(TIME, fan$time, kind = if (TEMPORAL) "temporal" else "numeric"),
  value = cs_col(VALUE, fan$mean, kind = "numeric"),
  kind = cs_col("kind", fan$kind, kind = "categorical", levels = c("actual", "forecast")),
  series = cs_col("series", fan$series, kind = "categorical", levels = shown)
)
for (level in c(80, 95)) {
  if (level %in% LEVELS) {
    roles[[paste0("lo_", lv(level))]] <- cs_col(paste0("lo_", lv(level)), fan[[paste0("lo_", lv(level))]], kind = "numeric")
    roles[[paste0("hi_", lv(level))]] <- cs_col(paste0("hi_", lv(level)), fan[[paste0("hi_", lv(level))]], kind = "numeric")
  }
}
charts[[1]] <- cs_chart("forecast", "forecast-fan", sprintf("Reconciled forecasts of %s", VALUE), roles)
if (nrow(bt)) {
  errs <- bt[bt$level == 0, , drop = FALSE]
  charts[[2]] <- cs_chart("backtest", "backtest-errors", "Backtest errors of the total by horizon", list(
    h = cs_col("horizon", errs$h, kind = "numeric"),
    error = cs_col("error", errs$actual - errs$mean, kind = "numeric"),
    origin = cs_col("origin", errs$origin, kind = "categorical")
  ))
}

# %% Result
tables <- list()
if (nrow(bt)) {
  tables[[1]] <- list(
    key = "levels",
    title = sprintf("Backtest accuracy by level — base vs reconciled (%d origin%s, horizon %d)", n_origins, if (n_origins != 1) "s" else "", H),
    columns = list(list(key = "level", label = "Level"), list(key = "nodes", label = "Series", type = "number"),
                   list(key = "mae_base", label = "MAE (base)", type = "number"), list(key = "mae", label = "MAE (reconciled)", type = "number"),
                   list(key = "mase_base", label = "MASE (base)", type = "number"), list(key = "mase", label = "MASE (reconciled)", type = "number")),
    rows = by_level
  )
}
fc_cols <- list(list(key = "series", label = "Series"), list(key = "time", label = TIME), list(key = "base", label = "Base", type = "number"),
                list(key = "mean", label = "Reconciled", type = "number"))
for (level in LEVELS) {
  fc_cols <- c(fc_cols, list(list(key = paste0("lo_", lv(level)), label = sprintf("%s%% low", lv(level)), type = "number"),
                             list(key = paste0("hi_", lv(level)), label = sprintf("%s%% high", lv(level)), type = "number")))
}
keep <- setdiff(names(forecasts), c("t", "kind", "level"))
tables[[length(tables) + 1]] <- list(key = "forecast", title = "Reconciled forecast", columns = fc_cols,
  rows = lapply(seq_len(min(300, nrow(forecasts))), function(i) as.list(forecasts[i, keep, drop = FALSE])))
notes <- c(notes, "Missing periods of a series count as zero (no row = no sales). Reconciled intervals combine the base forecasts' standard errors with the shrunk correlation of the in-sample residuals.")
summary <- sprintf("%s: %d-step forecasts of %s for %d series (%d at the bottom, %s data, %d periods).", values$model_label, H, VALUE, n_nodes, nb, freq$label, n)
if (!is.null(accuracy$mase) && !is.null(base_acc$mase)) {
  summary <- paste0(summary, sprintf(" Backtest MASE %s reconciled vs %s base.", format(signif(accuracy$mase, 3)), format(signif(base_acc$mase, 3))))
}
cs_publish(list(
  title = "Hierarchical forecast (reconciliation)",
  engine = cs_engine_info("forecast", "nanoparquet"),
  n = length(times),
  summary = summary,
  statistics = lapply(intersect(c("mae", "rmse", "mase"), names(accuracy)), function(k) list(key = k, label = toupper(k), value = accuracy[[k]])),
  tables = tables,
  values = values,
  warnings = warnings,
  notes = notes,
  charts = charts,
  artifacts = artifacts
))

Sources

  • Hyndman RJ, Ahmed RA, Athanasopoulos G, Shang HL (2011). Optimal combination forecasts for hierarchical time series. Computational Statistics & Data Analysis 55(9), 2579–2589.
  • Wickramasuriya SL, Athanasopoulos G, Hyndman RJ (2019). Optimal forecast reconciliation for hierarchical and grouped time series through trace minimization. JASA 114(526), 804–819.
  • Schäfer J, Strimmer K (2005). A shrinkage approach to large-scale covariance matrix estimation. Statistical Applications in Genetics and Molecular Biology 4(1).

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