Prescriptive Analytics & Decision Intelligence
Overview / Module 5 / Day 42
Module 5 · Simulation and Monte Carlo · Day 42 of 80

Input Distributions and Forecast Errors

A simulation is only as good as its random numbers. Today you build them from data: you clean the van trip log, compare actual and planned minutes, fit distributions and check whether they match the tails that matter, and turn the forecast errors from Day 19's history into demand inputs.

▶
Video for Day 42 coming soon

In this lesson

Today's 5-hour plan

LessonProjectBreakCommit
0:00–0:45
42.1 Look at the data first
0:45–1:45
42.2 Actual against planned; 42.3 which distribution?
1:45–2:00
Break
2:00–2:45
42.4 Demand: forecast errors and counts
2:45–3:45
Fitted or empirical?; a planted bug
3:45–4:00
Break
4:00–4:45
Mini-project: buffers by weather
4:45–5:00
Commit with Git + checklist

42.1 Look at the data first

trip_log holds 1,872 van trips: date, weather, from and to, planned minutes (from delivery_matrix) and actual minutes. Create day42/inputs.py:

"""Day 42: where the random numbers come from. Clean the trip log, fit travel-time and demand distributions.

Import it:  from inputs import load_trips, clean_trips, travel_sampler, demand_error_sd
"""
import numpy as np
import pandas as pd


def load_trips(con):
    t = con.sql("SELECT * FROM trip_log ORDER BY trip_id").df()
    t["ratio"] = t.actual_minutes / t.planned_minutes
    return t


def clean_trips(trips):
    """Drop impossible records: no time, negative time, or more than three times the plan plus an hour
    (a tracker left running). A short trip that took 30 minutes more is a real incident: keep it."""
    bad = (trips.actual_minutes <= 0) | (trips.actual_minutes > 3 * trips.planned_minutes + 60)
    return trips[~bad].copy(), trips[bad].copy()


def weekly_errors(con):
    """Chain-wide weekly units of the three history products, and the 'same as last week' forecast error
    as a ratio: actual / forecast."""
    s = con.sql("""SELECT week_start, sku, sum(units_sold) AS units FROM bakery_sales_weekly
                   GROUP BY week_start, sku ORDER BY sku, week_start""").df()
    s["forecast"] = s.groupby("sku").units.shift(1)
    s = s.dropna()
    s["ratio"] = s.units / s.forecast
    return s


def travel_sampler(trips, rng, weather_mix=None):
    """A function that draws one morning of trip factors: pick the morning's weather (from the log's mix,
    or weather_mix), then for each trip a ratio drawn from that weather's cleaned history (a bootstrap)."""
    by_weather = {w: g.ratio.to_numpy() for w, g in trips.groupby("weather")}
    days = trips.groupby("trip_date").weather.first()
    mix = weather_mix or days.value_counts(normalize=True).to_dict()
    names, probs = list(mix), np.array(list(mix.values()))

    def morning():
        w = names[rng.choice(len(names), p=probs / probs.sum())]
        pool = by_weather[w]
        return w, (lambda: pool[rng.integers(len(pool))])
    return morning


def demand_error_sd(con):
    """Forecast error (standard deviation of actual / forecast) by category: bread from BK-SD and BK-WW,
    viennoiserie from BK-CR; cakes and cookies have no history, so they borrow viennoiserie's (an assumption)."""
    e = weekly_errors(con).groupby("sku").ratio.std()
    bread, vien = float(e[["BK-SD", "BK-WW"]].mean()), float(e["BK-CR"])
    return {"bread": bread, "viennoiserie": vien, "cake": vien, "cookie": vien}

Then day42/fit_inputs.py:

# ---------- 42.1 Look at the data first ----------
trips = load_trips(con)
print(f"{len(trips)} trips from {trips.trip_date.min():%Y-%m-%d} to {trips.trip_date.max():%Y-%m-%d}")
print(trips.ratio.describe().round(3).to_string())
clean, bad = clean_trips(trips)
print(f"dropped {len(bad)} impossible records:")
print(bad[["trip_id", "trip_date", "planned_minutes", "actual_minutes"]].to_string(index=False))
1872 trips from 2026-05-25 to 2026-11-21
count    1872.000
mean        1.157
std         0.630
min        -0.107
25%         0.991
50%         1.091
75%         1.207
max        23.538
dropped 4 impossible records:
trip_id  trip_date  planned_minutes  actual_minutes
 T00041 2026-05-28               20             0.0
 T00312 2026-06-23               55             0.0
 T00903 2026-08-20               26           612.0
 T01456 2026-10-13               28            -3.0

A negative trip, two trips of zero minutes and one of 612 minutes for a 26-minute run: tracker glitches. They go. But a short trip that took 30 minutes more than planned stays: that's a real incident (a crash, a closed street), and exactly the kind of tail a simulation must keep. Write the cleaning rule down, and print what it drops.

42.2 Actual against planned

