1.1 The analytics ladder
Analytics answers four kinds of question. Each step up is harder and worth more.
| Step | Question | Bakery example | Typical tool |
|---|---|---|---|
| Descriptive | What happened? | How many sourdough loaves did we sell last December? | SQL, dashboards |
| Diagnostic | Why did it happen? | Did the price change cause the drop? | Causal inference |
| Predictive | What will happen? | How many will we sell next week? | Forecasting, machine learning |
| Prescriptive | What should we do? | How many batches of each product should we bake next week? | Optimization, simulation, decision analysis |
A forecast alone does not tell the bakery what to bake. The ovens, the bakers and the sourdough starter all have limits, and the products compete for them. Prescriptive analytics takes the forecast and the rules, and computes the best action that respects every rule.
Meet Northbound Fresh
Northbound Fresh is a fictional grocery chain with 40 stores in Ontario and Quebec, served by three distribution centres (Mississauga, Ottawa and Montreal). In Module 1 we work on its central bakery, which makes three private-label products:
| SKU | Product | One batch |
|---|---|---|
| BK-SD | Sourdough loaf | 100 loaves |
| BK-WW | Whole-wheat loaf | 100 loaves |
| BK-CR | Croissant 6-pack | 50 packs |
Every Friday the bakery planner decides how many batches of each product to bake next week. She has used the same plan since September 2025: 25 sourdough, 35 whole-wheat, 10 croissant. By Day 3 you will know whether she can do better, and by how much.
Set up your repository
You work in GitHub Codespaces for the whole course.
- On GitHub, create a new private repository called
northbound-decisionswith a README. - Click Code → Codespaces → Create codespace on main.
- In the Codespace terminal, create a Python environment and install the course packages:
python -m venv .venv
source .venv/bin/activate
cat > requirements.txt <<'EOF'
duckdb==2.0.1
pandas==3.1.1
numpy==2.5.5
scipy==1.18.1
matplotlib==3.11.2
pyomo==6.11.0
highspy==1.16.0
EOF
pip install -r requirements.txt
- Open the Course data page on this site, copy the whole of
make_data.py, and save it at the root of your repository asmake_data.py. - Create a
.gitignoreso generated files stay out of Git:
printf ".venv/\ndata/\nfigures/\n__pycache__/\n" > .gitignore
- Generate the data:
python make_data.py
data/dcs.csv: 3 rows
data/stores.csv: 40 rows
data/bakery_products.csv: 3 rows
data/bakery_recipe.csv: 7 rows
data/bakery_resources.csv: 3 rows
data/bakery_current_plan.csv: 3 rows
data/bakery_sales_weekly.csv: 12,360 rows
Everyone's data is identical because the generator uses a fixed random seed (2026). If your row counts differ, you copied an older version of the script.
Decision it supports: none yet. This is the workshop where every later decision is built.
Other uses of the same set-up: rerun
make_data.pyany time you damage the data · share the repository with a classmate and get the same numbers.
1.2 Descriptive: what happened?
Create day01/ladder.py. We start by pointing DuckDB at the CSV files. DuckDB reads CSV files directly, so there is nothing to load.
import os
import duckdb
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
os.makedirs("figures", exist_ok=True)
con = duckdb.connect()
con.sql("CREATE VIEW sales AS SELECT * FROM 'data/bakery_sales_weekly.csv'")
con.sql("CREATE VIEW products AS SELECT * FROM 'data/bakery_products.csv'")
con.sql("CREATE VIEW stores AS SELECT * FROM 'data/stores.csv'")
print(con.sql("""
SELECT count(*) AS n_rows, count(DISTINCT week_start) AS n_weeks,
count(DISTINCT store_id) AS n_stores,
min(week_start) AS first_week, max(week_start) AS last_week
FROM sales"""))
┌────────┬─────────┬──────────┬────────────┬────────────┐
│ n_rows │ n_weeks │ n_stores │ first_week │ last_week │
│ int64 │ int64 │ int64 │ date │ date │
├────────┼─────────┼──────────┼────────────┼────────────┤
│ 12360 │ 104 │ 40 │ 2024-11-25 │ 2026-11-16 │
└────────┴─────────┴──────────┴────────────┴────────────┘
Two years of weekly sales: 104 weeks, 40 stores, 3 products. That would be 12,480 rows, but there are 12,360. Keep that gap in mind for Try it 1.2.
Now the chain total per week and product, and a chart:
weekly = con.sql("""
SELECT week_start, sku, sum(units_sold)::INTEGER AS units
FROM sales GROUP BY ALL ORDER BY week_start, sku""").df()
fig, ax = plt.subplots(figsize=(10, 4))
for sku, g in weekly.groupby("sku"):
ax.plot(g["week_start"], g["units"], label=sku)
ax.set_title("Northbound Fresh bakery: units sold per week, all stores")
ax.set_ylabel("units per week")
ax.legend()
fig.tight_layout()
fig.savefig("figures/day01_weekly_sales.png", dpi=120)

