{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Lesson 20: Hierarchical Forecasting and Reconciliation\n",
        "\n",
        "**CS230 inspiration:** Structuring ML projects and evaluating models against real operational constraints.\n",
        "\n",
        "**Demand forecasting focus:** Make item-store forecasts coherent with item, store, and total planning views.\n",
        "\n",
        "**Learning objectives**\n",
        "\n",
        "- Evaluate forecasts across hierarchy levels.\n",
        "- Understand why independently trained forecasts can become incoherent.\n",
        "- Reconcile bottom-level forecasts to top-level planning constraints.\n",
        "\n",
        "**Senior-readiness checkpoint:** You can support finance, supply chain, and store operations with one coherent forecast story.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Code Cell 1 Explanation\n",
        "\n",
        "**What this cell does:** This setup cell imports the shared scientific Python stack and the curriculum helpers used by later cells. It also establishes the deterministic seed convention so repeated runs are comparable.\n",
        "\n",
        "**Why it matters:** A restart-and-run notebook should make its dependencies explicit before any modeling work begins. For forecasting, reproducibility is especially important because small data or seed changes can change validation conclusions.\n",
        "\n",
        "**Key operations to notice:** confirm that shared helper imports match the lesson's code path; check that `SEED` is defined before any generated data or model training\n",
        "\n",
        "**What to inspect:** Check that imports are grouped by purpose: general analysis packages, forecasting data helpers, metrics, plotting utilities, and any lesson-specific libraries.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\n",
        "import numpy as np\n",
        "import pandas as pd\n",
        "\n",
        "from demand_forecasting_curriculum.data import (\n",
        "    DEFAULT_FEATURE_COLUMNS,\n",
        "    generate_daily_demand,\n",
        "    make_sequence_dataset,\n",
        "    make_supervised_table,\n",
        "    time_series_split,\n",
        ")\n",
        "from demand_forecasting_curriculum.metrics import (\n",
        "    interval_coverage,\n",
        "    mase,\n",
        "    pinball_loss,\n",
        "    smape,\n",
        "    wmape,\n",
        ")\n",
        "from demand_forecasting_curriculum.plotting import plot_predictions, plot_series\n",
        "\n",
        "SEED = 42\n",
        "np.random.seed(SEED)\n",
        "\n",
        "from sklearn.ensemble import HistGradientBoostingRegressor\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Hiring-Manager Signal\n",
        "\n",
        "Real demand forecasts are consumed at multiple levels: SKU-store, store total, item total, region, and business total. A senior-ready Data Scientist knows that a model can look good at one level while creating planning conflicts elsewhere.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Code Cell 2 Explanation\n",
        "\n",
        "**What this cell does:** This cell advances **Hierarchical Forecasting and Reconciliation** by working on synthetic demand generation, time-based splitting, supervised feature construction, forecast metrics. It creates or updates `df`, `supervised`, `train`, `valid`, `test`, `feature_cols` and prepares evidence that later cells use rather than hiding state in prose.\n",
        "\n",
        "**Why it matters:** The goal is tied to this lesson's forecasting focus: Make item-store forecasts coherent with item, store, and total planning views. Each object is kept inspectable so the learner can connect code, assumptions, and modeling consequences.\n",
        "\n",
        "**Key operations to notice:** creates a synthetic retail panel with known demand drivers; turns time series rows into forecast-origin training examples; keeps train, validation, and test windows ordered by date; trains a strong tabular baseline; evaluates scale-weighted forecast error\n",
        "\n",
        "**What to inspect:** Before moving on, inspect shapes, date ranges, metric values, segment behavior, or generated tables. If a value looks surprisingly good, surprisingly bad, or unavailable at forecast time, treat that as a modeling clue.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "df = generate_daily_demand(n_stores=5, n_items=8, periods=540, seed=SEED)\n",
        "supervised = make_supervised_table(df, horizon=7)\n",
        "train, valid, test = time_series_split(supervised, valid_days=60, test_days=60)\n",
        "\n",
        "feature_cols = [\"store_id\", \"item_id\", *DEFAULT_FEATURE_COLUMNS]\n",
        "model = HistGradientBoostingRegressor(max_iter=100, learning_rate=0.05, random_state=SEED)\n",
        "model.fit(train[feature_cols], train[\"y\"])\n",
        "bottom = test[[\"date\", \"store_id\", \"item_id\", \"y\", \"lag_7\"]].assign(\n",
        "    prediction=model.predict(test[feature_cols])\n",
        ")\n",
        "wmape(bottom[\"y\"], bottom[\"prediction\"])\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Code Cell 3 Explanation\n",
        "\n",
        "**What this cell does:** This cell advances **Hierarchical Forecasting and Reconciliation** by working on forecast metrics. It creates or updates `bottom_up_total`, `top_level_history`, `top_test` and prepares evidence that later cells use rather than hiding state in prose.\n",
        "\n",
        "**Why it matters:** The goal is tied to this lesson's forecasting focus: Make item-store forecasts coherent with item, store, and total planning views. Each object is kept inspectable so the learner can connect code, assumptions, and modeling consequences.\n",
        "\n",
        "**Key operations to notice:** evaluates scale-weighted forecast error\n",
        "\n",
        "**What to inspect:** Before moving on, inspect shapes, date ranges, metric values, segment behavior, or generated tables. If a value looks surprisingly good, surprisingly bad, or unavailable at forecast time, treat that as a modeling clue.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "bottom_up_total = (\n",
        "    bottom.groupby(\"date\", as_index=False)\n",
        "    .agg(actual=(\"y\", \"sum\"), bottom_up_prediction=(\"prediction\", \"sum\"))\n",
        "    .sort_values(\"date\")\n",
        ")\n",
        "top_level_history = (\n",
        "    supervised.groupby(\"date\", as_index=False)\n",
        "    .agg(total_y=(\"y\", \"sum\"), total_lag_7=(\"lag_7\", \"sum\"))\n",
        "    .sort_values(\"date\")\n",
        ")\n",
        "top_test = bottom_up_total.merge(\n",
        "    top_level_history[[\"date\", \"total_lag_7\"]],\n",
        "    on=\"date\",\n",
        "    how=\"left\",\n",
        ")\n",
        "\n",
        "{\n",
        "    \"bottom_level_wmape\": wmape(bottom[\"y\"], bottom[\"prediction\"]),\n",
        "    \"bottom_up_total_wmape\": wmape(top_test[\"actual\"], top_test[\"bottom_up_prediction\"]),\n",
        "    \"independent_top_naive_wmape\": wmape(top_test[\"actual\"], top_test[\"total_lag_7\"]),\n",
        "}\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Code Cell 4 Explanation\n",
        "\n",
        "**What this cell does:** This cell advances **Hierarchical Forecasting and Reconciliation** by working on the lesson workflow. It creates or updates `top_constraint`, `reconciled`, `bottom_sum`, `coherence` and prepares evidence that later cells use rather than hiding state in prose.\n",
        "\n",
        "**Why it matters:** The goal is tied to this lesson's forecasting focus: Make item-store forecasts coherent with item, store, and total planning views. Each object is kept inspectable so the learner can connect code, assumptions, and modeling consequences.\n",
        "\n",
        "**Key operations to notice:** follow the assignments, final displayed object, and any checks in the cell because those are the evidence the next cell depends on\n",
        "\n",
        "**What to inspect:** Before moving on, inspect shapes, date ranges, metric values, segment behavior, or generated tables. If a value looks surprisingly good, surprisingly bad, or unavailable at forecast time, treat that as a modeling clue.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "top_constraint = top_test[[\"date\", \"total_lag_7\"]].rename(\n",
        "    columns={\"total_lag_7\": \"top_constraint\"}\n",
        ")\n",
        "reconciled = bottom.merge(top_constraint, on=\"date\")\n",
        "bottom_sum = reconciled.groupby(\"date\")[\"prediction\"].transform(\"sum\")\n",
        "reconciled[\"scale_factor\"] = reconciled[\"top_constraint\"] / bottom_sum.replace(0, np.nan)\n",
        "reconciled[\"reconciled_prediction\"] = (\n",
        "    reconciled[\"prediction\"] * reconciled[\"scale_factor\"].fillna(1.0)\n",
        ")\n",
        "\n",
        "coherence = (\n",
        "    reconciled.groupby(\"date\")\n",
        "    .agg(\n",
        "        top_constraint=(\"top_constraint\", \"first\"),\n",
        "        reconciled_total=(\"reconciled_prediction\", \"sum\"),\n",
        "    )\n",
        "    .assign(abs_gap=lambda x: (x[\"top_constraint\"] - x[\"reconciled_total\"]).abs())\n",
        ")\n",
        "coherence[\"abs_gap\"].max()\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Code Cell 5 Explanation\n",
        "\n",
        "**What this cell does:** This cell advances **Hierarchical Forecasting and Reconciliation** by working on forecast metrics. It creates or updates `comparison` and prepares evidence that later cells use rather than hiding state in prose.\n",
        "\n",
        "**Why it matters:** The goal is tied to this lesson's forecasting focus: Make item-store forecasts coherent with item, store, and total planning views. Each object is kept inspectable so the learner can connect code, assumptions, and modeling consequences.\n",
        "\n",
        "**Key operations to notice:** evaluates scale-weighted forecast error; creates an inspectable table for assumptions, metrics, or decisions\n",
        "\n",
        "**What to inspect:** Before moving on, inspect shapes, date ranges, metric values, segment behavior, or generated tables. If a value looks surprisingly good, surprisingly bad, or unavailable at forecast time, treat that as a modeling clue.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "comparison = pd.DataFrame(\n",
        "    [\n",
        "        (\"unreconciled_bottom\", wmape(bottom[\"y\"], bottom[\"prediction\"])),\n",
        "        (\"reconciled_bottom\", wmape(reconciled[\"y\"], reconciled[\"reconciled_prediction\"])),\n",
        "        (\n",
        "            \"reconciled_total\",\n",
        "            wmape(\n",
        "                top_test[\"actual\"],\n",
        "                reconciled.groupby(\"date\")[\"reconciled_prediction\"].sum(),\n",
        "            ),\n",
        "        ),\n",
        "    ],\n",
        "    columns=[\"forecast\", \"wmape\"],\n",
        ")\n",
        "comparison\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Lesson Recap\n",
        "\n",
        "In this lesson, we used 5 runnable code cells to work through **Hierarchical Forecasting and Reconciliation**. The practical focus was: Make item-store forecasts coherent with item, store, and total planning views.\n",
        "\n",
        "We did this because deep learning for demand forecasting is not only about choosing an architecture. The learner needs to understand the data contract, the target and horizon, the validation path, the metric, and the operational decision supported by the forecast.\n",
        "\n",
        "The core takeaways were:\n",
        "\n",
        "- Evaluate forecasts across hierarchy levels.\n",
        "- Understand why independently trained forecasts can become incoherent.\n",
        "- Reconcile bottom-level forecasts to top-level planning constraints.\n",
        "\n",
        "By the end, you should be able to explain not just what the code produced, but why each step was necessary and what could go wrong if the same step were skipped or performed with leakage.\n",
        "\n",
        "**Senior-readiness reminder:** You can support finance, supply chain, and store operations with one coherent forecast story.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Exercises\n",
        "\n",
        "- Reconcile to a blended top forecast instead of pure seasonal naive.\n",
        "- Compute WMAPE by store before and after reconciliation.\n",
        "- Explain when coherence is worth a small loss in bottom-level accuracy.\n"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python (deep-learning-demand)",
      "language": "python",
      "name": "deep-learning-demand"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.12"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
