Update the course data
Copy the latest make_data.py from the Course data page and rebuild (python make_data.py, python day01/ladder.py, python day06/load_tables.py). New for Days 44–47: bakery_disruptions (an oven breakdown, a packing line failure), receiving_log (four weeks of trucks arriving at DC-MTL at night) and receiving_settings (doors, drivers, detention charges). Install SimPy for Day 46: pip install simpy==4.1.2 (it's in requirements.txt).
44.1 Do the errors move together?
Create day44/correlated.py:
"""Day 44: risks that move together. Whole historical weeks as demand scenarios, mornings with one weather,
and rare disruptions.
Import it: from correlated import error_table, demand_weeks, pooled_morning, disrupted_profit
"""
import numpy as np
import pyomo.environ as pyo
from bakery import build_model, solve
from inputs import weekly_errors
def error_table(con):
"""Forecast errors (actual / forecast), one row per week, one column per history product."""
return weekly_errors(con).pivot(index="week_start", columns="sku", values="ratio")
def demand_weeks(con, rng, together=True):
"""A demand sampler. together=True: draw one historical week and use all its errors at once (bread from the
mean of BK-SD and BK-WW, everything else from BK-CR), so products move together as they did.
together=False: every product draws its own week, as on Day 43."""
e = error_table(con)
bread = ((e["BK-SD"] + e["BK-WW"]) / 2).to_numpy()
other = e["BK-CR"].to_numpy()
n = len(e)
def week(cap, category):
k = rng.integers(n)
out = {}
for p, c in cap.items():
j = k if together else rng.integers(n)
out[p] = c * (bread[j] if category[p] == "bread" else other[j])
return out
return week
def pooled_morning(trips, rng):
"""Travel times with the weather ignored: every trip draws from all trips of all days, independently."""
pool = trips.ratio.to_numpy()
def morning():
return "any", (lambda: pool[rng.integers(len(pool))])
return morning
def disrupted_profit(d, resource, capacity_left):
"""The best profit in a week when a resource loses part of its capacity (the plan is re-made for that week)."""
week = {**d, "capacity": {**d["capacity"], resource: d["capacity"][resource] * capacity_left}}
m = build_model(week)
solve(m)
return pyo.value(m.total_profit)
def simulate_years(weekly_profits, events, loss, rng, years=2_000, chance=None):
"""Years of 52 weeks: weekly profits (from the demand simulation) minus each disruption's loss in the weeks
it strikes. chance overrides an event's weekly chance, e.g. {"oven_breakdown": 0.015}.
Returns (annual profit per year, number of disruptions per year)."""
profits = np.asarray(weekly_profits)[: years * 52].reshape(years, 52).copy()
count = np.zeros(years, dtype=int)
for r in events.itertuples():
p = (chance or {}).get(r.event, r.chance_per_week)
hit = rng.random((years, 52)) < p
profits -= hit * loss[r.event]
count += hit.sum(axis=1)
return profits.sum(axis=1), count
demand_weeks(together=True) draws one historical week and applies all its errors at once: the products keep the relationships they really had. Then day44/run_correlated.py:
# ---------- 44.1 Do the products' errors move together? ----------
e = error_table(con)
print("Pearson correlation of forecast errors:")
print(e.corr().round(2).to_string())
print("Spearman (rank) correlation:")
print(e.corr(method="spearman").round(2).to_string())
worst = e.assign(spread=(e - 1).abs().max(axis=1)).sort_values("spread", ascending=False).head(5)
print("the five weeks with the biggest errors:")
print(worst.drop(columns="spread").round(3).to_string())
Pearson correlation of forecast errors:
sku BK-CR BK-SD BK-WW
sku
BK-CR 1.00 0.62 0.69
BK-SD 0.62 1.00 0.62
BK-WW 0.69 0.62 1.00
Spearman (rank) correlation:
sku BK-CR BK-SD BK-WW
sku
BK-CR 1.00 0.17 0.27
BK-SD 0.17 1.00 0.21
BK-WW 0.27 0.21 1.00
the five weeks with the biggest errors:
sku BK-CR BK-SD BK-WW
week_start
2024-12-16 1.492 1.127 1.140
2025-12-15 1.395 1.189 1.126
2025-01-06 0.624 0.853 0.857
2026-01-05 0.658 0.892 0.870
2025-09-01 1.125 1.205 1.143
errors mean sd p5 mean_of_worst_5pct
Pearson correlations of 0.6 to 0.7, but rank correlations of only 0.2 to 0.3. The table of extreme weeks explains it: in an ordinary week the errors are nearly independent, but at Christmas they all jump up together and in early January they all fall together. The dependence lives in the tails. A single correlation number hides this; resampling whole weeks keeps it.
44.2 The production plan, errors apart or together
# ---------- 44.2 The production plan, errors apart or together ----------
d = load_data(con)
m = build_model(d)
solve(m)
make = {p: pyo.value(m.x[p]) for p in m.P if pyo.value(m.x[p]) > 1e-6}
econ = bakery_economics(con)
rows = []
for name, together in [("each product its own week (Day 43)", False), ("whole weeks: products together", True)]:
sims = simulate_bakery(make, d["cap"], d["category"], econ, demand_weeks(con, np.random.default_rng(44), together), 10_000)
r = risk_summary(sims.profit)
rows.append((name, round(r["mean"], 2), round(r["sd"], 2), round(r["p5"], 2), round(r["mean_of_worst_5pct"], 2)))
print(pd.DataFrame(rows, columns=["errors", "mean", "sd", "p5", "mean_of_worst_5pct"]).to_string(index=False))
each product its own week (Day 43) 106024.21 1511.51 103020.32 101747.92
whole weeks: products together 106020.37 5914.40 103010.74 86389.85
Same average, four times the spread, and a much worse bad tail: the worst 5% of weeks average $86,390 instead of $101,748. With independent errors, a product that sells too little is offset by one that sells too much. In a holiday week nothing offsets anything. Ignoring correlation makes a plan look safer than it is.
44.3 Mornings with one weather
# ---------- 44.3 Mornings: one weather for every trip ----------
stops, ids, km, minutes = load_run(con)
plan = solve_vrptw(stops, ids, km, minutes, load_fleet(con))
trips, _ = clean_trips(load_trips(con))
rows = []
for name, sampler in [("trips independent, weather ignored", pooled_morning(trips, np.random.default_rng(1))),
("one weather a morning", travel_sampler(trips, np.random.default_rng(1)))]:
sims = simulate_routes(plan, stops, ids, minutes, sampler, 5_000)
rows.append((name, round(sims.late.mean(), 3), round((sims.late >= 3).mean(), 4), round((sims.late >= 5).mean(), 4),
int(sims.late.max())))
print(pd.DataFrame(rows, columns=["travel times", "late_per_morning", "P(3+ late)", "P(5+ late)", "worst_morning"])
.to_string(index=False))
travel times late_per_morning P(3+ late) P(5+ late) worst_morning
trips independent, weather ignored 0.934 0.0398 0.0076 6
one weather a morning 0.919 0.0514 0.0084 7
Here the effect is smaller: drawing one weather for the whole morning raises the chance of 3 or more late deliveries from 4.0% to 5.1%. Rain and snow slow every trip at once, so bad mornings come in clusters, but the trip-to-trip variation still dominates. Measure correlation; don't assume it's large or small.
44.4 Rare disruptions over a year
Two events from bakery_disruptions: an oven breakdown (3% chance a week; 30% of oven hours lost that week) and a packing line failure (2%; 25% of packing hours). When one strikes, the bakery re-plans that week (Day 6's model with less capacity).
# ---------- 44.4 Rare disruptions over a year ----------
events = con.sql("SELECT * FROM bakery_disruptions").df()
normal = pyo.value(m.total_profit)
loss = {}
for r in events.itertuples():
loss[r.event] = normal - disrupted_profit(d, r.resource, r.capacity_left)
print(f"{r.event}: {r.chance_per_week:.0%} a week; that week the best plan earns ${loss[r.event]:,.2f} less")
weekly = simulate_bakery(make, d["cap"], d["category"], econ, demand_weeks(con, np.random.default_rng(4), True),
52 * 2_000).profit
annual, count = simulate_years(weekly, events, loss, np.random.default_rng(5))
print(f"a year: average ${annual.mean():,.0f}; 5th percentile ${np.quantile(annual, 0.05):,.0f}; "
f"years with no disruption {np.mean(count == 0):.0%}; with 3 or more {np.mean(count >= 3):.1%}")
print(f"disruptions cost ${sum(52 * r.chance_per_week * loss[r.event] for r in events.itertuples()):,.0f} a year on average")
oven_breakdown: 3% a week; that week the best plan earns $25,230.35 less
packing_line_failure: 2% a week; that week the best plan earns $15,797.68 less
a year: average $5,454,979; 5th percentile $5,354,489; years with no disruption 8%; with 3 or more 48.3%
disruptions cost $55,789 a year on average
- An oven breakdown costs about $25,000 in the week it happens; a packing failure about $16,000.
- Each is rare, but over a year they're likely: 9 years in 10 have at least one, and almost half have three or more.
- On average they cost about $56,000 a year: simulate a year, not a week, when rare events matter.
Decision it supports: how much risk a plan really carries when bad things happen together, and what rare events cost.
Other decisions you can support the same way: portfolio risk (assets falling together) · supplier risk (one region, one storm) · insurance and spare-parts decisions.
The planted bug
day44/bug_sales_correlation.py measures how the products move together by correlating their weekly sales. Run it.
sales = con.sql("""SELECT week_start, sku, sum(units_sold) AS units FROM bakery_sales_weekly
GROUP BY week_start, sku""").df().pivot(index="week_start", columns="sku", values="units")
print(sales.corr().round(2).to_string())
print("so demand errors are about 0.9 correlated: use that in the simulation")
What happens, and why
sku BK-CR BK-SD BK-WW
sku
BK-CR 1.00 0.84 0.86
BK-SD 0.84 1.00 0.95
BK-WW 0.86 0.95 1.00
so demand errors are about 0.9 correlated: use that in the simulation
Correlations of 0.84 to 0.95, because all three products follow the same season (more in December, less in summer). But the forecast already knows the season. The simulation needs the correlation of the errors, what the forecast gets wrong, which is much weaker except at holidays. Correlating the wrong quantity would wildly overstate the risk. Always simulate what is uncertain, not what is predictable.
Mini-project: an oven maintenance contract
A maintenance contract costs $16,000 a year and halves the chance of an oven breakdown (3% to 1.5% a week). Simulate 2,000 years with and without it, on the same simulated weeks. Is it worth it on average? In a bad year?
Solution
"""Day 44 mini-project: a maintenance contract for the ovens costs $16,000 a year and halves the chance of a
breakdown (3% to 1.5% a week). Is it worth it, on average and in a bad year?
Run from the repository root (after day06/load_tables.py): python day44/mini_project_maintenance.py (about 1 minute)
"""
import sys
import duckdb
import numpy as np
import pandas as pd
import pyomo.environ as pyo
for folder in ("day06", "day41", "day42", "day43", "day44"):
sys.path.insert(0, folder)
from bakery import build_model, load_data, solve
from correlated import demand_weeks, disrupted_profit, simulate_years
from montecarlo import bakery_economics
from plan_risk import simulate_bakery
con = duckdb.connect("northbound.duckdb", read_only=True)
d = load_data(con)
m = build_model(d)
solve(m)
make = {p: pyo.value(m.x[p]) for p in m.P if pyo.value(m.x[p]) > 1e-6}
events = con.sql("SELECT * FROM bakery_disruptions").df()
loss = {r.event: pyo.value(m.total_profit) - disrupted_profit(d, r.resource, r.capacity_left) for r in events.itertuples()}
weekly = simulate_bakery(make, d["cap"], d["category"], bakery_economics(con),
demand_weeks(con, np.random.default_rng(4), True), 52 * 2_000).profit
rows = []
for name, chance, fee in [("no contract", None, 0), ("contract", {"oven_breakdown": 0.015}, 16_000)]:
annual, count = simulate_years(weekly, events, loss, np.random.default_rng(5), chance=chance) # same years
annual = annual - fee
rows.append((name, round(annual.mean()), round(np.quantile(annual, 0.05)), round(np.quantile(annual, 0.01)),
round(count.mean(), 2)))
t = pd.DataFrame(rows, columns=["option", "average_year", "p5_year", "p1_year", "disruptions_a_year"])
print(t.to_string(index=False))
print(f"contract: {t.average_year[1] - t.average_year[0]:+,} on average, {t.p5_year[1] - t.p5_year[0]:+,} in a 1-in-20 "
f"bad year, {t.p1_year[1] - t.p1_year[0]:+,} in a 1-in-100 year")
option average_year p5_year p1_year disruptions_a_year
no contract 5454979 5354489 5308464 2.62
contract 5458899 5361683 5314526 1.83
contract: +3,920 on average, +7,194 in a 1-in-20 bad year, +6,062 in a 1-in-100 year
- On average the contract pays for itself and a little more (about +$3,900 a year): it avoids 0.78 breakdowns a year at about $25,000 each.
- In bad years it helps more (about +$7,000 in a 1-in-20 year): insurance is worth more than its average when it protects the tail.
- Both options use the same simulated weeks and the same random numbers for the events (
np.random.default_rng(5)), so the difference is the contract, not luck.
Memo: "Sign the oven maintenance contract: it is slightly cheaper than the breakdowns it prevents on average ($3,900 a year), and it reduces the loss in a bad year."
Commit
git add .
git commit -m "Day 44: correlated risks and disruptions"
git push
Day 44 checklist
- I can measure dependence with Pearson and rank correlations, and look at the extremes.
- I can keep real dependence by resampling whole periods.
- I showed that correlation leaves the average and worsens the tail.
- I can simulate rare disruptions over a year, with re-planning when they strike.
- I correlate forecast errors, not sales.