# ---------- 42.2 Actual against planned ----------
print("--- actual / planned minutes, by weather")
print(clean.groupby("weather").ratio.agg(trips="size", mean="mean", median="median", p95=lambda r: r.quantile(0.95))
      .round(3).to_string())
print(f"the planning matrix is optimistic: on clear days trips take {clean[clean.weather == 'clear'].ratio.median():.3f} "
      f"times the plan (median)")
--- actual / planned minutes, by weather
         trips   mean  median    p95
weather
clear     1353  1.116   1.064  1.391
rain       467  1.200   1.157  1.492
snow        48  1.495   1.390  1.795
the planning matrix is optimistic: on clear days trips take 1.064 times the plan (median)

The planning matrix is optimistic: even on clear days, the median trip takes 6% longer than planned; in rain 16%, in snow 39%. Every Module 4 route was planned with these minutes. This is the first finding of any input study: compare the model's numbers with what really happens.

42.3 Which distribution?

Fit candidate distributions to the clear-day ratios (actual / planned) with scipy.stats and compare them: the log-likelihood (higher is better), AIC (lower is better: it charges for parameters), the Kolmogorov–Smirnov statistic (the largest gap between the fitted and the data's cumulative distribution), and above all the tail that matters for lateness.

# ---------- 42.3 Which distribution? ----------
x = clean[clean.weather == "clear"].ratio.to_numpy()
rows = []
for name, dist in [("normal", stats.norm), ("lognormal", stats.lognorm), ("gamma", stats.gamma)]:
    params = dist.fit(x) if name == "normal" else dist.fit(x, floc=0)
    ll = dist.logpdf(x, *params).sum()
    ks = stats.kstest(x, dist.cdf, args=params).statistic
    rows.append((name, round(ll, 1), round(2 * len(params) - 2 * ll, 1), round(ks, 4),
                 round(float(dist.sf(1.5, *params)), 4), round(float(dist.ppf(0.99, *params)), 3)))
print("--- distributions fitted to the clear-day ratios")
emp = [("data", None, None, None, round(float((x > 1.5).mean()), 4), round(float(np.quantile(x, 0.99)), 3))]
print(pd.DataFrame(emp + rows, columns=["model", "log_likelihood", "AIC", "KS", "P(ratio > 1.5)", "99th percentile"])
      .to_string(index=False))
--- distributions fitted to the clear-day ratios
    model  log_likelihood    AIC     KS  P(ratio > 1.5)  99th percentile
     data             NaN    NaN    NaN          0.0362            2.607
   normal          -424.0  851.9 0.2128          0.1229            1.886
lognormal           137.0 -267.9 0.1179          0.0551            1.737
    gamma           -15.4   36.8 0.1488          0.0711            1.775
  • The lognormal fits best of the three (AIC), as expected for a quantity that is a product of many small delays, and is never negative.
  • The normal is the worst: it puts weight on impossible values and too much in the wrong tail.
  • None of them has the incidents: the data's 99th percentile is 2.6 times the plan, the fits say 1.7 to 1.9. The incidents are a separate mechanism: about 3% of trips, plus 10 to 35 minutes.

So the simulation on Day 43 resamples the cleaned trips themselves (an empirical bootstrap), by weather: it keeps the incidents and the weather effect, with no distribution to choose. Fitted distributions are better when data are scarce, when you need to extrapolate (a worse winter than the log has seen), or when you want parameters to vary in experiments.

42.4 Demand: forecast errors and counts

# ---------- 42.4 Demand: forecast errors and counts ----------
errors = weekly_errors(con)
print("--- forecast errors of 'same as last week', actual / forecast")
print(errors.groupby("sku").ratio.agg(weeks="size", mean="mean", sd="std").round(4).to_string())
for sku, g in errors.groupby("sku"):
    r = g.ratio.to_numpy()
    print(f"{sku}: lag-1 autocorrelation of errors {np.corrcoef(r[:-1], r[1:])[0, 1]:+.2f}, "
          f"Shapiro-Wilk p = {stats.shapiro(r).pvalue:.3f}")
print("error sd used for every category (Day 43):", {k: round(v, 4) for k, v in demand_error_sd(con).items()})
s01 = con.sql("SELECT units_sold FROM bakery_sales_weekly WHERE store_id = 'S01' AND sku = 'BK-CR'").df().units_sold
print(f"S01 croissants a week: mean {s01.mean():.2f}, variance {s01.var():.2f} "
      f"(Poisson has variance = mean: dispersion {s01.var() / s01.mean():.2f})")
--- forecast errors of 'same as last week', actual / forecast
       weeks    mean      sd
sku
BK-CR    103  1.0048  0.0873
BK-SD    103  1.0021  0.0483
BK-WW    103  1.0025  0.0440
BK-CR: lag-1 autocorrelation of errors +0.13, Shapiro-Wilk p = 0.000
BK-SD: lag-1 autocorrelation of errors -0.19, Shapiro-Wilk p = 0.000
BK-WW: lag-1 autocorrelation of errors -0.02, Shapiro-Wilk p = 0.000
error sd used for every category (Day 43): {'bread': 0.0461, 'viennoiserie': 0.0873, 'cake': 0.0873, 'cookie': 0.0873}
S01 croissants a week: mean 25.55, variance 25.16 (Poisson has variance = mean: dispersion 0.98)
  • The "same as last week" forecast is unbiased (mean ratio 1.00) with an error of 4–5% for bread and 9% for croissants.
  • The errors are not normal (Shapiro–Wilk p ≈ 0): holiday weeks give fat tails. Again, resampling the actual errors keeps them.
  • Errors are only weakly autocorrelated: a bad week isn't usually followed by another. (Day 44 deals with errors that move together.)
  • Cakes and cookies have no history; they borrow the croissant errors. That is an assumption, and it goes in the memo.
  • A single store's weekly croissant sales look Poisson: the variance (25.16) equals the mean (25.55). At store level, Poisson or negative binomial counts are the natural model; chain-wide, a ratio error on the forecast is.

Decision it supports: which random numbers to feed a simulation, so its risk estimates can be trusted.

Other decisions you can support the same way: service times in a call centre · machine failure times · lead times from suppliers · patient arrivals.

The planted bug

day42/bug_dirty_fit.py fits a normal distribution to the raw trip log. Run it.

trips = load_trips(con)
mean, sd = stats.norm.fit(trips.ratio)
print(f"fitted: actual / planned ~ normal(mean {mean:.3f}, sd {sd:.3f})")
draws = np.random.default_rng(42).normal(mean, sd, 100_000)
print(f"simulated trips faster than half the plan: {(draws < 0.5).mean():.1%}; taking negative time: {(draws < 0).mean():.1%}")
print(f"real trips faster than half the plan: {(trips.ratio[trips.actual_minutes > 0] < 0.5).mean():.1%}")
What happens, and why
fitted: actual / planned ~ normal(mean 1.157, sd 0.630)
simulated trips faster than half the plan: 15.0%; taking negative time: 3.4%
real trips faster than half the plan: 0.0%

The glitches (612 minutes, −3 minutes) inflate the standard deviation from 0.36 to 0.63, and the normal distribution then makes 3.4% of simulated trips take negative time, and 15% faster than half the plan, which never happens. Two mistakes compound: dirty data and a distribution that allows impossible values. Clean first, check the fitted distribution's range, and compare its tails with the data.

Mini-project: buffers by weather

Dispatchers want a rule of thumb: "multiply the planned minutes by … in this weather". Compute the multiplier that covers 50%, 80%, 90% and 95% of trips in each weather, and the share of trips with an incident.

Solution
"""Day 42 mini-project: dispatchers want a rule of thumb: "multiply the planned minutes by ... in this weather".
What multiplier covers half, 80%, 90% and 95% of trips in each weather, and how often is there an incident?

Run from the repository root (after day06/load_tables.py):  python day42/mini_project_buffers.py
"""
import sys

import duckdb
import pandas as pd

sys.path.insert(0, "day42")
from inputs import clean_trips, load_trips

pd.set_option("display.width", 160)
con = duckdb.connect("northbound.duckdb", read_only=True)
trips, _ = clean_trips(load_trips(con))
trips["incident"] = trips.actual_minutes > 1.6 * trips.planned_minutes + 8      # far beyond the usual spread
table = trips.groupby("weather").agg(
    trips=("ratio", "size"), p50=("ratio", lambda r: r.quantile(0.50)), p80=("ratio", lambda r: r.quantile(0.80)),
    p90=("ratio", lambda r: r.quantile(0.90)), p95=("ratio", lambda r: r.quantile(0.95)), incidents=("incident", "mean"))
print(table.round(3).to_string())
days = trips.groupby("trip_date").weather.first().value_counts()
print("mornings in the log:", days.to_dict())
         trips    p50    p80    p90    p95  incidents
weather
clear     1353  1.064  1.200  1.287  1.391      0.022
rain       467  1.157  1.293  1.391  1.492      0.017
snow        48  1.390  1.615  1.724  1.795      0.042
mornings in the log: {'clear': 113, 'rain': 39, 'snow': 4}

Note to the dispatchers: "Planned minutes are short. To arrive on time for 9 trips in 10, allow 1.3 times the planned minutes in clear weather, 1.4 in rain and 1.7 in snow. About 2–4% of trips meet an incident that no multiplier covers; keep one van on standby on snow mornings. We'll update the planning matrix (Day 43 tests what a buffer costs)."

One caution: a route is several trips, and a buffer per trip is not the same as a buffer per route (errors partly cancel along a route, and the weather moves them all together). Day 43 simulates whole routes.

Commit

git add .
git commit -m "Day 42: input distributions and forecast errors"
git push

Day 42 checklist

  • I look at and clean data before fitting, with a written rule, and keep real extremes.
  • I compare the model's input numbers with what actually happens.
  • I can fit and compare distributions with log-likelihood, AIC, KS and tail probabilities.
  • I know when to resample the data (bootstrap) instead of fitting a distribution.
  • I can turn a forecast history into forecast errors for a simulation, and state the assumptions.