45.1 The brief and the stores' demand
- Demand: each store's croissant sales over the last 13 weeks, divided over 6 selling days with Day 40's day-of-week factors. Day 42 found a store's sales are Poisson, so daily demand is Poisson with that mean.
- Today's rule: each store gets its average, rounded.
- Economics (Day 41): a croissant sells for $7.00 and costs $2.00; unsold ones are thrown away.
- Questions: how often do stores run out? What's lost to empty shelves and to waste? What should each store receive?
Create day45/stockouts.py:
"""Day 45 mini-project: how often do stores run out of croissants? Fresh croissants arrive every morning and
what isn't sold is thrown away.
Import it: from stockouts import store_day_means, simulate_store_days, poisson_check
"""
import numpy as np
import pandas as pd
from scipy import stats
def store_day_means(con, weeks=13):
"""Each store's average croissants a day over the last `weeks` weeks (6 selling days), by day of week:
the weekly average / 6 x the day's factor (Day 40's delivery_days)."""
weekly = con.sql(f"""SELECT store_id, avg(units_sold) AS week_mean FROM bakery_sales_weekly
WHERE sku = 'BK-CR' AND week_start > (SELECT max(week_start) FROM bakery_sales_weekly)
- INTERVAL {weeks} WEEK
GROUP BY store_id ORDER BY store_id""").df().set_index("store_id").week_mean
days = con.sql("SELECT day, rack_factor FROM delivery_days").df()
factor = days.rack_factor / days.rack_factor.mean()
rows = [(s, day, w / 6 * f) for s, w in weekly.items() for day, f in zip(days.day, factor)]
return pd.DataFrame(rows, columns=["store_id", "day", "mean"])
def simulate_store_days(means, quantity, rng, weeks=52, common_sd=0.0):
"""Poisson demand for every store and day over `weeks` weeks. common_sd: a chain-wide factor for each date
(weather, a holiday) that raises or lowers every store's demand together."""
lam = np.tile(means["mean"].to_numpy(), (weeks, 1)) # weeks x (stores x days)
if common_sd > 0:
n_days = means.day.nunique()
day_index = pd.factorize(means.day)[0]
shock = rng.lognormal(-common_sd ** 2 / 2, common_sd, (weeks, n_days))
lam = lam * shock[:, day_index]
demand = rng.poisson(lam)
q = np.tile(np.asarray(quantity), (weeks, 1))
sold = np.minimum(demand, q)
return demand, q, sold
def poisson_check(means, quantity):
"""The same numbers without simulation: P(demand > q) and expected units short, from the Poisson formulas."""
lam, q = means["mean"].to_numpy(), np.asarray(quantity)
p_out = stats.poisson.sf(q, lam)
k = np.arange(0, 200)[:, None]
short = (np.maximum(k - q, 0) * stats.poisson.pmf(k, lam)).sum(axis=0)
return p_out.mean(), short.sum()
Then day45/run_stockouts.py:
# ---------- 45.1 The stores' daily demand ----------
means = store_day_means(con)
print(f"{means.store_id.nunique()} stores x {means.day.nunique()} days; croissants a store a day: "
f"{means['mean'].min():.1f} to {means['mean'].max():.1f} (average {means['mean'].mean():.1f})")
print(means.pivot(index="store_id", columns="day", values="mean")[["Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]]
.head(4).round(2).to_string())
40 stores x 6 days; croissants a store a day: 2.8 to 10.3 (average 6.1)
day Mon Tue Wed Thu Fri Sat
store_id
S01 3.66 3.86 4.06 4.26 4.87 4.67
S02 3.41 3.60 3.79 3.98 4.55 4.36
S03 5.55 5.86 6.17 6.47 7.40 7.09
S04 6.42 6.78 7.14 7.50 8.57 8.21
45.2 Today's rule: send the average
def evaluate(name, quantity, common_sd=0.0, seed=45):
demand, q, sold = simulate_store_days(means, quantity, np.random.default_rng(seed), common_sd=common_sd)
waste = q - sold
out = demand > q
per_day = out.reshape(out.shape[0], -1)
return {"rule": name, "croissants_sent_a_week": int(np.asarray(quantity).sum()),
"days_out": round(out.mean(), 3), "fill_rate": round(sold.sum() / demand.sum(), 4),
"short_a_week": round((demand - sold).sum() / demand.shape[0], 1),
"wasted_a_week": round(waste.sum() / demand.shape[0], 1),
"profit_a_week": round((price * sold - cost * q).sum() / demand.shape[0], 2)}
# ---------- 45.2 Today's rule: send the average ----------
today = np.round(means["mean"]).astype(int)
rows = [evaluate("today: the average, rounded", today)]
p_out, short = poisson_check(means, today)
print(f"Poisson formulas for today's rule: out of stock on {p_out:.3f} of store-days; {short:.1f} croissants short a week "
f"(simulation: see the table)")
Poisson formulas for today's rule: out of stock on 0.392 of store-days; 232.1 croissants short a week (simulation: see the table)
The formula and the simulation agree: stores run out on 39% of days. Sending the average means demand exceeds it almost half the time. A check like this (a formula you trust against your simulation) is how you know the simulation is right before you use it for anything harder.
45.3 A service target, and 45.4 the most profitable quantity
# ---------- 45.3 A service target, 45.4 the most profitable quantity ----------
ratio = (price - cost) / price # Day 41: (lost margin) / (lost margin + waste)
for name, level in [("in stock 95% of days", 0.95), (f"most profitable (critical ratio {ratio:.0%})", ratio)]:
rows.append(evaluate(name, stats.poisson.ppf(level, means["mean"]).astype(int)))
print(pd.DataFrame(rows).to_string(index=False))
Poisson formulas for today's rule: out of stock on 0.392 of store-days; 232.1 croissants short a week (simulation: see the table)
rule croissants_sent_a_week days_out fill_rate short_a_week wasted_a_week profit_a_week
today: the average, rounded 1463 0.392 0.8409 232.8 232.1 5690.60
in stock 95% of days 2488 0.035 0.9901 14.5 1038.7 5168.88
most profitable (critical ratio 71%) 1774 0.220 0.9206 116.2 426.4 5884.90
| Rule | Days out | Waste a week | Profit a week |
|---|---|---|---|
| Today: the average | 39% | 232 | $5,690.60 |
| In stock 95% of days | 3.5% | 1,039 | $5,168.88 |
| Most profitable (critical ratio 71%) | 22% | 426 | $5,884.90 |
- A 95% in-stock target almost ends empty shelves, but more than quadruples waste and earns $522 a week less than today.
- The most profitable quantity (Day 41's newsvendor rule: the 71st percentile of each store's demand) earns $194 a week more than today, with stores out on 22% of days.
- The decision is a trade-off between empty shelves and waste, and the right point depends on what an empty shelf really costs (a customer who doesn't come back costs more than one lost croissant).
45.5 When every store has a bad day together
A cold, rainy morning or a holiday raises or lowers demand at every store at once. Add a chain-wide factor for each date (a lognormal with a 10% spread):
# ---------- 45.5 When every store has a bad day together ----------
best = stats.poisson.ppf(ratio, means["mean"]).astype(int)
rows = []
for name, sd in [("stores independent", 0.0), ("a chain-wide factor each day, sd 10%", 0.10)]:
demand, q, sold = simulate_store_days(means, best, np.random.default_rng(7), common_sd=sd)
out_stores = (demand > q).reshape(demand.shape[0], 40, 6).sum(axis=1) # stores out, per date
waste_day = (q - sold).reshape(demand.shape[0], 40, 6).sum(axis=1)
rows.append((name, round(out_stores.mean(), 2), round((out_stores >= 20).mean(), 4), int(out_stores.max()),
round(np.quantile(waste_day, 0.95), 1)))
print(pd.DataFrame(rows, columns=["demand", "stores_out_a_day", "P(20+ stores out)", "most_stores_out",
"waste_on_a_bad_day_p95"]).to_string(index=False))
demand stores_out_a_day P(20+ stores out) most_stores_out waste_on_a_bad_day_p95
stores independent 9.03 0.0000 17 91.4
a chain-wide factor each day, sd 10% 8.54 0.0128 24 104.0
On average the same (about 9 stores out a day), but with the shared factor, 20 or more stores run out on 1.3% of days (never with independent stores), and waste on a bad day is higher. Head office sees days like that as "a croissant shortage", though each store's rule is the same: correlation again.
45.6 The memo
A model memo
To: Store Operations. Re: croissant deliveries.
"Today each store receives its average daily croissant sales. Because daily sales vary, stores run out on 39% of days, and about 230 croissants a week are thrown away across the chain.
We recommend sending each store the quantity it sells out of only 29% of the time (the 71st percentile of its daily demand), about 1,770 croissants a week instead of 1,460. Stores would run out on 22% of days instead of 39%, waste would rise to about 430 a week, and profit would rise by about $190 a week ($10,000 a year).
A 95% in-stock target is possible but costs about $520 a week against today: only worth it if an empty shelf loses customers for good. On a few days a year (holidays, storms) many stores will run out together; a small reserve at the bakery would help on those days."
Commit
git add .
git commit -m "Day 45: stock-out mini-project"
git push
Day 45 checklist
- I modelled daily store demand as Poisson from history.
- I checked a simulation against an exact formula before trusting it.
- I compared rules by days out, fill rate, waste and profit.
- I can find the most profitable quantity with the critical ratio.
- I showed how a shared factor makes many stores run out together.