{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Lesson 02: Forecasting Framing and Baselines\n",
        "\n",
        "**CS230 inspiration:** Neural-network basics and project framing before modeling.\n",
        "\n",
        "**Demand forecasting focus:** Turn a time series panel into supervised examples and compare simple baselines.\n",
        "\n",
        "**Learning objectives**\n",
        "\n",
        "- Define forecast origin, horizon, target, and features.\n",
        "- Build lag and rolling-window features without using future demand.\n",
        "- Evaluate seasonal naive and tabular baselines with forecasting metrics.\n",
        "\n",
        "**Senior-readiness checkpoint:** You can defend the baseline and explain why the neural model must beat it on the right split.\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",
        "from sklearn.linear_model import LinearRegression\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Code Cell 2 Explanation\n",
        "\n",
        "**What this cell does:** This cell advances **Forecasting Framing and Baselines** by working on synthetic demand generation, time-based splitting, supervised feature construction. 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: Turn a time series panel into supervised examples and compare simple baselines. 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\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=4, n_items=6, 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",
        "train[[\"date\", \"store_id\", \"item_id\", \"demand\", \"y\", \"lag_7\"]].head()\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Code Cell 3 Explanation\n",
        "\n",
        "**What this cell does:** This cell advances **Forecasting Framing and Baselines** by working on forecast metrics. It creates or updates `seasonal_naive`, `moving_average`, `baseline_scores` 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: Turn a time series panel into supervised examples and compare simple baselines. 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; evaluates symmetric percentage 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": [
        "seasonal_naive = valid[\"lag_7\"].to_numpy()\n",
        "moving_average = valid[\"rolling_mean_28\"].to_numpy()\n",
        "\n",
        "baseline_scores = pd.DataFrame(\n",
        "    [\n",
        "        (\"seasonal_naive_lag_7\", wmape(valid[\"y\"], seasonal_naive), smape(valid[\"y\"], seasonal_naive)),\n",
        "        (\"moving_average_28\", wmape(valid[\"y\"], moving_average), smape(valid[\"y\"], moving_average)),\n",
        "    ],\n",
        "    columns=[\"model\", \"wmape\", \"smape\"],\n",
        ")\n",
        "baseline_scores\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Code Cell 4 Explanation\n",
        "\n",
        "**What this cell does:** This cell advances **Forecasting Framing and Baselines** by working on forecast metrics. It creates or updates `X_train`, `y_train`, `X_valid`, `y_valid`, `linear`, `boosted` 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: Turn a time series panel into supervised examples and compare simple baselines. Each object is kept inspectable so the learner can connect code, assumptions, and modeling consequences.\n",
        "\n",
        "**Key operations to notice:** trains a strong tabular baseline; trains a simple interpretable baseline; evaluates scale-weighted forecast error; evaluates symmetric percentage 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": [
        "X_train, y_train = train[feature_cols], train[\"y\"]\n",
        "X_valid, y_valid = valid[feature_cols], valid[\"y\"]\n",
        "\n",
        "linear = LinearRegression()\n",
        "linear.fit(X_train, y_train)\n",
        "\n",
        "boosted = HistGradientBoostingRegressor(max_iter=80, learning_rate=0.05, random_state=SEED)\n",
        "boosted.fit(X_train, y_train)\n",
        "\n",
        "model_scores = pd.DataFrame(\n",
        "    [\n",
        "        (\"linear\", wmape(y_valid, linear.predict(X_valid)), smape(y_valid, linear.predict(X_valid))),\n",
        "        (\"hist_gradient_boosting\", wmape(y_valid, boosted.predict(X_valid)), smape(y_valid, boosted.predict(X_valid))),\n",
        "    ],\n",
        "    columns=[\"model\", \"wmape\", \"smape\"],\n",
        ")\n",
        "pd.concat([baseline_scores, model_scores], ignore_index=True).sort_values(\"wmape\")\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Code Cell 5 Explanation\n",
        "\n",
        "**What this cell does:** This cell advances **Forecasting Framing and Baselines** by working on visualization. It creates or updates `one_series`, `one_series`, `ax` 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: Turn a time series panel into supervised examples and compare simple baselines. Each object is kept inspectable so the learner can connect code, assumptions, and modeling consequences.\n",
        "\n",
        "**Key operations to notice:** visualizes model behavior or data quality\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": [
        "one_series = valid.query(\"store_id == 0 and item_id == 0\").sort_values(\"date\")\n",
        "one_series = one_series.assign(prediction=boosted.predict(one_series[feature_cols]))\n",
        "ax = plot_predictions(one_series[\"date\"], one_series[\"y\"], one_series[\"prediction\"])\n",
        "ax.set_title(\"Seven-day-ahead forecast for one series\")\n",
        "plt.show()\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Lesson Recap\n",
        "\n",
        "In this lesson, we used 5 runnable code cells to work through **Forecasting Framing and Baselines**. The practical focus was: Turn a time series panel into supervised examples and compare simple baselines.\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",
        "- Define forecast origin, horizon, target, and features.\n",
        "- Build lag and rolling-window features without using future demand.\n",
        "- Evaluate seasonal naive and tabular baselines with forecasting metrics.\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 defend the baseline and explain why the neural model must beat it on the right split.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Exercises\n",
        "\n",
        "- Change the horizon from 7 to 14 days and compare which baseline degrades fastest.\n",
        "- Add a `rolling_mean_14` feature in the helper or notebook and evaluate its impact.\n",
        "- Explain which feature would become leakage if it were computed after the forecast origin.\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
}