Three patterns stand out: a Christmas peak (largest for croissants), a summer dip in July and August, and slow growth from one year to the next.
print(con.sql("""
SELECT sku, arg_max(week_start, units) AS busiest_week, max(units) AS units
FROM (SELECT week_start, sku, sum(units_sold)::INTEGER AS units FROM sales GROUP BY ALL)
GROUP BY sku ORDER BY sku"""))
┌─────────┬──────────────┬───────┐
│ sku │ busiest_week │ units │
│ varchar │ date │ int32 │
├─────────┼──────────────┼───────┤
│ BK-CR │ 2025-12-22 │ 2479 │
│ BK-SD │ 2025-12-15 │ 4149 │
│ BK-WW │ 2025-12-22 │ 5387 │
└─────────┴──────────────┴───────┘
arg_max(week_start, units) returns the week_start of the row where units is largest: one function instead of a sort and a join.
Decision it supports: when to plan extra capacity (the Christmas weeks).
Other decisions you can support the same way: which months to schedule oven maintenance (the summer dip) · how much growth to budget for next year.
Try it 1.1
Which distribution centre's stores sold the most croissants over the two years? Join sales to stores.
Solution
print(con.sql("""
SELECT st.dc_id, sum(s.units_sold)::INTEGER AS croissants
FROM sales s JOIN stores st USING (store_id)
WHERE s.sku = 'BK-CR'
GROUP BY ALL ORDER BY croissants DESC"""))
┌─────────┬────────────┐
│ dc_id │ croissants │
│ varchar │ int32 │
├─────────┼────────────┤
│ DC-MTL │ 60538 │
│ DC-MIS │ 49455 │
│ DC-OTT │ 40558 │
└─────────┴────────────┘
Montreal, with 15 stores, sells the most.
Try it 1.2
The table has 120 rows fewer than 104 weeks × 40 stores × 3 products. Find the store responsible, and the reason.
Solution
print(con.sql("""
SELECT store_id, count(DISTINCT week_start) AS n_weeks, min(week_start) AS first_week
FROM sales GROUP BY ALL ORDER BY n_weeks LIMIT 3"""))
print(con.sql("SELECT store_id, store_name, opened_date FROM stores WHERE store_id = 'S40'"))
┌──────────┬─────────┬────────────┐
│ store_id │ n_weeks │ first_week │
│ varchar │ int64 │ date │
├──────────┼─────────┼────────────┤
│ S40 │ 64 │ 2025-09-01 │
│ S03 │ 104 │ 2024-11-25 │
│ S04 │ 104 │ 2024-11-25 │
└──────────┴─────────┴────────────┘
┌──────────┬─────────────────────────┬─────────────┐
│ store_id │ store_name │ opened_date │
│ varchar │ varchar │ date │
├──────────┼─────────────────────────┼─────────────┤
│ S40 │ Northbound Sherbrooke 2 │ 2025-09-01 │
└──────────┴─────────────────────────┴─────────────┘
Store S40 opened on 1 September 2025: 40 weeks × 3 products = 120 missing rows. They are missing because the store did not exist, not because data were lost. Part of the growth you saw in the chart comes from this new store.
1.3 Predictive: what will happen next week?
We need a forecast for the week of 23 November 2026. We try two simple methods and test them on the last 26 weeks: for each week, forecast it from the weeks before, then measure the miss.
- Last week: next week sells what this week sold.
- 8-week average: next week sells the average of the last 8 weeks.
print(con.sql("""
WITH w AS (
SELECT week_start, sku, sum(units_sold) AS units FROM sales GROUP BY ALL
), f AS (
SELECT week_start, sku, units,
lag(units) OVER (PARTITION BY sku ORDER BY week_start) AS last_week,
avg(units) OVER (PARTITION BY sku ORDER BY week_start
ROWS BETWEEN 8 PRECEDING AND 1 PRECEDING) AS avg_8_weeks
FROM w
)
SELECT sku,
round(avg(abs(units - last_week)), 1) AS mae_last_week,
round(avg(abs(units - avg_8_weeks)), 1) AS mae_avg_8_weeks
FROM f
WHERE week_start > (SELECT max(week_start) FROM w) - INTERVAL 26 WEEK
GROUP BY sku ORDER BY sku"""))
┌─────────┬───────────────┬─────────────────┐
│ sku │ mae_last_week │ mae_avg_8_weeks │
│ varchar │ double │ double │
├─────────┼───────────────┼─────────────────┤
│ BK-CR │ 36.0 │ 78.6 │
│ BK-SD │ 95.2 │ 171.2 │
│ BK-WW │ 99.9 │ 219.9 │
└─────────┴───────────────┴─────────────────┘
MAE is the mean absolute error: the average size of the miss, in units. "Last week" misses by about half as much. The 8-week average lags behind: the last 26 weeks include the summer dip and the September recovery, and an average of old weeks is slow to follow them. So "last week" is our forecast.
forecast = con.sql("""
SELECT s.sku, p.units_per_batch,
sum(s.units_sold)::INTEGER AS forecast_units,
round(sum(s.units_sold) / p.units_per_batch, 2) AS forecast_batches,
round(sum(s.units_sold) / p.units_per_batch)::INTEGER AS demand_cap_batches
FROM sales s JOIN products p USING (sku)
WHERE s.week_start = (SELECT max(week_start) FROM sales)
GROUP BY s.sku, p.units_per_batch ORDER BY s.sku""")
print(forecast)
forecast.write_csv("data/forecast_next_week.csv")
┌─────────┬─────────────────┬────────────────┬──────────────────┬────────────────────┐
│ sku │ units_per_batch │ forecast_units │ forecast_batches │ demand_cap_batches │
│ varchar │ int64 │ int32 │ double │ int32 │
├─────────┼─────────────────┼────────────────┼──────────────────┼────────────────────┤
│ BK-CR │ 50 │ 1551 │ 31.02 │ 31 │
│ BK-SD │ 100 │ 3500 │ 35.0 │ 35 │
│ BK-WW │ 100 │ 4499 │ 44.99 │ 45 │
└─────────┴─────────────────┴────────────────┴──────────────────┴────────────────────┘
demand_cap_batches is the forecast rounded to whole batches. It becomes a rule tomorrow: don't bake more than we expect to sell. Day 2 reads this file, so keep it.
In real work you would use a better forecasting model (that is the predictive course). Here the point is the hand-off: the forecast is an input to the decision, not the decision.
Decision it supports: choosing a forecasting method by testing it on past weeks, not by taste.
Other decisions you can support the same way: whether a new model is worth replacing the old one · how far ahead a forecast stays useful.
1.4 Prescriptive: what should we bake?
The bakery has three limits each week:
print(open("data/bakery_resources.csv").read())
print(open("data/bakery_recipe.csv").read())
resource,unit,weekly_capacity,note
oven_hours,hours,100,2 deck ovens x 50 usable hours
baker_hours,hours,80,2 bakers x 40 hours
sourdough_starter,batches,40,starter culture can feed at most 40 batches a week
sku,resource,use_per_batch
BK-SD,oven_hours,2.0
BK-SD,baker_hours,1.0
BK-SD,sourdough_starter,1.0
BK-WW,oven_hours,1.0
BK-WW,baker_hours,1.0
BK-CR,oven_hours,1.5
BK-CR,baker_hours,1.5
And each product earns a profit per batch: units per batch × (transfer price − ingredient cost).
print(con.sql("""
SELECT sku, product_name,
units_per_batch * (transfer_price - ingredient_cost) AS profit_per_batch
FROM products ORDER BY sku"""))
┌─────────┬──────────────────┬──────────────────┐
│ sku │ product_name │ profit_per_batch │
│ varchar │ varchar │ double │
├─────────┼──────────────────┼──────────────────┤
│ BK-CR │ Croissant 6-pack │ 250.0 │
│ BK-SD │ Sourdough loaf │ 300.0 │
│ BK-WW │ Whole-wheat loaf │ 200.0 │
└─────────┴──────────────────┴──────────────────┘
Checking a plan
A function that takes any plan and reports what it uses and earns:
con.sql("CREATE VIEW recipe AS SELECT * FROM 'data/bakery_recipe.csv'")
con.sql("CREATE VIEW resources AS SELECT * FROM 'data/bakery_resources.csv'")
con.sql("CREATE VIEW plan AS SELECT * FROM 'data/bakery_current_plan.csv'")
def check_plan(con, plan_sql):
"""Resources used by a plan versus capacity, and the plan's weekly profit."""
con.sql(f"CREATE OR REPLACE TEMP VIEW p AS {plan_sql}")
use = con.sql("""
SELECT r.resource, sum(r.use_per_batch * p.batches_per_week) AS used,
any_value(c.weekly_capacity) AS capacity,
used <= capacity AS ok
FROM recipe r JOIN p USING (sku) JOIN resources c USING (resource)
GROUP BY r.resource ORDER BY r.resource""")
profit = con.sql("""
SELECT sum(p.batches_per_week * units_per_batch * (transfer_price - ingredient_cost)) AS weekly_profit
FROM p JOIN products USING (sku)""").fetchall()[0][0]
return use, profit
use, profit = check_plan(con, "SELECT * FROM plan")
print(use)
print(f"weekly profit: ${profit:,.0f}")
┌───────────────────┬────────┬──────────┬─────────┐
│ resource │ used │ capacity │ ok │
│ varchar │ double │ int64 │ boolean │
├───────────────────┼────────┼──────────┼─────────┤
│ baker_hours │ 75.0 │ 80 │ true │
│ oven_hours │ 100.0 │ 100 │ true │
│ sourdough_starter │ 25.0 │ 40 │ true │
└───────────────────┴────────┴──────────┴─────────┘
weekly profit: $17,000
The current plan fits: the ovens are exactly full, with 5 baker hours and 15 starter batches spare. It earns $17,000 a week.
Why not simply bake what the forecast says we can sell?
use, profit = check_plan(con, "SELECT sku, demand_cap_batches AS batches_per_week FROM 'data/forecast_next_week.csv'")
print(use)
print(f"weekly profit: ${profit:,.0f} (but is it possible?)")
┌───────────────────┬────────┬──────────┬─────────┐
│ resource │ used │ capacity │ ok │
│ varchar │ double │ int64 │ boolean │
├───────────────────┼────────┼──────────┼─────────┤
│ baker_hours │ 126.5 │ 80 │ false │
│ oven_hours │ 161.5 │ 100 │ false │
│ sourdough_starter │ 35.0 │ 40 │ true │
└───────────────────┴────────┴──────────┴─────────┘
weekly profit: $27,250 (but is it possible?)
Baking to forecast needs 161.5 oven hours and 126.5 baker hours. We have 100 and 80. The $27,250 is a fantasy. This is the gap prescriptive analytics fills: the forecast says what we could sell; capacity says what we can make; the decision has to respect both.
The anatomy of a decision
Every prescriptive model has the same four parts. Write them in words before any code.
| Part | Bakery |
|---|---|
| Decisions (what we choose) | Batches of sourdough, whole-wheat and croissant to bake next week |
| Objective (what we want) | Maximize weekly profit |
| Constraints (rules we must respect) | Oven hours ≤ 100; baker hours ≤ 80; starter ≤ 40 batches; no product above its demand cap; no negative batches |
| Data (numbers we are given) | Profit per batch, use per batch, capacities, forecast |
Then as mathematics. Call the batches (sourdough), (whole-wheat) and (croissant):
This is a linear program: the objective and every constraint are sums of numbers times decision variables. Days 2 and 3 solve it; Day 4 writes it in Pyomo.
Trying every plan
With three products and caps of 35, 45 and 31 batches, there are only 36 × 46 × 32 = 52,992 whole-batch plans. A computer can try them all. Create day01/brute_force.py:
import time
import numpy as np
profit = {"BK-SD": 300, "BK-WW": 200, "BK-CR": 250}
oven = {"BK-SD": 2.0, "BK-WW": 1.0, "BK-CR": 1.5}
baker = {"BK-SD": 1.0, "BK-WW": 1.0, "BK-CR": 1.5}
cap = {"BK-SD": 35, "BK-WW": 45, "BK-CR": 31} # demand caps from the forecast
start = time.perf_counter()
sd, ww, cr = np.meshgrid(np.arange(cap["BK-SD"] + 1),
np.arange(cap["BK-WW"] + 1),
np.arange(cap["BK-CR"] + 1), indexing="ij")
sd, ww, cr = sd.ravel(), ww.ravel(), cr.ravel()
oven_used = oven["BK-SD"] * sd + oven["BK-WW"] * ww + oven["BK-CR"] * cr
baker_used = baker["BK-SD"] * sd + baker["BK-WW"] * ww + baker["BK-CR"] * cr
fits = (oven_used <= 100) & (baker_used <= 80) & (sd <= 40)
value = profit["BK-SD"] * sd + profit["BK-WW"] * ww + profit["BK-CR"] * cr
value = np.where(fits, value, -1)
best = value.max()
winners = np.flatnonzero(value == best)
seconds = time.perf_counter() - start
print(f"plans tried: {sd.size:,}")
print(f"plans that fit: {fits.sum():,}")
print(f"best profit: ${best:,}")
for i in winners:
print(f" best plan: sourdough {sd[i]}, whole-wheat {ww[i]}, croissant {cr[i]}")
print(f"time: {seconds:.3f} s")
print()
print("Plans to try if each product can take 0..40 batches:")
for n_products in (3, 10, 30, 120):
print(f" {n_products:>4} products: 41^{n_products} = {41 ** n_products:.2e}")
plans tried: 52,992
plans that fit: 37,559
best profit: $17,500
best plan: sourdough 20, whole-wheat 45, croissant 10
time: 0.008 s
Plans to try if each product can take 0..40 batches:
3 products: 41^3 = 6.89e+04
10 products: 41^10 = 1.34e+16
30 products: 41^30 = 2.42e+48
120 products: 41^120 = 3.42e+193
(Your time will differ.) The best plan, 20 sourdough, 45 whole-wheat, 10 croissant, earns $17,500 a week: $500 more than the current plan, or about $26,000 a year, from the same ovens and bakers.
Brute force works for 3 products. Northbound Fresh's full bakery has 30 products; at a billion plans a second, 41^30 plans would take far longer than the age of the universe. That is why the rest of the course uses solvers, which find the best plan without trying them all.
Decision it supports: next week's bake plan, and how much the current rule of thumb costs.
Other decisions you can support the same way: a weekly staffing mix within a budget · how many trucks of each size to rent.
Try it 1.3
Bakers ask for overtime: 90 baker hours instead of 80. Change one number in brute_force.py. What is the best profit now, and is the best plan unique?
Solution
Change (baker_used <= 80) to (baker_used <= 90):
best profit: $17,800
best plan: sourdough 10, whole-wheat 44, croissant 24
best plan: sourdough 11, whole-wheat 45, croissant 22
Ten extra baker hours add $300 a week. Two different plans tie: the best plan is not always unique. Day 3 shows why from the geometry.
Mini-project: write a decision statement
Northbound Fresh must decide which of its 3 distribution centres supplies each of its 40 stores. Without any code, write in day01/decision_statement.md:
- The decisions, in one sentence.
- The objective, and its unit.
- At least four constraints, in plain words.
- The data you would need, and which file in
data/already has part of it. - How many possible assignments there are, if every store can be served by any DC.
Model answer
- Decisions: for each store, which DC supplies it.
- Objective: minimize total weekly transport cost, in dollars per week.
- Constraints: every store is served by exactly one DC; each DC ships no more than its weekly capacity; delivery time from DC to store is under a maximum (fresh products); Quebec stores need French-labelled stock that only some DCs carry.
- Data: store demand (from
bakery_sales_weekly.csv, and later all products), DC capacities, cost per kilometre or per pallet for each DC–store pair, travel times.stores.csvanddcs.csvhave the locations and the current DC. - 3^40 = 12,157,665,459,056,928,801 (about 1.2 × 10^19) assignments. Brute force is hopeless; this is the Day 15 mini-project, solved in under a second.
Commit
git add .
git commit -m "Day 1: analytics ladder, forecast, plan checks, brute force"
git push
Day 1 checklist
- I can place a question on the analytics ladder (descriptive, diagnostic, predictive, prescriptive).
- I generated the course data and got 12,360 sales rows.
- I chose a forecast by testing it on past weeks.
- I can explain why "bake to forecast" is impossible next week.
- I can name the four parts of a decision model: decisions, objective, constraints, data.
- I found the best plan by brute force ($17,500) and know why brute force will not scale.