Rana Maninder Singh
Lesson 7 of 7Time Series Forecasting

Capstone — Forecast a KPI

Lesson opener

In one line: Running an end-to-end offline forecast on a synthetic Indian ops KPI.

Why it matters: A forecast decision is a conjunction of simplicity and measured skill - not a single pretty chart.

Before this lesson: A/B Testing / Inferential stats

Before you start

ResourceLink
PreviousEvaluation and backtesting
NextPortfolio
PrerequisitesAll timeseries lessons, A/B Testing or Inferential stats
Time~75 minutes

What you will learn

  • Running an end-to-end offline forecast on a synthetic Indian ops KPI
  • Comparing seasonal naive, Holt-Winters, and ARIMA on a locked holdout
  • Applying a short expanding-window check before the decision
  • Writing a one-page recommend / do-not-promote note from pre-registered rules
  • Packaging helpers so a teammate can re-run the readout

Pinned libraries for this course

pip install -r docs/timeseries/requirements.txt

Pinned in docs/timeseries/requirements.txt:

numpy==2.1.3
pandas==2.2.3
statsmodels==0.14.4
scipy==1.14.1

This capstone uses numpy, pandas, and statsmodels together — still offline. No live warehouse is required. Each Python fence rebuilds data and helpers so scripts/test_course_code.py can execute blocks in isolation; that redundancy is intentional for the course runner, not a style to copy into production services.


Business brief

Stakeholder: Warehouse ops lead, Bengaluru D2C brand.

KPI: Daily fulfilled orders (count).

Frequency: Daily.

