19.1 The history
store_pallets_history has 53 weeks of pallets per store, ending with the week of 23 November 2026. Create day19/compare.py:
import sys
import duckdb
import pandas as pd
sys.path.insert(0, "day19")
from evaluate import plan_and_live
from forecasts import accuracy, make_forecasts
pd.set_option("display.width", 160)
con = duckdb.connect("northbound.duckdb", read_only=True)
# ---------- 19.1 The history ----------
print(con.sql("""
SELECT week_start, sum(pallets)::INTEGER AS pallets FROM store_pallets_history
GROUP BY ALL ORDER BY week_start""").df().iloc[[0, 1, 2, 3, 4, 5, 26, -4, -3, -2, -1]].to_string(index=False))
week_start pallets
2025-11-24 3394
2025-12-01 3405
2025-12-08 3707
2025-12-15 4110
2025-12-22 4117
2025-12-29 3033
2026-05-25 3521
2026-11-02 3596
2026-11-09 3461
2026-11-16 3491
2026-11-23 3574
Last December the chain went from about 3,400 pallets a week to 4,117 in the week before Christmas, then fell to about 3,000 in the first week of January. This year's recent weeks run about 3,500–3,575. Any forecast for December 2026 has to bring both facts together: this year's level and last year's December shape.
19.2 Four forecasts and their accuracy
day19/forecasts.py builds three forecasts with SQL, in the same shape as store_week_forecast so the Day 18 model can read them unchanged. Each splits a store's total into ambient and chilled using the store's usual chilled share.
| Forecast | Weeks 1–4 total per store |
|---|---|
fc_last_week | The last week of history, repeated |
fc_avg_4_weeks | The average of the last 4 weeks, repeated |
fc_last_year_plus_3pct | The same week last year, plus 3% growth (the planning team's method) |
"""Day 19: four ways to forecast December's pallets, store by store.
Import it: from forecasts import make_forecasts
"""
import duckdb
import pandas as pd
def make_forecasts(con):
"""Write one forecast table per method, in the same shape as store_week_forecast
(week, store_id, ambient_pallets, chilled_pallets). Forecasts are made at the end of the history."""
con.sql("""
CREATE OR REPLACE TEMP VIEW hist AS
SELECT h.*, (date_diff('week', h.week_start, (SELECT max(week_start) FROM store_pallets_history))) AS weeks_ago
FROM store_pallets_history h""")
con.sql("""
CREATE OR REPLACE TEMP VIEW chilled_share AS
SELECT store_id, chilled_pallets_per_week / pallets_per_week AS share FROM store_logistics""")
totals = {
"last_week": "SELECT store_id, w.week, pallets AS total FROM hist, range(1, 5) w(week) WHERE weeks_ago = 0",
"avg_4_weeks": """SELECT store_id, w.week, avg(pallets) AS total FROM hist, range(1, 5) w(week)
WHERE weeks_ago < 4 GROUP BY store_id, w.week""",
"last_year_plus_3pct": """SELECT store_id, 52 - weeks_ago AS week, 1.03 * pallets AS total FROM hist
WHERE weeks_ago BETWEEN 48 AND 51""",
}
for name, sql in totals.items():
con.sql(f"""
CREATE OR REPLACE TEMP TABLE fc_{name} AS
SELECT week::INTEGER AS week, store_id,
round(total) - round(round(total) * share) AS ambient_pallets,
round(round(total) * share) AS chilled_pallets
FROM ({sql}) JOIN chilled_share USING (store_id)""")
return ["fc_" + n for n in totals]
def accuracy(con, table):
"""Mean absolute error and bias per store-week, against what actually happened."""
return con.sql(f"""
SELECT '{table}' AS forecast,
round(avg(abs(f.ambient_pallets + f.chilled_pallets - a.ambient_pallets - a.chilled_pallets)), 2) AS mae_pallets,
round(avg(f.ambient_pallets + f.chilled_pallets - a.ambient_pallets - a.chilled_pallets), 2) AS bias_pallets,
sum(f.ambient_pallets + f.chilled_pallets)::INTEGER AS forecast_total,
sum(a.ambient_pallets + a.chilled_pallets)::INTEGER AS actual_total
FROM {table} f JOIN store_week_actual a USING (week, store_id)""").df()
date_diff('week', …) counts weeks back from the last week of history; range(1, 5) w(week) repeats a value for weeks 1–4. accuracy compares each forecast with store_week_actual: MAE is the average miss per store and week, in pallets; bias is the average signed miss (negative means the forecast is too low).
# ---------- 19.2 Four forecasts and their accuracy ----------
tables = make_forecasts(con) + ["store_week_forecast", "store_week_actual"]
acc = pd.concat([accuracy(con, t) for t in tables])
print(acc.to_string(index=False))
forecast mae_pallets bias_pallets forecast_total actual_total
fc_last_week 12.38 -10.07 14296 15908
fc_avg_4_weeks 12.30 -11.05 14140 15908
fc_last_year_plus_3pct 7.33 -0.66 15803 15908
store_week_forecast 7.33 -0.66 15803 15908
store_week_actual 0.00 0.00 15908 15908
- Last week and 4-week average miss by about 12 pallets per store-week and are biased low by about 10–11 pallets: they know nothing about December, so they forecast November into the peak.
- Last year plus 3% misses by 7.3 and is almost unbiased: it carries last December's shape into this one.
store_week_forecastis the planning team's version of the same method. It differs only in rounding: Python rounds halves to the even number (round(2.5) = 2), DuckDB rounds them away from zero (2.5 becomes 3). Tiny, but a reminder that "the same method" in two tools can give different numbers.store_week_actualis the perfect forecast, available only in hindsight: the benchmark for what any forecast could achieve.
19.3 Plan, then live through the actual weeks
A forecast's real test is the cost of the decisions made with it. December has a natural split:
- Decide now: the supplier orders, i.e. how many pallets each DC receives each week. They are placed at the start of the month and can't be cancelled.
- Adapt later: once actual demand is known week by week, shipments to stores adapt. A DC can rush extra pallets in the same week at $25 a pallet more (within its receiving capacity). Chilled pallets that arrive but aren't needed are thrown away.
Create day19/evaluate.py:
"""Day 19: plan with a forecast, then live through the actual weeks.
Import it: from evaluate import plan_and_live
"""
import sys
import pyomo.environ as pyo
sys.path.insert(0, "day18")
from flows import build_weeks, load_weeks
solver = pyo.SolverFactory("highs")
def plan_and_live(con, forecast_table, adjust=None):
"""1. Plan the four weeks with the forecast. The supplier orders (pallets received at each DC each week)
are placed now and cannot be cancelled.
2. Live through the actual weeks: shipments adapt to actual demand; a DC can order extra pallets
for the same week at a premium (rush); chilled pallets that arrive but are not needed are thrown away.
adjust(d), if given, changes the data (for example a capacity) in both steps.
Returns (planned cost, actual cost, pallets rushed, chilled pallets thrown away, lost pallets)."""
adjust = adjust or (lambda d: d)
plan = build_weeks(adjust(load_weeks(con, forecast_table)))
solver.solve(plan)
d = adjust(load_weeks(con, "store_week_actual"))
live = build_weeks(d)
premium = d["costs"]["emergency_premium_per_pallet"]
live.rush = pyo.Var(live.K, live.D, live.T, within=pyo.NonNegativeReals)
for k in live.K:
for dc in live.D:
for t in live.T:
ordered = pyo.value(plan.receive[k, dc, t])
live.receive[k, dc, t].setlb(ordered) # what was ordered arrives
live.receive[k, dc, t].setub(ordered + 10_000)
live.add_component(f"rush_{k}_{dc}_{t}".replace("-", "_"),
pyo.Constraint(expr=live.rush[k, dc, t] >= live.receive[k, dc, t] - ordered))
# Unneeded chilled pallets may go to waste instead of being shipped
for dc in live.D:
for t in live.T:
live.chilled_balance[dc, t].set_value(live.receive["chilled", dc, t] >= sum(live.ship["chilled", dc, s, t] for s in live.S))
live.cost.deactivate()
live.actual_cost = pyo.Objective(expr=live.cost.expr + premium * sum(live.rush[k, dc, t] for k in live.K for dc in live.D for t in live.T))
result = solver.solve(live, load_solutions=False)
if result.solver.termination_condition != pyo.TerminationCondition.optimal:
raise RuntimeError(f"{forecast_table}: {result.solver.termination_condition}")
live.solutions.load_from(result)
rushed = sum(pyo.value(x) for x in live.rush.values())
wasted = sum(pyo.value(live.receive["chilled", dc, t]) - sum(pyo.value(live.ship["chilled", dc, s, t]) for s in live.S)
for dc in live.D for t in live.T)
lost = sum(pyo.value(x) for x in live.short.values())
return pyo.value(plan.cost), pyo.value(live.actual_cost), rushed, wasted, lost
How it works:
- The plan is solved with the forecast; its
receivevalues are the orders. - The "live" model is the Day 18 model with actual demand, where each
receivevariable must be at least what was ordered (setlb), and anything above it is a rush order, paid at the premium. - The chilled balance becomes "received ≥ shipped": unneeded chilled pallets are lost, not stored.
- The live model's cost is what December would really cost with that forecast.
# ---------- 19.3 Plan with each forecast, then live through the actual weeks ----------
rows = []
for t in tables:
planned, actual, rushed, wasted, lost = plan_and_live(con, t)
rows.append((t, round(planned, 2), round(actual, 2), round(rushed), round(wasted), round(lost)))
result = pd.DataFrame(rows, columns=["forecast", "planned_cost", "actual_cost", "rushed", "chilled_wasted", "lost"])
best = result.actual_cost[result.forecast == "store_week_actual"].iloc[0]
result["cost_of_forecast_error"] = (result.actual_cost - best).round(2)
print(result.to_string(index=False))
forecast planned_cost actual_cost rushed chilled_wasted lost cost_of_forecast_error
fc_last_week 202164.26 302130.89 1271 0 341 33907.89
fc_avg_4_weeks 196924.47 305767.87 1436 0 332 37544.87
fc_last_year_plus_3pct 256514.93 269372.85 0 0 251 1149.85
store_week_forecast 256444.53 269362.74 0 0 250 1139.74
store_week_actual 268223.00 268223.00 0 0 162 0.00
The ranking changes the size of the gaps:
- The two naive forecasts cost $34,000–$37,500 more than perfect hindsight. They under-order for the peak, rush 1,300–1,400 pallets at a premium, and lose more pallets.
- Last year plus 3% costs only $1,140 more than perfect hindsight. Its MAE is half the naive forecasts' (7.3 against 12.3), but its cost of error is about a thirtieth.
- Even the perfect forecast loses 162 pallets: capacity, not forecasting, limits December.
- Planned cost is not actual cost. The naive forecasts plan to spend under $203,000 and actually spend over $300,000. A plan's own cost estimate is only as good as its forecast.
Decision it supports: which forecast to plan with, judged by what its plans cost in practice.
Other decisions you can support the same way: staffing from a call-volume forecast · energy purchases from a load forecast · inventory from a sales forecast.
19.4 Is it better to forecast high?
Running short costs $120 a pallet; ordering a pallet too many costs a few dollars of receiving and holding. So should planners inflate the forecast a little? day19/bias_sweep.py scales the planning team's forecast and lives through December each time:
import sys
import duckdb
sys.path.insert(0, "day19")
from evaluate import plan_and_live
con = duckdb.connect("northbound.duckdb", read_only=True)
print(f"{'factor':>7}{'planned cost':>15}{'actual cost':>15}{'rushed':>8}{'wasted':>8}{'lost':>6}")
for factor in (0.90, 0.95, 1.00, 1.02, 1.05, 1.10, 1.20):
con.sql(f"""
CREATE OR REPLACE TEMP TABLE fc_scaled AS
SELECT week, store_id, round(ambient_pallets * {factor}) AS ambient_pallets,
round(chilled_pallets * {factor}) AS chilled_pallets
FROM store_week_forecast""")
planned, actual, rushed, wasted, lost = plan_and_live(con, "fc_scaled")
print(f"{factor:>7.2f}{planned:>15,.2f}{actual:>15,.2f}{rushed:>8.0f}{wasted:>8.0f}{lost:>6.0f}")
factor planned cost actual cost rushed wasted lost
0.90 198,824.79 303,385.49 1330 0 338
0.95 218,750.34 284,692.75 580 0 338
1.00 256,444.53 269,362.74 0 0 250
1.02 277,855.65 271,370.72 0 0 225
1.05 312,579.24 272,986.69 0 26 190
1.10 381,306.56 274,339.01 0 0 228
1.20 536,182.67 287,035.74 0 19 408
- Forecasting low is expensive: 10% low costs $34,000 more than the unscaled forecast.
- Forecasting high is not free either: 5% high costs $3,600 more, 20% high $17,700 more, and at 20% high more pallets go short than with the unscaled forecast (408 against 250). With receiving full, every extra ambient pallet ordered takes a receiving slot a chilled pallet needed, and chilled pallets can't be received early. When capacity is shared, over-ordering one commodity starves the other.
- The best factor here is 1.00: an unbiased forecast. Inflating a forecast to protect against shortages works when capacity is plentiful (Module 6's newsvendor), not when it is the bottleneck.
Mini-project: a fifth forecast
Build a seasonal index forecast, store by store: this year's level (average of the last 2 weeks) times last year's December shape (each December week last year divided by last year's level at the same point). History starts 52 weeks ago, so last year's level can only use the 2 weeks around 1 December 2025. Measure its accuracy and its December cost, and recommend a forecast to the planning team.
Solution
import sys
import duckdb
sys.path.insert(0, "day19")
from evaluate import plan_and_live
from forecasts import accuracy, make_forecasts
con = duckdb.connect("northbound.duckdb", read_only=True)
make_forecasts(con) # creates the hist and chilled_share views
con.sql("""
CREATE OR REPLACE TEMP TABLE fc_seasonal_index AS
WITH level_now AS (
SELECT store_id, avg(pallets) AS level FROM hist WHERE weeks_ago < 2 GROUP BY store_id
), level_last_year AS (
SELECT store_id, avg(pallets) AS level FROM hist WHERE weeks_ago BETWEEN 51 AND 52 GROUP BY store_id
), shape AS (
SELECT h.store_id, 52 - h.weeks_ago AS week, h.pallets / l.level AS index
FROM hist h JOIN level_last_year l USING (store_id) WHERE h.weeks_ago BETWEEN 48 AND 51
)
SELECT week::INTEGER AS week, store_id,
round(n.level * s.index) - round(round(n.level * s.index) * c.share) AS ambient_pallets,
round(round(n.level * s.index) * c.share) AS chilled_pallets
FROM shape s JOIN level_now n USING (store_id) JOIN chilled_share c USING (store_id)""")
print(con.sql("SELECT min(weeks_ago) AS newest, max(weeks_ago) AS oldest FROM hist"))
print(accuracy(con, "fc_seasonal_index").to_string(index=False))
planned, actual, rushed, wasted, lost = plan_and_live(con, "fc_seasonal_index")
print(f"actual cost ${actual:,.2f}; rushed {rushed:.0f}, wasted {wasted:.0f}, lost {lost:.0f}")
┌────────┬────────┐
│ newest │ oldest │
│ int64 │ int64 │
├────────┼────────┤
│ 0 │ 52 │
└────────┴────────┘
forecast mae_pallets bias_pallets forecast_total actual_total
fc_seasonal_index 7.62 0.24 15947 15908
actual cost $269,644.29; rushed 0, wasted 0, lost 214
The seasonal index misses a little more often than last year plus 3% (MAE 7.62 against 7.33) and costs a little more ($269,644.29 against $269,362.74). Both are within 0.6% of perfect hindsight. The first query shows the limit of the data: with only 53 weeks of history, last year's level rests on 2 weeks.
Memo to planning: "Keep using last year's week plus 3%: it costs only $1,140 more over December than a perfect forecast would. Don't inflate it: with our receiving capacity full, a high forecast costs more than an accurate one. Don't use recent weeks alone for December: they under-order the peak and cost about $35,000. Collect a second year of history so a seasonal index can rest on more than two weeks."
Commit
git add .
git commit -m "Day 19: forecasts, plan versus actual, bias sweep"
git push
Day 19 checklist
- I built several forecasts in SQL, in the shape the model reads.
- I measured accuracy (MAE) and bias against actual demand.
- I separated decisions made now (orders) from decisions that adapt (shipments, rush orders).
- I evaluated each forecast by the cost of living through the actual weeks.
- I found that the most accurate forecast is not automatically the cheapest, and why the gap sizes differ.
- I tested whether biasing a forecast helps, and explained why it doesn't here.