|
Run in Colab Enterprise |
Run in Colab Enterprise: click the badge to import this notebook, pick a runtime, and Run all. The Terraform-deployed templates already carry the
SF_*run identity in their env, so there's no environment cell to fill in. Runs on thesf-mainruntime template (Python 3.11) — or fully locally with just a clone; this notebook needs no cloud at all. Seedocs/notebook_runtimes.mdfor the per-notebook template mapping and the headless acceptance harness.
00 · Interactive Model Playground: Zero-GCP Sandbox for Models, Metrics, Regimes & SDK Helpers¶
Welcome to the Interactive Model Playground (00_model_playground.ipynb) for scale-forecasting. This notebook is your zero-cloud entry point: explore all 37 forecasting models across 5 model families and 21 evaluation metrics, inspect deterministic synthetic time-series archetypes, compare local vs. global vs. hybrid training regimes, test 3-tier exogenous covariates, Two-Tier Feature Attributions, all 9 hierarchical & cross-temporal reconciliation methods, Track J Causal Guardrails (@monotone), Double/Debiased ML Promo Elasticity (promo_elasticity_df()), Moving-Holiday Windows (holiday_window) & Full-Chain Margin/Inventory What-If (simulate_scenarios()), and Track K Cross-Temporal Reconciliation (THieF), Compositional Simplex (@transform_clr / @transform_ilr) & Top-Down Goal-Seek QP (allocate_target) — all 100% offline in local memory with zero Google Cloud setup.
At a glance¶
| Dimension | Details |
|---|---|
| Learning outcomes | Discover all 37 models & 21 metrics, generate synthetic archetypes, fit local/global/hybrid regimes, reconcile a 3-level hierarchy across FPP3 & cross-temporal THieF methods, inspect Two-Tier feature attributions, run Track J causal guardrails (@monotone, holiday_window) + Double-ML promo_elasticity_df() + full-chain simulate_scenarios(), and run Track K temporal_reconcile_df(), @transform_clr/@transform_ilr simplex forecasting, and allocate_target() top-down Goal-Seek QP. |
| Prerequisites | Python 3.11 + scale-forecasting (no Google Cloud project, credentials, or billing required). |
| Estimated time | ~3–5 minutes end-to-end on local CPU. |
| Estimated run cost | \$0.00 (runs 100% locally in memory; zero Google Cloud services billed). |
| Ongoing cost | None (\$0 when idle; no cloud resources created). |
[!NOTE] Identical Execution Contract (
worker.run_cell&worker.run_panel): Everything you run in this playground executes the exact same pure Python worker functions that run across Dataproc Spark executors, Vertex AI Ray actors, Vertex CustomJob worker pools, GKE Indexed Jobs, and GCE VMs at 100,000-series scale.
flowchart TD
subgraph Local["Pure Offline Layer (Zero GCP Credentials Required)"]
GEN["sample_data()
Synthetic Multi-Archetype Panel"] --> VAL["validate_panel()
Schema & Frequency Guard"]
VAL --> CELL["worker.run_cell()
Local Per-Series Fit + Backtest"]
VAL --> PANEL["worker.run_panel()
Global & Hybrid Cross-Series Fit"]
CELL & PANEL --> CAL["calibration.py
Residual Conformal Intervals"]
CAL --> MET["metrics.compute_metrics()
21-Metric Evaluation Panel"]
MET --> REC["reconciliation.py · temporal_reconciliation.py · simplex.py
9 Hierarchy/THieF Methods + Simplex Closure + 9 Ensembles"]
end
REC --> SDK["Explanatory & Decision Workbench Helpers
explain() · promo_elasticity_df() · simulate_scenarios() · temporal_reconcile_df() · allocate_target()"]
What You Will Explore in This Notebook¶
| Section | Platform Surface | Key Functions & Classes |
|---|---|---|
| Act 2 · Catalog Discovery | All 37 Models (5 families) & 21 Metrics (16 point + 5 interval) | model_catalog(), metric_catalog(), available_models() |
| Act 3 · Synthetic Archetypes | Deterministic daily/weekly/monthly generator with covariates & hierarchy | sample_data(with_exog=True, with_hierarchy=True) |
| Act 4 · Fit, Backtest & Intervals | Rolling-origin CV, conformal prediction bands, and forecast plotting | run_model(), summarize(), build_predictions_frame(), plot_forecasts_frame() |
| Act 5 · Training Regimes | local (per-series) vs. global (cross-series) vs. hybrid (local trend + global residual) |
worker.run_cell(), worker.run_panel() |
| Act 6 · Hierarchy & Reconciliation | Bottom-up rollup (S matrix) & all 8 FPP3 reconciliation estimators |
build_hierarchy(), reconcile_forecasts(), verify_coherence(), plot_hierarchy_frame() |
| Act 7 · Multi-Model Bake-Off, Attributions & SDK | Head-to-head comparison + Two-Tier Feature Attributions + inverse_error & nnls ensembles + Forecaster.explain() |
bakeoff(), build_attributions_frame(), plot_attributions(), Forecaster.explain(validate_data=False) |
| Act 8 · Forecaster Workbench & Track J Causal Guardrails | FVA, horizon decay, inventory policy, @monotone sign constraints, holiday_window, Double/Debiased ML promo_elasticity_df(), and full-chain margin/inventory simulate_scenarios() |
fva_df(), inventory_policy_df(), promo_elasticity_df(), simulate_scenarios(unit_cost=..., reconcile=True, include_inventory_impact=True) |
| Act 9 · Glass-Box Auto-Forecaster | Automated data profiling, ConfigBlueprint compilation, and bounded autofocus |
Forecaster.build_config(), Forecaster.auto(autofocus=True) |
Act 10 · Track K: Cross-Temporal (THieF), Compositional Simplex & Top-Down Goal-Seek QP |
Temporal & simultaneous cross_temporal_mint reconciliation, @transform_clr / @transform_ilr simplex closure, and constrained allocate_target() QP with margin/inventory impact |
temporal_reconcile_df(), forecast_simplex_panel(), verify_simplex(), allocate_target(), plot_goal_seek() |
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 = []
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
Act 2 · Discover the 37-Model & 21-Metric Catalogs¶
model_catalog() inspects the live model factory (src/scale_forecasting/models/) and returns one row per registered model with its family (statistical, ml, deep_learning, automl, native), runtime compatibility (python_local, vertex_automl, bigquery_sql), GPU capability, 3-tier covariate support (future_covariates, past_covariates, static_covariates), explainability (supports_explainability), and global_mode / hybrid_mode flags.
metric_catalog() inspects the metric factory (src/scale_forecasting/metrics/) across all 21 evaluation metrics (16 point accuracy metrics + 5 prediction interval metrics).
import pandas as pd
from scale_forecasting import metric_catalog, model_catalog
from scale_forecasting.playground import available_models
pd.set_option("display.max_columns", 25)
pd.set_option("display.width", 140)
models_df = model_catalog()
print(f"Total registered models: {len(models_df)} | Locally available in this kernel: {len(available_models(installed_only=True))}")
print("Models by family:", models_df.groupby("family")["model"].count().to_dict())
display(models_df)
Total registered models: 37 | Locally available in this kernel: 31
Models by family: {'automl': 4, 'deep_learning': 8, 'ml': 5, 'native': 2, 'statistical': 18}
| model | family | runtime | package | package_url | available | local | spark | ray | gpu | vertex_automl | bigquery | exog | future_covariates | past_covariates | static_covariates | explainability | monotonic_constraints | global_mode | hybrid_mode | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | arima_plus | native | bigquery | bigquery-ml | https://cloud.google.com/bigquery/docs/bqml-in... | True | False | False | False | False | False | True | True | True | False | False | True | False | False | False |
| 1 | timesfm | native | bigquery | bigquery-ml | https://cloud.google.com/bigquery/docs/bqml-in... | True | False | False | False | False | False | True | True | True | True | False | False | False | False | False |
| 2 | chronos2 | deep_learning | python | chronos-forecasting | https://github.com/amazon-science/chronos-fore... | True | True | True | True | True | False | False | True | True | True | True | False | False | True | False |
| 3 | chronos_bolt | deep_learning | python | chronos-forecasting | https://github.com/amazon-science/chronos-fore... | True | True | True | True | True | False | False | False | False | False | False | False | False | True | False |
| 4 | neuralprophet | deep_learning | python | neuralprophet | https://neuralprophet.com/ | True | True | True | True | True | False | False | False | False | False | False | False | False | True | True |
| 5 | patchtst | deep_learning | python | neuralforecast | https://nixtlaverse.nixtla.io/neuralforecast/i... | True | True | True | True | True | False | False | False | False | False | False | False | False | True | False |
| 6 | tft | deep_learning | python | neuralforecast | https://nixtlaverse.nixtla.io/neuralforecast/i... | True | True | True | True | True | False | False | True | True | True | True | False | False | True | False |
| 7 | tide | deep_learning | python | neuralforecast | https://nixtlaverse.nixtla.io/neuralforecast/i... | True | True | True | True | True | False | False | True | True | True | True | False | False | True | False |
| 8 | timesfm_torch | deep_learning | python | timesfm | https://github.com/google-research/timesfm | True | True | True | True | True | False | False | True | True | True | True | False | False | True | False |
| 9 | tsmixer | deep_learning | python | neuralforecast | https://nixtlaverse.nixtla.io/neuralforecast/i... | True | True | True | True | True | False | False | True | True | True | True | False | False | True | False |
| 10 | catboost | ml | python | catboost | https://catboost.ai/ | True | True | True | True | False | False | False | True | True | True | False | True | True | False | False |
| 11 | lightgbm | ml | python | lightgbm | https://lightgbm.readthedocs.io/ | True | True | True | True | False | False | False | True | True | True | False | True | True | False | False |
| 12 | random_forest | ml | python | scikit-learn | https://scikit-learn.org/ | True | True | True | True | False | False | False | True | True | True | False | True | True | False | False |
| 13 | regression_lags | ml | python | numpy | https://numpy.org/ | True | True | True | True | False | False | False | True | True | True | False | True | True | False | False |
| 14 | xgboost | ml | python | xgboost | https://xgboost.readthedocs.io/ | True | True | True | True | False | False | False | True | True | True | False | True | True | False | False |
| 15 | auto_arima | statistical | python | statsforecast | https://nixtlaverse.nixtla.io/statsforecast/ | True | True | True | True | False | False | False | True | True | True | False | False | False | False | False |
| 16 | auto_ces | statistical | python | statsforecast | https://nixtlaverse.nixtla.io/statsforecast/ | True | True | True | True | False | False | False | False | False | False | False | False | False | False | False |
| 17 | auto_theta | statistical | python | statsforecast | https://nixtlaverse.nixtla.io/statsforecast/ | True | True | True | True | False | False | False | False | False | False | False | False | False | False | False |
| 18 | autoets | statistical | python | statsmodels | https://www.statsmodels.org/ | True | True | True | True | False | False | False | False | False | False | False | False | False | False | False |
| 19 | croston | statistical | python | numpy | https://numpy.org/ | True | True | True | True | False | False | False | False | False | False | False | False | False | False | False |
| 20 | fft | statistical | python | scipy | https://scipy.org/ | True | True | True | True | False | False | False | False | False | False | False | False | False | False | False |
| 21 | holtwinters | statistical | python | statsmodels | https://www.statsmodels.org/ | True | True | True | True | False | False | False | False | False | False | False | False | False | False | False |
| 22 | kalman | statistical | python | statsmodels | https://www.statsmodels.org/ | True | True | True | True | False | False | False | True | True | True | False | False | False | False | False |
| 23 | naive_drift | statistical | python | numpy | https://numpy.org/ | True | True | True | True | False | False | False | False | False | False | False | False | False | False | False |
| 24 | naive_mean | statistical | python | numpy | https://numpy.org/ | True | True | True | True | False | False | False | False | False | False | False | False | False | False | False |
| 25 | naive_moving_average | statistical | python | numpy | https://numpy.org/ | True | True | True | True | False | False | False | False | False | False | False | False | False | False | False |
| 26 | naive_seasonal | statistical | python | numpy | https://numpy.org/ | True | True | True | True | False | False | False | False | False | False | False | False | False | False | False |
| 27 | prophet | statistical | python | prophet | https://facebook.github.io/prophet/ | True | True | True | True | False | False | False | True | True | True | False | False | False | False | False |
| 28 | sarimax | statistical | python | statsmodels | https://www.statsmodels.org/ | True | True | True | True | False | False | False | True | True | True | False | False | False | False | False |
| 29 | stl_bagging | statistical | python | statsmodels | https://www.statsmodels.org/ | True | True | True | True | False | False | False | False | False | False | False | False | False | False | False |
| 30 | tbats | statistical | python | statsforecast | https://nixtlaverse.nixtla.io/statsforecast/ | True | True | True | True | False | False | False | False | False | False | False | False | False | False | False |
| 31 | theta | statistical | python | statsmodels | https://www.statsmodels.org/ | True | True | True | True | False | False | False | False | False | False | False | False | False | False | False |
| 32 | ucm | statistical | python | statsmodels | https://www.statsmodels.org/ | True | True | True | True | False | False | False | True | True | True | False | False | False | False | False |
| 33 | vertex_l2l | automl | vertex_automl | google-cloud-pipeline-components | https://docs.cloud.google.com/gemini-enterpris... | True | False | False | False | True | True | False | True | True | True | True | True | False | True | False |
| 34 | vertex_seq2seq | automl | vertex_automl | google-cloud-pipeline-components | https://docs.cloud.google.com/gemini-enterpris... | True | False | False | False | True | True | False | True | True | True | True | True | False | True | False |
| 35 | vertex_tft | automl | vertex_automl | google-cloud-pipeline-components | https://docs.cloud.google.com/gemini-enterpris... | True | False | False | False | True | True | False | True | True | True | True | True | False | True | False |
| 36 | vertex_tide | automl | vertex_automl | google-cloud-pipeline-components | https://docs.cloud.google.com/gemini-enterpris... | True | False | False | False | True | True | False | True | True | True | True | True | False | True | False |
metrics_df = metric_catalog()
print(f"Total registered metrics: {len(metrics_df)} "
f"({(metrics_df['kind'] == 'point').sum()} point + {(metrics_df['kind'] == 'interval').sum()} interval)")
display(metrics_df)
Total registered metrics: 21 (16 point + 5 interval)
| metric | kind | direction | needs_intervals | needs_train_history | needs_seasonal_period | mean_optimal | |
|---|---|---|---|---|---|---|---|
| 0 | mae | point | lower | False | False | False | False |
| 1 | rmse | point | lower | False | False | False | True |
| 2 | mse | point | lower | False | False | False | True |
| 3 | mape | point | lower | False | False | False | False |
| 4 | smape | point | lower | False | False | False | False |
| 5 | wape | point | lower | False | False | False | False |
| 6 | mase | point | lower | False | True | False | False |
| 7 | rmsse | point | lower | False | True | False | True |
| 8 | bias | point | zero | False | False | False | True |
| 9 | coverage | interval | higher | True | False | False | False |
| 10 | pinball | interval | lower | True | False | False | False |
| 11 | mase_seasonal | point | lower | False | True | True | False |
| 12 | maape | point | lower | False | False | False | False |
| 13 | interval_score | interval | lower | True | False | False | False |
| 14 | interval_width | interval | lower | True | False | False | False |
| 15 | ope | point | lower | False | False | False | False |
| 16 | rmsle | point | lower | False | False | False | False |
| 17 | msse | point | lower | False | True | False | True |
| 18 | msis | interval | lower | True | True | True | False |
| 19 | r2 | point | higher | False | False | False | True |
| 20 | cv | point | lower | False | False | False | True |
Act 3 · Deterministic Synthetic Panel with Exogenous Covariates & Hierarchy¶
sample_data() calls the exact same deterministic panel generator (scale_forecasting.data_gen.generator.generate_panel) used to seed the 100,000-series BigQuery benchmark tables. Passing with_exog=True and with_hierarchy=True adds:
- Static Hierarchy Attributes:
region(NORTH,SOUTH, ...) andcategory(A,B, ...) - Known-Future Covariates (
future_covariates):promo_flagandprice_index - Observed-Past Covariate (
past_covariates):temperature(known historically, unknown in the future horizon)
import matplotlib.pyplot as plt
from scale_forecasting.playground import sample_data
panel = sample_data(n_series=6, history=365, freq="D", with_exog=True, with_hierarchy=True)
print(f"Panel shape: {panel.shape} | Unique series: {panel['ts_id'].nunique()}")
print("Columns:", list(panel.columns))
display(panel.head())
fig, axes = plt.subplots(2, 3, figsize=(14, 5.5), sharex=True)
for ax, (ts_id, g) in zip(axes.flat, panel.groupby("ts_id")):
archetype = g["archetype"].iloc[0]
region = g["region"].iloc[0]
cat = g["category"].iloc[0]
ax.plot(pd.to_datetime(g["ds"]), g["y"], lw=1.1, color="#1967D2")
ax.set_title(f"{ts_id} ({archetype} · {region}/{cat})", fontsize=9.5)
ax.grid(alpha=0.25)
fig.suptitle("Synthetic Time-Series Archetypes (Daily Panel)", fontsize=12)
fig.tight_layout()
plt.show()
Panel shape: (2190, 9) | Unique series: 6 Columns: ['ts_id', 'archetype', 'region', 'category', 'ds', 'y', 'promo_flag', 'price_index', 'temperature']
| ts_id | archetype | region | category | ds | y | promo_flag | price_index | temperature | |
|---|---|---|---|---|---|---|---|---|---|
| 0 | s_000000 | smooth_seasonal | NA | enterprise | 2021-01-01 | 233.786 | 1 | 107.555 | 9.374 |
| 1 | s_000000 | smooth_seasonal | NA | enterprise | 2021-01-02 | 217.825 | 1 | 108.811 | 7.711 |
| 2 | s_000000 | smooth_seasonal | NA | enterprise | 2021-01-03 | 229.825 | 0 | 110.024 | 11.371 |
| 3 | s_000000 | smooth_seasonal | NA | enterprise | 2021-01-04 | 209.891 | 0 | 111.190 | 8.136 |
| 4 | s_000000 | smooth_seasonal | NA | enterprise | 2021-01-05 | 161.967 | 0 | 112.304 | 6.044 |
Act 4 · Single-Series Fit, Rolling-Origin Backtest & Conformal Intervals¶
Let's run a single model (theta) on s_000000 with backtest=True (3 rolling-origin folds of 28 days each). Under the hood, run_model() validates the panel with validate_panel(), builds a RunConfig, and calls worker.run_cell():
- Rolling-Origin Backtest (
backtest_cell): Fits the model on each fold's training window, predicts the validation horizon, and scores all 21 evaluation metrics. - Conformal Interval Calibration (
calibration.py): Uses out-of-fold signed residuals to calibrate empirical prediction bands (yhat_lower,yhat_upper) at the nominal0.80level. - Visual Inspection (
build_predictions_frame+plot_forecasts_frame): Overlays historical actuals, out-of-fold backtest predictions, and the future forecast fan chart.
from scale_forecasting import (
build_predictions_frame,
explain_forecast_frame,
plot_forecast_explanation,
plot_forecasts_frame,
)
from scale_forecasting.playground import run_model, summarize
run = run_model("theta", data=panel, ts_id="s_000000", horizon=28, backtest=True)
print(summarize(run))
# Convert the single-cell result into the standard long-format predictions frame used by the SDK
pred_rows = (
run.result.predictions.rename(columns={"ds": "forecast_date"})
.assign(ts_id=run.result.ts_id, model_type=run.result.model_type)
.to_dict("records")
)
oof_rows = (
run.result.oof.rename(columns={"ds": "forecast_date"})
.assign(ts_id=run.result.ts_id, model_type=run.result.model_type)
.to_dict("records")
)
hist_rows = run.series[["ts_id", "ds", "y"]].to_dict("records")
pf = build_predictions_frame(pred_rows, oof_rows=oof_rows, history_rows=hist_rows)
fig = plot_forecasts_frame(pf, history_tail=120)
plt.show()
# 4-panel Forecast Explainability & Structural Attribution (Trend + Regime Shift + Seasonality + Exog + Uncertainty)
exog_df = run.series[["ts_id", "ds", "promo_flag", "price_index", "temperature"]]
exp_df = explain_forecast_frame(pf, covariate_df=exog_df, seasonal_period=7)
display(exp_df.tail(10))
plot_forecast_explanation(exp_df, history_tail=120)
plt.show()
model : theta series : s_000000 (365 obs) engine : spark status : ok forecast : 28 steps horizon : 2022-01-01 → 2022-01-28 metrics : mae=20.992, rmse=27.562, mse=868.198, mape=0.100, smape=0.109, wape=0.108, mase=0.806, rmsse=0.901, bias=-19.168, coverage=0.988, pinball=13.928, mase_seasonal=1.539, maape=0.099, interval_score=278.556, interval_width=278.461, ope=0.098, rmsle=0.138, msse=0.925, msis=20.459, r2=0.372, cv=0.141
| 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 | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 383 | s_000000 | theta | forecast | 2022-01-19 | NaN | 229.731851 | 212.769441 | 291.902236 | 283.046109 | -75.702006 | -42.500641 | 4.050408 | NaN | 79.132795 | 4.437616 | 0.008648 | -0.395856 |
| 384 | s_000000 | theta | forecast | 2022-01-20 | NaN | 241.982758 | 222.942752 | 303.211413 | 283.473299 | -75.702006 | -34.427255 | 4.050408 | NaN | 80.268661 | 4.437616 | 0.008648 | -0.395856 |
| 385 | s_000000 | theta | forecast | 2022-01-21 | NaN | 285.889898 | 265.627669 | 345.896330 | 283.913297 | -75.702006 | 1.917987 | 4.050408 | NaN | 80.268661 | 4.437616 | 0.008648 | -0.395856 |
| 386 | s_000000 | theta | forecast | 2022-01-22 | NaN | 326.950255 | 306.688027 | 386.956688 | 283.356285 | -75.702006 | 33.684912 | 4.050408 | NaN | 80.268661 | 4.437616 | 0.008648 | -0.395856 |
| 387 | s_000000 | theta | forecast | 2022-01-23 | NaN | 336.288757 | 320.952732 | 396.376869 | 283.710607 | -75.702006 | 41.596991 | 4.050408 | NaN | 75.424137 | 4.437616 | 0.008648 | -0.395856 |
| 388 | s_000000 | theta | forecast | 2022-01-24 | NaN | 310.767908 | 277.204897 | 370.856020 | 283.045334 | -75.702006 | 20.950685 | 4.050408 | NaN | 93.651123 | 4.437616 | 0.008648 | -0.395856 |
| 389 | s_000000 | theta | forecast | 2022-01-25 | NaN | 251.882568 | 223.912853 | 305.535526 | 282.183880 | -75.702006 | -21.222680 | 4.050408 | NaN | 81.622673 | 4.437616 | 0.008648 | -0.395856 |
| 390 | s_000000 | theta | forecast | 2022-01-26 | NaN | 232.212102 | 198.194206 | 316.815728 | 274.722817 | -75.702006 | -42.500641 | 4.050408 | NaN | 118.621521 | 4.437616 | 0.008648 | -0.395856 |
| 391 | s_000000 | theta | forecast | 2022-01-27 | NaN | 237.325853 | 208.331255 | 326.952776 | 262.409629 | -75.702006 | -34.427255 | 4.050408 | NaN | 118.621521 | 4.437616 | 0.008648 | -0.395856 |
| 392 | s_000000 | theta | forecast | 2022-01-28 | NaN | 279.859717 | 250.865118 | 369.486640 | 250.320060 | -75.702006 | 1.917987 | 4.050408 | NaN | 118.621521 | 4.437616 | 0.008648 | -0.395856 |
Act 5 · Training Regimes Offline: local vs. global vs. hybrid¶
scale-forecasting supports three distinct training regimes via model_params[model]['training_mode']:
local: Fits an independent model instance per(ts_id, model)cell (worker.run_cell).global: Pools all series in the panel into a single cross-series neural network (worker.run_panelwithtraining_mode='global'), supported by all 5deep_learningarchitectures (neuralprophet,tide,tsmixer,patchtst,tft).hybrid(Local + Global Shared-Plus-Series Network): Combines shared cross-series trend/seasonality representations with per-series local parameters (worker.run_panelwithtraining_mode='hybrid', supported byneuralprophet).
from scale_forecasting.config import RunConfig
from scale_forecasting.worker import run_cell, run_panel
regime_cfg = RunConfig.model_validate({
"run_name": "playground-regimes",
"data": {"source_table": "playground", "freq": "D", "horizon": 14},
"models": ["neuralprophet"],
"model_params": {"neuralprophet": {"epochs": 15}},
"backtest": {"enabled": True, "n_folds": 2, "horizon": 14, "step": 14},
})
# 1. Local per-series fit on all 6 series
local_results = [
run_cell(g.reset_index(drop=True), "neuralprophet", regime_cfg)
for _, g in panel.groupby("ts_id", sort=True)
]
# 2. Global pooled fit across all 6 series simultaneously
global_results = run_panel(panel, "neuralprophet", regime_cfg, params={"training_mode": "global", "epochs": 15})
# 3. Hybrid local+global fit across all 6 series
hybrid_results = run_panel(panel, "neuralprophet", regime_cfg, params={"training_mode": "hybrid", "epochs": 15})
comparison_rows = []
for mode_label, res_list in [("local", local_results), ("global", global_results), ("hybrid", hybrid_results)]:
for r in res_list:
comparison_rows.append({
"training_mode": mode_label,
"ts_id": r.ts_id,
"wape": r.metrics.get("wape"),
"mae": r.metrics.get("mae"),
"mase": r.metrics.get("mase"),
"coverage": r.metrics.get("coverage"),
})
regime_df = pd.DataFrame(comparison_rows)
display(regime_df.groupby("training_mode")[["wape", "mae", "mase", "coverage"]].mean().reset_index())
| training_mode | wape | mae | mase | coverage | |
|---|---|---|---|---|---|
| 0 | global | 0.504413 | 23.290220 | 1.680554 | 0.738095 |
| 1 | hybrid | 0.386277 | 22.470124 | 1.126287 | 0.672619 |
| 2 | local | 0.406539 | 22.152474 | 1.110474 | 0.964286 |
Act 6 · Hierarchical Aggregation & All 7 FPP3 Reconciliation Methods Offline¶
When hierarchy.enabled=True, build_hierarchy() rolls the bottom-level series (ts_id) up every level of the tree (__total__ $\rightarrow$ region $\rightarrow$ region/category $\rightarrow$ ts_id) and constructs the summing matrix $S$. After base models forecast every node independently, reconcile_forecasts() projects the incoherent base forecasts $\hat{y}$ onto the coherent subspace $\tilde{y} = S G \hat{y}$ using any of the 7 FPP3 reconciliation estimators:
bottom_up,top_down,middle_out,ols,wls_struct,wls_var,mint_shrink
from scale_forecasting import (
build_hierarchy,
build_hierarchy_frame,
plot_hierarchy_frame,
reconcile_forecasts,
verify_coherence,
)
hier_cfg = RunConfig.model_validate({
"run_name": "playground-hierarchy",
"data": {"source_table": "playground", "freq": "D", "horizon": 14},
"models": ["theta"],
"hierarchy": {
"enabled": True,
"levels": [["region"], ["region", "category"]],
"reconciliation_methods": ["bottom_up", "top_down", "middle_out", "ols", "wls_struct", "wls_var", "mint_shrink"],
"middle_level": ["region"],
},
"backtest": {"enabled": True, "n_folds": 2, "horizon": 14, "step": 14},
})
full_panel, spec = build_hierarchy(panel, hier_cfg)
print(f"Hierarchy nodes: {spec.n_nodes} total ({spec.n_bottom} bottom + {spec.n_aggregated} aggregate) | S shape: {spec.summing_matrix.shape}")
# Fit a fast statistical model ('theta') on every node in the hierarchy
node_cells = [
run_cell(g.reset_index(drop=True), "theta", hier_cfg)
for _, g in full_panel.groupby("ts_id", sort=True)
]
base_preds = pd.concat([
c.predictions.rename(columns={"ds": "forecast_date"}).assign(ts_id=c.ts_id, model_type=c.model_type)
for c in node_cells
], ignore_index=True)
base_oof = pd.concat([
c.oof.rename(columns={"ds": "forecast_date"}).assign(ts_id=c.ts_id, model_type=c.model_type)
for c in node_cells if c.oof is not None
], ignore_index=True)
# Compare all 7 FPP3 reconciliation methods and verify exact mathematical coherence
methods = ["bottom_up", "top_down", "middle_out", "ols", "wls_struct", "wls_var", "mint_shrink"]
coherence_rows = []
for m in methods:
rec_df = reconcile_forecasts(
base_preds, spec, m,
history_df=full_panel, oof_df=base_oof,
middle_level=["region"] if m == "middle_out" else None,
)
max_discrepancy = verify_coherence(rec_df, spec)
coherence_rows.append({"method": m, "max_coherence_error": max_discrepancy, "coherent": max_discrepancy < 1e-6})
display(pd.DataFrame(coherence_rows))
# Visualize node rollups across hierarchy levels for mint_shrink
mint_df = reconcile_forecasts(base_preds, spec, "mint_shrink", history_df=full_panel, oof_df=base_oof)
hf = build_hierarchy_frame(mint_df.to_dict("records"))
display(hf)
plot_hierarchy_frame(mint_df)
plt.show()
Hierarchy nodes: 17 total (6 bottom + 11 aggregate) | S shape: (17, 6)
| method | max_coherence_error | coherent | |
|---|---|---|---|
| 0 | bottom_up | 1.136868e-13 | True |
| 1 | top_down | 1.136868e-13 | True |
| 2 | middle_out | 1.136868e-13 | True |
| 3 | ols | 3.410605e-13 | True |
| 4 | wls_struct | 3.410605e-13 | True |
| 5 | wls_var | 1.136868e-13 | True |
| 6 | mint_shrink | 2.273737e-13 | True |
| model_type | level | n_series | n_points | mean_yhat | sum_yhat | max_coherence_residual | |
|---|---|---|---|---|---|---|---|
| 0 | theta_mint_shrink | total | 1 | 14 | 830.535936 | 11627.503106 | 2.273737e-13 |
| 1 | theta_mint_shrink | aggregate | 10 | 140 | 166.107187 | 23255.006212 | 2.273737e-13 |
| 2 | theta_mint_shrink | bottom | 6 | 84 | 138.422656 | 11627.503106 | 2.273737e-13 |
Act 7 · Multi-Model Bake-Off, Two-Tier Feature Attributions, Ensemble Weights & Forecaster.explain()¶
bakeoff() runs multiple candidate models head-to-head on a single series and combines them using both:
- Calculated Ensembling (
inverse_error): Weights each model inversely proportional to its validation loss. - Learned Stacking (
nnls): Fits non-negative least squares weights across out-of-fold backtest predictions.
We also inspect Two-Tier Feature Attributions (build_attributions_frame() and plot_attributions() — Tier 1 global driver importance and Tier 2 per-horizon-step TreeSHAP attributions for xgboost), visualize learned stacking weights with plot_ensemble_weights(), and preview Forecaster.explain(validate_data=False) on a 5-family RunConfig before any cloud job is launched.
from scale_forecasting import (
Forecaster,
build_attributions_frame,
build_ensemble_weights_frame,
plot_attributions,
plot_ensemble_weights,
)
from scale_forecasting.ensembler import fit_learned
from scale_forecasting.playground import bakeoff
bo = bakeoff(data=panel, ts_id="s_000000", models=["theta", "holtwinters", "stl_bagging", "xgboost"], horizon=28, n_folds=2)
display(bo.leaderboard[["model", "kind", "status", "wape", "mae", "rmse", "mase", "coverage", "interval_score"]])
# Fit learned stackers (nnls, ridge, xgb) on the bake-off base models to inspect and plot stacking weights
stack_cfg = bo.config.model_copy(update={"ensemble": bo.config.ensemble.model_copy(update={"strategies": ["nnls", "ridge", "xgb"]})})
oof_frames = []
xgb_cell = None
for m in ["theta", "holtwinters", "stl_bagging", "xgboost"]:
c = run_cell(bo.series, m, stack_cfg)
if m == "xgboost":
xgb_cell = c
if c.oof is not None:
oof_frames.append(c.oof.rename(columns={"ds": "forecast_date"}).assign(ts_id="s_000000", model_type=m))
# Inspect Two-Tier Feature Attributions (Tier 1 global + Tier 2 per-horizon-step TreeSHAP) on xgboost
global_attr_df = build_attributions_frame(
[{"ts_id": "s_000000", "model_type": "xgboost", "fit_diagnostics": xgb_cell.diagnostics}],
level="global",
)
local_attr_df = build_attributions_frame(
[
{"ts_id": "s_000000", "model_type": "xgboost", "forecast_date": row["ds"], "yhat": row["yhat"], "explanations": exp}
for row, exp in zip(xgb_cell.predictions.to_dict("records"), xgb_cell.explanations or [])
],
level="local",
)
display(global_attr_df.head(8))
plot_attributions(global_attr_df, model_type="xgboost", ts_id="s_000000", title="Tier 1 Global TreeSHAP Importance (xgboost)")
plt.show()
plot_attributions(local_attr_df, model_type="xgboost", ts_id="s_000000", title="Tier 2 Local Per-Step TreeSHAP Attributions (xgboost)")
plt.show()
learned_w, _, _ = fit_learned(pd.concat(oof_frames, ignore_index=True), stack_cfg)
weight_rows = [
{"ts_id": "s_000000", "model_type": f"ensemble_{strat}", "is_ensemble": True, "best_params": wmap}
for strat, wmap in learned_w.items()
]
w_df = build_ensemble_weights_frame(weight_rows)
display(w_df)
plot_ensemble_weights(w_df)
plt.show()
# Preview Forecaster.explain() on a 5-family production RunConfig (no cloud needed with validate_data=False)
preview_cfg = RunConfig.model_validate({
"run_name": "enterprise-preview",
"python_runtime": "spark",
"data": {"source_table": "source_series_iceberg", "horizon": 28, "series_limit": 500},
"models": ["theta", "autoets", "lightgbm", "xgboost", "neuralprophet", "vertex_tide", "arima_plus", "timesfm"],
"compute": {
"families": {
"deep_learning": {"runtime": "ray", "hardware": "gpu", "gpu_type": "L4", "min_workers": 1, "max_workers": 2},
"automl": {"runtime": "vertex_automl", "automl_mode": "tabular_workflow", "hardware": "gpu", "gpu_type": "L4"},
},
},
"features": {"holidays": ["US"], "future_covariates": ["promo_flag"]},
"backtest": {"enabled": True, "n_folds": 2, "horizon": 28, "step": 28},
"ensemble": {"enabled": True, "strategies": ["inverse_error", "nnls", "ridge"]},
})
plan_df = Forecaster(preview_cfg).explain(validate_data=False)
display(plan_df)
| model | kind | status | wape | mae | rmse | mase | coverage | interval_score | |
|---|---|---|---|---|---|---|---|---|---|
| 0 | holtwinters | base | ok | 0.098104 | 19.716912 | 26.835893 | 0.755259 | 0.500000 | 119.839309 |
| 1 | ensemble_inverse_error | ensemble | ok | 0.106172 | 21.544101 | 29.359942 | 0.825276 | 0.821429 | 97.503710 |
| 2 | xgboost | base | ok | 0.112572 | 22.841938 | 31.155169 | 0.874991 | 0.053571 | 224.679197 |
| 3 | stl_bagging | base | ok | 0.113094 | 23.052544 | 30.493329 | 0.883072 | 0.375000 | 178.833948 |
| 4 | theta | base | ok | 0.115866 | 23.499630 | 31.542060 | 0.900184 | 0.982143 | 283.769321 |
| 5 | ensemble_nnls | ensemble | ok | 0.115866 | 23.499630 | 31.542060 | 0.900184 | 0.785714 | 109.867593 |
| ts_id | model_type | compute_engine | feature | importance | |
|---|---|---|---|---|---|
| 0 | s_000000 | xgboost | None | lag_7 | 0.862970 |
| 1 | s_000000 | xgboost | None | month | 0.032247 |
| 2 | s_000000 | xgboost | None | lag_14 | 0.031003 |
| 3 | s_000000 | xgboost | None | dow | 0.018567 |
| 4 | s_000000 | xgboost | None | doy | 0.016951 |
| 5 | s_000000 | xgboost | None | lag_1 | 0.011887 |
| 6 | s_000000 | xgboost | None | lag_28 | 0.007921 |
| 7 | s_000000 | xgboost | None | lag_3 | 0.006987 |
| ts_id | ensemble_model | strategy | base_model | weight | wape | |
|---|---|---|---|---|---|---|
| 0 | s_000000 | ensemble_nnls | nnls | holtwinters | 0.000000 | None |
| 1 | s_000000 | ensemble_nnls | nnls | stl_bagging | 0.000000 | None |
| 2 | s_000000 | ensemble_nnls | nnls | theta | 1.085770 | None |
| 3 | s_000000 | ensemble_nnls | nnls | xgboost | 0.000000 | None |
| 4 | s_000000 | ensemble_ridge | ridge | holtwinters | 0.416270 | None |
| 5 | s_000000 | ensemble_ridge | ridge | stl_bagging | -0.330450 | None |
| 6 | s_000000 | ensemble_ridge | ridge | theta | 1.114132 | None |
| 7 | s_000000 | ensemble_ridge | ridge | xgboost | -0.102504 | None |
| 8 | s_000000 | ensemble_xgb | xgb | holtwinters | 0.000000 | None |
| 9 | s_000000 | ensemble_xgb | xgb | stl_bagging | 0.033383 | None |
| 10 | s_000000 | ensemble_xgb | xgb | theta | 0.848006 | None |
| 11 | s_000000 | ensemble_xgb | xgb | xgboost | 0.118612 | None |
| 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 | enterprise-preview-6669e98516e2 | statistical | sf-enterprise-preview-6669e98516e2-statistical-a1 | spark | None | NaN | cpu | None | theta, autoets | theta:local, autoets:local | 500 | 2 | 1000 | future(1) | |
| 1 | enterprise-preview-6669e98516e2 | ml | sf-enterprise-preview-6669e98516e2-ml-a1 | spark | None | NaN | cpu | None | lightgbm, xgboost | lightgbm:local, xgboost:local | 500 | 2 | 1000 | future(1) | |
| 2 | enterprise-preview-6669e98516e2 | deep_learning | sf-enterprise-preview-6669e98516e2-deep_learni... | ray | None | NaN | gpu | L4 | neuralprophet | neuralprophet:local | 500 | 2 | 500 | future(1) | |
| 3 | enterprise-preview-6669e98516e2 | automl | sf-enterprise-preview-6669e98516e2-automl-a1 | vertex_automl | None | NaN | gpu | L4 | vertex_tide | vertex_tide:global | 500 | 2 | 500 | future(1) | |
| 4 | enterprise-preview-6669e98516e2 | native | sf-enterprise-preview-6669e98516e2-native-a1 | bigquery | sql | 1.0 | sql | None | arima_plus, timesfm | arima_plus:local, timesfm:local | 500 | 2 | 1000 | future(1) | |
| 5 | enterprise-preview-6669e98516e2 | ensemble | sf-enterprise-preview-6669e98516e2-ensemble-a1 | bigquery | sql | 1.0 | sql | None | ensemble_inverse_error, ensemble_nnls, ensembl... | barrier | 500 | 2 | 1500 | future(1) | sf-enterprise-preview-6669e98516e2-statistical... |
Act 8 · Forecaster Workbench: Quantiles, FVA, Horizon Decay, Causal Guardrails (@monotone), Double-ML Promo Elasticity, Full-Chain Margin/Inventory What-If & Track L Prescriptive Decisioning¶
Beyond model fitting and stacking, the Forecaster Workbench (docs/forecaster_workbench.md) gives demand planners, merchandisers, and econometricians direct access to:
- Forecast Value Added (
bo.fva_df()): Step-by-step accuracy gain overnaive_seasonalwith Harvey–Leybourne–Newbold (1997) modified Diebold–Mariano (dm_pvalue) and paired Wilcoxon significance tests. - Lead-Time Horizon Decay (
bo.horizon_decay_df()) & Trigg Bias Audit (bo.bias_df()): Per-step error degradation ($h = 1 \dots H$) and chronic directional bias tracking signals. - Autocorrelation-Aware Time Rollups (
bo.rollup_time(freq="W")) & Exception Triage (bo.exceptions_df()): Weekly replenishment totals with empirical AR(1) error covariance intervals and composite severity triage. - Operational Inventory & Replenishment Policy Translation (
bo.inventory_policy_df()): Translates calibrated forward forecasts, empirical AR(1) residual autocorrelation ($\hat{\rho}_1$), and supplier lead-time variability ($\mu_L, \sigma_L$) into continuous-review $(s, S)$ and periodic-review $(R, S)$ Reorder Points (ROP), Safety Stock (SS), Order-Up-To Levels ($S$), Recommended Order Quantities ($Q$), and Newsvendor Holding vs. Stockout Cost tables. - Causal & Econometric Guardrails (
@monotone&holiday_window) + Double/Debiased ML Promo Elasticity (promo_elasticity_df()): Enforce non-positive price response (price_index: -1) and non-negative promo response (promo_flag: +1) on@monotonemodel variants (lightgbm@monotone,regression_lags@monotone), expand point holidays into asymmetric pre-holiday build-up and post-holiday slump ramps (holiday_window={"pre_holiday_days": 7, "post_holiday_days": 3}), and run Robinson (1988) / Chernozhukov et al. (2018) cross-fitted Double/Debiased ML residualization (promo_elasticity_df(),summarize_promo_elasticity()) to decomposebaseline_yhat,incremental_promo_lift,pull_forward_dip,cannibalization_effect, andnet_causal_elasticity. - Full-Chain Counterfactual Scenario Simulation (
simulate_scenarioswith Gross Margin, Reconciliation & Inventory $\Delta\text{ROP}$ / $\Delta\text{SS}$): Propagate price and promotional shocks (+,*,=) through@monotonebase models, the winning ensemble, andmint_nonneghierarchy reconciliation (0.000000coherence discrepancy) into gross-margin delta (gross_margin_delta,compare_scenario_margin_curves()) and operational replenishment shifts (delta_reorder_point,delta_safety_stock,delta_order_qty). - Track L — Cold-Start Transfer (
cold_start_transfer_df), Online ACI (aci_df), Copula Tail Risk (sample_trajectories,tail_risk_df), Portfolio Inventory Optimizer (optimize_inventory_df) & Prescriptive Price/Promo Optimizer (optimize_scenario): Synthesize NPI trajectories ondgp_19(cold_start_short_history), recalibrate intervals online under volatility drift ondgp_20(regime_shift_volatility_drift), simulate joint Gaussian/Student-$t$ copula paths for portfolio VaR/CVaR, solve multi-SKU working-capital-constrained replenishment, and optimize the forward price & promo calendar over Double-ML elasticities.
import warnings
warnings.filterwarnings("ignore")
from scale_forecasting import (
cold_start_transfer_df,
compare_scenario_margin_curves,
compute_aci_df,
compute_demand_profile,
load_benchmark,
plot_aci,
plot_cold_start_transfer,
plot_inventory_frontier,
plot_optimal_scenario,
plot_trajectories,
summarize_promo_elasticity,
summarize_scenarios,
)
from scale_forecasting.playground import run_model
# 1. Demand regime profile (Syntetos-Boylan-Croston ADI vs CV^2 classification)
profiles_df = pd.DataFrame(
[{"ts_id": tid, **compute_demand_profile(g["y"])} for tid, g in panel.groupby("ts_id")]
)
display(profiles_df)
# 2. Forecast Value Added (FVA) waterfall with modified Diebold-Mariano p-values, bias audit & weekly rollup
wb_bo = bakeoff(
data=panel,
ts_id="s_000000",
models=["naive_seasonal", "theta", "holtwinters", "xgboost"],
horizon=14,
n_folds=3,
floor=0.0,
quantiles=[0.10, 0.50, 0.90, 0.95],
)
display(wb_bo.fva_df()[["model_type", "fva_stage", "mean_metric", "fva_pct", "p_value_dm", "significant_at_05"]])
display(wb_bo.bias_df()[["ts_id", "model_type", "bias_pct", "tracking_signal", "bias_status"]])
display(wb_bo.rollup_time(freq="W").head(6))
# 3. Operational Inventory & Replenishment Policy (ROP, Safety Stock, Order-Up-To & Newsvendor Cost)
inv_policy_df = wb_bo.inventory_policy_df(
lead_time=7.0,
lead_time_std=1.0,
service_level=0.95,
on_hand=800.0,
on_order=200.0,
order_multiple=10.0,
)
display(
inv_policy_df[
[
"ts_id",
"model_type",
"lead_time_demand",
"error_autocorr_rho",
"safety_stock",
"naive_iid_safety_stock",
"reorder_point",
"recommended_order_qty",
"expected_total_cost",
]
]
)
# 4. Track J: @monotone Sign Guardrails, Moving-Holiday Windows (holiday_window),
# Double/Debiased ML Promo Elasticity (promo_elasticity_df) & Full-Chain Margin/Inventory What-If
f_causal = Forecaster(
RunConfig(
run_name="playground_track_j_demo",
data={"source_table": "local_panel", "horizon": 14},
models=["regression_lags", "regression_lags@monotone", "lightgbm@monotone"],
features={
"holidays": ["US"],
"holiday_window": {"pre_holiday_days": 7, "post_holiday_days": 3},
"future_covariates": ["promo_flag", "price_index"],
"exog_lags": {"promo_flag": [1, 7]},
"monotonic_constraints": {"price_index": -1, "promo_flag": 1},
},
hierarchy={
"enabled": True,
"levels": [["region"], ["region", "category"]],
"reconciliation_methods": ["mint_nonneg"],
},
backtest={"enabled": True, "n_folds": 2, "horizon": 14, "step": 14},
ensemble={"enabled": True, "strategies": ["inverse_error", "nnls"]},
output={"floor": 0.0},
)
)
print("--- Double/Debiased ML Promo & Price Elasticity Decomposition (promo_elasticity_df) ---")
el_df = f_causal.promo_elasticity_df(panel)
display(
el_df[
[
"ts_id",
"ds",
"baseline_yhat",
"incremental_promo_lift",
"pull_forward_dip",
"cannibalization_effect",
"net_causal_elasticity",
]
].tail(6)
)
display(summarize_promo_elasticity(el_df))
print("--- Full-Chain Scenario Simulation (Ensemble -> mint_nonneg Reconciliation -> Gross Margin -> Inventory ROP/SS) ---")
scen_df = f_causal.simulate_scenarios(
scenarios={
"promo_push_10pct_off": {"promo_flag": ("=", 1.0), "price_index": ("*", 0.90)},
"price_increase_8pct": {"promo_flag": ("=", 0.0), "price_index": ("*", 1.08)},
},
data=panel,
price_col="price_index",
unit_cost=65.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(8))
# 5. Track L: Cold-Start Transfer (dgp_11_cold_start_mixed), Online ACI (dgp_20_monthly_regime_drift_damped),
# Copula VaR/CVaR, Portfolio Inventory Optimizer & Prescriptive Price/Promo Calendar Optimizer
print("--- Track L.1: Cold-Start Analog Transfer on dgp_11_cold_start_mixed ---")
dgp11 = load_benchmark("dgp_11_cold_start_mixed")
cs_df = cold_start_transfer_df(dgp11.df, min_obs=14, method="auto", horizon=14)
display(
cs_df[
[
"ts_id",
"n_obs",
"is_cold_start",
"selected_archetype",
"donor_ts_ids",
"empirical_bayes_weight",
"yhat_mean",
"interval_width_80",
]
].head(6)
)
plot_cold_start_transfer(cs_df, panel_df=dgp11.df)
plt.show()
print("--- Track L.2: Online Adaptive Conformal Inference (ACI) on dgp_20_monthly_regime_drift_damped ---")
dgp20 = load_benchmark("dgp_20_monthly_regime_drift_damped")
f_dgp20 = Forecaster(
RunConfig(
run_name="playground_dgp20_aci",
data={"source_table": "local_dgp20", "freq": "MS", "horizon": 6},
models=["naive_seasonal", "theta"],
backtest={
"enabled": True,
"n_folds": 3,
"horizon": 6,
"step": 3,
"short_series": "shrink_train",
"min_train_floor": 24,
},
output={"calibration_method": "aci_normalized", "aci_gamma": 0.05},
)
)
aci_res_df = f_dgp20.aci_df(
data=dgp20.df[dgp20.df["ts_id"] == sorted(dgp20.df["ts_id"].unique())[0]],
gamma=0.05,
normalized=True,
)
display(aci_res_df.head(6))
plot_aci(aci_res_df)
plt.show()
print("--- Track L.3: Joint Copula Trajectories & Portfolio VaR / CVaR Tail Risk ---")
traj_df = f_causal.sample_trajectories(data=panel, n_paths=150, copula_type="auto")
risk_df = f_causal.tail_risk_df(traj_df, data=panel, window=7, alphas=(0.90, 0.95, 0.99))
display(risk_df.head(6))
plot_trajectories(traj_df, max_spaghetti_paths=25)
plt.show()
print("--- Track L.4: Multi-SKU Portfolio-Constrained Inventory Optimizer ---")
port_inv_df = f_causal.optimize_inventory_df(
data=panel,
trajectories_df=traj_df,
max_budget=35000.0,
target_portfolio_fill_rate=0.95,
uncertainty_source="copula",
)
display(port_inv_df.head(6))
plot_inventory_frontier(port_inv_df)
plt.show()
print("--- Track L.5: Prescriptive Price & Promotional Calendar Optimizer ---")
opt_scen = f_causal.optimize_scenario(
data=panel,
objective="risk_adjusted_profit",
price_col="price_index",
promo_col="promo_flag",
price_bounds=(-0.10, 0.10),
max_promo_days=4,
min_cooldown_days=2,
unit_cost=55.0,
risk_aversion_lambda=0.25,
)
display(opt_scen.schedule_df.head(8))
plot_optimal_scenario(opt_scen)
plt.show()
| ts_id | demand_class | adi | cv2 | zero_share | n_obs | |
|---|---|---|---|---|---|---|
| 0 | s_000000 | smooth | 1.0000 | 0.0635 | 0.0000 | 365 |
| 1 | s_000001 | intermittent | 2.6449 | 0.2716 | 0.6219 | 365 |
| 2 | s_000002 | smooth | 1.0000 | 0.0282 | 0.0000 | 365 |
| 3 | s_000003 | smooth | 1.0000 | 0.1287 | 0.0000 | 365 |
| 4 | s_000004 | smooth | 1.0224 | 0.1912 | 0.0219 | 365 |
| 5 | s_000005 | smooth | 1.0000 | 0.0891 | 0.0000 | 365 |
| model_type | fva_stage | mean_metric | fva_pct | p_value_dm | significant_at_05 | |
|---|---|---|---|---|---|---|
| 0 | naive_seasonal | Baseline | 0.113968 | 0.000000 | 1.000000 | False |
| 1 | holtwinters | Statistical | 0.083552 | 0.266884 | 0.000690 | True |
| 2 | theta | Statistical | 0.100899 | 0.114675 | 0.177091 | False |
| 3 | xgboost | Machine Learning | 0.105612 | 0.073315 | 0.120773 | False |
| 4 | ensemble_inverse_error | Ensemble | 0.094542 | 0.170450 | 0.000540 | True |
| 5 | ensemble_nnls | Ensemble | 0.097623 | 0.143416 | 0.071293 | False |
| ts_id | model_type | bias_pct | tracking_signal | bias_status | |
|---|---|---|---|---|---|
| 0 | s_000000 | theta | -0.094996 | -39.543011 | under_forecasting |
| 1 | s_000000 | ensemble_nnls | -0.091397 | -39.321576 | under_forecasting |
| 2 | s_000000 | ensemble_inverse_error | -0.085645 | -38.047537 | under_forecasting |
| 3 | s_000000 | naive_seasonal | -0.097732 | -36.016798 | under_forecasting |
| 4 | s_000000 | holtwinters | -0.070094 | -35.235300 | under_forecasting |
| 5 | s_000000 | xgboost | -0.085298 | -33.921426 | under_forecasting |
| ts_id | model_type | period_start | period_end | n_steps | y_true | yhat | yhat_lower | yhat_upper | naive_sum_lower | naive_sum_upper | error_autocorr_rho | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | s_000000 | ensemble_inverse_error | 2022-01-01 | 2022-01-02 | 2 | NaN | 605.535435 | 593.533738 | 646.678663 | 591.707310 | 652.939874 | 0.506568 |
| 1 | s_000000 | ensemble_inverse_error | 2022-01-03 | 2022-01-09 | 7 | NaN | 1880.846098 | 1803.196211 | 2129.059085 | 1757.128635 | 2287.049198 | 0.506568 |
| 2 | s_000000 | ensemble_inverse_error | 2022-01-10 | 2022-01-14 | 5 | NaN | 1326.086395 | 1317.625033 | 1569.962826 | 1313.570583 | 1687.874776 | 0.506568 |
| 3 | s_000000 | ensemble_nnls | 2022-01-01 | 2022-01-02 | 2 | NaN | 639.593638 | 628.235883 | 677.011081 | 626.431303 | 682.956162 | 0.489187 |
| 4 | s_000000 | ensemble_nnls | 2022-01-03 | 2022-01-09 | 7 | NaN | 1946.905894 | 1896.029690 | 2185.099067 | 1862.805106 | 2342.879365 | 0.489187 |
| 5 | s_000000 | ensemble_nnls | 2022-01-10 | 2022-01-14 | 5 | NaN | 1338.349126 | 1332.902735 | 1584.990301 | 1330.706931 | 1706.181282 | 0.489187 |
| ts_id | model_type | lead_time_demand | error_autocorr_rho | safety_stock | naive_iid_safety_stock | reorder_point | recommended_order_qty | expected_total_cost | |
|---|---|---|---|---|---|---|---|---|---|
| 0 | s_000000 | ensemble_inverse_error | 1854.929976 | 0.506568 | 507.036444 | 467.670138 | 2361.966420 | 1370.0 | 571.440300 |
| 1 | s_000000 | ensemble_nnls | 1927.929821 | 0.489187 | 518.022499 | 482.833987 | 2445.952320 | 1450.0 | 583.821806 |
| 2 | s_000000 | holtwinters | 1929.857505 | 0.472821 | 513.066168 | 481.847516 | 2442.923674 | 1450.0 | 578.235921 |
| 3 | s_000000 | naive_seasonal | 1839.363000 | 0.489468 | 484.116575 | 456.229809 | 2323.479575 | 1330.0 | 545.609145 |
| 4 | s_000000 | theta | 1928.085987 | 0.493423 | 495.330014 | 472.295665 | 2423.416001 | 1430.0 | 558.246918 |
| 5 | s_000000 | xgboost | 1698.736893 | 0.515082 | 498.396102 | 442.966928 | 2197.132995 | 1200.0 | 561.702461 |
--- Double/Debiased ML Promo & Price Elasticity Decomposition (promo_elasticity_df) ---
| ts_id | ds | baseline_yhat | incremental_promo_lift | pull_forward_dip | cannibalization_effect | net_causal_elasticity | |
|---|---|---|---|---|---|---|---|
| 2184 | s_000005 | 2021-12-26 | 269.8154 | 0.0 | -1.6951 | -0.0 | -0.006283 |
| 2185 | s_000005 | 2021-12-27 | 238.7986 | 0.0 | -1.4685 | -0.0 | -0.006150 |
| 2186 | s_000005 | 2021-12-28 | 188.7708 | 0.0 | -1.4685 | -0.0 | -0.007779 |
| 2187 | s_000005 | 2021-12-29 | 155.5111 | 0.0 | 0.0000 | -0.0 | 0.000000 |
| 2188 | s_000005 | 2021-12-30 | 168.0489 | 0.0 | 0.0000 | -0.0 | 0.000000 |
| 2189 | s_000005 | 2021-12-31 | 237.8268 | 0.0 | 0.0000 | -0.0 | -0.000000 |
| 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 | 27 | 222.3604 | 5.8665 | 26.1909 | 346.45 | 158.3955 | 0.0000 | 0.0000 | 158.3955 | 1.0000 |
| 1 | s_000001 | 26 | 2.6062 | 0.5102 | 1.0208 | 100.08 | 13.2652 | -16.8987 | 0.0000 | -3.6335 | -0.2739 |
| 2 | s_000002 | 281 | 136.8407 | 15.1938 | 1.0931 | -92.81 | 4269.4559 | 0.0000 | -43.5072 | 4225.9493 | 0.9898 |
| 3 | s_000003 | 273 | 37.3656 | 43.2270 | 0.2309 | -99.47 | 11800.9711 | -19.8640 | -226.1371 | 11554.9691 | 0.9792 |
| 4 | s_000004 | 27 | 76.2745 | 8.2976 | 7.6015 | -8.39 | 224.0352 | -66.0452 | 0.0000 | 157.9900 | 0.7052 |
| 5 | s_000005 | 26 | 223.8515 | 19.5251 | 46.9190 | 140.30 | 507.6526 | -60.2173 | 0.0000 | 447.4353 | 0.8814 |
--- Full-Chain Scenario Simulation (Ensemble -> mint_nonneg Reconciliation -> Gross Margin -> Inventory ROP/SS) ---
| 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@monotone | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 |
| 45 | baseline | s_000000 | lightgbm@monotone | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 |
| 51 | baseline | __total__ | ensemble_inverse_error | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 |
| 62 | baseline | s_000000 | ensemble_inverse_error | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 |
| 68 | baseline | __total__ | ensemble_nnls | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 |
| 79 | baseline | s_000000 | ensemble_nnls | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.000000 |
| 85 | promo_push_10pct_off | __total__ | regression_lags | 824.665701 | -49695.751935 | -103299.022499 | 263.445641 | -0.151506 | 263.445641 |
| 96 | promo_push_10pct_off | s_000000 | regression_lags | 105.974085 | -31515.247518 | -38403.563055 | 26.126736 | -0.047562 | 26.126736 |
| 102 | promo_push_10pct_off | __total__ | regression_lags@monotone | 2093.008374 | 67231.089206 | -68814.455126 | 700.535735 | -0.000031 | 700.535735 |
| 113 | promo_push_10pct_off | s_000000 | regression_lags@monotone | 598.153163 | 16637.305225 | -22242.650354 | 186.358274 | -0.001067 | 186.358274 |
| 119 | promo_push_10pct_off | __total__ | lightgbm@monotone | 374.026934 | -80774.319627 | -105086.070320 | 159.604305 | 1.131834 | 159.604305 |
| 130 | promo_push_10pct_off | s_000000 | lightgbm@monotone | 94.537965 | -30166.999652 | -36311.967390 | 47.902142 | 0.021676 | 47.902142 |
| 136 | promo_push_10pct_off | __total__ | ensemble_inverse_error | 1000.838612 | -29705.405554 | -94759.915313 | 351.118945 | 0.141861 | 351.118945 |
| 147 | promo_push_10pct_off | s_000000 | ensemble_inverse_error | 194.067470 | -22090.854356 | -34705.239931 | 67.235230 | 0.031794 | 67.235230 |
| 153 | promo_push_10pct_off | __total__ | ensemble_nnls | 1148.612029 | -15106.879012 | -89766.660912 | 409.071541 | 0.150110 | 409.071541 |
| 164 | promo_push_10pct_off | s_000000 | ensemble_nnls | 257.740826 | -15416.868002 | -32170.021685 | 91.534240 | 0.033213 | 91.534240 |
| 170 | price_increase_8pct | __total__ | regression_lags | 117.294763 | 110943.895045 | 103319.735465 | 65.062300 | 0.194911 | 65.062300 |
| 181 | price_increase_8pct | s_000000 | regression_lags | 47.069665 | 37916.717457 | 34857.189231 | 22.964241 | 0.065212 | 22.964241 |
| 187 | price_increase_8pct | __total__ | regression_lags@monotone | -254.828009 | 67575.435989 | 84139.256590 | -91.891325 | 0.000061 | -91.891325 |
| 198 | price_increase_8pct | s_000000 | regression_lags@monotone | -92.106418 | 20141.493065 | 26128.410229 | -33.902510 | 0.002570 | -33.902510 |
| 204 | price_increase_8pct | __total__ | lightgbm@monotone | -175.072168 | 70285.866505 | 81665.557409 | -60.696415 | -0.628372 | -60.696415 |
| 215 | price_increase_8pct | s_000000 | lightgbm@monotone | -77.714874 | 22364.118253 | 27415.585066 | -28.229635 | -0.026589 | -28.229635 |
| 221 | price_increase_8pct | __total__ | ensemble_inverse_error | -60.428641 | 87928.590730 | 91856.452427 | -18.899917 | -0.071263 | -18.899917 |
| 232 | price_increase_8pct | s_000000 | ensemble_inverse_error | -3.115639 | 31331.063271 | 31533.579836 | -0.186832 | -0.015699 | -0.186832 |
| 238 | price_increase_8pct | __total__ | ensemble_nnls | -160.586489 | 76262.083449 | 86700.205226 | -61.440747 | -0.078888 | -61.440747 |
| 249 | price_increase_8pct | s_000000 | ensemble_nnls | -46.423562 | 25895.079199 | 28912.610720 | -17.672105 | -0.016972 | -17.672105 |
| scenario | ts_id | model_type | n_steps | baseline_units | scenario_units | delta_units | delta_pct | baseline_revenue | scenario_revenue | revenue_delta | revenue_delta_pct | ... | baseline_reorder_point | scenario_reorder_point | 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_8pct | __total__ | regression_lags | 14 | 12233.965783 | 12351.260545 | 117.294763 | 0.009588 | 1.204370e+06 | 1.315314e+06 | 110943.895045 | 0.092118 | ... | 6117.662234 | 6182.724534 | 65.062300 | 65.062300 | 338.039953 | 338.234864 | 0.194911 | 0.194911 | 6117.662234 | 6182.724534 | 65.062300 | 65.062300 |
| 1 | price_increase_8pct | __total__ | ensemble_inverse_error | 14 | 11818.044807 | 11757.616165 | -60.428641 | -0.005113 | 1.167426e+06 | 1.255354e+06 | 87928.590730 | 0.075318 | ... | 5809.325118 | 5790.425201 | -18.899917 | -18.899917 | 151.416212 | 151.344949 | -0.071263 | -0.071263 | 5809.325118 | 5790.425201 | -18.899917 | -18.899917 |
| 2 | price_increase_8pct | __total__ | ensemble_nnls | 14 | 11729.210965 | 11568.624476 | -160.586489 | -0.013691 | 1.160069e+06 | 1.236331e+06 | 76262.083449 | 0.065739 | ... | 5785.222929 | 5723.782182 | -61.440747 | -61.440747 | 154.441296 | 154.362408 | -0.078888 | -0.078888 | 5785.222929 | 5723.782182 | -61.440747 | -61.440747 |
| 3 | price_increase_8pct | __total__ | regression_lags@monotone | 14 | 11853.062778 | 11598.234769 | -254.828009 | -0.021499 | 1.171394e+06 | 1.238970e+06 | 67575.435989 | 0.057688 | ... | 5969.933311 | 5878.041986 | -91.891325 | -91.891325 | 315.758970 | 315.759031 | 0.000061 | 0.000061 | 5969.933311 | 5878.041986 | -91.891325 | -91.891325 |
| 4 | price_increase_8pct | __total__ | lightgbm@monotone | 14 | 11203.294819 | 11028.222651 | -175.072168 | -0.015627 | 1.111009e+06 | 1.181295e+06 | 70285.866505 | 0.063263 | ... | 5721.792864 | 5661.096449 | -60.696415 | -60.696415 | 298.557346 | 297.928974 | -0.628372 | -0.628372 | 5721.792864 | 5661.096449 | -60.696415 | -60.696415 |
| 5 | price_increase_8pct | region=NA | regression_lags | 14 | 5189.290902 | 5431.286123 | 241.995221 | 0.046634 | 5.253769e+05 | 5.934616e+05 | 68084.723395 | 0.129592 | ... | 2549.732691 | 2654.741714 | 105.009024 | 105.009024 | 195.375584 | 195.414238 | 0.038654 | 0.038654 | 2549.732691 | 2654.741714 | 105.009024 | 105.009024 |
| 6 | price_increase_8pct | region=NA | ensemble_inverse_error | 14 | 4823.459942 | 4857.054542 | 33.594601 | 0.006965 | 4.887567e+05 | 5.313092e+05 | 42552.486304 | 0.087063 | ... | 2370.766796 | 2387.460607 | 16.693811 | 16.693811 | 133.730858 | 133.615789 | -0.115069 | -0.115069 | 2370.766796 | 2387.460607 | 16.693811 | 16.693811 |
| 7 | price_increase_8pct | region=NA | ensemble_nnls | 14 | 4729.644938 | 4655.815067 | -73.829872 | -0.015610 | 4.792499e+05 | 5.093579e+05 | 30108.056992 | 0.062823 | ... | 2337.163351 | 2309.636784 | -27.526567 | -27.526567 | 136.158256 | 136.032642 | -0.125614 | -0.125614 | 2337.163351 | 2309.636784 | -27.526567 | -27.526567 |
8 rows × 29 columns
--- Track L.1: Cold-Start Analog Transfer on dgp_11_cold_start_mixed ---
| ts_id | n_obs | is_cold_start | selected_archetype | donor_ts_ids | empirical_bayes_weight | yhat_mean | interval_width_80 | |
|---|---|---|---|---|---|---|---|---|
| 0 | series_001 | 140 | False | analog_transfer | series_016,series_015,series_014 | 0.985915 | 93.4940 | 7.7620 |
| 1 | series_002 | 140 | False | analog_transfer | series_016,series_015,series_014 | 0.985915 | 91.5211 | 7.5587 |
| 2 | series_003 | 140 | False | analog_transfer | series_016,series_015,series_014 | 0.985915 | 117.1875 | 10.1501 |
| 3 | series_004 | 140 | False | analog_transfer | series_016,series_015,series_014 | 0.985915 | 108.4979 | 9.3685 |
| 4 | series_005 | 140 | False | analog_transfer | series_016,series_015,series_014 | 0.985915 | 139.7854 | 11.7423 |
| 5 | series_006 | 140 | False | analog_transfer | series_016,series_015,series_014 | 0.985915 | 131.5975 | 11.4758 |
--- Track L.2: Online Adaptive Conformal Inference (ACI) on dgp_20_monthly_regime_drift_damped ---
| ts_id | model_type | ds | step_idx | fold_id | horizon_step | y_true | yhat | abs_error | volatility_scale | local_scale | alpha_t | ... | aci_covered | covered_split | covered_aci | static_coverage | aci_coverage | rolling_coverage_split | rolling_coverage_aci | target_coverage | static_width | aci_width | interval_width_ratio | drift_detected | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | series_001 | naive_seasonal | 2029-01-01 | 0 | 0 | 1 | 227.3076 | 239.28255 | 11.97495 | 1.000000 | 1.000000 | 0.20 | ... | False | False | False | 0.000000 | 0.000000 | 0.000000 | 0.000000 | 0.8 | 16.8649 | 16.864900 | 1.000000 | False |
| 1 | series_001 | naive_seasonal | 2029-02-01 | 1 | 0 | 2 | 239.4826 | 247.91505 | 8.43245 | 1.000000 | 1.000000 | 0.20 | ... | True | True | True | 0.500000 | 0.500000 | 0.500000 | 0.500000 | 0.8 | 16.8649 | 16.864900 | 1.000000 | False |
| 2 | series_001 | naive_seasonal | 2029-03-01 | 2 | 0 | 3 | 254.6851 | 260.01215 | 5.32705 | 1.000000 | 1.000000 | 0.20 | ... | True | True | True | 0.666667 | 0.666667 | 0.666667 | 0.666667 | 0.8 | 16.8649 | 16.864900 | 1.000000 | False |
| 3 | series_001 | naive_seasonal | 2029-04-01 | 3 | 0 | 4 | 264.6143 | 265.35045 | 0.73615 | 1.000000 | 1.000000 | 0.20 | ... | True | True | True | 0.750000 | 0.750000 | 0.750000 | 0.750000 | 0.8 | 16.8649 | 16.864900 | 1.000000 | False |
| 4 | series_001 | naive_seasonal | 2029-04-01 | 4 | 1 | 1 | 264.6143 | 264.59760 | 0.01670 | 1.049437 | 1.049437 | 0.19 | ... | True | True | True | 0.800000 | 0.800000 | 0.800000 | 0.800000 | 0.8 | 16.8649 | 20.362451 | 1.207386 | False |
| 5 | series_001 | naive_seasonal | 2029-05-01 | 5 | 0 | 5 | 276.0769 | 276.23365 | 0.15675 | 1.049437 | 1.049437 | 0.19 | ... | True | True | True | 0.833333 | 0.833333 | 0.833333 | 0.833333 | 0.8 | 16.8649 | 18.099537 | 1.073207 | False |
6 rows × 34 columns
--- Track L.3: Joint Copula Trajectories & Portfolio VaR / CVaR Tail Risk ---
| ts_id | model_type | copula_type | n_paths | horizon | window | expected_cumulative_demand | std_cumulative_demand | iid_std_cumulative_demand | copula_amplification_ratio | var_90 | cvar_90 | ... | cvar_99 | var_alpha | cvar_alpha | peak_window_mean | peak_window_var | peak_window_cvar | exceedance_prob | expected_shortfall_units | crps | energy_score | variogram_score | risk_verdict | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | __total__ | regression_lags | student_t | 150 | 14 | 7 | 12246.670571 | 301.384525 | 220.702501 | 1.365569 | 12585.165145 | 12739.700836 | ... | 12989.254217 | 12697.789392 | 12820.235706 | 6413.790138 | 6732.903340 | 6816.330379 | 0.1 | 15.453569 | 12.272766 | 57.722036 | 1.274535 | amplified_tail_risk |
| 1 | region=APAC | regression_lags | student_t | 150 | 14 | 7 | 2383.220443 | 69.663547 | 48.317351 | 1.441792 | 2463.339969 | 2504.891936 | ... | 2576.900081 | 2487.798232 | 2529.306744 | 1220.621965 | 1297.312545 | 1330.500496 | 0.1 | 4.155197 | 2.724598 | 12.745696 | 1.004889 | amplified_tail_risk |
| 2 | region=EMEA | regression_lags | student_t | 150 | 14 | 7 | 3640.207835 | 66.539965 | 43.197482 | 1.540367 | 3717.936856 | 3771.524394 | ... | 3842.426535 | 3744.665429 | 3804.022373 | 1907.796690 | 1984.964366 | 2026.562000 | 0.1 | 5.358754 | 2.361421 | 11.319714 | 0.173920 | amplified_tail_risk |
| 3 | region=LATAM | regression_lags | student_t | 150 | 14 | 7 | 1167.287349 | 67.699571 | 46.484222 | 1.456399 | 1238.587358 | 1293.207965 | ... | 1416.695322 | 1274.434183 | 1329.804474 | 612.412360 | 708.083596 | 747.761271 | 0.1 | 5.462061 | 2.423560 | 11.318270 | 1.861664 | amplified_tail_risk |
| 4 | region=NA | regression_lags | student_t | 150 | 14 | 7 | 5055.954945 | 200.213325 | 155.281547 | 1.289357 | 5293.017836 | 5371.677539 | ... | 5539.905665 | 5331.259781 | 5428.510552 | 2729.968662 | 2906.642513 | 2996.972989 | 0.1 | 7.865970 | 9.341330 | 46.338521 | 2.201480 | amplified_tail_risk |
| 5 | region=APAC/category=enterprise | regression_lags | student_t | 150 | 14 | 7 | 2383.220443 | 69.663547 | 48.317351 | 1.441792 | 2463.339969 | 2504.891936 | ... | 2576.900081 | 2487.798232 | 2529.306744 | 1220.621965 | 1297.312545 | 1330.500496 | 0.1 | 4.155197 | 2.724598 | 12.745696 | 1.004889 | amplified_tail_risk |
6 rows × 27 columns
--- Track L.4: Multi-SKU Portfolio-Constrained Inventory Optimizer ---
| ts_id | model_type | policy_type | target_mode | lead_time | lead_time_std | review_period | protection_steps | mean_step_demand | lead_time_demand | protection_demand | error_autocorr_rho | ... | unit_volume | vendor_moq | order_cost | order_spend | order_volume | allocation_ratio | shadow_price_budget | shadow_price_volume | shadow_price_units | portfolio_fill_rate | binding_constraint | uncertainty_source | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | __total__ | lightgbm@monotone | continuous_s_S | cycle_service_level | 7.0 | 0.0 | 0.0 | 7.0 | 760.405247 | 5322.836730 | 5322.836730 | 0.601650 | ... | 1.0 | 0.0 | 1374.481229 | 1374.481229 | 137.448123 | 0.023998 | 0.260062 | 0.0 | 0.0 | 0.980337 | budget+fill_rate | copula |
| 1 | __total__ | lightgbm@monotone_mint_nonneg | continuous_s_S | cycle_service_level | 7.0 | 0.0 | 0.0 | 7.0 | 773.695266 | 5415.866860 | 5415.866860 | 0.604364 | ... | 1.0 | 0.0 | 1398.503789 | 1398.503789 | 139.850379 | 0.024397 | 0.260062 | 0.0 | 0.0 | 0.980337 | budget+fill_rate | copula |
| 2 | __total__ | regression_lags | continuous_s_S | cycle_service_level | 7.0 | 0.0 | 0.0 | 7.0 | 818.599377 | 5730.195638 | 5730.195638 | 0.603766 | ... | 1.0 | 0.0 | 1479.670849 | 1479.670849 | 147.967085 | 0.024408 | 0.260062 | 0.0 | 0.0 | 0.980337 | budget+fill_rate | copula |
| 3 | __total__ | regression_lags@monotone | continuous_s_S | cycle_service_level | 7.0 | 0.0 | 0.0 | 7.0 | 803.979762 | 5627.858334 | 5627.858334 | 0.611657 | ... | 1.0 | 0.0 | 1453.244958 | 1453.244958 | 145.324496 | 0.024295 | 0.260062 | 0.0 | 0.0 | 0.980337 | budget+fill_rate | copula |
| 4 | __total__ | regression_lags@monotone_mint_nonneg | continuous_s_S | cycle_service_level | 7.0 | 0.0 | 0.0 | 7.0 | 806.048966 | 5642.342761 | 5642.342761 | 0.583543 | ... | 1.0 | 0.0 | 1456.985177 | 1456.985177 | 145.698518 | 0.024186 | 0.260062 | 0.0 | 0.0 | 0.980337 | budget+fill_rate | copula |
| 5 | __total__ | regression_lags_mint_nonneg | continuous_s_S | cycle_service_level | 7.0 | 0.0 | 0.0 | 7.0 | 834.297732 | 5840.084123 | 5840.084123 | 0.589910 | ... | 1.0 | 0.0 | 1508.046632 | 1508.046632 | 150.804663 | 0.024727 | 0.260062 | 0.0 | 0.0 | 0.980337 | budget+fill_rate | copula |
6 rows × 47 columns
--- Track L.5: Prescriptive Price & Promotional Calendar Optimizer ---
| ts_id | model_type | ds | forecast_date | horizon_step | baseline_price | optimal_price | price | price_change_pct | baseline_promo | optimal_promo | promo | ... | gross_margin_delta | gross_margin_delta_pct | margin_pct | baseline_reorder_point | optimal_reorder_point | delta_reorder_point | baseline_safety_stock | optimal_safety_stock | delta_safety_stock | baseline_order_qty | optimal_order_qty | delta_order_qty | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | __total__ | regression_lags | 2022-01-01 | 2022-01-01 | 1 | 114.050884 | 125.459010 | 125.459010 | 10.002663 | 0.0 | 0.333333 | 0.333333 | ... | 19547.951393 | 32.191783 | 0.561610 | 6608.223979 | 6489.881269 | -118.34271 | 660.420353 | 641.403658 | -19.016695 | 6608.223979 | 6489.881269 | -118.34271 |
| 1 | __total__ | regression_lags | 2022-01-02 | 2022-01-02 | 2 | 114.052826 | 125.458333 | 125.458333 | 10.000197 | 0.0 | 0.166667 | 0.166667 | ... | 9284.644316 | 16.379502 | 0.561607 | 6608.223979 | 6489.881269 | -118.34271 | 660.420353 | 641.403658 | -19.016695 | 6608.223979 | 6489.881269 | -118.34271 |
| 2 | __total__ | regression_lags | 2022-01-03 | 2022-01-03 | 3 | 114.052905 | 125.458095 | 125.458095 | 9.999913 | 0.0 | 0.000000 | 0.000000 | ... | 6418.552058 | 13.210106 | 0.561607 | 6608.223979 | 6489.881269 | -118.34271 | 660.420353 | 641.403658 | -19.016695 | 6608.223979 | 6489.881269 | -118.34271 |
| 3 | __total__ | regression_lags | 2022-01-04 | 2022-01-04 | 4 | 114.052527 | 125.457719 | 125.457719 | 9.999947 | 0.0 | 0.000000 | 0.000000 | ... | 5994.830953 | 13.511023 | 0.561605 | 6608.223979 | 6489.881269 | -118.34271 | 660.420353 | 641.403658 | -19.016695 | 6608.223979 | 6489.881269 | -118.34271 |
| 4 | __total__ | regression_lags | 2022-01-05 | 2022-01-05 | 5 | 114.052929 | 125.458210 | 125.458210 | 9.999989 | 0.0 | 0.000000 | 0.000000 | ... | 5874.661982 | 13.831439 | 0.561607 | 6608.223979 | 6489.881269 | -118.34271 | 660.420353 | 641.403658 | -19.016695 | 6608.223979 | 6489.881269 | -118.34271 |
| 5 | __total__ | regression_lags | 2022-01-06 | 2022-01-06 | 6 | 114.053484 | 125.458833 | 125.458833 | 10.000000 | 0.0 | 0.000000 | 0.000000 | ... | 6063.966464 | 13.944479 | 0.561609 | 6608.223979 | 6489.881269 | -118.34271 | 660.420353 | 641.403658 | -19.016695 | 6608.223979 | 6489.881269 | -118.34271 |
| 6 | __total__ | regression_lags | 2022-01-07 | 2022-01-07 | 7 | 114.055173 | 125.460690 | 125.460690 | 10.000000 | 0.0 | 0.000000 | 0.000000 | ... | 7656.685848 | 13.944225 | 0.561616 | 6608.223979 | 6489.881269 | -118.34271 | 660.420353 | 641.403658 | -19.016695 | 6608.223979 | 6489.881269 | -118.34271 |
| 7 | __total__ | regression_lags | 2022-01-08 | 2022-01-08 | 8 | 114.055993 | 125.463741 | 125.463741 | 10.001884 | 0.0 | 0.500000 | 0.500000 | ... | 21331.111377 | 33.030260 | 0.561626 | 6608.223979 | 6489.881269 | -118.34271 | 660.420353 | 641.403658 | -19.016695 | 6608.223979 | 6489.881269 | -118.34271 |
8 rows × 47 columns
Act 9 · Glass-Box Auto-Forecaster (Forecaster.build_config & Bounded autofocus)¶
When you want scale-forecasting to inspect a panel, compile an explicit, editable RunConfig with per-parameter evidence rationales, and run a bounded 2-pass Observe -> Review -> Re-Plan loop with zero-waste cell borrowing, use Forecaster.build_config() and Forecaster.auto() (explored in full in 11_auto_forecaster_and_autofocus.ipynb):
from scale_forecasting import load_benchmark
# 1. Inspect a synthetic DGP benchmark panel & compile a Glass-Box ConfigBlueprint
dgp_cov = load_benchmark("dgp_04_true_vs_decoy_covs", n_series=3)
bp = Forecaster.build_config(dgp_cov.panel_df, tier="first_light", where="local")
display(bp.rationale_df)
# 2. Run 2-pass bounded autofocus (Pass 2 prunes decoy noise covariates & borrows Pass 1 baselines)
f_auto = Forecaster.auto(
dgp_cov.panel_df,
tier="first_light",
where="local",
autofocus=True,
max_passes=2,
)
display(f_auto.autofocus_ledger_df())
display(f_auto.preview_next_loop().to_dataframe())
| category | parameter | value | evidence | rationale | |
|---|---|---|---|---|---|
| 0 | scale_regime | scale_regime | micro (Micro Panel (1–14 series)) | n_series=3, n_rows=420 | Per-series local statistical, tree, and zero-s... |
| 1 | models | naive_seasonal | include (statistical) | freq=D, median_acf=0.48 | Establishes the zero-skill seasonal benchmark ... |
| 2 | models | theta | include (statistical) | dominant_regime=smooth | Fast M3-winning exponential smoothing with dri... |
| 3 | models | lightgbm | include (ml) | n_series=3, covariates=5 | Fast gradient boosted decision trees capturing... |
| 4 | models | regression_lags | include (ml) | fut_covs=5, growth=1.11 | Fast ridge lag regression for linear trend and... |
| 5 | output | output.floor | 0.0 | min(y) >= 0.0 across 100% of historical observ... | Enforces physical non-negativity on point fore... |
| 6 | backtest | backtest.decision_metric | wape | goal='accuracy', intermittent=False | Optimizes model selection and ensemble weights... |
| 7 | features | features.monotonic_constraints | {'promo_depth': 1, 'price_index': -1} | price/promo drivers detected: ['promo_depth', ... | Enforces structural sign guardrails (negative ... |
| 8 | baseline_ladder | baselines | naive_seasonal (naive_anchor), theta (plain_un... | 4-anchor baseline ladder (naive, plain univari... | Guarantees protected baseline anchors across p... |
| 9 | features | features.future_covariates | promo_depth, price_index, noise_a, noise_b, no... | 5 known future driver(s) detected | Registers known future drivers for elastic and... |
| pass_index | pass_id | parent_pass_ids | branch_hypothesis | run_id | tier | models_total | models_borrowed | models_executed | champion_model | decision_metric | champion_score | ... | covariate_lift_pct | reconciliation_lift_pct | champion_is_univariate | beaten_challengers | dm_pvalue | predicted_p50_s | actual_wall_s | continue_confidence | expected_next_gain_pct | mutations_applied | is_session_champion | stop_or_continue_reason | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | 1 | root | Initial Tier Exposure | auto-first-light-c4f8027a5a33 | first_light | 4 | 0 | 4 | ensemble_inverse_error | wape | 0.0506 | ... | 0.0 | 0.0 | False | (none) | 0.0000 | 0.56 | 2.79 | 0.92 | 25.0 | initial_tier_compilation | False | Pass 2 approved (confidence=0.92 >= 0.35, expe... |
| 1 | 2 | 2A | 1 | Target Transform & Structural Hygiene | auto-first-light-p2a-83d5e6c68b04 | first_light | 7 | 4 | 3 | ensemble_champion | wape | 0.0379 | ... | 0.0 | 0.0 | False | (none) | 0.0002 | 0.98 | 3.35 | 0.00 | 0.0 | inject_transform_log1p | False | Reached max_passes=2 for the selected exposure... |
| 2 | 2 | 2B | 1 | Covariate Pruning & Direct Horizon Specialists | auto-first-light-p2b-30554d65c537 | first_light | 8 | 2 | 6 | ensemble_champion | wape | 0.0361 | ... | 0.0 | 0.0 | False | (none) | 0.0000 | 2.15 | 4.33 | 0.00 | 0.0 | prune_decoy_covariates, inject_monotone_guardr... | False | Reached max_passes=2 for the selected exposure... |
| 3 | 3 | 3 | 2A, 2B | Level-3 Tournament Synthesis & Learned Stacking | auto-first-light-p3-synth-540a3869320b | first_light | 11 | 9 | 2 | ensemble_champion | wape | 0.0339 | ... | 0.0 | 0.0 | False | (none) | 0.0000 | 2.44 | 1.83 | 0.00 | 0.0 | synthesize_winning_dag_branches | True | Reached max_passes=2 for the selected exposure... |
4 rows × 27 columns
| next_pass_index | pass_id | branch_hypothesis | should_continue | confidence | expected_gain_pct | borrowed_models | new_models_to_fit | predicted_p50_seconds | reason | |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 4 | 4 | None | False | 0.0 | 0.0 | naive_seasonal, theta, lightgbm, regression_la... | (none) | 0.39 | Reached max_passes=2 for the selected exposure... |
Act 10 · Track K: 3-Mode Coherent Reconciliation (THieF & spatial_temporal_weight="auto"), Coherent Sample Paths (sample_coherent_paths), Compositional Simplex (verify_simplex), Smooth Goal-Seek QP (smoothness_weight) & f.assess()¶
Enterprise S&OP and merchandise planning require three mathematical guarantees beyond standard per-series forecasting:
- Three-Mode Reconciliation (
spatial_only,temporal_only,cross_temporalwithspatial_temporal_weight="auto") & Coherent Path Simulation (sample_coherent_paths): Daily forecasts ($k=1$) sum coherently to weekly ($k=7$), bi-weekly ($k=14$), and 4-week ($k=28$) operational buckets while simultaneously summing up the cross-sectional hierarchy (ts_id$\to$region/category$\to$region$\to$__total__) with $< 10^{-6}$ discrepancy (temporal_reconcile_df(),sample_coherent_paths(),verify_temporal_coherence(),verify_cross_temporal_coherence()). - Compositional Simplex Transforms (
@transform_clr&@transform_ilr) & 7-Question Assessment (f.assess()): Maps market-share percentages to unconstrained log-ratio space and closes predictions back onto the simplex (forecast_simplex_panel(),verify_simplex()), with Question 3 and Question 5 off.assess()reporting causal guardrails, active reconciliation mode, and simplex closure. - Smooth Multi-Period Top-Down Goal-Seek Constrained QP (
allocate_target(..., smoothness_weight=10.0)&plot_goal_seek()): Disaggregates an executive top-down unit or revenue target across leaf series and dates via precision-weighted Minimum-Trace Quadratic Programming with $\ell_2$ temporal roughness smoothing (smoothness_weight) while honoringlocked_nodes, box[lower_bounds, upper_bounds], and propagating gross margin (gross_margin_delta) and inventory replenishment shifts (delta_reorder_point,delta_safety_stock).
import numpy as np
import warnings
from scale_forecasting import (
allocate_target,
close_simplex,
forecast_simplex_panel,
plot_goal_seek,
reconcile_forecasts,
reconcile_temporal_forecasts,
sample_coherent_paths,
summarize_goal_seek,
temporal_reconcile_df,
verify_coherence,
verify_cross_temporal_coherence,
verify_simplex,
verify_temporal_coherence,
)
warnings.filterwarnings("ignore")
# 1. Three-Mode Reconciliation (Spatial-Only vs. Temporal-Only vs. Cross-Temporal with spatial_temporal_weight="auto") & Coherent Paths
print("--- 1. Three-Mode Reconciliation & Coherent Sample Paths (sample_coherent_paths) ---")
f_ct = Forecaster(
RunConfig(
run_name="playground_track_k_cross_temporal",
data={"source_table": "local_panel", "freq": "D", "horizon": 28},
models=["theta", "holtwinters"],
hierarchy={
"enabled": True,
"levels": [["region"], ["region", "category"]],
"reconciliation_methods": ["wls_struct", "mint_shrink", "cross_temporal_mint"],
"reconcile_temporal": True,
"cross_temporal": True,
"spatial_temporal_weight": "auto",
"temporal_aggregations": [7, 14, 28],
},
backtest={"enabled": True, "n_folds": 2, "horizon": 28, "step": 28},
)
)
rec_ct_df, coarse_aggs = f_ct.temporal_reconcile_df(
data=panel,
method="cross_temporal_mint",
model_type="theta",
temporal_aggregations=[7, 14, 28],
return_aggregations=True,
)
hier_spec = rec_ct_df.attrs["hierarchy_spec"]
ct_diag = rec_ct_df.attrs.get("cross_temporal_diagnostics", {})
temp_disc = verify_temporal_coherence(rec_ct_df, coarse_aggs)
cs_temp_disc = verify_cross_temporal_coherence(rec_ct_df, hier_spec, coarse_aggs)
paths_df = sample_coherent_paths(rec_ct_df, hier_spec, history_df=panel, n_paths=50, seed=42)
max_path_cs = max(verify_coherence(g, hier_spec) for _, g in paths_df.groupby("path_id"))
print(
f"Mode 3 Cross-Temporal ({rec_ct_df['ts_id'].nunique()} nodes, k in [1, 7, 14, 28]): "
f"mode={ct_diag.get('mode')}, alpha={ct_diag.get('spatial_weight_alpha', 0.5):.3f}, "
f"temp_disc={temp_disc:.2e}, joint_disc={cs_temp_disc:.2e}\n"
f"sample_coherent_paths(n_paths=50): {len(paths_df)} rows, max path coherence discrepancy = {max_path_cs:.2e}"
)
display(rec_ct_df.head(6))
# 2. Compositional Simplex Forecasting (@transform_clr & @transform_ilr, S = 100.0%) + Practitioner Assessment (f.assess())
print("--- 2. Compositional Simplex (@transform_clr & @transform_ilr, S = 100.0%) & f.assess() ---")
simplex_panel = close_simplex(
panel[panel["ts_id"].isin(sorted(panel["ts_id"].unique())[:4])][["ts_id", "ds", "y"]],
value_col="y",
simplex_sum=100.0,
)
ilr_preds = forecast_simplex_panel(
simplex_panel,
model_name="theta@transform_ilr",
transform="ilr",
horizon=14,
simplex_sum=100.0,
)
clr_preds = forecast_simplex_panel(
simplex_panel,
model_name="holtwinters@transform_clr",
transform="clr",
horizon=14,
simplex_sum=100.0,
)
simplex_disc_ilr = verify_simplex(ilr_preds, simplex_sum=100.0)
simplex_disc_clr = verify_simplex(clr_preds, simplex_sum=100.0)
date_sums = (
ilr_preds.groupby("ds", as_index=False)["yhat"]
.sum()
.rename(columns={"yhat": "sum_of_brand_shares_pct"})
)
print(
f"Max simplex discrepancy: ILR = {simplex_disc_ilr:.2e}, CLR = {simplex_disc_clr:.2e} "
f"(all {len(date_sums)} horizon dates sum to 100.0%)"
)
f_sim_auto = Forecaster.auto(
simplex_panel,
horizon=14,
freq="D",
models=["naive_mean@transform_ilr", "theta@transform_clr"],
baselines=["naive_mean"],
hpo=False,
calibration=False,
explainability=False,
n_folds=1,
autofocus=False,
)
display(
f_sim_auto.practitioner_assessment_df()[
["question_id", "verdict", "answer", "evidence", "recommendation"]
]
)
# 3. Smooth Multi-Period Top-Down Goal-Seek Constrained QP (allocate_target with smoothness_weight=10.0)
print("--- 3. Smooth Top-Down Goal-Seek Constrained QP (smoothness_weight=10.0 + Margin & Inventory Impact) ---")
root_baseline = float(rec_ct_df[rec_ct_df["ts_id"] == "__total__"]["yhat"].sum())
leaf_ids = sorted(panel["ts_id"].unique())
locked_leaf = leaf_ids[0]
goal_unsmoothed = f_ct.allocate_target(
target_total=root_baseline * 1.15,
forecasts_df=rec_ct_df,
data=panel,
locked_nodes=[locked_leaf],
floor=0.0,
cap=5000.0,
smoothness_weight=0.0,
)
goal_df = f_ct.allocate_target(
target_total=root_baseline * 1.15,
forecasts_df=rec_ct_df,
data=panel,
locked_nodes=[locked_leaf],
floor=0.0,
cap=5000.0,
smoothness_weight=10.0,
prices=24.0,
unit_cost=14.0,
include_inventory_impact=True,
)
def _leaf_roughness(df_alloc):
sub = df_alloc[df_alloc["ts_id"].isin(leaf_ids)].sort_values(["ts_id", "ds"])
return float(
sum(
np.sum(
np.diff(
grp["allocated_yhat"].to_numpy(float) - grp["baseline_yhat"].to_numpy(float)
)
** 2
)
for _, grp in sub.groupby("ts_id")
)
)
print(
f"Temporal trajectory roughness: smoothness_weight=0.0 -> {_leaf_roughness(goal_unsmoothed):.4f}, "
f"smoothness_weight=10.0 -> {_leaf_roughness(goal_df):.4f}"
)
display(summarize_goal_seek(goal_df))
display(
goal_df[goal_df["ts_id"].isin(["__total__", locked_leaf, leaf_ids[1]])][
[
"ts_id",
"ds",
"baseline_yhat",
"allocated_yhat",
"delta_units",
"delta_pct",
"constraint_status",
"gross_margin_delta",
"delta_reorder_point",
]
].head(9)
)
ax_gs = plot_goal_seek(
goal_df, top_n=6, title="Smooth Top-Down Goal-Seek (+15% Target, smoothness_weight=10.0)"
)
plt.show()
--- 1. Three-Mode Reconciliation & Coherent Sample Paths (sample_coherent_paths) ---
Mode 3 Cross-Temporal (17 nodes, k in [1, 7, 14, 28]): mode=cross_temporal, alpha=0.433, temp_disc=0.00e+00, joint_disc=2.27e-13 sample_coherent_paths(n_paths=50): 23800 rows, max path coherence discrepancy = 2.27e-13
| ts_id | ds | yhat | yhat_raw | yhat_adjusted | yhat_lower | yhat_upper | quantiles | model_type | |
|---|---|---|---|---|---|---|---|---|---|
| 0 | __total__ | 2022-01-01 | 921.754476 | 944.241565 | 921.754476 | 855.911211 | 987.597742 | {"0.1": 893.5919366870033, "0.5": 931.95781922... | theta |
| 1 | region=APAC | 2022-01-01 | 221.834914 | 224.085880 | 221.834914 | 210.413402 | 233.256426 | {"0.1": 210.75460570243578, "0.5": 228.4883289... | theta |
| 2 | region=EMEA | 2022-01-01 | 288.507022 | 295.878887 | 288.507022 | 269.198118 | 307.815925 | {"0.1": 265.0761074355628, "0.5": 284.01433131... | theta |
| 3 | region=LATAM | 2022-01-01 | 69.059524 | 62.402896 | 69.059524 | 53.637227 | 84.481821 | {"0.1": 62.48524753279387, "0.5": 71.101733047... | theta |
| 4 | region=NA | 2022-01-01 | 342.353017 | 361.873903 | 342.353017 | 305.505934 | 379.200101 | {"0.1": 306.7721149469057, "0.5": 359.44270892... | theta |
| 5 | region=APAC/category=enterprise | 2022-01-01 | 221.834914 | 224.085880 | 221.834914 | 210.413402 | 233.256426 | {"0.1": 210.75460570243578, "0.5": 228.4883289... | theta |
--- 2. Compositional Simplex (@transform_clr & @transform_ilr, S = 100.0%) & f.assess() ---
Max simplex discrepancy: ILR = 2.84e-14, CLR = 2.84e-14 (all 14 horizon dates sum to 100.0%)
| question_id | verdict | answer | evidence | recommendation | |
|---|---|---|---|---|---|
| 0 | model_vs_baseline | verified_lift | Champion 'ensemble_ridge' reduced wape by +8.2... | champion=ensemble_ridge (wape=0.3110), fva_nai... | Inspect f.baseline_value_df() and f.compare_mo... |
| 1 | ensemble_vs_single | ensemble_helps | Yes — 'ensemble_ridge' outperformed the best s... | best_single=theta@transform_clr (0.3209), best... | Ensembles must beat the best single model by t... |
| 2 | covariates_vs_overfitting | univariate_panel | No external covariates in source data; forecas... | covariates=0 | Inspect f.attributions_df() and f.promo_elasti... |
| 3 | global_vs_local | local_per_series_optimal | Per-series local and zero-shot models are opti... | n_series=4, scale_regime='micro', cross_series... | Global pooling pays off most when n_series >= ... |
| 4 | hierarchy_reconciliation | coherent_and_verified | Flat panel (no hierarchy columns); output.floo... | mode='none', hierarchy_id_cols=[], is_composit... | Inspect f.hierarchy_value_df() for Root, Inter... |
| 5 | horizon_stability | late_horizon_decay | Late-horizon error grows 2.35x vs. early steps... | late_early_ratio=2.35, crossover_step=6, direc... | Inspect f.horizon_decay_df() for step-by-step ... |
| 6 | forecast_trust | high_confidence | Evaluated on 1 rolling out-of-fold backtest wi... | n_folds=1, calibration_method='conformal', aci... | Inspect f.aci_df(), f.tail_risk_df(), and f.ex... |
--- 3. Smooth Top-Down Goal-Seek Constrained QP (smoothness_weight=10.0 + Margin & Inventory Impact) ---
Temporal trajectory roughness: smoothness_weight=0.0 -> 2228.9141, smoothness_weight=10.0 -> 21.6750
| ts_id | model_type | baseline_total_units | allocated_total_units | y_allocated_sum | baseline_yhat | allocated_yhat | delta_units | delta_yhat | delta_pct | allocation_weight | constraint_status | ... | allocated_gross_margin | gross_margin_delta | delta_gross_margin | baseline_reorder_point | allocated_reorder_point | delta_reorder_point | baseline_safety_stock | allocated_safety_stock | delta_safety_stock | baseline_order_qty | allocated_order_qty | delta_order_qty | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | __total__ | theta | 23190.119382 | 26668.637290 | 26668.637290 | 23190.119382 | 26668.637290 | 3478.517907 | 3478.517907 | 15.000000 | 1.000000 | FREE | ... | 266686.372898 | 34785.179074 | 34785.179074 | 5883.091172 | 6623.591151 | 740.499979 | 337.233248 | 337.233248 | 0.000000e+00 | 5883.091172 | 6623.591151 | 740.499979 |
| 1 | region=APAC | theta | 5675.642808 | 5856.830346 | 5856.830346 | 5675.642808 | 5856.830346 | 181.187538 | 181.187538 | 3.192370 | 0.030337 | FREE | ... | 58568.303460 | 1811.875378 | 1811.875378 | 1383.405472 | 1421.728895 | 38.323423 | 55.892047 | 55.892047 | 0.000000e+00 | 1383.405472 | 1421.728895 | 38.323423 |
| 2 | region=EMEA | theta | 6645.924077 | 7457.957717 | 7457.957717 | 6645.924077 | 7457.957717 | 812.033639 | 812.033639 | 12.218521 | 0.144910 | FREE | ... | 74579.577166 | 8120.336392 | 8120.336392 | 1723.574003 | 1888.737702 | 165.163700 | 98.251389 | 98.251389 | -2.842171e-14 | 1723.574003 | 1888.737702 | 165.163700 |
| 3 | region=LATAM | theta | 1810.662359 | 2303.971577 | 2303.971577 | 1810.662359 | 2303.971577 | 493.309218 | 493.309218 | 27.244683 | 0.087251 | FREE | ... | 23039.715767 | 4933.092181 | 4933.092181 | 519.394631 | 609.421654 | 90.027023 | 77.699198 | 77.699198 | 0.000000e+00 | 519.394631 | 609.421654 | 90.027023 |
| 4 | region=NA | theta | 9057.890138 | 11049.877651 | 11049.877651 | 9057.890138 | 11049.877651 | 1991.987512 | 1991.987512 | 21.991738 | 0.737502 | FREE | ... | 110498.776505 | 19919.875123 | 19919.875123 | 2339.704018 | 2786.689852 | 446.985834 | 188.377566 | 188.377566 | -2.842171e-14 | 2339.704018 | 2786.689852 | 446.985834 |
| 5 | region=APAC/category=enterprise | theta | 5675.642808 | 5856.830346 | 5856.830346 | 5675.642808 | 5856.830346 | 181.187538 | 181.187538 | 3.192370 | 0.030337 | FREE | ... | 58568.303460 | 1811.875378 | 1811.875378 | 1383.405472 | 1421.728895 | 38.323423 | 55.892047 | 55.892047 | 0.000000e+00 | 1383.405472 | 1421.728895 | 38.323423 |
| 6 | region=EMEA/category=SMB | theta | 6611.355124 | 7409.716575 | 7409.716575 | 6611.355124 | 7409.716575 | 798.361450 | 798.361450 | 12.075610 | 0.142726 | FREE | ... | 74097.165749 | 7983.614504 | 7983.614504 | 1719.081532 | 1880.614976 | 161.533443 | 102.849765 | 102.849765 | 0.000000e+00 | 1719.081532 | 1880.614976 | 161.533443 |
| 7 | region=EMEA/category=enterprise | theta | 34.568953 | 48.241142 | 48.241142 | 34.568953 | 48.241142 | 13.672189 | 13.672189 | 39.550486 | 0.002184 | AT_FLOOR | ... | 482.411417 | 136.721888 | 136.721888 | 21.752193 | 30.228146 | 8.475952 | 12.291284 | 17.507043 | 5.215759e+00 | 21.752193 | 30.228146 | 8.475952 |
| 8 | region=LATAM/category=enterprise | theta | 1810.662359 | 2303.971577 | 2303.971577 | 1810.662359 | 2303.971577 | 493.309218 | 493.309218 | 27.244683 | 0.087251 | FREE | ... | 23039.715767 | 4933.092181 | 4933.092181 | 519.394631 | 609.421654 | 90.027023 | 77.699198 | 77.699198 | 0.000000e+00 | 519.394631 | 609.421654 | 90.027023 |
| 9 | region=NA/category=SMB | theta | 1637.912193 | 3629.899705 | 3629.899705 | 1637.912193 | 3629.899705 | 1991.987512 | 1991.987512 | 121.617479 | 0.357615 | FREE | ... | 36298.997051 | 19919.875123 | 19919.875123 | 532.774841 | 979.760675 | 446.985834 | 158.443044 | 158.443044 | 0.000000e+00 | 532.774841 | 979.760675 | 446.985834 |
| 10 | region=NA/category=enterprise | theta | 7419.977945 | 7419.977945 | 7419.977945 | 7419.977945 | 7419.977945 | 0.000000 | 0.000000 | 0.000000 | 0.379887 | LOCKED | ... | 74199.779455 | 0.000000 | 0.000000 | 2011.669711 | 2011.669711 | 0.000000 | 234.675056 | 234.675056 | 0.000000e+00 | 2011.669711 | 2011.669711 | 0.000000 |
| 11 | s_000000 | theta | 7419.977945 | 7419.977945 | 7419.977945 | 7419.977945 | 7419.977945 | 0.000000 | 0.000000 | 0.000000 | 0.379887 | LOCKED | ... | 74199.779455 | 0.000000 | 0.000000 | 2011.669711 | 2011.669711 | 0.000000 | 234.675056 | 234.675056 | 0.000000e+00 | 2011.669711 | 2011.669711 | 0.000000 |
| 12 | s_000001 | theta | 34.568953 | 48.241142 | 48.241142 | 34.568953 | 48.241142 | 13.672189 | 13.672189 | 39.550486 | 0.002184 | AT_FLOOR | ... | 482.411417 | 136.721888 | 136.721888 | 21.752193 | 30.228146 | 8.475952 | 12.291284 | 17.507043 | 5.215759e+00 | 21.752193 | 30.228146 | 8.475952 |
| 13 | s_000002 | theta | 5675.642808 | 5856.830346 | 5856.830346 | 5675.642808 | 5856.830346 | 181.187538 | 181.187538 | 3.192370 | 0.030337 | FREE | ... | 58568.303460 | 1811.875378 | 1811.875378 | 1383.405472 | 1421.728895 | 38.323423 | 55.892047 | 55.892047 | 0.000000e+00 | 1383.405472 | 1421.728895 | 38.323423 |
| 14 | s_000003 | theta | 1810.662359 | 2303.971577 | 2303.971577 | 1810.662359 | 2303.971577 | 493.309218 | 493.309218 | 27.244683 | 0.087251 | FREE | ... | 23039.715767 | 4933.092181 | 4933.092181 | 519.394631 | 609.421654 | 90.027023 | 77.699198 | 77.699198 | 0.000000e+00 | 519.394631 | 609.421654 | 90.027023 |
| 15 | s_000004 | theta | 1637.912193 | 3629.899705 | 3629.899705 | 1637.912193 | 3629.899705 | 1991.987512 | 1991.987512 | 121.617479 | 0.357615 | FREE | ... | 36298.997051 | 19919.875123 | 19919.875123 | 532.774841 | 979.760675 | 446.985834 | 158.443044 | 158.443044 | 0.000000e+00 | 532.774841 | 979.760675 | 446.985834 |
| 16 | s_000005 | theta | 6611.355124 | 7409.716575 | 7409.716575 | 6611.355124 | 7409.716575 | 798.361450 | 798.361450 | 12.075610 | 0.142726 | FREE | ... | 74097.165749 | 7983.614504 | 7983.614504 | 1719.081532 | 1880.614976 | 161.533443 | 102.849765 | 102.849765 | 4.263256e-14 | 1719.081532 | 1880.614976 | 161.533443 |
17 rows × 29 columns
| ts_id | ds | baseline_yhat | allocated_yhat | delta_units | delta_pct | constraint_status | gross_margin_delta | delta_reorder_point | |
|---|---|---|---|---|---|---|---|---|---|
| 0 | __total__ | 2022-01-01 | 921.754476 | 1024.333920 | 102.579444 | 11.128717 | FREE | 1025.794435 | 740.499979 |
| 1 | __total__ | 2022-01-02 | 938.785073 | 1041.790454 | 103.005381 | 10.972201 | FREE | 1030.053812 | 740.499979 |
| 2 | __total__ | 2022-01-03 | 834.617668 | 938.490466 | 103.872798 | 12.445555 | FREE | 1038.727981 | 740.499979 |
| 3 | __total__ | 2022-01-04 | 714.678501 | 819.896779 | 105.218278 | 14.722463 | FREE | 1052.182782 | 740.499979 |
| 4 | __total__ | 2022-01-05 | 651.715150 | 758.492084 | 106.776934 | 16.383988 | FREE | 1067.769343 | 740.499979 |
| 5 | __total__ | 2022-01-06 | 669.704978 | 778.309933 | 108.604955 | 16.216836 | FREE | 1086.049554 | 740.499979 |
| 6 | __total__ | 2022-01-07 | 814.602078 | 925.044266 | 110.442188 | 13.557808 | FREE | 1104.421881 | 740.499979 |
| 7 | __total__ | 2022-01-08 | 930.066289 | 1042.344327 | 112.278038 | 12.072047 | FREE | 1122.780383 | 740.499979 |
| 8 | __total__ | 2022-01-09 | 924.482228 | 1038.646391 | 114.164163 | 12.348984 | FREE | 1141.641629 | 740.499979 |
Act 11 · Track P (Act 9): Multi-Modal Time-Series Similarity, Physics/Attractor & Foundation Embeddings, Assortment Substitution, Emerging Trend Sensing & @similarity_global¶
When panels contain multiple behavioral archetypes or coincidental seasonal twins across unrelated departments, static category tags or pure trajectory matching alone fail to capture true product substitutability and dynamical synchronization. Track P (v1.8.0) introduces a pure-Python/NumPy/SciPy multi-modal similarity, digital-twin, assortment substitution, and emerging trend engine (similarity.py) wired across feature engineering, global pooling, Day-0 $\rightarrow$ Day-14 cold-start transfer, hierarchy reconciliation, ensembling, Auto-Forecaster Step 0 profiling, and Forecaster.evolve(target="similarity_kernel"):
- 7 Similarity Lenses & Multi-Modal Semantic/Attribute/Hierarchy Fusion (
similarity_df/compute_similarity_matrix): Compare pairwise[0, 1]similarity across"hybrid"(consensus PSD kernel fusing rank-normalized RBF kernels),"physics_attractor"(Takens delay-coordinate phase-space manifold, Sliced Wasserstein-1 distance, Largest Lyapunov exponent $\lambda_{\max}$, Permutation Entropy, and OU damping rate),"spectral_phase"(Hilbert Kuramoto phase-locking $R_{i,j}$, Welch PSD Jensen–Shannon divergence, and optimal lead-lag $\tau_{i \to j}^*$),"elastic_dtw"(Sakoe–Chiba banded elastic spring DTW),"minirocket"(84 ternary dilated convolutional PPV kernels),"structural_signature"(24-D econometric signature), and"foundation_latent"(Chronos-Bolt / Chronos-2 / TimesFM encoder representation similarity with deterministic MiniRocket + structural fallback), fused withtext_cols(TF-IDF character/word N-gram LSAsemantic_sim),attribute_cols(mixed Gower/Jaccard similarity), andhierarchy_cols(Wu–Palmer Lowest Common Ancestorhierarchy_sim). - 3-Mode Digital-Twin Analog Search (
find_similar_series_df) & Behavioral Clustering (cluster_by_similarity_df,plot_similarity_map): Retrieve top-$K$ analog series via"full_history","recent_window"(rolling recent trajectory window withoptimal_lag), or"launch_prefix"(Day-0 to Day-14 NPI launch matching with velocity/acceleration $(\dot{y}, \ddot{y})$ andwithin_hierarchy_levelscoping), and partition series into behavioral clusters with medoid and silhouette diagnostics. - Stockout-Aware Assortment Substitution (
recommend_substitutes_df) & Emerging Trend Breakout Sensing (detect_emerging_trends_df): Recommend in-stock same-department SKU substitutes (substitution_score,stock_status,substitution_rationale) and detect viral velocity/acceleration breakouts (trend_regime,breakout_zscore) alongside lagging bellwether followers (leading_bellwether_ts_id,lag_behind_leader,co_promote_candidates,recommended_merchandising_action). - Similarity-Woven Forecasting (
@similarity_global,@similarity_cold_start,similarity_hierarchy=True&Forecaster.evolve(target="similarity_kernel")): Train cluster-pooled global models (tide@similarity_global), transfer donor trajectories to cold-start series (theta@similarity_cold_start), reconcile synthesized cluster hierarchies (similarity_cluster_id=cluster_*/__sim_cluster_*__), and evolve custom similarity kernels through the 3-Gate Anti-Overfitting Ratchet (target="similarity_kernel").
import logging
import warnings
from scale_forecasting import (
cluster_by_similarity_df,
compute_similarity_matrix,
detect_emerging_trends_df,
embed_series_df,
find_similar_series_df,
plot_similarity_map,
recommend_substitutes_df,
)
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. Compare 7 Similarity Methods (Hybrid, Takens Attractor, Spectral Phase, Elastic DTW, MiniRocket, Structural Signature, Foundation Latent)
print("--- 1. Multi-Method Time-Series Similarity Comparison (f_ct.similarity_df / compute_similarity_matrix) ---")
method_rows = []
for m_name in (
"hybrid",
"physics_attractor",
"spectral_phase",
"elastic_dtw",
"minirocket",
"structural_signature",
"foundation_latent",
):
pairs_m = compute_similarity_matrix(panel, method=m_name).pairs_df
off_diag = pairs_m[pairs_m["ts_id_a"] != pairs_m["ts_id_b"]]
top_row = off_diag.sort_values("similarity", ascending=False).iloc[0]
method_rows.append(
{
"method": m_name,
"mean_similarity": float(off_diag["similarity"].mean()),
"max_similarity": float(top_row["similarity"]),
"top_pair": f"{top_row['ts_id_a']} <-> {top_row['ts_id_b']}",
"optimal_lag": int(top_row["optimal_lag"]),
}
)
display(pd.DataFrame(method_rows))
# 2. Behavioral Clustering (cluster_by_similarity_df), Digital-Twin Analog Search (find_similar_series_df) & Visual Map
print("--- 2. Behavioral Clustering & Zero-Metadata Launch-Prefix Digital-Twin Search ---")
clusters_p = cluster_by_similarity_df(panel, n_clusters=3, method="hybrid")
display(clusters_p)
analogs_p = find_similar_series_df(
panel,
query_ts_id=leaf_ids[0],
top_k=3,
method="hybrid",
mode="launch_prefix",
prefix_len=14,
)
display(analogs_p)
plot_similarity_map(panel, method="hybrid")
plt.show()
# 3. Cluster-Pooled @similarity_global, @similarity_cold_start & Evolutionary Similarity Kernel (target="similarity_kernel")
print("--- 3. @similarity_global + @similarity_cold_start + Forecaster.evolve(target='similarity_kernel') ---")
cfg_pg_sim = RunConfig(
run_name="playground_track_p_similarity",
data={"source_table": "local_panel", "freq": "D", "horizon": 14},
models=["theta", "theta@similarity_cold_start", "tide@global", "tide@similarity_global"],
model_params={"tide": {"max_steps": 10, "input_size": 14, "random_seed": 42}},
features={
"similarity_cluster_feature": True,
"similarity_n_clusters": 2,
"cold_start_transfer": True,
"cold_start_matching": "similarity",
},
hierarchy={
"enabled": True,
"similarity_hierarchy": True,
"similarity_n_clusters": 2,
"reconciliation_methods": ["mint_shrink"],
},
backtest={"enabled": True, "n_folds": 2, "horizon": 14, "step": 14},
)
pg_sim_cells, _ = execute_panel(panel, cfg_pg_sim)
pg_sim_summary = (
pd.DataFrame(
[
{
"model_type": c.model_type,
"wape": float(c.metrics.get("wape", float("nan"))),
"mae": float(c.metrics.get("mae", float("nan"))),
}
for c in pg_sim_cells
if c.status == "ok"
]
)
.groupby("model_type", as_index=False)
.agg(mean_wape=("wape", "mean"), mean_mae=("mae", "mean"))
.sort_values("mean_wape")
.reset_index(drop=True)
)
display(pg_sim_summary)
ev_sim = Forecaster.evolve(
panel,
horizon=14,
target="similarity_kernel",
backend="mock",
max_evaluations=2,
)
print(
f"Forecaster.evolve(target='similarity_kernel'): promoted={ev_sim.promoted}, "
f"inner_cv={ev_sim.baseline_score:.4f} -> {ev_sim.inner_cv_score:.4f} (FVA={ev_sim.fva_pct:+.2f}%), "
f"lockdown={ev_sim.lockdown_baseline_score:.4f} -> {ev_sim.lockdown_candidate_score:.4f}"
)
display(
ev_sim.leaderboard_df[
[
"candidate_id",
"status",
"inner_cv_score",
"inner_fva_pct",
"lockdown_candidate_score",
"promoted",
]
]
)
# 4. Multi-Modal Semantic/Attribute/Hierarchy Similarity, Assortment Substitution & Emerging Trend Sensing
print("--- 4. Multi-Modal Retail Similarity, recommend_substitutes_df & detect_emerging_trends_df ---")
pg_catalog = {
leaf_ids[0]: ("Oat Milk Vanilla 64oz Carton", "OatPure", "64oz", "Dairy_Alt", "Plant_Milk"),
leaf_ids[1]: ("Oat Milk Original 64oz Carton", "OatPure", "64oz", "Dairy_Alt", "Plant_Milk"),
leaf_ids[2]: ("Oat Milk Barista Edition 32oz", "OatPure", "32oz", "Dairy_Alt", "Plant_Milk"),
leaf_ids[3]: ("Artisan Vanilla Bean Gelato 16oz", "DolceVita", "16oz", "Frozen", "Ice_Cream"),
leaf_ids[4]: ("Artisan Chocolate Gelato 16oz", "DolceVita", "16oz", "Frozen", "Ice_Cream"),
leaf_ids[5]: ("Mineral SunBlock SPF50 Lotion 8oz", "SolarShield", "8oz", "Personal_Care", "Sun_Care"),
}
panel_retail = panel.copy()
for idx_c, col_c in enumerate(["product_title", "brand", "pack_size", "department", "subcategory"]):
panel_retail[col_c] = panel_retail["ts_id"].map(lambda s, i=idx_c: pg_catalog[str(s)][i])
mm_pairs_df = compute_similarity_matrix(
panel_retail,
method="hybrid",
text_cols=["product_title"],
attribute_cols=["brand", "pack_size"],
hierarchy_cols=["department", "subcategory"],
).pairs_df
display(
mm_pairs_df[mm_pairs_df["ts_id"] == leaf_ids[0]][
["ts_id", "neighbor_ts_id", "rank", "similarity_score", "semantic_sim", "hierarchy_sim", "physics_sim", "spectral_sim"]
].head(5)
)
inv_pg_df = pd.DataFrame(
[
{"ts_id": leaf_ids[0], "on_hand": 0.0, "safety_stock": 40.0},
{"ts_id": leaf_ids[1], "on_hand": 320.0, "safety_stock": 50.0},
{"ts_id": leaf_ids[2], "on_hand": 140.0, "safety_stock": 45.0},
{"ts_id": leaf_ids[3], "on_hand": 210.0, "safety_stock": 40.0},
{"ts_id": leaf_ids[4], "on_hand": 180.0, "safety_stock": 40.0},
{"ts_id": leaf_ids[5], "on_hand": 400.0, "safety_stock": 50.0},
]
)
subs_pg_df = recommend_substitutes_df(
panel_retail,
inventory_df=inv_pg_df,
query_ts_id=leaf_ids[0],
top_k=3,
text_cols=["product_title"],
attribute_cols=["brand", "pack_size"],
hierarchy_cols=["department", "subcategory"],
within_hierarchy_level="department",
require_in_stock=True,
)
display(subs_pg_df)
trends_pg_df = detect_emerging_trends_df(
panel_retail,
window=14,
top_k_related=2,
max_lag=5,
text_cols=["product_title"],
attribute_cols=["brand", "pack_size"],
hierarchy_cols=["department", "subcategory"],
)
display(trends_pg_df)
--- 1. Multi-Method Time-Series Similarity Comparison (f_ct.similarity_df / compute_similarity_matrix) ---
method mean_similarity max_similarity top_pair optimal_lag
hybrid 0.442064 0.757890 s_000000 <-> s_000005 0
physics_attractor 0.459787 0.775932 s_000000 <-> s_000005 0
spectral_phase 0.428556 0.917028 s_000000 <-> s_000005 0
elastic_dtw 0.477413 0.740320 s_000000 <-> s_000005 0
minirocket 0.402984 0.642992 s_000000 <-> s_000005 0
structural_signature 0.444000 0.653984 s_000000 <-> s_000002 0
foundation_latent 0.855884 0.960040 s_000000 <-> s_000002 0
--- 2. Behavioral Clustering & Zero-Metadata Launch-Prefix Digital-Twin 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.246647 0.246647 3 smooth_seasonal_sync cluster_0:smooth_seasonal_sync
s_000001 cluster_1 1 cluster_1 s_000003 s_000003 False 0.384001 0.078006 0.078006 3 high_velocity_trending cluster_1:high_velocity_trending
s_000002 cluster_0 0 cluster_0 s_000000 s_000000 False 0.567615 0.146371 0.146371 3 smooth_seasonal_sync cluster_0:smooth_seasonal_sync
s_000003 cluster_1 1 cluster_1 s_000003 s_000003 True 1.000000 0.004926 0.004926 3 high_velocity_trending cluster_1:high_velocity_trending
s_000004 cluster_1 1 cluster_1 s_000003 s_000003 False 0.558247 0.041345 0.041345 3 high_velocity_trending cluster_1:high_velocity_trending
s_000005 cluster_0 0 cluster_0 s_000000 s_000000 False 0.757890 0.240575 0.240575 3 smooth_seasonal_sync cluster_0:smooth_seasonal_sync
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.861841 0.861841 0.371698 0.813141 0.905079 0.621718 0.726994 0.0 0.0 0 0.923616 1.058783 11.188643 0.937798 0.868612 launch_prefix hybrid
s_000000 s_000000 s_000002 s_000002 2 0.837453 0.837453 0.403171 0.652017 0.944683 0.650711 0.757422 0.0 0.0 0 0.910071 1.936410 97.454286 0.902372 0.825480 launch_prefix hybrid
s_000000 s_000000 s_000004 s_000004 3 0.518552 0.518552 0.693865 0.590362 0.332258 0.450874 0.435751 0.0 0.0 0 0.217911 2.405923 117.763857 0.548695 0.495550 launch_prefix hybrid
--- 3. @similarity_global + @similarity_cold_start + Forecaster.evolve(target='similarity_kernel') ---
model_type mean_wape mean_mae
theta@similarity_cold_start_mint_shrink 0.293196 20.881092
theta_mint_shrink 0.293196 20.881092
tide@similarity_global_mint_shrink 0.331363 32.199538
tide@global_mint_shrink 0.340929 33.598721
tide@similarity_global 0.345332 32.230385
theta 0.353366 24.040542
theta@similarity_cold_start 0.353366 24.040542
tide@global 0.356949 33.536366
Forecaster.evolve(target='similarity_kernel'): promoted=False, inner_cv=0.5957 -> 0.5088 (FVA=+14.59%), lockdown=0.3673 -> 0.4058
candidate_id status inner_cv_score inner_fva_pct lockdown_candidate_score promoted
cand_similarity_kernel_g01 rejected_gate2 0.508763 14.5932 NaN False
cand_similarity_kernel_g02 rejected_gate2 0.508762 14.5933 0.405828 False
--- 4. Multi-Modal Retail Similarity, recommend_substitutes_df & detect_emerging_trends_df ---
ts_id neighbor_ts_id rank similarity_score semantic_sim hierarchy_sim physics_sim spectral_sim
s_000000 s_000001 1 0.602717 0.754689 1.0 0.250227 0.177941
s_000000 s_000002 2 0.598917 0.311635 1.0 0.741194 0.580561
s_000000 s_000003 3 0.250632 0.188223 0.0 0.449329 0.562424
s_000000 s_000005 4 0.121887 0.008399 0.0 0.775932 0.917028
s_000000 s_000004 5 0.073709 0.005719 0.0 0.467672 0.370730
query_ts_id substitute_ts_id rank substitution_score similarity_score semantic_sim hierarchy_sim available_units stock_status substitution_rationale
s_000000 s_000001 1 0.740871 0.602717 0.754689 1.0 270.0 in_stock_surplus Substitute s_000001 for s_000000: semantic_sim=0.75, hierarchy_sim=1.00, trajectory_sim=0.28, stock=in_stock_surplus (available_units=270.0)
s_000000 s_000002 2 0.583534 0.598917 0.311635 1.0 95.0 in_stock_surplus Substitute s_000002 for s_000000: semantic_sim=0.31, hierarchy_sim=1.00, trajectory_sim=0.57, stock=in_stock_surplus (available_units=95.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_000002 0.397916 steady_growth 0.003347 0.006047 1.884552 0.678168 cluster_0 s_000002 0 s_000000,s_000001 promote_trend_leader
s_000000 0.191072 stable 0.006516 0.008640 0.395786 0.702760 cluster_0 0 s_000001,s_000002 hold_baseline
s_000005 0.145734 stable -0.006969 0.006600 -0.057711 0.691780 cluster_0 0 s_000000,s_000002 hold_baseline
s_000004 0.127945 stable -0.002858 0.017462 -0.318070 0.716733 cluster_1 0 s_000003,s_000000 hold_baseline
s_000001 0.127888 stable -0.102416 -0.089837 -0.318961 0.572306 cluster_0 0 s_000000,s_000002 hold_baseline
s_000003 0.123484 stable -0.008284 0.006262 -0.389046 0.716824 cluster_1 0 s_000004,s_000000 hold_baseline
Act 12 · Lifecycle Markdown, Perishable Expiry, Space Reclamation, Contract Volume, Assortment, Pre-Packs & Store Rebalancing (Track Q / R)¶
When seasonal, promotional, or perishable inventory approaches an end-of-season or shelf-life deadline (expiry_step), Lifecycle Markdown & Perishable Clearance Optimization (optimize_clearance) solves a Mixed-Integer Linear Program (scipy.optimize.milp via HiGHS) over discrete markdown ladders (0% -> 10% -> 25% -> 50%) with monotone non-decreasing price steps, warehouse/shelf space reclamation targets (target_space_freed), and cross-SKU cannibalization penalties. In parallel, Vendor Contract Volume Optimization (optimize_contract_volume) finds the minimum-discount promotional schedule needed to hit cumulative vendor volume tiers (contract_tiers) under Copula CVaR.
Track Q.2 / R.2 (v1.9.1) completes the retail, apparel, grocery, and logistics optimization suite with three additional solvers on PlaygroundRun and Forecaster:
- Assortment Rationalization & Delisting Transference (
optimize_assortment/optimize_assortment_df): Uses the multi-modal similarity matrix $\mathbf{S}_{ij}$ to decompose delisted SKU demand into retained sibling transference vs. lost categorywalk_rateunder shelf-facing and SKU-count caps. - Simplex Size-Curve & Integer Pre-Pack Allocation (
optimize_prepacks/optimize_prepacks_df): Estimates store-cluster compositional size curves via Aitchison Centered Log-Ratio (CLR) Empirical-Bayes shrinkage and solves an integer pre-pack bundle MILP (pack_core = [1S, 2M, 2L, 1XL]) minimizing stockout + overstock mismatch. - Lateral Store-to-Store / Depot Rebalancing (
optimize_rebalancing/optimize_rebalancing_df): Solves a Hitchcock–Koopmans minimum-cost transshipment LP/MILP moving excess inventory from over-stocked origins to stockout-risk destinations within the effective transfer lead-time window.
# 1. Lifecycle Markdown, Digital-Twin Elasticity Borrowing & Space Reclamation MILP
bo_clearance = bakeoff(
data=panel[panel["ts_id"].isin(leaf_ids[:3])],
models=["theta", "holtwinters"],
horizon=14,
n_folds=2,
)
clearance_res = bo_clearance.optimize_clearance(
initial_inventory={leaf_ids[0]: 1800.0, leaf_ids[1]: 1500.0, leaf_ids[2]: 2200.0},
expiry_step={leaf_ids[0]: 10, leaf_ids[1]: 12, leaf_ids[2]: 14},
unit_volume={leaf_ids[0]: 1.5, leaf_ids[1]: 2.0, leaf_ids[2]: 1.0},
target_space_freed=4200.0,
reclaim_by_step=10,
spoilage_cost=3.0,
salvage_value=1.0,
)
print(
f"Clearance Status: {clearance_res.status} (is_feasible={clearance_res.is_feasible}) | "
f"Net Profit: ${clearance_res.total_optimal_profit:,.2f} (Baseline: ${clearance_res.total_baseline_profit:,.2f}, "
f"Incremental Lift: +${clearance_res.total_profit_lift:,.2f}) | "
f"Space Freed: {clearance_res.total_space_freed:,.1f} / {clearance_res.target_space_freed:,.1f}"
)
display(
clearance_res.summary_df[
[
"ts_id",
"initial_inventory",
"optimal_sell_through_units",
"unsold_terminal_units",
"sell_through_pct",
"total_space_freed",
"max_discount_pct",
"price_elasticity",
"elasticity_source",
"optimal_gross_profit",
"net_profit_lift",
]
]
)
bo_clearance.plot_clearance_schedule(clearance_res)
plt.show()
# 2. Vendor Contract Volume & Tiered Rebate / Take-or-Pay Optimization
contract_res = bo_clearance.optimize_contract_volume(
contract_tiers=[(2500.0, 4500.0), (3800.0, 12000.0)],
min_contract_volume=3500.0,
shortfall_penalty_per_unit=6.0,
risk_aversion_lambda=0.5,
)
print(
f"\nContract Volume Status: {contract_res.status} | "
f"Volume: {contract_res.optimal_portfolio_units:,.1f} (Baseline: {contract_res.baseline_portfolio_units:,.1f}, "
f"CVaR Shortfall: {contract_res.cvar_shortfall_units:,.1f}) | "
f"Rebate Tier Reached: {contract_res.achieved_tier_units:,.0f} units (${contract_res.rebate_earned:,.2f}) | "
f"Net Value Lift: +${contract_res.net_value_lift:,.2f}"
)
display(contract_res.summary_df)
# 3. Assortment Rationalization & Delisting Walk-Rate MILP (keep at most 2 of 3 leaf SKUs)
assortment_res = bo_clearance.optimize_assortment(
forecasts_df=base_preds[base_preds["ts_id"].isin(leaf_ids[:3])],
max_skus=2,
base_price=24.0,
unit_cost=10.0,
walk_rate=0.25,
)
print(
f"\nAssortment Rationalization Status: {assortment_res.status} | "
f"Retained SKUs: {assortment_res.retained_skus} / {assortment_res.total_candidate_skus} "
f"(Delisted: {assortment_res.delisted_skus}) | "
f"Transferred Units: {assortment_res.transferred_units:,.1f} | "
f"Lost Walk Units: {assortment_res.lost_walk_units:,.1f}"
)
print(assortment_res.assortment_df.iloc[:, :7].to_string(index=False))
# 4. Simplex Size-Curve & Integer Pre-Pack Allocation MILP
prepack_res = bo_clearance.optimize_prepacks(
forecasts_df=base_preds[base_preds["ts_id"].isin(leaf_ids[:3])],
)
print(
f"\nInteger Pre-Pack MILP Status: {prepack_res.status} | "
f"Total Allocated Units: {prepack_res.total_allocated_units:,.0f} "
f"(Fill Rate: {prepack_res.fill_rate:.1%}, Size Curve L1 Error: {prepack_res.size_curve_l1_error:.4f})"
)
print(prepack_res.pack_orders_df.head(6).to_string(index=False))
# 5. Lateral Store-to-Store Rebalancing LP
rebalance_res = bo_clearance.optimize_rebalancing(
forecasts_df=base_preds[base_preds["ts_id"].isin(leaf_ids[:3])],
initial_inventory={leaf_ids[0]: 4500.0, leaf_ids[1]: 200.0, leaf_ids[2]: 300.0},
transfer_cost=1.25,
transfer_lead_time=2.0,
)
print(
f"\nLateral Store Rebalancing Status: {rebalance_res.status} | "
f"Transferred: {rebalance_res.total_transferred_units:,.1f} units | "
f"Stockout Avoided: {rebalance_res.stockout_units_avoided:,.1f} units | "
f"Net Cost Savings: +${rebalance_res.net_cost_savings:,.2f}"
)
Clearance Status: infeasible (is_feasible=False) | Net Profit: $21,600.00 (Baseline: $21,600.00, Incremental Lift: +$0.00) | Space Freed: 2,700.0 / 4,200.0
| ts_id | initial_inventory | optimal_sell_through_units | unsold_terminal_units | sell_through_pct | total_space_freed | max_discount_pct | price_elasticity | elasticity_source | optimal_gross_profit | net_profit_lift | |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | s_000000 | 1800.0 | 1800.0 | 4.547474e-13 | 1.0 | 2700.0 | 0.0 | -3.587408 | digital_twin_borrowed | 21600.0 | 0.0 |
Contract Volume Status: optimal | Volume: 11,927.2 (Baseline: 4,249.5, CVaR Shortfall: 0.0) | Rebate Tier Reached: 3,800 units ($12,000.00) | Net Value Lift: +$32,497.17
| ts_id | baseline_units | optimal_units | incremental_units | mean_discount_pct | max_discount_pct | baseline_margin | optimal_margin | rebate_allocated | shortfall_penalty_allocated | net_contract_value | price_elasticity | elasticity_source | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | s_000000 | 4249.460013 | 11927.240872 | 7677.780859 | 0.25 | 0.25 | 50993.520161 | 83490.686105 | 12000.0 | 0.0 | 95490.686105 | -3.587408 | digital_twin_borrowed |
Assortment Rationalization Status: optimal | Retained SKUs: 2 / 3 (Delisted: 1) | Transferred Units: 16.9 | Lost Walk Units: 5.6 ts_id action is_retained baseline_units walk_rate transferable_share transferred_out_units s_000000 KEEP True 3683.268197 0.25 0.75 0.000000 s_000001 DELIST False 22.583356 0.25 0.75 16.937517 s_000002 KEEP True 2924.132206 0.25 0.75 0.000000 Integer Pre-Pack MILP Status: optimal | Total Allocated Units: 6,630 (Fill Rate: 100.0%, Size Curve L1 Error: 0.0001) store_id pack_id packs_ordered units_per_pack total_pack_units pack_cost total_pack_spend pack_composition s_000000 pack_core 229 6.0 1374.0 6.0 1374.0 S:1, M:2, L:2, XL:1 s_000000 pack_small 231 5.0 1155.0 5.0 1155.0 S:2, M:2, L:1 s_000000 pack_large 231 5.0 1155.0 5.0 1155.0 M:1, L:2, XL:2 s_000001 pack_core 2 6.0 12.0 6.0 12.0 S:1, M:2, L:2, XL:1 s_000001 pack_small 1 5.0 5.0 5.0 5.0 S:2, M:2, L:1 s_000001 pack_large 1 5.0 5.0 5.0 5.0 M:1, L:2, XL:2 Lateral Store Rebalancing Status: optimal | Transferred: 994.1 units | Stockout Avoided: 994.1 units | Net Cost Savings: +$23,611.03
Where next¶
- Next in Track 1 (Local Sandbox & Plugins):
09_custom_models_and_metrics.ipynb— author custom 1-fileBaseModelandBaseMetricplugins in local memory. - Deep Dive into Glass-Box Auto-Forecasting:
11_auto_forecaster_and_autofocus.ipynb— explore all 4 observational astronomy exposure tiers, the 12-panel DGP benchmark bank, and boundedautofocus. - Move to Track 2 (Cloud Runtimes):
01_bigquery_native_sql.ipynb— executeARIMA_PLUSandTimesFM 2.0(AI.FORECAST) directly in BigQuery SQL. - Documentation: Getting started · Glass-Box Auto-Forecaster · Models reference · Evaluation metrics reference