Horizon: 7 days (next week's shift plan).

Decision rule (pre-registered): promote a candidate only if holdout MAE beats seasonal naive by ≥ 5%; otherwise keep seasonal naive. Backtest mean MAE on ≥ 3 expanding origins must not be worse than seasonal naive by more than 10%.

WHY A forecast decision is a conjunction of simplicity and measured skill — not a single pretty chart.

WHEN After the locked window ends; never while quietly retuning on the test week.

Demo 1 — Synthesize the KPI

# Offline demo: Bengaluru daily fulfilled orders with weekly season + mild trend
import numpy as np
import pandas as pd

rng = np.random.default_rng(42)
n = 84
idx = pd.date_range("2026-01-05", periods=n, freq="D")
trend = np.linspace(420, 500, n)
season = np.tile([0.0, 5, 2, 8, 18, 28, -15], 12)
noise = rng.normal(0, 6, n)
orders = np.clip(trend + season + noise, 1, None).round().astype(int)
y = pd.Series(orders, index=idx, name="fulfilled_orders")
print(y.tail())
print(y.groupby(y.index.dayofweek).mean().round(1))
assert len(y) == 84
assert y.min() >= 1

Demo 2 — Locked holdout and baseline forecasts

# Offline demo: train/test split + seasonal naive + drift
import numpy as np
import pandas as pd

rng = np.random.default_rng(42)
n = 84
idx = pd.date_range("2026-01-05", periods=n, freq="D")
y = pd.Series(
    np.clip(
        np.linspace(420, 500, n)
        + np.tile([0.0, 5, 2, 8, 18, 28, -15], 12)
        + rng.normal(0, 6, n),
        1,
        None,
    ).round().astype(int),
    index=idx,
    name="fulfilled_orders",
)
train, test = y.iloc[:-7], y.iloc[-7:]


def seasonal_naive(train, horizon=7, period=7):
    hist = train.to_numpy(dtype=float)
    out = [hist[-period + ((h - 1) % period)] for h in range(1, horizon + 1)]
    idx = pd.date_range(train.index[-1] + train.index.freq, periods=horizon, freq=train.index.freq)
    return pd.Series(out, index=idx, name="seasonal_naive")


def mae(a, p):
    return float(np.mean(np.abs(a.to_numpy() - p.to_numpy())))


sn = seasonal_naive(train)
print("seasonal naive MAE:", round(mae(test, sn), 2))
assert len(test) == 7
assert mae(test, sn) < 40

Demo 3 — Holt-Winters and ARIMA candidates

# Offline demo: HW and ARIMA on the same locked holdout
import numpy as np
import pandas as pd
from statsmodels.tsa.holtwinters import ExponentialSmoothing
from statsmodels.tsa.arima.model import ARIMA
import warnings

rng = np.random.default_rng(42)
n = 84
idx = pd.date_range("2026-01-05", periods=n, freq="D")
y = pd.Series(
    np.clip(
        np.linspace(420, 500, n)
        + np.tile([0.0, 5, 2, 8, 18, 28, -15], 12)
        + rng.normal(0, 6, n),
        1,
        None,
    ).round().astype(int),
    index=idx,
)
train, test = y.iloc[:-7], y.iloc[-7:]


def mae(a, p):
    return float(np.mean(np.abs(np.asarray(a, dtype=float) - np.asarray(p, dtype=float))))


with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    hw = (
        ExponentialSmoothing(train, trend="add", seasonal="add", seasonal_periods=7)
        .fit(optimized=True)
        .forecast(7)
    )
    ar = ARIMA(train, order=(1, 1, 1)).fit().forecast(7)
print({"hw_mae": round(mae(test, hw), 2), "arima_mae": round(mae(test, ar), 2)})
assert np.isfinite(mae(test, hw))
assert np.isfinite(mae(test, ar))

Demo 4 — Pre-registered promote rule

# Offline demo: promote only if MAE beats seasonal naive by >= 5%
def decision(sn_mae: float, candidate_mae: float, name: str, min_improve: float = 0.05) -> dict:
    improve = (sn_mae - candidate_mae) / sn_mae if sn_mae else 0.0
    promote = improve >= min_improve
    return {
        "model": name,
        "sn_mae": round(sn_mae, 2),
        "candidate_mae": round(candidate_mae, 2),
        "improve_pct": round(100 * improve, 1),
        "action": "promote" if promote else "keep_seasonal_naive",
    }


assert decision(20.0, 18.5, "hw")["action"] == "promote"  # 7.5% > 5%
assert decision(20.0, 19.5, "hw")["action"] == "keep_seasonal_naive"
print(decision(20.0, 17.0, "holt_winters"))

Demo 5 — Mini expanding-window gate

# Offline demo: mean MAE across a few origins for seasonal naive vs HW
import numpy as np
import pandas as pd
from statsmodels.tsa.holtwinters import ExponentialSmoothing
import warnings

rng = np.random.default_rng(42)
n = 84
idx = pd.date_range("2026-01-05", periods=n, freq="D")
y = pd.Series(
    np.clip(
        np.linspace(420, 500, n)
        + np.tile([0.0, 5, 2, 8, 18, 28, -15], 12)
        + rng.normal(0, 6, n),
        1,
        None,
    ),
    index=idx,
)


def seasonal_naive_arr(train, horizon=7, period=7):
    hist = train.to_numpy(dtype=float)
    return np.array([hist[-period + ((h - 1) % period)] for h in range(1, horizon + 1)])


horizon, min_train = 7, 56
origins = list(range(min_train, len(y) - horizon + 1, 7))
sn_maes, hw_maes = [], []
with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    for i in origins:
        train = y.iloc[:i]
        actual = y.iloc[i : i + horizon].to_numpy()
        sn_maes.append(float(np.mean(np.abs(actual - seasonal_naive_arr(train)))))
        hw = (
            ExponentialSmoothing(train, trend="add", seasonal="add", seasonal_periods=7)
            .fit(optimized=True)
            .forecast(horizon)
            .to_numpy()
        )
        hw_maes.append(float(np.mean(np.abs(actual - hw))))
summary = {
    "origins": len(origins),
    "sn_mean_mae": round(float(np.mean(sn_maes)), 2),
    "hw_mean_mae": round(float(np.mean(hw_maes)), 2),
}
print(summary)
assert summary["origins"] >= 3
# Gate: HW not worse than SN by >10% on mean MAE
assert summary["hw_mean_mae"] <= summary["sn_mean_mae"] * 1.10

Demo 6 — One-page readout dict

# Offline demo: assemble readout fields for the ops lead
readout = {
    "kpi": "fulfilled_orders",
    "city": "Bengaluru",
    "horizon_days": 7,
    "holdout_sn_mae": 9.4,
    "holdout_hw_mae": 7.8,
    "holdout_arima_mae": 11.2,
    "backtest_origins": 4,
    "backtest_sn_mean_mae": 10.1,
    "backtest_hw_mean_mae": 8.6,
    "rule": "promote if holdout MAE beats seasonal naive by >=5% and backtest within +10%",
}


def final_action(r: dict) -> str:
    improve = (r["holdout_sn_mae"] - r["holdout_hw_mae"]) / r["holdout_sn_mae"]
    back_ok = r["backtest_hw_mean_mae"] <= r["backtest_sn_mean_mae"] * 1.10
    if improve >= 0.05 and back_ok:
        return "promote_holt_winters"
    return "keep_seasonal_naive"


assert final_action(readout) == "promote_holt_winters"
print(final_action(readout))
print("pins: numpy==2.1.3 pandas==2.2.3 statsmodels==0.14.4 scipy==1.14.1")

Demo 7 — Contribution sketch in INR (planning only)

# Offline demo: translate MAE improvement into rough INR planning value
def weekly_value_inr(mae_improvement_orders: float, contribution_per_order_inr: float) -> float:
    # Better forecast reduces over/under-staff waste; sketch only
    return round(mae_improvement_orders * 7 * contribution_per_order_inr * 0.25, 0)


sketch = weekly_value_inr(1.6, 120.0)
print({"approx_weekly_inr": sketch})
assert sketch > 0

Write the recommendation

Your readout to the warehouse lead should include: KPI definition, pins (numpy==2.1.3, pandas==2.2.3, statsmodels==0.14.4, scipy==1.14.1), holdout table, backtest means, festival caveats, and the promote / keep-baseline action from the pre-registered rule only. Do not retune after seeing the locked week.

WHY Pre-registration is the same discipline you used in A/B testing — peeking invents winners.

WHEN Before the Monday shift roster freezes.


Failure modes in the capstone

  1. Quietly dropping a bad origin until HW wins.
  2. Fitting on full history including the holdout.
  3. Selling ARIMA when seasonal naive wins the table.
  4. Ignoring IST calendar shutdowns in the narrative.

Explaining this to a workplace stakeholder

In Indian product and ops teams the forecast is a staffing and cash decision, not a notebook trophy. Walk the stakeholder through three questions before any chart: what KPI is defined in the dictionary, what timezone and calendar the daily bucket uses, and what happens on known closure days. If those answers are fuzzy, stop modelling and fix the definition. A crisp definition plus seasonal naive often beats a glamorous model on a muddy series.

When you present numbers, lead with units the listener already uses — paid orders, tickets, settlements — and put the baseline column first. Only then show the candidate. If the candidate wins by a thin margin, say so out loud and recommend keeping the simpler method until the edge is stable across several origins. Document the pinned library versions (numpy==2.1.3, pandas==2.2.3, statsmodels==0.14.4, scipy==1.14.1) in the same ticket so a teammate in another city can reproduce the table next Monday without guessing which wheel file you had installed.

Watch for process failure modes that look like model failure: a marketing push that was not flagged, a payment-rail outage labelled as demand drop, or a festival week treated as ordinary seasonality. Write those caveats next to the MAE. The goal of this course lesson is judgment under workplace constraints — reproducible pins, chronological validation, and a decision rule you can defend in a standup without inventing accuracy.

For remote-friendly handoffs, paste the decision rule and the latest rolling means into the ticket description. Link the official docs you relied on. Avoid pasting secrets, live warehouse credentials, or hard-coded FX rates. Keep the script offline-friendly so continuous integration can re-run every code fence the same way learners do on a laptop in Pune or Hyderabad.

Finally, schedule an owner for the Monday re-run. Models without owners quietly rot after the first festival. A one-page readout with KPI, pins, origins, control MAE, candidate MAE, and the ship-or-keep decision is enough for most Bengaluru and Mumbai ops leads if the numbers are honest.

Treat this capstone as a rehearsal for a real ticket: freeze the KPI, freeze the rule, run the bakeoff, write the decision, and name the owner. If leadership asks for a neural net later, you still have the seasonal naive column and the pinned versions to show what skill actually improved.

Verified against numpy 2.1.3, pandas 2.2.3, statsmodels 0.14.4 (+1 more) documentation, September 2026.

Test yourself

  1. What horizon does this Bengaluru staffing brief use?
  2. What improve threshold promotes a candidate over seasonal naive?
  3. Why run a mini expanding-window gate after the holdout?
  4. True or false: you may refit on the locked test week before publishing MAE.
  5. Which model classes did the bakeoff compare?
  6. What should the readout list about library versions?
  7. Name one festival-related caveat for Indian retail orders.
  8. What action do you take if HW loses to seasonal naive?
  9. Why map MAE to a rough INR sketch for stakeholders?
  10. True or false: ARIMA must ship because the name sounds more advanced.