Hierarchical Reconciliation¶
reconciliation
¶
Hierarchical and grouped time-series aggregation and coherent forecast reconciliation.
Implements the Hyndman & Athanasopoulos (Forecasting: Principles and Practice, 3rd ed., Ch. 11) and Wickramasuriya, Athanasopoulos & Hyndman (2019) optimal reconciliation framework in pure pandas/NumPy:
- Hierarchy aggregation (
build_hierarchy) — Given a bottom-level panel andconfig.HierarchyConfig, constructs the aggregated series for the total node ("__total__") and every cross-sectional level incfg.hierarchy.levels(both strictly nested hierarchies and cross-classified grouped structures), together with the binary summing matrixSof shape(n_total, n_bottom)satisfyingy_t = S @ b_t. -
Reconciliation projection (
reconcile_matrix) — Computes the mapping matrixGof shape(n_bottom, n_total)such thaty_tilde = S @ G @ y_hatis coherent across the entire hierarchy for all eight supported methods: -
bottom_up— sum bottom-level base forecasts upward (G = [0 | I]). top_down— disaggregate the top-level base forecast by average historical proportions (FPP3 §11.2).middle_out— anchor on an intermediatemiddle_level, summing upward above it and disaggregating downward to the bottom series via historical proportions within each middle-level node.ols— ordinary least squares identity-weighted MinT (W_h = I).wls_struct— structural scaling WLS (W_h = diag(S @ 1)), requiring onlyS.wls_var— variance scaling WLS (W_h = diag(W_hat_1)) from 1-step/OOF residual variances.mint_shrink— Minimum Trace with analytical Schäfer-Strimmer shrinkage covariance of residuals (W_h = lambda_D * diag(W_hat_1) + (1 - lambda_D) * W_hat_1), guaranteed symmetric positive-definite even whenn_series >> T_obs.mint_nonneg— Wickramasuriya, Turlach & Hyndman (2020) non-negative Minimum Trace reconciliation solving the constrained quadratic programmin_{b >= 0} (y_hat - S b)^T W_h^{-1} (y_hat - S b)via non-negative least squares (scipy.optimize.nnls) soy_tilde = S @ b_tilde >= 0is both coherent and non-negative.- Forecast, OOF, and cell reconciliation (
reconcile_forecasts,reconcile_oof,reconcile_cells,verify_coherence) — Projects point forecasts (yhat,yhat_raw) viaP = S @ Gand prediction intervals (yhat_lower,yhat_upper) via the projected error variancediag(P @ W_h @ P.T), then re-scores reconciled cells on the backtest OOF window.
HierarchySpec
dataclass
¶
The structural definition of a hierarchical or grouped time-series panel.
Attributes:
| Name | Type | Description |
|---|---|---|
node_ids |
tuple[str, ...]
|
Ordered tuple of all |
bottom_ids |
tuple[str, ...]
|
Ordered tuple of the |
level_nodes |
dict[str, tuple[str, ...]]
|
Mapping from level key ( |
summing_matrix |
ndarray
|
Binary matrix |
build_hierarchy
¶
Aggregate a bottom-level panel across cfg.hierarchy.levels and build S (pure).
Given a bottom-level DataFrame containing cfg.data.ts_id_col, cfg.data.date_col,
cfg.data.target_col, the hierarchy attribute columns named in cfg.hierarchy.levels, and
any declared covariates:
- Prepends the top-level total series (
ts_id == "__total__"). - Builds one aggregated series per distinct group tuple at each level in
cfg.hierarchy.levels(skipping any level whose node IDs would duplicate an already-added level). Target values (y) are summed across constituent bottom series at each date; numeric covariate columns are averaged across constituent bottom series so rates and bounded indicators stay on scale. - Appends the bottom-level leaf series and constructs the binary summing matrix
Sof shape(n_total, n_bottom).
Returns (hierarchical_panel, HierarchySpec).
Source code in src/scale_forecasting/reconciliation.py
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 | |
reconcile_cells
¶
Reconcile a full hierarchy's CellResults across cfg.hierarchy.reconciliation_methods.
Takes the base CellResults for all n_nodes series in spec and returns new
CellResults for every (base_model, reconciliation_method) pair, with model_type
stamped as f"{base_model}_{method}", coherent predictions and oof frames, and
freshly computed backtest metrics (metrics.compute_metrics).
Source code in src/scale_forecasting/reconciliation.py
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 | |
reconcile_forecasts
¶
reconcile_forecasts(
predictions_df,
spec,
method,
*,
history_df=None,
oof_df=None,
middle_level=None,
date_col="forecast_date",
ts_id_col="ts_id",
target_col="y",
stamp_method=True,
)
Reconcile base forecasts across spec using method (pure).
Applies y_tilde = S @ G @ y_hat at every forecast date (and per model_type when the
column is present). When stamp_method=True (default), stamps model_type as
f"{base_model}_{method}" so reconciled forecasts can sit alongside base forecasts in the
registry and leaderboard.
Source code in src/scale_forecasting/reconciliation.py
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 | |
reconcile_matrix
¶
reconcile_matrix(
spec,
method,
*,
history_df=None,
residuals_df=None,
middle_level=None,
date_col="ds",
ts_id_col="ts_id",
target_col="y",
)
Compute the (n_bottom, n_nodes) reconciliation matrix G for method (pure).
Every reconciled forecast vector is formed as y_tilde = S @ G @ y_hat. Because S maps
the n_bottom leaf forecasts b_tilde = G @ y_hat to all n_nodes series, y_tilde
is coherent across the hierarchy by construction.
Source code in src/scale_forecasting/reconciliation.py
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 | |
reconcile_oof
¶
reconcile_oof(
oof_df,
spec,
method,
*,
cfg=None,
history_df=None,
middle_level=None,
ts_id_col="ts_id",
target_col="y",
stamp_method=True,
)
Reconcile backtest OOF predictions across spec using method (pure).
When cfg is provided and more than one backtest fold exists, estimates residual-covariance
weights (wls_var, mint_shrink, mint_nonneg) strictly from inner folds
(fold_id != holdout_fold_id(cfg)) so the holdout fold is never leaked into the reconciliation
matrix G.
Source code in src/scale_forecasting/reconciliation.py
schafer_strimmer_shrinkage
¶
Compute the Schäfer-Strimmer (2005) shrinkage covariance matrix and shrinkage intensity.
Given a residual matrix E of shape (T, n) (rows = time points, columns = series),
shrinks the sample covariance W_hat = (E.T @ E) / T toward its diagonal variance target
W_diag = diag(diag(W_hat)):
``W_shrink = lambda_D * W_diag + (1 - lambda_D) * W_hat``
where the analytical shrinkage intensity lambda_D in [0, 1] is estimated from the sample
correlations r_ij of the standardized residuals (Wickramasuriya et al. 2019, §2.4).
Source code in src/scale_forecasting/reconciliation.py
verify_coherence
¶
verify_coherence(
df,
spec,
*,
value_col="yhat",
date_col="forecast_date",
ts_id_col="ts_id",
atol=1e-06,
)
Verify exact additive coherence y_t == S @ b_t across all timestamps and models.
Returns the maximum absolute discrepancy max_{m, t} ||y_{m, t} - S @ b_{m, t}||_inf and
raises DataError if it exceeds atol.