import matplotlib.pyplot as plt
SOURCE_TABLE = "source_series_covariates_native"
HORIZON = 14
05 · Three-Tier Exogenous Covariates & Global Cross-Series Models¶
Real-world enterprise demand and financial forecasting relies on three distinct tiers of exogenous information (features.py), each with strict causal availability:
- Static Covariates (
features.static_covariates): Time-invariant series metadata (region,category). Target-encoded and one-hot encoded across global panels so cross-series models learn segment-specific elasticities. - Known-Future Covariates (
features.future_covariates): Planned promotions (promo_flag), scheduled pricing (price_index), and calendar holidays known across both historical training and the future forecast horizon $t+1 \dots t+H$ (including multi-day pre/post-holiday lead/lag windows viafeatures.holiday_window). - Observed-Past Covariates (
features.past_covariates): Historical weather (temperature), foot traffic, or macro indicators observed only up to the forecast origin $t$. To prevent future leakage while forecasting step $h \in [1, H]$, the feature engine automatically shiftspast_covariatesbyexog_lags$\ge h$. - Causal & Econometric Guardrails (
features.monotonic_constraints,@monotone,promo_elasticity_df()& Full-Chainsimulate_scenarios()): Enforce economic sign priors (price_index: -1,promo_flag: +1), orthogonalize seasonal/holiday confounding via Double/Debiased ML, and propagate counterfactual shocks through ensembles,mint_nonneghierarchy reconciliation, gross margin (unit_cost), and inventory replenishment (delta_reorder_point,delta_safety_stock,delta_order_qty).
At a glance¶
| Dimension | Details |
|---|---|
| Learning outcomes | Configure 3-tier exogenous features (static_covariates, future_covariates, lag-shifted past_covariates), test on_unsupported_covariates policies, inspect Two-Tier global & per-horizon-step feature attributions, and run Track J causal guardrails (@monotone, holiday_window), Double/Debiased ML promo_elasticity_df(), and full-chain gross-margin + inventory simulate_scenarios() (Act 6). |
| Prerequisites | Deployed scale-forecasting Google Cloud project (SF_* env vars) + scale-forecasting[gcp]. |
| Estimated time | ~5–8 minutes. |
| Estimated run cost | Estimated ~\$0.10–\$0.40 USD (Vertex AI / Compute Engine / BigQuery ML compute for the 20-series panel + BigQuery Storage API). |
| Ongoing cost | Zero compute when idle (ephemeral job compute tears down automatically on completion). |
flowchart TD
subgraph Tiers["Three-Tier Exogenous Feature Contract (features.py)"]
T1["static_covariates
region · category
(Time-invariant metadata)"]
T2["future_covariates + holiday_window
promo_flag · price_index · holidays (pre_holiday_days=7, post_holiday_days=3)
(Known in history & future horizon)"]
T3["past_covariates
temperature + exog_lags {temperature: [7, 14]}
(Observed in history only — lag-shifted)"]
end
subgraph Policy["Causal Guardrails & Covariate Policy"]
P1["monotonic_constraints: {price_index: -1, promo_flag: +1}
+ @monotone variants (lightgbm@monotone · regression_lags@monotone)"]
P2["on_unsupported_covariates: fallback (default) | error"]
end
T1 & T2 & T3 --> Policy --> FIT["Global ML (lightgbm · xgboost · catboost)
& Local Exog (sarimax · prophet · regression_lags)"]
FIT --> CAUSAL["Act 6 · Double/Debiased ML promo_elasticity_df()
& Full-Chain simulate_scenarios() (Gross Margin + Inventory ROP/SS)"]
Act 1 · Cloud Bootstrap & Deployment Resolution¶
On a managed cloud notebook (Colab Enterprise, Vertex AI Workbench) the bootstrap cell below clones or updates the repository and installs the locked dependency set (uv.lock) into an isolated .colab-deps prefix so import scale_forecasting resolves against the exact package versions every cloud worker uses. In a local clone with .venv, this cell is a fast no-op.
# Cloud bootstrap: clone + install the LOCKED dependency set (uv.lock) so
# `import scale_forecasting` resolves against the exact versions every other surface runs.
import importlib.util
import os
import shutil
import subprocess
import sys
REPO_URL = os.environ.get("SF_REPO_URL", "https://github.com/statmike/scale-forecasting.git")
REPO_DIR = os.environ.get("SF_REPO_DIR", "scale-forecasting")
EXTRAS = ['gcp']
if importlib.util.find_spec("scale_forecasting") is None:
if not os.path.isdir(REPO_DIR):
subprocess.run(["git", "clone", "--depth", "1", REPO_URL, REPO_DIR], check=True)
uv = shutil.which("uv")
if uv is None:
subprocess.run([sys.executable, "-m", "pip", "install", "-q", "uv"], check=True)
uv = shutil.which("uv") or "uv"
reqs = os.path.abspath(os.path.join(REPO_DIR, "colab-requirements.txt"))
extra_flags = [f for e in EXTRAS for f in ("--extra", e)]
subprocess.run(
[uv, "export", "--frozen", "--no-emit-project", "--no-hashes", "--no-dev", *extra_flags, "-o", reqs],
cwd=REPO_DIR,
check=True,
)
target = os.path.abspath(os.path.join(REPO_DIR, ".colab-deps"))
subprocess.run(
[uv, "pip", "install", "--python", sys.executable, "--target", target, "-r", reqs],
check=True,
)
sys.path.insert(0, target)
sys.path.insert(0, os.path.join(REPO_DIR, "src"))
print("installed scale_forecasting from", REPO_DIR)
else:
print("scale_forecasting already importable — skipping bootstrap")
scale_forecasting already importable — skipping bootstrap
Resolve the Live GCP Deployment (Settings.resolve())¶
Settings.resolve() reads the SF_* environment variables (SF_PROJECT_ID, SF_REGION, SF_DATASET_ID, SF_WAREHOUSE_URI, SF_CONNECTION, SF_COMPUTE_SA) pre-populated by Terraform in the sf-main runtime template (or your local shell).
from google.cloud import bigquery
from scale_forecasting.settings import Settings
settings = Settings.resolve()
client = bigquery.Client(project=settings.project_id)
DATASET = settings.dataset_ref
print(f"Deployment: {DATASET} | Region: {settings.region} | Bucket: {settings.warehouse_uri}")
Deployment: statmike-scale-forecasting.scale_forecasting | Region: us-central1 | Bucket: gs://statmike-scale-forecasting-warehouse/warehouse
Act 2 · Inspect Model Covariate Capabilities & Configure a 3-Tier Global Run¶
First, let's filter model_catalog() to inspect which models support future_covariates, past_covariates, static_covariates, and global_mode.
from scale_forecasting import Forecaster, RunConfig, model_catalog
cat = model_catalog()
display(cat[cat["future_covariates"] | cat["past_covariates"] | cat["static_covariates"]][[
"model", "family", "future_covariates", "past_covariates", "static_covariates", "explainability", "global_mode", "hybrid_mode"
]])
| model | family | future_covariates | past_covariates | static_covariates | explainability | global_mode | hybrid_mode | |
|---|---|---|---|---|---|---|---|---|
| 0 | arima_plus | native | True | False | False | True | False | False |
| 1 | timesfm | native | True | True | False | False | False | False |
| 2 | chronos2 | deep_learning | True | True | True | False | True | False |
| 6 | tft | deep_learning | True | True | True | False | True | False |
| 7 | tide | deep_learning | True | True | True | False | True | False |
| 8 | timesfm_torch | deep_learning | True | True | True | False | True | False |
| 9 | tsmixer | deep_learning | True | True | True | False | True | False |
| 10 | catboost | ml | True | True | False | True | False | False |
| 11 | lightgbm | ml | True | True | False | True | False | False |
| 12 | random_forest | ml | True | True | False | True | False | False |
| 13 | regression_lags | ml | True | True | False | True | False | False |
| 14 | xgboost | ml | True | True | False | True | False | False |
| 15 | auto_arima | statistical | True | True | False | False | False | False |
| 22 | kalman | statistical | True | True | False | False | False | False |
| 27 | prophet | statistical | True | True | False | False | False | False |
| 28 | sarimax | statistical | True | True | False | False | False | False |
| 32 | ucm | statistical | True | True | False | False | False | False |
| 33 | vertex_l2l | automl | True | True | True | True | True | False |
| 34 | vertex_seq2seq | automl | True | True | True | True | True | False |
| 35 | vertex_tft | automl | True | True | True | True | True | False |
| 36 | vertex_tide | automl | True | True | True | True | True | False |
import time
# === Parameters — edit me ===============================================
RUN_NAME = f"nb05 covariates global {int(time.time())}"
SOURCE_TABLE = "source_series_covariates_native" # or "source_series_covariates_iceberg"
MODELS = ["tide", "tsmixer", "lightgbm", "xgboost", "theta"]
HORIZON = 14
SERIES_LIMIT = 20
# ========================================================================
cfg = RunConfig(
run_name=RUN_NAME,
python_runtime="vertex",
data={
"source_table": SOURCE_TABLE,
"horizon": HORIZON,
"series_limit": SERIES_LIMIT,
},
models=MODELS,
model_params={
"tide": {"training_mode": "global", "max_epochs": 15},
"tsmixer": {"training_mode": "global", "max_epochs": 15},
},
compute={
"families": {
"deep_learning": {"runtime": "vertex", "hardware": "cpu"},
"ml": {"runtime": "vertex"},
"statistical": {"runtime": "vertex"},
}
},
features={
"holidays": ["US"],
"static_covariates": ["region", "category"],
"future_covariates": ["promo_flag", "price_index"],
"past_covariates": ["temperature"],
"exog_lags": {"promo_flag": [1, 7], "temperature": [7, 14]},
"on_unsupported_covariates": "fallback",
},
backtest={"enabled": True, "n_folds": 2, "horizon": HORIZON, "step": HORIZON},
ensemble={"enabled": True, "strategies": ["inverse_error", "nnls"]},
)
forecaster = Forecaster(cfg, settings=settings)
print("run_id:", forecaster.run_id)
display(forecaster.explain(validate_data=False))
run_id: nb05-covariates-global-1791391135-dfcbfde016ec
| run_id | family | job_key | runtime | machine_type | workers | hardware | gpu_type | models | training_modes | n_series | n_folds | expected_cells | covariates | depends_on | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | nb05-covariates-global-1791391135-dfcbfde016ec | statistical | sf-nb05-covariates-global-1791391135-dfcbfde01... | vertex | n2-standard-8 | 1 | cpu | None | theta | theta:local | 20 | 2 | 20 | future(2), past(1), static(2) | |
| 1 | nb05-covariates-global-1791391135-dfcbfde016ec | ml | sf-nb05-covariates-global-1791391135-dfcbfde01... | vertex | n2-standard-8 | 1 | cpu | None | lightgbm, xgboost | lightgbm:local, xgboost:local | 20 | 2 | 40 | future(2), past(1), static(2) | |
| 2 | nb05-covariates-global-1791391135-dfcbfde016ec | deep_learning | sf-nb05-covariates-global-1791391135-dfcbfde01... | vertex | n2-standard-8 | 2 | cpu | None | tide, tsmixer | tide:global, tsmixer:global | 20 | 2 | 40 | future(2), past(1), static(2) | |
| 3 | nb05-covariates-global-1791391135-dfcbfde016ec | ensemble | sf-nb05-covariates-global-1791391135-dfcbfde01... | bigquery | sql | 1 | sql | None | ensemble_inverse_error, ensemble_nnls | barrier | 20 | 2 | 40 | future(2), past(1), static(2) | sf-nb05-covariates-global-1791391135-dfcbfde01... |
Act 3 · Launch & Monitor Live (forecaster.run_live())¶
Notice in the explain() table above that:
- The
deep_learningfamily (tide,tsmixer) runs inglobalcross-series mode using all three covariate tiers (future,past,static). - The
mlfamily (lightgbm,xgboost) runs inlocalmode usingfuture_covariatesand lag-shiftedpast_covariates. - The
statisticalfamily (theta) automatically strips unsupported covariates underon_unsupported_covariates='fallback'.
result = forecaster.run_live(poll_s=15.0, probe=True)
print(f"Completed {result.run_id}: status={result.status}, runtime={result.runtime_seconds:.1f}s")
2026-10-07 16:38:55,890 WARNING scale_forecasting.dag: model 'lightgbm' does not support configured covariate tier(s) ['static_covariates'] and will fall back to its supported tiers ['future_covariates', 'past_covariates'] (set features.on_unsupported_covariates='error' to refuse instead).
2026-10-07 16:38:55,892 WARNING scale_forecasting.dag: model 'xgboost' does not support configured covariate tier(s) ['static_covariates'] and will fall back to its supported tiers ['future_covariates', 'past_covariates'] (set features.on_unsupported_covariates='error' to refuse instead).
2026-10-07 16:38:55,894 WARNING scale_forecasting.dag: model 'theta' does not support configured covariate tier(s) ['future_covariates', 'past_covariates', 'static_covariates'] and will fall back to univariate forecasting (set features.on_unsupported_covariates='error' to refuse instead).
Completed nb05-covariates-global-1791391135-dfcbfde016ec: status=COMPLETED, runtime=456.2s
Act 4 · Review Leaderboard, Interval Calibration, Two-Tier Feature Attributions & Structural Decomposition¶
Let's compare the global and covariate-aware models against the univariate baseline on the leaderboard, inspect conformal interval calibration by horizon step (forecaster.plot_calibration()), examine Two-Tier Feature Attributions (forecaster.attributions_df(model_type="lightgbm") and forecaster.plot_attributions(model_type="lightgbm") — Tier 1 global feature importance and Tier 2 per-horizon-step TreeSHAP attributions across recursive target lags, calendar features, and exogenous covariates), and decompose the lightgbm forecast into its structural trend, seasonality, and exogenous covariate contributions (promo_flag, price_index, temperature) via forecaster.plot_forecast_explanation().
import matplotlib.pyplot as plt
from scale_forecasting import plot_leaderboard, plot_metric_distribution
display(forecaster.leaderboard_df())
review = forecaster.review_run()
plot_leaderboard(review)
plt.show()
plot_metric_distribution(review)
plt.show()
forecaster.plot_forecasts(history_tail=90)
plt.show()
forecaster.plot_calibration()
plt.show()
print("--- Two-Tier TreeSHAP Feature Attributions (forecaster.attributions_df & plot_attributions) ---")
attr_df = forecaster.attributions_df(model_type="lightgbm", level="global")
display(attr_df.head(10))
forecaster.plot_attributions(model_type="lightgbm", level="global", title="Tier 1 Global TreeSHAP Importance (lightgbm)")
plt.show()
forecaster.plot_attributions(model_type="lightgbm", level="local", title="Tier 2 Local Per-Step TreeSHAP Attributions (lightgbm)")
plt.show()
exp_df = forecaster.explain_forecast(model_type="lightgbm")
display(exp_df.tail(10))
forecaster.plot_forecast_explanation(model_type="lightgbm", history_tail=90)
plt.show()
| rank | model_type | family | is_ensemble | ensemble_id | compute_engine | n_series | decision_metric | score | pooled_wape | ... | mean_mae | mean_rmse | mean_coverage | mean_interval_score | mean_fit_seconds | median_fit_seconds | no_artifact_rate | n_predictions | lift_vs_best_base | lift_pct | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | ensemble_inverse_error | ensemble | True | 34432fdde9fa | ensemble | 20 | wape | 0.406179 | 0.137957 | ... | 12.511065 | 17.542903 | NaN | NaN | NaN | NaN | 1.0 | 280 | 0.024027 | 0.055851 |
| 1 | 2 | theta | statistical | False | None | vertex | 20 | wape | 0.430206 | 0.155773 | ... | 14.755309 | 19.577359 | 0.991071 | 170.476561 | 4.247834 | 2.654362 | 1.0 | 280 | NaN | NaN |
| 2 | 3 | ensemble_nnls | ensemble | True | 34432fdde9fa | ensemble | 20 | wape | 0.432475 | 0.145220 | ... | 12.810496 | 18.003265 | NaN | NaN | NaN | NaN | 0.0 | 280 | -0.002269 | -0.005274 |
| 3 | 4 | tsmixer | deep_learning | False | None | vertex | 20 | wape | 0.441231 | 0.214435 | ... | 20.504270 | 26.229074 | 0.816071 | 110.581714 | 1.507077 | 1.507077 | 1.0 | 280 | NaN | NaN |
| 4 | 5 | lightgbm | ml | False | None | vertex | 20 | wape | 0.444321 | 0.144800 | ... | 13.657062 | 18.708318 | 0.237500 | 104.295213 | 4.469882 | 2.508540 | 1.0 | 280 | NaN | NaN |
| 5 | 6 | xgboost | ml | False | None | vertex | 20 | wape | 0.446640 | 0.151259 | ... | 13.162259 | 18.580552 | 0.164286 | 108.298528 | 4.192350 | 4.344461 | 1.0 | 280 | NaN | NaN |
| 6 | 7 | tide | deep_learning | False | None | vertex | 20 | wape | 0.461806 | 0.169715 | ... | 15.458432 | 20.967358 | 0.841071 | 94.894177 | 2.581071 | 2.581071 | 1.0 | 280 | NaN | NaN |
7 rows × 25 columns
<Figure size 1000x450 with 1 Axes>
<Figure size 1000x450 with 1 Axes>
<Figure size 1100x1020 with 3 Axes>
--- Two-Tier TreeSHAP Feature Attributions (forecaster.attributions_df & plot_attributions) ---
| ts_id | model_type | compute_engine | feature | importance | |
|---|---|---|---|---|---|
| 0 | s_000000 | lightgbm | vertex | lag_7 | 0.117444 |
| 1 | s_000000 | lightgbm | vertex | lag_1 | 0.099000 |
| 2 | s_000000 | lightgbm | vertex | doy | 0.088111 |
| 3 | s_000000 | lightgbm | vertex | temperature_lag_7 | 0.081000 |
| 4 | s_000000 | lightgbm | vertex | lag_14 | 0.077333 |
| 5 | s_000000 | lightgbm | vertex | lag_3 | 0.075667 |
| 6 | s_000000 | lightgbm | vertex | temperature_lag_14 | 0.074889 |
| 7 | s_000000 | lightgbm | vertex | lag_28 | 0.072556 |
| 8 | s_000000 | lightgbm | vertex | price_index | 0.071111 |
| 9 | s_000000 | lightgbm | vertex | temperature | 0.069111 |
<Figure size 950x450 with 1 Axes>
| ts_id | model_type | segment | ds | y_true | yhat | yhat_lower | yhat_upper | trend_baseline | level_shift | seasonal_effect | covariate_effect | oof_residual | interval_width | cov_promo_flag | cov_price_index | cov_temperature | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 124 | s_000000 | lightgbm | forecast | 2025-01-04 | NaN | 275.075040 | 244.507923 | 287.328154 | 249.533191 | 72.779333 | 32.545727 | -3.705789 | NaN | 42.820230 | -0.669871 | -1.338342 | -1.697576 |
| 125 | s_000000 | lightgbm | forecast | 2025-01-05 | NaN | 278.684157 | 247.957379 | 301.089794 | 244.116069 | 72.779333 | 39.063253 | -3.705789 | NaN | 53.132415 | -0.669871 | -1.338342 | -1.697576 |
| 126 | s_000000 | lightgbm | forecast | 2025-01-06 | NaN | 259.804869 | 229.611275 | 282.743690 | 245.970480 | 72.779333 | 20.402427 | -3.705789 | NaN | 53.132415 | -0.669871 | -1.338342 | -1.697576 |
| 127 | s_000000 | lightgbm | forecast | 2025-01-07 | NaN | 223.414274 | 198.289640 | 247.311521 | 248.326396 | 72.779333 | -19.018635 | -3.705789 | NaN | 49.021881 | -0.669871 | -1.338342 | -1.697576 |
| 128 | s_000000 | lightgbm | forecast | 2025-01-08 | NaN | 228.002887 | 202.878253 | 251.900134 | 250.304848 | 72.779333 | -40.607435 | -3.705789 | NaN | 49.021881 | -0.669871 | -1.338342 | -1.697576 |
| 129 | s_000000 | lightgbm | forecast | 2025-01-09 | NaN | 217.971142 | 202.830404 | 241.970415 | 250.507421 | 72.779333 | -35.352640 | -3.705789 | NaN | 39.140011 | -0.669871 | -1.338342 | -1.697576 |
| 130 | s_000000 | lightgbm | forecast | 2025-01-10 | NaN | 255.332401 | 240.918954 | 280.058965 | 250.267611 | 72.779333 | 2.967304 | -3.705789 | NaN | 39.140011 | -0.669871 | -1.338342 | -1.697576 |
| 131 | s_000000 | lightgbm | forecast | 2025-01-11 | NaN | 288.924208 | 274.510762 | 313.650773 | 254.743168 | 72.779333 | 32.545727 | -3.705789 | NaN | 39.140011 | -0.669871 | -1.338342 | -1.697576 |
| 132 | s_000000 | lightgbm | forecast | 2025-01-12 | NaN | 280.102168 | 265.688722 | 304.828732 | 260.091224 | 72.779333 | 39.063253 | -3.705789 | NaN | 39.140011 | -0.669871 | -1.338342 | -1.697576 |
| 133 | s_000000 | lightgbm | forecast | 2025-01-13 | NaN | 258.126200 | 243.712753 | 282.852764 | 270.621244 | 72.779333 | 20.402427 | -3.705789 | NaN | 39.140011 | -0.669871 | -1.338342 | -1.697576 |
<Figure size 1100x920 with 4 Axes>
Act 6 · Causal & Econometric Guardrails (@monotone), Double/Debiased ML Promo Elasticity (promo_elasticity_df) & Full-Chain Margin/Inventory What-If (simulate_scenarios)¶
In observational retail and financial panels, promotions (promo_flag) and price changes (price_index) frequently coincide with peak seasonal holidays. Without econometric guardrails, unconstrained regressions and gradient-boosted trees can learn confounded wrong-signed elasticities (e.g., predicting higher demand when price rises during a holiday peak). Track J (v1.5.0) and Track P.2 (v1.8.1) provide integrated capabilities to guarantee causal validity from feature engineering through operational replenishment:
@monotonePrice/Promo/Degree-Day Sign Constraints (features.monotonic_constraints&features.degree_day_cols): Declaringmonotonic_constraints={"price_index": -1, "promo_flag": 1}(plus automatic+1sign inference for piecewisehdd_<col>/cdd_<col>weather splines generated viadegree_day_cols) and pairing unconstrained models with@monotonevariants (lightgbm@monotone,regression_lags@monotone) guarantees non-positive price response ($\hat{y}(p + \Delta p) \le \hat{y}(p)$ for $\Delta p > 0$) and non-negative promotional and degree-day lift.- Orthogonalized Double/Debiased ML Promo, Ad-Stock, Cannibalization & Complementary Halo Decomposition (
f.promo_elasticity_df()): Uses Robinson (1988) / Chernozhukov et al. (2018) cross-fitted residualization across out-of-fold nuisance models to partial out seasonal, trend, and holiday confounders before estimating causal effects—decomposing demand intobaseline_yhat,incremental_promo_lift,adstock_effect(adstock_decaygeometric carryover $A_{i,t} = D_{i,t} + \lambda A_{i,t-1}$),pull_forward_dip(exog_lagspost-promo dip), negative substitutecannibalization_dip($\gamma_{ij} < 0$), positive complementaryhalo_lift($\gamma_{ij} > 0$,top_halo_ts_id), andnet_causal_elasticity. - Multi-Day Moving-Holiday Lead/Lag Windows (
features.holiday_window),@arps_decline&supersession_map: Settingholiday_window={"pre_holiday_days": 7, "post_holiday_days": 3}expands point calendar holidays into asymmetric pre-holiday build-up ([-7..-1]) and post-holiday slump ([+1..+3]) distance covariates (pre_holiday_window,post_holiday_window,days_to_next_holiday,days_since_prev_holiday), whilesupersession_mapsplices multi-generationv1 -> v2 -> v3SKU histories and@arps_declinefits hyperbolic decline curves with analytical Estimated Ultimate Recovery (eur_total,eur_remaining). - Full-Chain Counterfactual Scenario Simulation (
f.simulate_scenarios(..., unit_cost=..., reconcile=True, include_inventory_impact=True)): Propagates price and promo shocks through@monotonebase models, the winning ensemble, andmint_nonneghierarchy reconciliation (0.000000coherence discrepancy) into gross-margin delta (gross_margin_delta) and inventory replenishment shifts (delta_reorder_point,delta_safety_stock,delta_order_qty).
flowchart TD
subgraph Guardrails["1. Causal Feature & Learner Guardrails"]
HW["features.holiday_window
pre_holiday_days=7 · post_holiday_days=3 · degree_day_cols"]
MC["features.monotonic_constraints
{price_index: -1, promo_flag: +1, hdd_*: +1, cdd_*: +1}
lightgbm@monotone · regression_lags@monotone"]
end
subgraph DML["2. Double/Debiased ML Decomposition (f.promo_elasticity_df)"]
RES["Cross-Fitted Nuisance Residualization
Partial out seasonal + trend + holiday W_t"]
DEC["Unit Decomposition
baseline_yhat · incremental_promo_lift · adstock_effect
pull_forward_dip · cannibalization_dip (-) · halo_lift (+)"]
RES --> DEC
end
subgraph Sim["3. Full-Chain Counterfactual Simulator (f.simulate_scenarios)"]
ENS["Base Models -> Winning Ensemble (inverse_error · nnls)"]
REC["Hierarchy Reconciliation (mint_nonneg · 0.000000 discrepancy)"]
FIN["Gross-Margin Delta (gross_margin_delta)
& Inventory Policy Shift (delta_reorder_point · delta_safety_stock · delta_order_qty)"]
ENS --> REC --> FIN
end
Guardrails --> DML & Sim
from scale_forecasting import (
compare_scenario_margin_curves,
summarize_promo_elasticity,
summarize_scenarios,
)
# 1. Load a 6-series slice from the BigQuery covariate benchmark table
panel_cov = client.query(
f"""
SELECT *
FROM `{DATASET}.{SOURCE_TABLE}`
WHERE ts_id IN ('s_000000', 's_000001', 's_000002', 's_000003', 's_000004', 's_000005')
ORDER BY ts_id, ds
"""
).to_dataframe()
print(f"Loaded covariate panel: {panel_cov.shape} across {panel_cov['ts_id'].nunique()} series")
# 2. Configure Track J Causal Guardrails (@monotone, monotonic_constraints & holiday_window)
cfg_causal = RunConfig(
run_name="nb05_act6_track_j_causal_guardrails",
python_runtime="vertex",
data={"source_table": SOURCE_TABLE, "horizon": HORIZON, "series_limit": 6},
models=[
"regression_lags",
"regression_lags@monotone",
"lightgbm",
"lightgbm@monotone",
],
features={
"holidays": ["US"],
"holiday_window": {"pre_holiday_days": 7, "post_holiday_days": 3},
"static_covariates": ["region", "category"],
"future_covariates": ["promo_flag", "price_index"],
"past_covariates": ["temperature"],
"exog_lags": {"promo_flag": [1, 7], "temperature": [7, 14]},
"monotonic_constraints": {"price_index": -1, "promo_flag": 1},
"on_unsupported_covariates": "fallback",
},
hierarchy={
"enabled": True,
"levels": [["region"], ["region", "category"]],
"reconciliation_methods": ["mint_nonneg"],
},
backtest={"enabled": True, "n_folds": 2, "horizon": HORIZON, "step": HORIZON},
ensemble={"enabled": True, "strategies": ["inverse_error", "nnls"]},
output={"floor": 0.0},
)
f_causal = Forecaster(cfg_causal, settings=settings)
# 3. Orthogonalized Double/Debiased ML Promo & Price Elasticity Decomposition (promo_elasticity_df)
print("--- Double/Debiased ML Promo Elasticity Decomposition (f_causal.promo_elasticity_df) ---")
el_df = f_causal.promo_elasticity_df(panel_cov)
display(
el_df[
[
"ts_id",
"ds",
"baseline_yhat",
"incremental_promo_lift",
"pull_forward_dip",
"cannibalization_effect",
"net_causal_elasticity",
]
].tail(8)
)
display(summarize_promo_elasticity(el_df))
f_causal.plot_promo_elasticity(el_df, ts_id="s_000000")
plt.show()
# 4. Full-Chain Counterfactual Scenario Simulation (unit_cost, reconcile=True, include_inventory_impact=True)
print("--- Full-Chain Counterfactual Scenario Simulation (f_causal.simulate_scenarios) ---")
scen_df = f_causal.simulate_scenarios(
scenarios={
"promo_push_10pct_off": {"promo_flag": ("=", 1.0), "price_index": ("*", 0.90)},
"price_increase_10pct": {"promo_flag": ("=", 0.0), "price_index": ("*", 1.10)},
},
data=panel_cov,
price_col="price_index",
unit_cost=85.0,
reconcile=True,
include_inventory_impact=True,
)
scen_summary = summarize_scenarios(scen_df)
display(
scen_summary[scen_summary["ts_id"].isin(["__total__", "s_000000"])][
[
"scenario",
"ts_id",
"model_type",
"delta_units",
"revenue_delta",
"gross_margin_delta",
"delta_reorder_point",
"delta_safety_stock",
"delta_order_qty",
]
]
)
display(compare_scenario_margin_curves(scen_df).head(10))
f_causal.plot_scenarios(scen_df, ts_id="__total__", model_type="ensemble_nnls", show_revenue=True)
plt.show()
Loaded covariate panel: (8760, 10) across 6 series --- Double/Debiased ML Promo Elasticity Decomposition (f_causal.promo_elasticity_df) ---
| ts_id | ds | baseline_yhat | incremental_promo_lift | pull_forward_dip | cannibalization_effect | net_causal_elasticity | |
|---|---|---|---|---|---|---|---|
| 8752 | s_000005 | 2024-12-23 | 260.9271 | 0.0 | -0.0 | -0.0 | -0.0 |
| 8753 | s_000005 | 2024-12-24 | 203.1534 | 0.0 | -0.0 | -0.0 | -0.0 |
| 8754 | s_000005 | 2024-12-25 | 168.3461 | 0.0 | 0.0 | -0.0 | 0.0 |
| 8755 | s_000005 | 2024-12-26 | 179.9181 | 0.0 | 0.0 | -0.0 | 0.0 |
| 8756 | s_000005 | 2024-12-27 | 227.6258 | 0.0 | 0.0 | -0.0 | -0.0 |
| 8757 | s_000005 | 2024-12-28 | 273.9311 | 0.0 | 0.0 | -0.0 | -0.0 |
| 8758 | s_000005 | 2024-12-29 | 285.6822 | 0.0 | 0.0 | -0.0 | 0.0 |
| 8759 | s_000005 | 2024-12-30 | 254.2908 | 0.0 | 0.0 | -0.0 | 0.0 |
| ts_id | promo_days | mean_baseline_demand | mean_causal_promo_lift | mean_naive_ols_lift | confounding_bias_pct | total_gross_causal_lift | total_pull_forward_dip | total_cannibalization_dip | total_net_incremental_units | net_to_gross_lift_ratio | |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | s_000000 | 106 | 186.4914 | 15.0970 | 32.5478 | 115.59 | 1600.2820 | 0.0000 | 0.0000 | 1600.2820 | 1.0000 |
| 1 | s_000001 | 0 | 2.4811 | 0.0000 | 0.0000 | 0.00 | 0.0000 | -15.2048 | 0.0000 | -15.2048 | 0.0000 |
| 2 | s_000002 | 104 | 135.2489 | 5.0061 | 13.3563 | 166.80 | 520.6344 | -119.8392 | -396.5632 | 4.2320 | 0.0081 |
| 3 | s_000003 | 1120 | 77.1946 | 2.8184 | 0.5080 | -81.98 | 3156.6331 | -505.9132 | 0.0000 | 2650.7175 | 0.8397 |
| 4 | s_000004 | 1120 | 39.5800 | 37.9015 | 0.9602 | -97.47 | 42449.6760 | -565.1700 | -190.1952 | 41694.3190 | 0.9822 |
| 5 | s_000005 | 104 | 219.4927 | 15.2863 | 41.1699 | 169.33 | 1589.7752 | -33.3008 | 0.0000 | 1556.4744 | 0.9791 |
<Figure size 1200x550 with 2 Axes>
--- Full-Chain Counterfactual Scenario Simulation (f_causal.simulate_scenarios) ---
| scenario | ts_id | model_type | delta_units | revenue_delta | gross_margin_delta | delta_reorder_point | delta_safety_stock | delta_order_qty | |
|---|---|---|---|---|---|---|---|---|---|
| 0 | baseline | __total__ | regression_lags | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 |
| 11 | baseline | s_000000 | regression_lags | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 |
| 17 | baseline | __total__ | regression_lags@monotone | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 |
| 28 | baseline | s_000000 | regression_lags@monotone | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 |
| 34 | baseline | __total__ | lightgbm | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 |
| 45 | baseline | s_000000 | lightgbm | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 |
| 51 | baseline | __total__ | lightgbm@monotone | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 |
| 62 | baseline | s_000000 | lightgbm@monotone | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 |
| 68 | baseline | __total__ | ensemble_inverse_error | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 |
| 79 | baseline | s_000000 | ensemble_inverse_error | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 |
| 85 | baseline | __total__ | ensemble_nnls | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 |
| 96 | baseline | s_000000 | ensemble_nnls | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 |
| 102 | promo_push_10pct_off | __total__ | regression_lags | 898.633256 | -26215.494743 | -102599.321532 | 257.362513 | -0.041857 | 257.362513 |
| 113 | promo_push_10pct_off | s_000000 | regression_lags | -92.985867 | -54631.788464 | -46727.989751 | -58.589215 | -0.664727 | -58.589215 |
| 119 | promo_push_10pct_off | __total__ | regression_lags@monotone | 2245.571331 | 88199.546109 | -102674.017051 | 790.249419 | 1.080544 | 790.249419 |
| 130 | promo_push_10pct_off | s_000000 | regression_lags@monotone | 816.098671 | 41654.252314 | -27714.134710 | 290.351198 | 0.826712 | 290.351198 |
| 136 | promo_push_10pct_off | __total__ | lightgbm | 643.938544 | -45881.192215 | -100615.968459 | 229.275135 | 1.025574 | 229.275135 |
| 147 | promo_push_10pct_off | s_000000 | lightgbm | 18.771147 | -39206.199645 | -40801.747149 | 3.447784 | 0.154479 | 3.447784 |
| 153 | promo_push_10pct_off | __total__ | lightgbm@monotone | 651.939563 | -44741.892457 | -100156.755340 | 215.162767 | 0.135855 | 215.162767 |
| 164 | promo_push_10pct_off | s_000000 | lightgbm@monotone | 30.697424 | -37659.878176 | -40269.159230 | 11.891602 | 0.180390 | 11.891602 |
| 170 | promo_push_10pct_off | __total__ | ensemble_inverse_error | 1167.929532 | -2760.140303 | -102034.150562 | 402.892304 | 1.677624 | 402.892304 |
| 181 | promo_push_10pct_off | s_000000 | ensemble_inverse_error | 206.919409 | -21075.250296 | -38663.400049 | 70.377975 | 0.505369 | 70.377975 |
| 187 | promo_push_10pct_off | __total__ | ensemble_nnls | 1150.680605 | -4083.528999 | -101891.380389 | 404.911982 | 2.173429 | 404.911982 |
| 198 | promo_push_10pct_off | s_000000 | ensemble_nnls | 164.261964 | -24790.479788 | -38752.746735 | 55.714172 | 0.664425 | 55.714172 |
| 204 | price_increase_10pct | __total__ | regression_lags | 788.732186 | 190171.188687 | 123128.952847 | 389.108415 | 0.089725 | 389.108415 |
| 215 | price_increase_10pct | s_000000 | regression_lags | 624.448974 | 125572.245158 | 72494.082403 | 264.858777 | 1.438153 | 264.858777 |
| 221 | price_increase_10pct | __total__ | regression_lags@monotone | -249.368374 | 82636.134291 | 103832.446120 | -86.243474 | -0.528159 | -86.243474 |
| 232 | price_increase_10pct | s_000000 | regression_lags@monotone | 113.596086 | 59461.180728 | 49805.513429 | 37.506063 | -0.402138 | 37.506063 |
| 238 | price_increase_10pct | __total__ | lightgbm | 591.643541 | 166209.935330 | 115920.234361 | 278.144292 | 1.921365 | 278.144292 |
| 249 | price_increase_10pct | s_000000 | lightgbm | 29.085158 | 44916.949710 | 42444.711249 | 8.710889 | 0.274289 | 8.710889 |
| 255 | price_increase_10pct | __total__ | lightgbm@monotone | -199.502365 | 80667.940563 | 97625.641547 | -94.945042 | -0.106552 | -94.945042 |
| 266 | price_increase_10pct | s_000000 | lightgbm@monotone | -84.662907 | 29903.830150 | 37100.177259 | -30.864726 | -0.063226 | -30.864726 |
| 272 | price_increase_10pct | __total__ | ensemble_inverse_error | 33.653332 | 109184.459615 | 106323.926406 | 35.749576 | 1.006513 | 35.749576 |
| 283 | price_increase_10pct | s_000000 | ensemble_inverse_error | -57.328586 | 35478.990061 | 40351.919832 | -19.336333 | 0.302522 | -19.336333 |
| 289 | price_increase_10pct | __total__ | ensemble_nnls | 118.420878 | 118106.585366 | 108040.810718 | 75.646297 | 2.550610 | 75.646297 |
| 300 | price_increase_10pct | s_000000 | ensemble_nnls | -51.485077 | 35424.308715 | 39800.540300 | -21.983850 | 0.777688 | -21.983850 |
| scenario | ts_id | model_type | n_steps | baseline_units | scenario_units | delta_units | delta_pct | baseline_revenue | scenario_revenue | ... | delta_reorder_point | reorder_point_delta | baseline_safety_stock | scenario_safety_stock | delta_safety_stock | safety_stock_delta | baseline_order_qty | scenario_order_qty | delta_order_qty | recommended_order_qty_delta | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | price_increase_10pct | __total__ | regression_lags | 14 | 10771.532236 | 11560.264422 | 788.732186 | 0.073224 | 1.053264e+06 | 1.243435e+06 | ... | 389.108415 | 389.108415 | 488.237861 | 488.327586 | 0.089725 | 0.089725 | 5802.602550 | 6191.710965 | 389.108415 | 389.108415 |
| 1 | price_increase_10pct | __total__ | lightgbm | 14 | 10489.450795 | 11081.094336 | 591.643541 | 0.056404 | 1.025670e+06 | 1.191880e+06 | ... | 278.144292 | 278.144292 | 252.012788 | 253.934153 | 1.921365 | 1.921365 | 5453.208575 | 5731.352866 | 278.144292 | 278.144292 |
| 2 | price_increase_10pct | __total__ | ensemble_nnls | 14 | 10775.125879 | 10893.546758 | 118.420878 | 0.010990 | 1.053612e+06 | 1.171719e+06 | ... | 75.646297 | 75.646297 | 190.108214 | 192.658823 | 2.550610 | 2.550610 | 5495.415248 | 5571.061545 | 75.646297 | 75.646297 |
| 3 | price_increase_10pct | __total__ | ensemble_inverse_error | 14 | 10795.065962 | 10828.719294 | 33.653332 | 0.003117 | 1.055563e+06 | 1.164747e+06 | ... | 35.749576 | 35.749576 | 188.386245 | 189.392758 | 1.006513 | 1.006513 | 5506.471740 | 5542.221316 | 35.749576 | 35.749576 |
| 4 | price_increase_10pct | __total__ | regression_lags@monotone | 14 | 11192.369515 | 10943.001140 | -249.368374 | -0.022280 | 1.094409e+06 | 1.177046e+06 | ... | -86.243474 | -86.243474 | 288.755545 | 288.227385 | -0.528159 | -0.528159 | 5722.588040 | 5636.344566 | -86.243474 | -86.243474 |
| 5 | price_increase_10pct | __total__ | lightgbm@monotone | 14 | 10443.544247 | 10244.041883 | -199.502365 | -0.019103 | 1.021187e+06 | 1.101855e+06 | ... | -94.945042 | -94.945042 | 280.840857 | 280.734305 | -0.106552 | -0.106552 | 5490.164955 | 5395.219913 | -94.945042 | -94.945042 |
| 6 | price_increase_10pct | region=NA | regression_lags | 14 | 4352.802029 | 5448.619068 | 1095.817039 | 0.251750 | 4.461978e+05 | 6.144123e+05 | ... | 460.571307 | 460.571307 | 361.920958 | 363.149559 | 1.228601 | 1.228601 | 2448.205917 | 2908.777225 | 460.571307 | 460.571307 |
| 7 | price_increase_10pct | region=NA/category=enterprise | regression_lags | 14 | 3788.300036 | 4412.749010 | 624.448974 | 0.164836 | 4.466674e+05 | 5.722396e+05 | ... | 264.858777 | 264.858777 | 183.151682 | 184.589835 | 1.438153 | 1.438153 | 2028.333178 | 2293.191956 | 264.858777 | 264.858777 |
| 8 | price_increase_10pct | s_000000 | regression_lags | 14 | 3788.300036 | 4412.749010 | 624.448974 | 0.164836 | 4.466674e+05 | 5.722396e+05 | ... | 264.858777 | 264.858777 | 183.151682 | 184.589835 | 1.438153 | 1.438153 | 2028.333178 | 2293.191956 | 264.858777 | 264.858777 |
| 9 | price_increase_10pct | region=NA | regression_lags@monotone | 14 | 4587.534413 | 5237.678771 | 650.144358 | 0.141720 | 4.702454e+05 | 5.906266e+05 | ... | 221.014812 | 221.014812 | 339.668661 | 338.883238 | -0.785422 | -0.785422 | 2493.604028 | 2714.618840 | 221.014812 | 221.014812 |
10 rows × 29 columns
<Figure size 1000x500 with 1 Axes>
Act 7 · Cluster-Pooled @similarity_global, Multi-Modal Retail Similarity, Assortment Substitution, Emerging Trend Sensing & Similarity-Synthesized Hierarchy Reconciliation¶
When a panel spans heterogeneous behavioral regimes (e.g., smooth seasonal staples alongside promotional spikes or coincidental seasonal twins across unrelated categories), training a single monolithic global model (@global) across every series simultaneously can suffer from negative cross-series transfer. Track P (v1.8.0) weaves multi-modal time-series similarity, dynamical systems phase-space embeddings, stockout-aware substitute recommendation, and emerging trend sensing directly into covariate feature engineering, global pooling, cold-start transfer, and hierarchical reconciliation:
- 7-Lens + Multi-Modal Retail Similarity (
f.similarity_df(),f.cluster_by_similarity_df(),f.find_similar_series_df(),f.plot_similarity_map()): Computes pairwise[0, 1]similarity across the 7 canonicalSIMILARITY_METHODS—"hybrid","physics_attractor","spectral_phase","elastic_dtw","minirocket","structural_signature", and"foundation_latent"— fused withtext_cols(TF-IDF N-gram LSAsemantic_sim),attribute_cols(Gower/Jaccard similarity), andhierarchy_cols(Wu–Palmer Lowest Common Ancestorhierarchy_sim), plus 3-mode digital-twin analog retrieval ("full_history","recent_window", and"launch_prefix"withwithin_hierarchy_levelscoping). - Cluster-Pooled Global Training (
@similarity_global&features.similarity_cluster_feature=True) & Cold-Start Transfer (@similarity_cold_start): Partitions the panel into homogeneous behavioral clusters (cluster_by_similarity_df) before fitting one global model per cluster (tide@similarity_global,lightgbm@similarity_global), and transfers donor trajectories across Day-0 to Day-14 NPI launches (cold_start_matching="hybrid"). - Stockout-Aware Substitute Recommendation (
f.recommend_substitutes_df()) & Emerging Trend Breakout Sensing (f.emerging_trends_df()): Ranks in-stock assortment substitutes (substitution_score,stock_status,substitution_rationale) and identifies accelerating bellwether leaders and lagging co-promotion twins (trend_regime,leading_bellwether_ts_id,lag_behind_leader,recommended_merchandising_action). - Similarity-Synthesized Hierarchy Reconciliation (
hierarchy.similarity_hierarchy=True+mint_shrink): Synthesizes behavioral cluster rollups (similarity_cluster_id=cluster_0..K/__sim_cluster_0..K__$\rightarrow$__total__) and reconciles bottom series, cluster nodes, and grand total via Minimum-Trace shrinkage (mint_shrink).
flowchart TD
subgraph SimEngine["1. 7-Lens + Multi-Modal Similarity Engine (similarity.py)"]
HYB["compute_similarity_matrix(method='hybrid')
text_cols (semantic_sim) · attribute_cols · hierarchy_cols (Wu-Palmer LCA)"]
CLU["cluster_by_similarity_df(n_clusters=3)
Medoids · Silhouette · Behavioral Archetypes"]
TWIN["find_similar_series_df(mode='launch_prefix')
recommend_substitutes_df() · detect_emerging_trends_df()"]
HYB --> CLU & TWIN
end
subgraph Pooling["2. Fold-Safe Cluster Features & @similarity_global Pooling"]
FEAT["features.similarity_cluster_feature=True
similarity_cluster_id · similarity_to_medoid"]
MOD["tide@similarity_global · lightgbm@similarity_global
theta@similarity_cold_start (cold_start_matching='hybrid')"]
FEAT --> MOD
end
subgraph Hier["3. Similarity-Synthesized Hierarchy & Ensemble Smoothing"]
SH["hierarchy.similarity_hierarchy=True
similarity_cluster_id=cluster_0..K -> __total__ (mint_shrink)"]
ENS["ensemble.similarity_smoothing=0.25
Laplacian Neighbor Weight Regularization"]
SH --> ENS
end
SimEngine --> Pooling --> Hier
import logging
import warnings
from scale_forecasting.engines.vertex_engine import execute_panel
warnings.filterwarnings("ignore")
logging.getLogger("pytorch_lightning").setLevel(logging.ERROR)
logging.getLogger("lightning.pytorch").setLevel(logging.ERROR)
# 1. Pairwise Similarity Matrix, Behavioral Clustering & Digital-Twin Analog Search on the Covariate Panel
print("--- 1. Hybrid Similarity Matrix, Behavioral Clusters & Digital-Twin Analog Search ---")
sim_pairs_df = f_causal.similarity_df(panel_cov, method="hybrid")
clusters_cov_df = f_causal.similarity_clusters_df(panel_cov, n_clusters=3, method="hybrid")
analogs_cov_df = f_causal.find_similar_series_df(
"s_000000",
data=panel_cov,
top_k=3,
method="hybrid",
mode="launch_prefix",
prefix_len=14,
)
display(clusters_cov_df)
display(analogs_cov_df)
f_causal.plot_similarity_map(panel_cov, method="hybrid")
plt.show()
# 2. Cluster-Pooled @similarity_global, @similarity_cold_start & Similarity-Synthesized Hierarchy (mint_shrink)
print("--- 2. Cluster-Pooled @similarity_global & Similarity Hierarchy Reconciliation ---")
cfg_sim_global = RunConfig(
run_name="nb05_act7_track_p_similarity_global",
python_runtime="gce",
data={"source_table": SOURCE_TABLE, "horizon": HORIZON, "series_limit": 6},
models=[
"theta",
"theta@similarity_cold_start",
"lightgbm",
"lightgbm@similarity_global",
"tide@global",
"tide@similarity_global",
],
model_params={
"lightgbm@similarity_global": {"training_mode": "local"},
"tide": {"max_steps": 15, "input_size": 14, "random_seed": 42},
},
features={
"holidays": ["US"],
"static_covariates": ["region", "category"],
"future_covariates": ["promo_flag", "price_index"],
"past_covariates": ["temperature"],
"similarity_cluster_feature": True,
"similarity_n_clusters": 2,
"cold_start_transfer": True,
"cold_start_matching": "similarity",
"cold_start_min_obs": 60,
"on_unsupported_covariates": "fallback",
},
hierarchy={
"enabled": True,
"similarity_hierarchy": True,
"similarity_n_clusters": 2,
"reconciliation_methods": ["mint_shrink"],
},
backtest={"enabled": True, "n_folds": 2, "horizon": HORIZON, "step": HORIZON},
)
sim_results, sim_status_df = execute_panel(panel_cov, cfg_sim_global)
sim_rows = [
{
"model_type": r.model_type,
"n_nodes": 1,
"wape": float(r.metrics.get("wape", float("nan"))),
"mae": float(r.metrics.get("mae", float("nan"))),
"has_similarity_clusters_diag": bool(
isinstance(r.diagnostics, dict) and "similarity_clusters" in r.diagnostics
),
}
for r in sim_results
if r.status == "ok"
]
sim_summary_df = (
pd.DataFrame(sim_rows)
.groupby("model_type", as_index=False)
.agg(
n_nodes=("n_nodes", "sum"),
mean_wape=("wape", "mean"),
mean_mae=("mae", "mean"),
cells_with_cluster_diag=("has_similarity_clusters_diag", "sum"),
)
.sort_values("mean_wape")
.reset_index(drop=True)
)
display(sim_summary_df)
sample_diag = next(
r.diagnostics["similarity_clusters"]
for r in sim_results
if isinstance(r.diagnostics, dict) and "similarity_clusters" in r.diagnostics
)
print("Sample forecast_metadata.fit_diagnostics['similarity_clusters']:", sample_diag)
# 3. Multi-Modal Semantic/Hierarchy Similarity, Assortment Substitution & Emerging Trend Sensing on panel_cov
print("--- 3. Multi-Modal Similarity, recommend_substitutes_df & detect_emerging_trends_df on panel_cov ---")
cov_titles = {
"s_000000": ("Sparkling Citrus Beverage 12pk", "FizzCraft"),
"s_000001": ("Sparkling Berry Beverage 12pk", "FizzCraft"),
"s_000002": ("Sparkling Lime Beverage 12pk", "FizzCraft"),
"s_000003": ("Artisan Sea Salt Crackers 8oz", "CrispBake"),
"s_000004": ("Artisan Rosemary Crackers 8oz", "CrispBake"),
"s_000005": ("Organic Cold Brew Coffee 48oz", "RoastCraft"),
}
panel_cov_mm = panel_cov.copy()
panel_cov_mm["product_title"] = panel_cov_mm["ts_id"].map(lambda s: cov_titles.get(str(s), ("Retail SKU", "BrandX"))[0])
panel_cov_mm["brand"] = panel_cov_mm["ts_id"].map(lambda s: cov_titles.get(str(s), ("Retail SKU", "BrandX"))[1])
mm_analogs_cov_df = f_causal.find_similar_series_df(
"s_000000",
data=panel_cov_mm,
top_k=3,
method="hybrid",
mode="launch_prefix",
prefix_len=14,
text_cols=["product_title"],
attribute_cols=["brand", "region", "category"],
hierarchy_cols=["region", "category"],
)
display(
mm_analogs_cov_df[
["query_ts_id", "neighbor_ts_id", "rank", "similarity_score", "semantic_sim", "hierarchy_sim", "velocity_sim", "matching_mode"]
]
)
inv_cov_df = pd.DataFrame(
[
{"ts_id": "s_000000", "on_hand": 0.0, "safety_stock": 45.0},
{"ts_id": "s_000001", "on_hand": 340.0, "safety_stock": 50.0},
{"ts_id": "s_000002", "on_hand": 210.0, "safety_stock": 45.0},
{"ts_id": "s_000003", "on_hand": 160.0, "safety_stock": 40.0},
{"ts_id": "s_000004", "on_hand": 95.0, "safety_stock": 40.0},
{"ts_id": "s_000005", "on_hand": 280.0, "safety_stock": 50.0},
]
)
subs_cov_df = f_causal.recommend_substitutes_df(
panel_cov_mm,
inventory_df=inv_cov_df,
query_ts_id="s_000000",
top_k=3,
text_cols=["product_title"],
attribute_cols=["brand", "region", "category"],
hierarchy_cols=["region", "category"],
require_in_stock=True,
)
display(subs_cov_df)
trends_cov_df = f_causal.emerging_trends_df(
panel_cov_mm,
window=14,
top_k_related=2,
max_lag=7,
text_cols=["product_title"],
attribute_cols=["brand", "region", "category"],
hierarchy_cols=["region", "category"],
)
display(trends_cov_df)
--- 1. Hybrid Similarity Matrix, Behavioral Clusters & Digital-Twin Analog Search ---
ts_id similarity_cluster_id cluster_int_id cluster_id cluster_medoid_ts_id medoid_ts_id is_medoid similarity_to_medoid cluster_silhouette silhouette_score cluster_size cluster_archetype cluster_label
s_000000 cluster_0 0 cluster_0 s_000000 s_000000 True 1.000000 0.0 0.0 6 high_velocity_trending cluster_0:high_velocity_trending
s_000001 cluster_0 0 cluster_0 s_000000 s_000000 False 0.192147 0.0 0.0 6 high_velocity_trending cluster_0:high_velocity_trending
s_000002 cluster_0 0 cluster_0 s_000000 s_000000 False 0.410031 0.0 0.0 6 high_velocity_trending cluster_0:high_velocity_trending
s_000003 cluster_0 0 cluster_0 s_000000 s_000000 False 0.273869 0.0 0.0 6 high_velocity_trending cluster_0:high_velocity_trending
s_000004 cluster_0 0 cluster_0 s_000000 s_000000 False 0.472295 0.0 0.0 6 high_velocity_trending cluster_0:high_velocity_trending
s_000005 cluster_0 0 cluster_0 s_000000 s_000000 False 0.482838 0.0 0.0 6 high_velocity_trending cluster_0:high_velocity_trending
query_ts_id ts_id neighbor_ts_id match_ts_id rank similarity_score similarity distance physics_sim spectral_sim shape_sim structural_sim semantic_sim hierarchy_sim optimal_lag lag_correlation scale_ratio level_offset velocity_sim acceleration_sim matching_mode method
s_000000 s_000000 s_000005 s_000005 1 0.752684 0.752684 0.497308 0.850388 0.919293 0.709057 0.680954 0.0 0.0 0 0.941045 1.150235 25.807714 0.943927 0.877381 launch_prefix hybrid
s_000000 s_000000 s_000002 s_000002 2 0.694860 0.694860 0.552395 0.505077 0.938677 0.583919 0.730891 0.0 0.0 0 0.879956 2.344701 113.319000 0.894984 0.824505 launch_prefix hybrid
s_000000 s_000000 s_000003 s_000003 3 0.646848 0.646848 0.594266 0.512357 0.916154 0.449329 0.631842 0.0 0.0 0 0.779206 2.961275 130.865214 0.857008 0.712723 launch_prefix hybrid
--- 2. Cluster-Pooled @similarity_global & Similarity Hierarchy Reconciliation ---
model_type n_nodes mean_wape mean_mae cells_with_cluster_diag
lightgbm@similarity_global_mint_shrink 9 0.255422 17.227375 0
lightgbm_mint_shrink 9 0.255422 17.227375 0
lightgbm 9 0.259532 18.289749 0
lightgbm@similarity_global 9 0.259532 18.289749 0
tide@similarity_global_mint_shrink 9 0.261210 27.777744 6
tide@similarity_global 9 0.269486 29.777260 6
theta@similarity_cold_start_mint_shrink 9 0.278938 24.756785 0
theta_mint_shrink 9 0.278938 24.756785 0
theta 9 0.283178 25.960205 0
theta@similarity_cold_start 9 0.283178 25.960205 0
tide@global_mint_shrink 9 0.304238 26.345315 6
tide@global 9 0.305554 26.934979 6
Sample forecast_metadata.fit_diagnostics['similarity_clusters']: {'similarity_cluster_id': 'cluster_0', 'cluster_id': 'cluster_0', 'cluster_int_id': 0, 'cluster_medoid_ts_id': 's_000005', 'similarity_to_medoid': 0.742828, 'cluster_silhouette': 0.284395, 'cluster_size': 3, 'cluster_archetype': 'smooth_seasonal_sync', 'method': 'hybrid'}
--- 3. Multi-Modal Similarity, recommend_substitutes_df & detect_emerging_trends_df on panel_cov ---
query_ts_id neighbor_ts_id rank similarity_score semantic_sim hierarchy_sim velocity_sim matching_mode
s_000000 s_000002 1 0.720909 0.645194 0.0 0.894984 launch_prefix
s_000000 s_000005 2 0.575740 0.000000 0.0 0.943927 launch_prefix
s_000000 s_000003 3 0.547560 0.116667 0.0 0.857008 launch_prefix
query_ts_id substitute_ts_id rank substitution_score similarity_score semantic_sim hierarchy_sim available_units stock_status substitution_rationale
s_000000 s_000002 1 0.501913 0.477426 0.645194 0.0 165.0 in_stock_surplus Substitute s_000002 for s_000000: semantic_sim=0.65, hierarchy_sim=0.00, trajectory_sim=0.63, stock=in_stock_surplus (available_units=165.0)
s_000000 s_000001 2 0.462014 0.322694 0.632231 0.0 290.0 in_stock_surplus Substitute s_000001 for s_000000: semantic_sim=0.63, hierarchy_sim=0.00, trajectory_sim=0.30, stock=in_stock_surplus (available_units=290.0)
s_000000 s_000004 3 0.352366 0.365819 0.116667 0.5 55.0 in_stock_surplus Substitute s_000004 for s_000000: semantic_sim=0.12, hierarchy_sim=0.50, trajectory_sim=0.46, stock=in_stock_surplus (available_units=55.0)
ts_id trend_score trend_regime recent_velocity recent_acceleration breakout_zscore hurst_exp similarity_cluster_id leading_bellwether_ts_id lag_behind_leader co_promote_candidates recommended_merchandising_action
s_000001 0.516445 stable 0.095925 -0.201546 0.318381 0.549764 cluster_0 0 s_000002,s_000000 hold_baseline
s_000002 0.358140 steady_growth 0.016149 -0.002266 1.286056 0.800103 cluster_0 s_000002 0 s_000000,s_000001 promote_trend_leader
s_000000 0.317085 stable 0.029788 -0.002569 0.634874 0.749792 cluster_0 0 s_000002,s_000004 hold_baseline
s_000003 0.152401 stable 0.021301 -0.007637 -0.098751 0.643783 cluster_1 0 s_000004,s_000000 hold_baseline
s_000005 0.138941 stable 0.013095 0.000101 0.100359 0.753701 cluster_0 0 s_000001,s_000004 hold_baseline
s_000004 0.132651 stable -0.006138 -0.043415 -0.245820 0.740267 cluster_1 0 s_000000,s_000003 hold_baseline
Where next¶
- Next in Track 3 (Accuracy & Post-Processing):
06_hierarchical_reconciliation.ipynb— reconcile forecasts acrosstotal -> region -> category -> itemhierarchies with all 7 Hyndman FPP3 estimators. - Documentation: Configuration reference (
features) · Models & explainability reference · Cost estimates & controls