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.
A real result
Example “Mint ets two levels”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
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
View data
| hi_80 | hi_95 | kind | lo_80 | lo_95 | series | month | sales |
|---|---|---|---|---|---|---|---|
| — | — | actual | — | — | Total | 1,609,459,200,000 | 371.10 |
| — | — | actual | — | — | Total | 1,612,137,600,000 | 393.20 |
| — | — | actual | — | — | Total | 1,614,556,800,000 | 397.40 |
| — | — | actual | — | — | Total | 1,617,235,200,000 | 407.40 |
| — | — | actual | — | — | Total | 1,619,827,200,000 | 397.50 |
| — | — | actual | — | — | Total | 1,622,505,600,000 | 422.20 |
| — | — | actual | — | — | Total | 1,625,097,600,000 | 383.50 |
| — | — | actual | — | — | Total | 1,627,776,000,000 | 357.30 |
| — | — | actual | — | — | Total | 1,630,454,400,000 | 312.10 |
| — | — | actual | — | — | Total | 1,633,046,400,000 | 300.20 |
| — | — | actual | — | — | Total | 1,635,724,800,000 | 316 |
| — | — | actual | — | — | Total | 1,638,316,800,000 | 349.50 |
| — | — | actual | — | — | Total | 1,640,995,200,000 | 386.30 |
| — | — | actual | — | — | Total | 1,643,673,600,000 | 411.70 |
| — | — | actual | — | — | Total | 1,646,092,800,000 | 419 |
| — | — | actual | — | — | Total | 1,648,771,200,000 | 415.60 |
| — | — | actual | — | — | Total | 1,651,363,200,000 | 432.90 |
| — | — | actual | — | — | Total | 1,654,041,600,000 | 430.70 |
| — | — | actual | — | — | Total | 1,656,633,600,000 | 397 |
| — | — | actual | — | — | Total | 1,659,312,000,000 | 375.50 |
| — | — | actual | — | — | Total | 1,661,990,400,000 | 327.70 |
| — | — | actual | — | — | Total | 1,664,582,400,000 | 324.70 |
| — | — | actual | — | — | Total | 1,667,260,800,000 | 324.50 |
| — | — | actual | — | — | Total | 1,669,852,800,000 | 378.40 |
| — | — | actual | — | — | Total | 1,672,531,200,000 | 409.80 |
| — | — | actual | — | — | Total | 1,675,209,600,000 | 437.60 |
| — | — | actual | — | — | Total | 1,677,628,800,000 | 434.30 |
| — | — | actual | — | — | Total | 1,680,307,200,000 | 432 |
| — | — | actual | — | — | Total | 1,682,899,200,000 | 451.70 |
| — | — | actual | — | — | Total | 1,685,577,600,000 | 456.50 |
| — | — | actual | — | — | Total | 1,688,169,600,000 | 419.90 |
| — | — | actual | — | — | Total | 1,690,848,000,000 | 391.70 |
| — | — | actual | — | — | Total | 1,693,526,400,000 | 340 |
| — | — | actual | — | — | Total | 1,696,118,400,000 | 332.10 |
| — | — | actual | — | — | Total | 1,698,796,800,000 | 351.90 |
| — | — | actual | — | — | Total | 1,701,388,800,000 | 405.20 |
| — | — | actual | — | — | Total | 1,704,067,200,000 | 442.60 |
| — | — | actual | — | — | Total | 1,706,745,600,000 | 452.90 |
| — | — | actual | — | — | Total | 1,709,251,200,000 | 472.10 |
| — | — | actual | — | — | Total | 1,711,929,600,000 | 473.70 |
| — | — | actual | — | — | Total | 1,714,521,600,000 | 481.70 |
| — | — | actual | — | — | Total | 1,717,200,000,000 | 468.30 |
| — | — | actual | — | — | Total | 1,719,792,000,000 | 458.20 |
| — | — | actual | — | — | Total | 1,722,470,400,000 | 412.30 |
| — | — | actual | — | — | Total | 1,725,148,800,000 | 368.40 |
| — | — | actual | — | — | Total | 1,727,740,800,000 | 332.80 |
| — | — | actual | — | — | Total | 1,730,419,200,000 | 351.10 |
| — | — | actual | — | — | Total | 1,733,011,200,000 | 430.60 |
| 464.43 | 470.31 | forecast | 442.19 | 436.30 | Total | 1,735,689,600,000 | 453.31 |
| 485.83 | 491.72 | forecast | 463.59 | 457.70 | Total | 1,738,368,000,000 | 474.71 |
| 492.68 | 498.57 | forecast | 470.43 | 464.54 | Total | 1,740,787,200,000 | 481.56 |
| 494.17 | 500.06 | forecast | 471.91 | 466.02 | Total | 1,743,465,600,000 | 483.04 |
| 502.94 | 508.83 | forecast | 480.68 | 474.78 | Total | 1,746,057,600,000 | 491.81 |
| 506.42 | 512.32 | forecast | 484.15 | 478.25 | Total | 1,748,736,000,000 | 495.28 |
| — | — | actual | — | — | region=north | 1,609,459,200,000 | 214 |
| — | — | actual | — | — | region=north | 1,612,137,600,000 | 225.60 |
| — | — | actual | — | — | region=north | 1,614,556,800,000 | 230.30 |
| — | — | actual | — | — | region=north | 1,617,235,200,000 | 233 |
| — | — | actual | — | — | region=north | 1,619,827,200,000 | 226.50 |
| — | — | actual | — | — | region=north | 1,622,505,600,000 | 244.40 |
First 60 of 432 rows.
View data
| error | horizon | origin |
|---|---|---|
| 15.452 | 1 | 2023-12-01 |
| 0.6523 | 2 | 2023-12-01 |
| 17.117 | 3 | 2023-12-01 |
| 17.284 | 4 | 2023-12-01 |
| 16.251 | 5 | 2023-12-01 |
| −6.250 | 6 | 2023-12-01 |
| 15.728 | 1 | 2024-06-01 |
| −4.870 | 2 | 2024-06-01 |
| −0.5380 | 3 | 2024-06-01 |
| −28.541 | 4 | 2024-06-01 |
| −22.040 | 5 | 2024-06-01 |
| 10.563 | 6 | 2024-06-01 |
Backtest accuracy by level — base vs reconciled (2 origins, horizon 6)
| Level | Series | MAE (base) | MAE (reconciled) | MASE (base) | MASE (reconciled) |
|---|---|---|---|---|---|
| Total | 1 | 12.979 | 12.940 | 0.6520 | 0.6500 |
| region | 2 | 7.011 | 7.012 | 0.6612 | 0.6612 |
| store | 5 | 3.711 | 3.715 | 0.6438 | 0.6450 |
Reconciled forecast
| Series | month | Base | Reconciled | 80% low | 80% high | 95% low | 95% high |
|---|---|---|---|---|---|---|---|
| Total | 2025-01-01 | 453.51 | 453.31 | 442.19 | 464.43 | 436.30 | 470.31 |
| Total | 2025-02-01 | 474.92 | 474.71 | 463.59 | 485.83 | 457.70 | 491.72 |
| Total | 2025-03-01 | 481.76 | 481.56 | 470.43 | 492.68 | 464.54 | 498.57 |
| Total | 2025-04-01 | 483.24 | 483.04 | 471.91 | 494.17 | 466.02 | 500.06 |
| Total | 2025-05-01 | 492.01 | 491.81 | 480.68 | 502.94 | 474.78 | 508.83 |
| Total | 2025-06-01 | 495.49 | 495.28 | 484.15 | 506.42 | 478.25 | 512.32 |
| region=north | 2025-01-01 | 263.83 | 263.75 | 254.02 | 273.47 | 248.87 | 278.62 |
| region=north | 2025-02-01 | 275.41 | 275.33 | 265.60 | 285.05 | 260.45 | 290.20 |
| region=north | 2025-03-01 | 278.81 | 278.73 | 269.00 | 288.45 | 263.86 | 293.59 |
| region=north | 2025-04-01 | 279.04 | 278.95 | 269.23 | 288.67 | 264.09 | 293.82 |
| region=north | 2025-05-01 | 285.98 | 285.90 | 276.18 | 295.62 | 271.03 | 300.76 |
| region=north | 2025-06-01 | 285.81 | 285.72 | 276.01 | 295.44 | 270.86 | 300.59 |
| region=south | 2025-01-01 | 189.75 | 189.56 | 183.83 | 195.28 | 180.80 | 198.32 |
| region=south | 2025-02-01 | 199.57 | 199.38 | 193.64 | 205.13 | 190.60 | 208.17 |
| region=south | 2025-03-01 | 203.02 | 202.83 | 197.07 | 208.60 | 194.01 | 211.65 |
| region=south | 2025-04-01 | 204.28 | 204.08 | 198.30 | 209.87 | 195.24 | 212.93 |
| region=south | 2025-05-01 | 206.10 | 205.91 | 200.11 | 211.72 | 197.03 | 214.79 |
| region=south | 2025-06-01 | 209.75 | 209.56 | 203.74 | 215.38 | 200.65 | 218.47 |
| region=north / store=N1 | 2025-01-01 | 169.13 | 169.08 | 162.13 | 176.03 | 158.46 | 179.71 |
| region=north / store=N1 | 2025-02-01 | 172.85 | 172.81 | 165.86 | 179.76 | 162.19 | 183.44 |
| region=north / store=N1 | 2025-03-01 | 172.68 | 172.64 | 165.69 | 179.58 | 162.01 | 183.26 |
| region=north / store=N1 | 2025-04-01 | 173.53 | 173.49 | 166.54 | 180.43 | 162.87 | 184.11 |
| region=north / store=N1 | 2025-05-01 | 181.73 | 181.68 | 174.74 | 188.62 | 171.07 | 192.30 |
| region=north / store=N1 | 2025-06-01 | 180.60 | 180.56 | 173.62 | 187.50 | 169.95 | 191.17 |
| region=north / store=N2 | 2025-01-01 | 94.619 | 94.664 | 88.254 | 101.07 | 84.861 | 104.47 |
| region=north / store=N2 | 2025-02-01 | 102.47 | 102.52 | 96.105 | 108.93 | 92.711 | 112.32 |
| region=north / store=N2 | 2025-03-01 | 106.05 | 106.09 | 99.678 | 112.50 | 96.284 | 115.90 |
| region=north / store=N2 | 2025-04-01 | 105.42 | 105.47 | 99.053 | 111.88 | 95.658 | 115.27 |
| region=north / store=N2 | 2025-05-01 | 104.17 | 104.22 | 97.801 | 110.63 | 94.406 | 114.02 |
| region=north / store=N2 | 2025-06-01 | 105.12 | 105.17 | 98.752 | 111.58 | 95.356 | 114.98 |
| region=south / store=S1 | 2025-01-01 | 82.963 | 83.079 | 79.617 | 86.540 | 77.785 | 88.372 |
| region=south / store=S1 | 2025-02-01 | 88.913 | 89.029 | 85.517 | 92.541 | 83.658 | 94.400 |
| region=south / store=S1 | 2025-03-01 | 90.237 | 90.353 | 86.791 | 93.915 | 84.906 | 95.800 |
| region=south / store=S1 | 2025-04-01 | 93.912 | 94.029 | 90.418 | 97.640 | 88.507 | 99.551 |
| region=south / store=S1 | 2025-05-01 | 93.537 | 93.654 | 89.995 | 97.313 | 88.058 | 99.250 |
| region=south / store=S1 | 2025-06-01 | 95.137 | 95.255 | 91.549 | 98.961 | 89.587 | 100.92 |
| region=south / store=S2 | 2025-01-01 | 45.279 | 45.350 | 41.976 | 48.724 | 40.190 | 50.510 |
| region=south / store=S2 | 2025-02-01 | 44.556 | 44.626 | 41.253 | 48.000 | 39.467 | 49.786 |
| region=south / store=S2 | 2025-03-01 | 45.780 | 45.850 | 42.477 | 49.224 | 40.691 | 51.010 |
| region=south / store=S2 | 2025-04-01 | 43.730 | 43.801 | 40.427 | 47.174 | 38.642 | 48.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.
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)
| Level | Series | MAE (base) | MAE (reconciled) | MASE (base) | MASE (reconciled) |
|---|---|---|---|---|---|
| Total | 1 | 12.979 | 12.940 | 0.6520 | 0.6500 |
| region | 2 | 7.011 | 7.012 | 0.6612 | 0.6612 |
| store | 5 | 3.711 | 3.715 | 0.6438 | 0.6450 |
Reconciled forecast
| Series | month | Base | Reconciled | 80% low | 80% high | 95% low | 95% high |
|---|---|---|---|---|---|---|---|
| Total | 2025-01-01 | 453.51 | 453.31 | 442.19 | 464.43 | 436.30 | 470.31 |
| Total | 2025-02-01 | 474.92 | 474.71 | 463.59 | 485.83 | 457.70 | 491.72 |
| Total | 2025-03-01 | 481.76 | 481.56 | 470.43 | 492.68 | 464.54 | 498.57 |
| Total | 2025-04-01 | 483.24 | 483.04 | 471.91 | 494.17 | 466.02 | 500.06 |
| Total | 2025-05-01 | 492.01 | 491.81 | 480.68 | 502.94 | 474.78 | 508.83 |
| Total | 2025-06-01 | 495.49 | 495.28 | 484.15 | 506.42 | 478.25 | 512.32 |
| region=north | 2025-01-01 | 263.83 | 263.75 | 254.02 | 273.47 | 248.87 | 278.62 |
| region=north | 2025-02-01 | 275.41 | 275.33 | 265.60 | 285.05 | 260.45 | 290.20 |
| region=north | 2025-03-01 | 278.81 | 278.73 | 269.00 | 288.45 | 263.86 | 293.59 |
| region=north | 2025-04-01 | 279.04 | 278.95 | 269.23 | 288.67 | 264.09 | 293.82 |
| region=north | 2025-05-01 | 285.98 | 285.90 | 276.18 | 295.62 | 271.03 | 300.76 |
| region=north | 2025-06-01 | 285.81 | 285.72 | 276.01 | 295.44 | 270.86 | 300.59 |
| region=south | 2025-01-01 | 189.75 | 189.56 | 183.83 | 195.28 | 180.80 | 198.32 |
| region=south | 2025-02-01 | 199.57 | 199.38 | 193.64 | 205.13 | 190.60 | 208.17 |
| region=south | 2025-03-01 | 203.02 | 202.83 | 197.07 | 208.60 | 194.01 | 211.65 |
| region=south | 2025-04-01 | 204.28 | 204.08 | 198.30 | 209.87 | 195.24 | 212.93 |
| region=south | 2025-05-01 | 206.10 | 205.91 | 200.11 | 211.72 | 197.03 | 214.79 |
| region=south | 2025-06-01 | 209.75 | 209.56 | 203.74 | 215.38 | 200.65 | 218.47 |
| region=north / store=N1 | 2025-01-01 | 169.13 | 169.08 | 162.13 | 176.03 | 158.46 | 179.71 |
| region=north / store=N1 | 2025-02-01 | 172.85 | 172.81 | 165.86 | 179.76 | 162.19 | 183.44 |
| region=north / store=N1 | 2025-03-01 | 172.68 | 172.64 | 165.69 | 179.58 | 162.01 | 183.26 |
| region=north / store=N1 | 2025-04-01 | 173.53 | 173.49 | 166.54 | 180.43 | 162.87 | 184.11 |
| region=north / store=N1 | 2025-05-01 | 181.73 | 181.68 | 174.74 | 188.62 | 171.07 | 192.30 |
| region=north / store=N1 | 2025-06-01 | 180.60 | 180.56 | 173.62 | 187.50 | 169.95 | 191.17 |
| region=north / store=N2 | 2025-01-01 | 94.619 | 94.664 | 88.254 | 101.07 | 84.861 | 104.47 |
| region=north / store=N2 | 2025-02-01 | 102.47 | 102.52 | 96.105 | 108.93 | 92.711 | 112.32 |
| region=north / store=N2 | 2025-03-01 | 106.05 | 106.09 | 99.678 | 112.50 | 96.284 | 115.90 |
| region=north / store=N2 | 2025-04-01 | 105.42 | 105.47 | 99.053 | 111.88 | 95.658 | 115.27 |
| region=north / store=N2 | 2025-05-01 | 104.17 | 104.22 | 97.801 | 110.63 | 94.406 | 114.02 |
| region=north / store=N2 | 2025-06-01 | 105.12 | 105.17 | 98.752 | 111.58 | 95.356 | 114.98 |
| region=south / store=S1 | 2025-01-01 | 82.963 | 83.079 | 79.617 | 86.540 | 77.785 | 88.372 |
| region=south / store=S1 | 2025-02-01 | 88.913 | 89.029 | 85.517 | 92.541 | 83.658 | 94.400 |
| region=south / store=S1 | 2025-03-01 | 90.237 | 90.353 | 86.791 | 93.915 | 84.906 | 95.800 |
| region=south / store=S1 | 2025-04-01 | 93.912 | 94.029 | 90.418 | 97.640 | 88.507 | 99.551 |
| region=south / store=S1 | 2025-05-01 | 93.537 | 93.654 | 89.995 | 97.313 | 88.058 | 99.250 |
| region=south / store=S1 | 2025-06-01 | 95.137 | 95.255 | 91.549 | 98.961 | 89.587 | 100.92 |
| region=south / store=S2 | 2025-01-01 | 45.279 | 45.350 | 41.976 | 48.724 | 40.190 | 50.510 |
| region=south / store=S2 | 2025-02-01 | 44.556 | 44.626 | 41.253 | 48.000 | 39.467 | 49.786 |
| region=south / store=S2 | 2025-03-01 | 45.780 | 45.850 | 42.477 | 49.224 | 40.691 | 51.010 |
| region=south / store=S2 | 2025-04-01 | 43.730 | 43.801 | 40.427 | 47.174 | 38.642 | 48.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.
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,
}
)
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.