Skip to content

Capstone 2 — Sales analysis

The head of retail prepares the 2025 budget. Before she splits it between the stores, the online channel, promotions and new products, she asks you for a 2023–2024 performance review. She wants answers to five questions, and she wants to know how sure you are:

  1. Can we trust the numbers? The store managers send a point-of-sale (POS) export by hand. The finance team uses the warehouse table sales.csv. Do the two agree?
  2. How much did we grow, and where did the growth come from? By region, category and channel, from the new store and the new products, and from the existing stores and products, in store and online.
  3. When do we earn the money? The yearly season, the weekly pattern and the promotion days, and what promotions cost in gross margin.
  4. Do online customers spend more per order? The online team asks for its own basket-building budget. It argues that online orders are larger.
  5. What should we do? A one-page memo: each finding as a claim, its evidence and its caveat.

The review supports three budget decisions: the store versus online split, the promotion calendar and the product launch plan.

Deliverables:

  • One script, sales_review.py, that runs from the project folder with python sales_review.py and prints every number it uses.
  • Five charts in output/review/, ready for the slides.
  • A findings memo, printed and saved as output/review/memo.txt. Every number in it comes from the script.

Skills practiced:

Module What you use it for
23. NumPy np.select, np.isclose, log transforms
24. pandas fundamentals typed loading, filtering, new columns
25. pandas advanced validated merges, named aggregation, pivot tables
26. Data cleaning your cleaning pipeline, reused; reconciliation
27. Exploratory data analysis KPIs, breakdowns, claim → evidence → caveat
28. Visualization finding titles, honest axes, a waterfall, a diverging heatmap
29. Statistics and probability Welch CI, Mann–Whitney, bootstrap, effect size, an equivalence bound
30. SQL for data analysis a DuckDB query over the CSV files
31. Polars a lazy second engine for the cross-check

All files are in data/. The data dictionary describes every column.

File Rows Columns used
data/sales_raw.csv 1,200 all 13, as text
data/sales.csv 20,228 order_id, order_date, customer_id, store_id, region, channel, product_id, product, category, unit_price, quantity, discount, revenue
data/stores.csv 12 store_id, city, region, size_sqm, opened
data/products.csv 30 product_id, product, category, unit_cost, unit_price, launch_date

Facts from the data dictionary that matter here:

  • sales.csv has one row per order line. One order has 1–3 lines. The pair (order_id, product_id) is unique. revenue is unit_price × quantity × (1 − discount), within 0.01.
  • For an online order, store_id and region name the store that fulfilled it.
  • sales_raw.csv is a sample of 1,164 lines of sales.csv plus 36 exact duplicates. The quirk table lists every injected problem with its count: three date formats, missing tokens ("", N/A, -), prices as text with $, regions in the wrong case, stray spaces in product names and 10 impossible quantities. Its revenue column is correct.
  • Store S12 opened on 2023-06-15. Four products launched inside the period: P019, P005, P007 and P025.
  • The documented promotion days are Black Friday (2023-11-24 and 2024-11-29), the weekend after it, Cyber Monday (2023-11-27 and 2024-12-02) and the summer sales (2023-07-11/12 and 2024-07-16/17).

Average order value (AOV) is revenue divided by the number of orders, not by the number of lines.

Milestone 1 — Audit, clean and reconcile the POS export

Section titled “Milestone 1 — Audit, clean and reconcile the POS export”

Goal: prove that the warehouse table tells the same story as the export the stores send.

Acceptance criteria:

  • Count each documented quirk in sales_raw.csv with code, and assert that every count equals the data dictionary.
  • Clean the export. You built this pipeline in the module 26 mini-project: reuse your clean_sales.py steps, or condense them into one function. The result has 1,164 lines.
  • The new work is the reconciliation. Match every clean line to sales.csv on (order_id, product_id) with a validated merge. Report, per column, the values that are equal, missing or different. “Different” must be 0.

Review: 26. Data cleaning, 25. pandas advanced.

Milestone 2 — Join and validate the analysis table

Section titled “Milestone 2 — Join and validate the analysis table”

Goal: one line-level table with store and product attributes, and one order-level table.

Acceptance criteria:

  • Merge stores.csv and products.csv into sales.csv with validate="many_to_one".
  • Assert at least six rules: every key found, region and product attributes agree with the reference tables, the revenue formula, no sale before a store opened or a product launched, a unique line key, and one channel, store and date per order.
  • Add year, gross profit and a driver label: new product, new store (in-store sales of a store that opened in the period), like-for-like online or like-for-like in-store. Online orders are labeled by channel, not by the store that fulfilled them.
  • Build an orders table with one row per order_id.

Review: 25. pandas advanced, 26. Data cleaning.

Goal: say how much the business grew and where the growth came from.

Acceptance criteria:

  • A yearly KPI table: revenue, orders, AOV, units, gross margin and online share of revenue, with the change from 2023 to 2024.
  • Growth by channel, region, category and driver, with each group’s share of the total growth.
  • Split each channel’s revenue change into an orders effect and an AOV effect, in USD, that add up to the change.
  • Two charts: a growth bridge (waterfall) from 2023 to 2024 revenue, and monthly orders and AOV by channel.

Review: 27. Exploratory data analysis, 28. Visualization.

Milestone 4 — Seasonality and promotion spikes

Section titled “Milestone 4 — Seasonality and promotion spikes”

Goal: show when revenue arrives and what the promotion days add and cost.

Acceptance criteria:

  • The share of each year’s revenue in November–December, and mean daily revenue per weekday.
  • A weekday × month heatmap of daily revenue, relative to the average day, with a diverging colormap whose neutral color sits at 1.
  • For each documented promotion day, the uplift in orders and revenue against a baseline: the median of the same weekday in the four weeks before. Compute the same uplift on every ordinary day to get a noise band, and chart the promotion days against it.
  • Compare promotion days with all other days: revenue share, discount depth and gross margin.

Review: 25. pandas advanced, 28. Visualization.

Milestone 5 — Online versus store order value

Section titled “Milestone 5 — Online versus store order value”

Goal: answer the online team’s claim with a sound statistical comparison.

Acceptance criteria:

  • State the question, the unit (one order) and an equivalence bound before you test: the smallest gap that would change the budget. The reference uses ±10% of the store AOV.
  • A Welch t-test with a 95% confidence interval for the difference in mean order value.
  • Robustness checks for skewed money data and repeat customers: Mann–Whitney U with its probability of superiority, a test on log order values, a bootstrap CI for the difference in medians, a bootstrap that resamples customers and the same Welch test within each year.
  • An effect size (Cohen’s d) and a plain-language conclusion that uses the interval, not only the p-value.
  • One chart: the order-value distributions and the means with their intervals.

Review: 29. Statistics and probability.

Milestone 6 — Cross-check the headline numbers with SQL

Section titled “Milestone 6 — Cross-check the headline numbers with SQL”

Goal: make sure that a bug in the pandas code cannot reach the memo.

Acceptance criteria:

  • Recompute the growth bridge (revenue per driver and year) with one DuckDB query that joins the three CSV files.
  • Recompute yearly revenue, orders and AOV with DuckDB and with a lazy Polars query.
  • Assert that all three engines agree to the cent: an absolute tolerance of 0.005 USD and no relative tolerance.

Review: 30. SQL for data analysis, 31. Polars.

Goal: a memo the head of retail can read in two minutes.

Acceptance criteria:

  • Five to seven findings. Each is a claim (one sentence a manager can act on), its evidence (numbers from variables, not typed in) and a caveat (what the evidence does not show).
  • At least one recommendation per budget decision.
  • The script prints the memo, saves it to output/review/memo.txt and ends with assert checks on the headline numbers and the output files.

Review: 27. Exploratory data analysis.

Score each criterion at one level. The maximum is 40 points.

Criterion Needs work (0–1) Meets (2–3) Excellent (4–5) Max
Data trust Cleans without counting the quirks Counts match the dictionary; clean file has 1,164 lines Plus a per-column reconciliation with 0 differences and named gaps 5
Joins and validation Merges without validate Validated merges and at least four rules Six or more asserted rules and an orders table 5
KPIs and growth Line averages reported as AOV Correct yearly KPIs and growth tables Growth split into channel-aware drivers and into USD orders and AOV effects 5
Seasonality and promos Only a monthly line Season, weekday and promo days quantified Promo uplift against a stated baseline and a noise band from ordinary days, plus the gross-margin cost 5
Statistics A p-value alone Welch CI and an effect size Plus robustness checks, a stated equivalence bound, a customer-level and a per-year check 5
Charts Default titles, cut axes Five labeled charts with units Finding titles, honest scales, annotations, color-blind palette 5
Cross-check None One engine agrees with pandas Two engines agree to the cent on the bridge and the yearly KPIs, with asserts 5
Memo Numbers typed by hand Claims with evidence Claim → evidence → caveat, computed numbers, a recommendation per decision 5
Total 40

32 points or more: you are ready for Capstone 3.

Try each milestone yourself first. Your names, layout and chart styling can differ; your numbers must not. The blocks run top to bottom as one script, sales_review.py.

Reference solution — Milestone 1: audit, clean and reconcile

Step 1 — Imports, display options and a save helper. The theme and the formatter serve every chart.

sales_review.py (setup)
import textwrap
from pathlib import Path
import duckdb
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import polars as pl
import seaborn as sns
from matplotlib.colors import LogNorm
from matplotlib.lines import Line2D
from matplotlib.ticker import FuncFormatter
from scipy import stats
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)
sns.set_theme(style="whitegrid", palette="colorblind")
OUT = Path("output/review")
OUT.mkdir(parents=True, exist_ok=True)
K = FuncFormatter(lambda value, pos: f"{value / 1000:,.0f}k")
def save(fig: plt.Figure, name: str) -> Path:
"""Save a chart for the slides and return its path."""
path = OUT / f"{name}.png"
fig.savefig(path, dpi=150, bbox_inches="tight")
return path

Step 2 — Count each documented quirk. Read every column as text with keep_default_na=False, so that no token turns into NaN before you count it. The documented counts come from the data dictionary; the found counts come from the file.

sales_review.py (quirk audit)
NA_TOKENS = ["", "N/A", "-"]
REGIONS = ["North", "South", "East", "West"]
raw = pd.read_csv("data/sales_raw.csv", dtype=str, keep_default_na=False)
date, region, price = raw["order_date"], raw["region"], raw["unit_price"]
product, qty = raw["product"], raw["quantity"].astype(int)
missing = {"region": 17, "customer_id": 23, "channel": 17, "discount": 24,
"unit_price": 10}
checks = [ # (problem, documented count, found count)
("exact duplicate rows", 36, raw.duplicated().sum()),
("date DD/MM/YYYY", 276, date.str.fullmatch(r"\d{2}/\d{2}/\d{4}").sum()),
("date Month D, YYYY", 201, date.str.fullmatch(r"\w+ \d{1,2}, \d{4}").sum()),
("date YYYY-MM-DD", 723, date.str.fullmatch(r"\d{4}-\d{2}-\d{2}").sum()),
("region case or spaces", 259, (~region.isin(REGIONS + NA_TOKENS)).sum()),
*[(f"missing {c}", n, raw[c].isin(NA_TOKENS).sum()) for c, n in missing.items()],
("price with $", 1190, price.str.startswith("$").sum()),
("price with a thousands comma", 47, price.str.contains(",").sum()),
("product leading space", 29, product.str.match(r"\s").sum()),
("product trailing space", 35, product.str.contains(r"\s$").sum()),
("product double inner space", 31, product.str.contains(r"\S\s{2,}\S").sum()),
("negative quantity", 6, (qty < 0).sum()),
("quantity above 50", 4, (qty > 50).sum()),
]
audit = pd.DataFrame(checks, columns=["problem", "documented", "found"])
audit["match"] = audit["documented"] == audit["found"]
print(raw.shape)
print(audit.to_string(index=False))
assert audit["match"].all()
Output
(1200, 13)
problem documented found match
exact duplicate rows 36 36 True
date DD/MM/YYYY 276 276 True
date Month D, YYYY 201 201 True
date YYYY-MM-DD 723 723 True
region case or spaces 259 259 True
missing region 17 17 True
missing customer_id 23 23 True
missing channel 17 17 True
missing discount 24 24 True
missing unit_price 10 10 True
price with $ 1190 1190 True
price with a thousands comma 47 47 True
product leading space 29 29 True
product trailing space 35 35 True
product double inner space 31 31 True
negative quantity 6 6 True
quantity above 50 4 4 True

All 17 counts match, so the documented problems are all present, in the documented amounts. Matching counts cannot prove that no undocumented problem hides in the file; the reconciliation in step 4 checks that. One thing the audit does show: the three date formats add up to 1,200 rows, so no fourth format exists.

Step 3 — Clean the export. This is the module 26 mini-project pipeline, condensed into one function. If you built clean_sales.py there, import its steps instead. Order matters: the quantity repair needs the price and the discount, and the discount recovery needs a correct quantity.

sales_review.py (cleaning)
DATE_FORMATS = ["%Y-%m-%d", "%d/%m/%Y", "%B %d, %Y"]
KEY = ["order_id", "product_id"]
def clean_raw(
text: pd.DataFrame, products: pd.DataFrame, stores: pd.DataFrame
) -> pd.DataFrame:
"""Turn the raw text export into typed, clean sales lines."""
df = text.mask(text.isin(NA_TOKENS)).drop_duplicates()
dates = [pd.to_datetime(df["order_date"], format=f, errors="coerce")
for f in DATE_FORMATS]
ref_price = df["product_id"].map(products.set_index("product_id")["unit_price"])
ref_region = df["store_id"].map(stores.set_index("store_id")["region"])
price = pd.to_numeric(df["unit_price"].str.replace(r"[$,]", "", regex=True))
df = df.assign(
order_date=dates[0].combine_first(dates[1]).combine_first(dates[2]),
region=df["region"].str.strip().str.title().fillna(ref_region),
product=df["product"].str.strip().str.replace(r"\s+", " ", regex=True),
unit_price=price.fillna(ref_price),
quantity=df["quantity"].astype(int),
discount=pd.to_numeric(df["discount"]),
revenue=pd.to_numeric(df["revenue"]),
)
# Repair impossible quantities from revenue, then recover missing discounts.
implied_qty = (df["revenue"] / (df["unit_price"] * (1 - df["discount"]))).round()
bad_qty = ~df["quantity"].between(1, 50)
df["quantity"] = df["quantity"].mask(bad_qty, implied_qty).astype("int64")
implied_disc = 1 - df["revenue"] / (df["unit_price"] * df["quantity"])
df["discount"] = df["discount"].fillna(implied_disc.round(2))
assert df["order_date"].notna().all() and df["quantity"].between(1, 50).all()
assert df["discount"].isin([0.0, 0.05, 0.1, 0.2]).all()
assert (df["unit_price"] == ref_price).all() and (df["region"] == ref_region).all()
return df
products = pd.read_csv("data/products.csv", parse_dates=["launch_date"])
stores = pd.read_csv("data/stores.csv", parse_dates=["opened"])
clean = clean_raw(raw, products, stores)
gaps = clean.isna().sum()
unique_raw = raw.drop_duplicates()
print(clean.shape, "gaps:", gaps[gaps > 0].to_dict())
bad_qty = ~unique_raw["quantity"].astype(int).between(1, 50)
print("quantities repaired:", bad_qty.sum(),
"| discounts recovered:", unique_raw["discount"].isin(NA_TOKENS).sum())
Output
(1164, 13) gaps: {'customer_id': 23, 'channel': 17}
quantities repaired: 10 | discounts recovered: 23

The clean export has 1,164 lines: 1,200 minus the 36 duplicates. Two columns keep gaps. The export cannot tell who the customer was or which channel the order used, so the function does not invent them.

Step 4 — Reconcile with the warehouse table. Reconciliation checks that two copies of the same data agree. Match each clean line to sales.csv on the line key and compare every column.

sales_review.py (reconciliation)
truth = pd.read_csv("data/sales.csv", parse_dates=["order_date"])
rec = clean.merge(truth, on=KEY, how="left", suffixes=("", "_truth"),
validate="one_to_one", indicator=True)
print(rec["_merge"].value_counts().to_dict())
rows = []
for col in truth.columns.drop(KEY):
mine, true = rec[col], rec[f"{col}_truth"]
if pd.api.types.is_float_dtype(mine):
same = np.isclose(mine, true, atol=0.005)
else:
same = (mine == true).to_numpy()
gap = mine.isna().to_numpy()
rows.append({"column": col, "equal": int((same & ~gap).sum()),
"gap": int(gap.sum()), "differ": int((~same & ~gap).sum())})
reconciliation = pd.DataFrame(rows)
print(reconciliation.to_string(index=False))
assert (reconciliation["differ"] == 0).all()
Output
{'both': 1164, 'left_only': 0, 'right_only': 0}
column equal gap differ
order_date 1164 0 0
customer_id 1141 23 0
store_id 1164 0 0
region 1164 0 0
channel 1147 17 0
product 1164 0 0
category 1164 0 0
unit_price 1164 0 0
quantity 1164 0 0
discount 1164 0 0
revenue 1164 0 0

Every clean line finds its twin, and no value differs. The strong evidence is in the columns the cleaning had to derive: the three date formats, the 10 repaired quantities and the 23 recovered discounts all equal the warehouse values. The unit_price and region gaps were filled from the reference tables, so those cells agree partly by construction. The only gaps are 23 customer ids and 17 channels, which sales.csv holds. So sales.csv is a consistent, more complete version of the same data. The rest of the review uses it, all 20,228 lines.

Reference solution — Milestone 2: join and validate

Step 1 — Join the reference tables. validate="many_to_one" raises an error if a store or a product appears twice in its table. The suffixes keep the reference copies of region, product, category and unit_price for the checks.

sales_review.py (join)
lines = (
truth.merge(stores, on="store_id", how="left", validate="many_to_one",
suffixes=("", "_store"))
.merge(products, on="product_id", how="left", validate="many_to_one",
suffixes=("", "_ref"))
)
same_product = lines[["product", "category", "unit_price"]].to_numpy() == lines[
["product_ref", "category_ref", "unit_price_ref"]].to_numpy()
per_order = lines.groupby("order_id")[["channel", "store_id", "order_date",
"customer_id"]].nunique()
expected = lines["unit_price"] * lines["quantity"] * (1 - lines["discount"])
rules = {
"every store and product found": lines[["city", "unit_cost"]].notna().all().all(),
"region equals the store region": (lines["region"] == lines["region_store"]).all(),
"product, category and price agree": same_product.all(),
"revenue = price x quantity x (1 - discount)":
np.isclose(expected, lines["revenue"], rtol=0, atol=0.01).all(),
"no sale before the store opened": (lines["order_date"] >= lines["opened"]).all(),
"no sale before the product launch":
(lines["order_date"] >= lines["launch_date"]).all(),
"(order_id, product_id) is unique": not lines.duplicated(KEY).any(),
"one channel, store, date, customer per order": (per_order == 1).all().all(),
}
for name, ok in rules.items():
print("PASS" if ok else "FAIL", name)
assert all(rules.values())
Output
PASS every store and product found
PASS region equals the store region
PASS product, category and price agree
PASS revenue = price x quantity x (1 - discount)
PASS no sale before the store opened
PASS no sale before the product launch
PASS (order_id, product_id) is unique
PASS one channel, store, date, customer per order

Step 2 — Add the analysis columns and the orders table. A product or store is “new” when it started inside the sales period. Each line gets one driver label. The rules apply in order:

  1. new product: a product launched in the period, in any channel.
  2. new store: an in-store sale in a store that opened in the period.
  3. like-for-like online: an online sale of an existing product, whichever store fulfilled it.
  4. like-for-like in-store: an in-store sale of an existing product in an existing store.

Online orders follow the channel, not the fulfilling store: the customer chose to order online, not to buy from S12. Without this rule, online demand that S12 fulfilled would look like an effect of the store opening, and the in-store and online trends of the existing business would blend into one number.

sales_review.py (columns and orders)
START = pd.Timestamp("2023-01-01")
new_products = products.loc[products["launch_date"] >= START, "product_id"]
new_stores = stores.loc[stores["opened"] >= START, "store_id"]
lines["year"] = lines["order_date"].dt.year
lines["profit"] = lines["revenue"] - lines["unit_cost"] * lines["quantity"]
in_store = lines["channel"] == "store"
lines["driver"] = np.select(
[lines["product_id"].isin(new_products),
lines["store_id"].isin(new_stores) & in_store,
~in_store],
["new product", "new store", "like-for-like online"],
default="like-for-like in-store",
)
orders = (
lines.groupby("order_id")
.agg(order_date=("order_date", "first"), channel=("channel", "first"),
customer_id=("customer_id", "first"), n_lines=("product_id", "size"),
revenue=("revenue", "sum"))
.assign(year=lambda d: d["order_date"].dt.year)
)
print("new products:", sorted(new_products), "new stores:", sorted(new_stores))
print("lines", lines.shape, "orders", orders.shape)
print(lines["driver"].value_counts().to_string())
Output
new products: ['P005', 'P007', 'P019', 'P025'] new stores: ['S12']
lines (20228, 25) orders (14877, 6)
driver
like-for-like in-store 10197
like-for-like online 7533
new product 2069
new store 429

The orders table has 14,877 rows, one per order_id. AOV must come from this table. The mean of revenue on the lines table is the mean line value, which is smaller.

Reference solution — Milestone 3: KPIs and growth drivers

Step 1 — The yearly KPI table. Rates change in percentage points (pp), not in percent. The pp change is computed from the rounded rates, so the printed numbers add up. online_rev_share is the online share of revenue; the data dictionary’s online share counts lines, so it differs.

sales_review.py (yearly KPIs)
by_year = lines.groupby("year")
kpi = pd.DataFrame({
"revenue": by_year["revenue"].sum(),
"orders": orders.groupby("year").size(),
"units": by_year["quantity"].sum(),
"gross_margin": by_year["profit"].sum() / by_year["revenue"].sum(),
"online_rev_share": lines["revenue"].where(lines["channel"] == "online")
.groupby(lines["year"]).sum() / by_year["revenue"].sum(),
})
kpi["aov"] = kpi["revenue"] / kpi["orders"]
growth = kpi.loc[2024, "revenue"] / kpi.loc[2023, "revenue"] - 1
print(f"{'metric':<14}{'2023':>14}{'2024':>14}{'change':>10}")
for col, fmt in [("revenue", ",.2f"), ("orders", ",.0f"), ("aov", ",.2f"),
("units", ",.0f")]:
a, b = kpi.loc[2023, col], kpi.loc[2024, col]
print(f"{col:<14}{a:>14{fmt}}{b:>14{fmt}}{b / a - 1:>+10.1%}")
for col in ["gross_margin", "online_rev_share"]:
a, b = (kpi.loc[year, col].round(3) * 100 for year in (2023, 2024))
print(f"{col:<16}{a:>12.1f}%{b:>13.1f}%{b - a:>+7.1f} pp")
Output
metric 2023 2024 change
revenue 1,645,589.59 1,950,934.24 +18.6%
orders 6,721 8,156 +21.4%
aov 244.84 239.20 -2.3%
units 13,190 16,343 +23.9%
gross_margin 48.3% 49.5% +1.2 pp
online_rev_share 37.8% 46.0% +8.2 pp

Revenue grew 18.6%. Orders grew faster than revenue, so the average order got slightly smaller. Growth came from more orders, not from bigger baskets.

Step 2 — Growth by channel, region, category and driver. The share of growth tells you which group delivered the increase. The shares of a dimension add up to 100%.

sales_review.py (growth tables)
def growth_by(dim: str) -> pd.DataFrame:
"""Revenue per year, growth and share of the total growth for one dimension."""
t = lines.pivot_table(index=dim, columns="year", values="revenue", aggfunc="sum")
delta = t[2024] - t[2023]
t["growth"] = t[2024] / t[2023] - 1
t["share_of_growth"] = delta / delta.sum()
t[[2023, 2024]] = t[[2023, 2024]].round().astype(int)
return t.sort_values("share_of_growth", ascending=False)
tables = {dim: growth_by(dim) for dim in ["channel", "region", "category", "driver"]}
for table in tables.values():
print(table, end="\n\n")
drivers = tables["driver"]
lfl_store_orders = lines[lines["driver"] == "like-for-like in-store"].groupby("year")[
"order_id"].nunique()
lfl_store_orders_change = lfl_store_orders[2024] / lfl_store_orders[2023] - 1
print("like-for-like in-store orders:", lfl_store_orders.to_dict(),
f"({lfl_store_orders_change:+.1%})")
Output
year 2023 2024 growth share_of_growth
channel
online 622853 896613 0.440 0.897
store 1022737 1054321 0.031 0.103
year 2023 2024 growth share_of_growth
region
East 448919 544765 0.214 0.314
South 409501 482265 0.178 0.238
West 376670 446175 0.185 0.228
North 410500 477729 0.164 0.220
year 2023 2024 growth share_of_growth
category
Home 274450 397845 0.450 0.404
Electronics 868183 939925 0.083 0.235
Sports 244532 299576 0.225 0.180
Clothing 143987 170700 0.186 0.087
Beauty 64973 85445 0.315 0.067
Books 49464 57444 0.161 0.026
year 2023 2024 growth share_of_growth
driver
new product 78549 314516 3.004 0.773
like-for-like online 592310 744043 0.256 0.497
new store 36023 43118 0.197 0.023
like-for-like in-store 938707 849257 -0.095 -0.293
like-for-like in-store orders: {2023: 3943, 2024: 3739} (-5.2%)

The driver table is the key result, and it tells two stories:

  • The four new products hold most of the measured growth. How much of it is extra demand, and how much is sales taken from older products, this split cannot say.
  • The existing range grew only online. In the existing stores, its in-store revenue fell by almost a tenth, and its in-store orders fell too. The channel table hid this: store revenue grew 3.1% only because the new products and S12 added in-store sales.

For the store versus online budget, the in-store decline of the existing business is the number to explain first.

Step 3 — Split the channel growth into orders and AOV. Revenue is orders × AOV. The orders effect is the extra orders valued at the old AOV. The AOV effect is the change in AOV applied to the new number of orders. The two add up to the revenue change exactly. The order matters: changing the AOV first gives slightly different parts, so name the order you use.

sales_review.py (orders x AOV by channel)
ch = orders.pivot_table(index="channel", columns="year", values="revenue",
aggfunc=["size", "mean"])
ch.columns = [f"{'orders' if s == 'size' else 'aov'}_{y}" for s, y in ch.columns]
ch.loc["total"] = [*kpi["orders"], *kpi["aov"]]
ch["orders_change"] = ch["orders_2024"] / ch["orders_2023"] - 1
ch["aov_change"] = ch["aov_2024"] / ch["aov_2023"] - 1
# Revenue = orders x AOV. Change the orders first, then the AOV:
ch["orders_effect"] = (ch["orders_2024"] - ch["orders_2023"]) * ch["aov_2023"]
ch["aov_effect"] = ch["orders_2024"] * (ch["aov_2024"] - ch["aov_2023"])
revenue_change = ch["orders_2024"] * ch["aov_2024"] - ch["orders_2023"] * ch["aov_2023"]
assert np.allclose(ch["orders_effect"] + ch["aov_effect"], revenue_change)
print(ch[["orders_change", "aov_change"]].round(3))
print(ch[["orders_effect", "aov_effect"]].round().astype(int))
Output
orders_change aov_change
channel
online 0.514 -0.049
store 0.036 -0.005
total 0.214 -0.023
orders_effect aov_effect
channel
online 320167 -46407
store 37019 -5435
total 351350 -46005

Online orders grew by half; store orders grew by a few percent. In both channels, the AOV fell slightly, by 5% at most. In USD, the orders effect dwarfs the AOV effect in every row: the business grew by winning orders, not by bigger baskets.

Step 4 — Chart 1, the growth bridge. A waterfall chart starts at one total, adds each contribution as a floating bar and ends at the next total. It answers “where did the growth come from” in one picture.

sales_review.py (chart 1: growth bridge)
order = ["like-for-like in-store", "like-for-like online", "new store", "new product"]
bridge = lines.pivot_table(index="driver", columns="year", values="revenue",
aggfunc="sum").loc[order]
delta = bridge[2024] - bridge[2023]
start, end = kpi.loc[2023, "revenue"], kpi.loc[2024, "revenue"]
assert np.isclose(start + delta.sum(), end, rtol=0, atol=0.005)
level = start + delta.cumsum() # running total after each step
labels = ["2023", "like-for-like\nin-store", "like-for-like\nonline",
f"new store\n({', '.join(new_stores)}, in-store)",
f"new products\n({len(new_products)})", "2024"]
heights = [start, *delta.abs(), end]
bottoms = [0, *np.minimum(level - delta, level), 0]
colors = ["0.6", *np.where(delta < 0, "C3", "C2"), "0.6"]
fig, ax = plt.subplots(figsize=(9, 4.2))
bars = ax.bar(labels, heights, bottom=bottoms, color=colors, width=0.6)
for i, (bar, h, b) in enumerate(zip(bars, heights, bottoms)):
x = bar.get_x() + bar.get_width() / 2
if i in (0, len(bars) - 1): # totals: label inside the bar
ax.text(x, h / 2, f"{h / 1000:,.0f}k", ha="center", va="center",
color="white", fontweight="bold")
else: # contributions: signed label above the bar
ax.text(x, b + h, f"{delta.iloc[i - 1] / 1000:+,.0f}k", ha="center",
va="bottom", fontweight="bold")
ax.yaxis.set_major_formatter(K)
ax.set_ylim(0, level.max() * 1.1)
lfl_store_growth = drivers.loc["like-for-like in-store", "growth"]
ax.set(title="Growth came from new products and online; in-store sales of the "
f"existing range fell {-lfl_store_growth:.1%}", ylabel="Revenue (USD)")
paths = [save(fig, "1_growth_bridge")]
plt.show()
print((delta / 1000).round(1).to_string())
Output
driver
like-for-like in-store -89.5
like-for-like online 151.7
new store 7.1
new product 236.0
Waterfall from 2023 revenue of 1,646k to 2024 revenue of 1,951k: in-store sales of the existing range in the existing stores fall by 89k, online sales of the existing range add 152k, in-store sales of the new store S12 add 7k and the four new products add 236k.
Chart 1: the growth bridge from 2023 to 2024 revenue, by channel-aware driver.

The axis starts at zero, so the two totals compare honestly; the price is that the floating bars look thin, so their labels sit above them. A falling step hangs down from the running total and has its own color, so the decline is not lost between two gains.

Step 5 — Chart 2, orders and AOV by channel per month. Two panels share the time axis: volume on top, order value below.

sales_review.py (chart 2: orders and AOV by channel)
monthly = orders.groupby([pd.Grouper(key="order_date", freq="MS"), "channel"])[
"revenue"].agg(["size", "mean"]).unstack("channel")
fig, (top, bottom) = plt.subplots(2, 1, figsize=(9, 5.5), sharex=True)
for i, channel in enumerate(["store", "online"]):
top.plot(monthly.index, monthly[("size", channel)], marker="o", markersize=3,
color=f"C{i}", label=channel)
bottom.plot(monthly.index, monthly[("mean", channel)], marker="o", markersize=3,
color=f"C{i}", label=channel)
top.set_ylim(0, None)
bottom.set_ylim(0, None)
top.set(ylabel="Orders per month",
title="Online orders grew fast; the value of an order stayed flat")
bottom.set(ylabel="AOV (USD)")
top.legend(title="Channel", frameon=False, loc="upper left")
paths.append(save(fig, "2_orders_aov_by_channel"))
plt.show()
Two panels over 2023–2024. Top: monthly online orders climb steadily and overtake store orders in November–December 2024, while store orders grow little apart from the year-end peaks. Bottom: monthly AOV of both channels moves around 200 to 300 USD with no trend and no lasting gap between the channels.
Chart 2: monthly orders (top) and average order value (bottom) by channel.
Reference solution — Milestone 4: seasonality and promotion spikes

Step 1 — The yearly and weekly pattern. Aggregate to one row per day first. A daily mean over order lines would weight each day by its number of lines. asfreq("D") makes the calendar explicit: a day without orders would appear as a gap, and the assert proves there is none, so a shift of 7 rows is a shift of 7 days.

sales_review.py (season and weekday)
daily = orders.groupby("order_date").agg(orders=("revenue", "size"),
revenue=("revenue", "sum")).asfreq("D")
assert len(daily) == 731 and daily.notna().all().all()
month = lines.groupby(["year", lines["order_date"].dt.month])["revenue"].sum()
nov_dec = month.loc[(slice(None), [11, 12])].groupby("year").sum() / kpi["revenue"]
weekday = daily.groupby(daily.index.day_name().rename("weekday"))["revenue"].mean()
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
print("Nov-Dec share of yearly revenue:", nov_dec.round(3).to_dict())
for label, (year, m) in [("lowest", month.idxmin()), ("highest", month.idxmax())]:
print(f"{label} month: {year}-{m:02d}, {month[(year, m)]:,.2f} USD")
print((weekday.reindex(days) / daily["revenue"].mean()).round(2).to_string())
Output
Nov-Dec share of yearly revenue: {2023: 0.265, 2024: 0.293}
lowest month: 2023-02, 77,405.21 USD
highest month: 2024-12, 302,911.77 USD
weekday
Monday 0.86
Tuesday 0.80
Wednesday 0.87
Thursday 0.90
Friday 1.14
Saturday 1.29
Sunday 1.15

November and December bring more than a quarter of each year. Saturday is the strongest day: about 30% above the average day.

Step 2 — Chart 3, the weekday × month heatmap. Each cell is the mean daily revenue of that weekday in that month, divided by the mean of all days. 1.0 is an average day. A diverging colormap shows above-average cells in one hue and below-average cells in the other. Ratios are symmetric on a log scale: 0.4 is as far below 1 as 2.5 is above it, because 0.4 × 2.5 = 1. So LogNorm(vmin=0.4, vmax=2.5) puts the neutral color exactly at 1 without seaborn’s center= argument, and no cell is clipped.

sales_review.py (chart 3: weekday x month heatmap)
grid = daily.assign(weekday=daily.index.day_of_week, month=daily.index.month)
index = grid.pivot_table(index="weekday", columns="month", values="revenue",
aggfunc="mean") / daily["revenue"].mean()
fig, ax = plt.subplots(figsize=(9, 3.8))
sns.heatmap(index, annot=True, fmt=".1f", cmap="vlag",
norm=LogNorm(vmin=0.4, vmax=2.5), linewidths=0.5, ax=ax,
annot_kws={"fontsize": 8},
cbar_kws={"label": "mean daily revenue / average day",
"ticks": [0.4, 0.6, 1, 1.6, 2.5], "format": "%.1f"})
ax.collections[0].colorbar.minorticks_off()
ax.set_yticks(np.arange(7) + 0.5, labels=[d[:3] for d in days], rotation=0)
ax.set_xticks(np.arange(12) + 0.5,
labels=pd.date_range("2024-01-01", periods=12, freq="MS").strftime("%b"))
ax.set(title="Weekends and November–December earn the most; "
"early-year weekdays the least",
xlabel="", ylabel="")
paths.append(save(fig, "3_weekday_month_heatmap"))
plt.show()
hot_day, hot_month = index.stack().idxmax()
cold_day, cold_month = index.stack().idxmin()
cells = index.stack()
print(f"hottest cell: {days[hot_day]} in month {hot_month}, {cells.max():.2f}")
print(f"coldest cell: {days[cold_day]} in month {cold_month}, {cells.min():.2f}")
Output
hottest cell: Friday in month 11, 2.45
coldest cell: Wednesday in month 2, 0.48
Heatmap of weekdays by months on a log color scale centered at 1: red cells, above an average day, fill November and December and most weekend cells from May on; blue cells, below average, fill the weekdays of January to April and of September and October, down to 0.5. The hottest cell is Friday in November at 2.4, inflated by Black Friday.
Chart 3: mean daily revenue by weekday and month, relative to the average day of 2023–2024.

The Friday–November cell is the hottest. It holds both Black Fridays, so one promotion day lifts a whole cell. The next step separates the promotions from the season.

Step 3 — Promotion uplift against a baseline and a noise band. The baseline of a day is what we would expect without the promotion. Here it is the median of the same weekday in the four weeks before. Uplift is the actual value divided by the baseline.

Be clear about what this baseline does. The same weekday removes the weekly pattern. The trailing median sets the level of the recent weeks and ignores one odd week. It does not remove a seasonal ramp inside those weeks: in a rising November, four earlier weeks are lower than today even without a promotion. It does not remove day-to-day noise either. So compute the same uplift on every ordinary day. Its spread is the noise band: a promotion day inside it cannot be told apart from an ordinary day.

sales_review.py (promotion uplift)
PROMOS = {
"2023-07-11": "summer sale", "2023-07-12": "summer sale",
"2023-11-24": "Black Friday", "2023-11-25": "BF weekend",
"2023-11-26": "BF weekend", "2023-11-27": "Cyber Monday",
"2024-07-16": "summer sale", "2024-07-17": "summer sale",
"2024-11-29": "Black Friday", "2024-11-30": "BF weekend",
"2024-12-01": "BF weekend", "2024-12-02": "Cyber Monday",
}
WEEKS = 4 # baseline window: the same weekday in the WEEKS weeks before
promo_days = pd.to_datetime(list(PROMOS))
for col in ["orders", "revenue"]:
same_weekday = pd.concat([daily[col].shift(7 * w) for w in range(1, WEEKS + 1)],
axis=1)
daily[f"{col}_base"] = same_weekday.median(axis=1)
daily[f"{col}_uplift"] = daily[col] / daily[f"{col}_base"]
ordinary = daily["orders_uplift"].drop(promo_days).dropna()
band = ordinary.quantile([0.05, 0.95])
late = ordinary[ordinary.index.month >= 11]
print(f"{len(ordinary)} ordinary days: median uplift {ordinary.median():.2f}, "
f"5th-95th percentile {band[0.05]:.2f} to {band[0.95]:.2f}, "
f"max {ordinary.max():.2f}")
print(f"{len(late)} ordinary Nov-Dec days: median {late.median():.2f}, "
f"95th percentile {late.quantile(0.95):.2f}")
promo = daily.loc[promo_days, ["orders", "orders_base", "orders_uplift",
"revenue_uplift"]]
promo.columns = ["orders", "base", "uplift", "rev_uplift"]
promo.insert(0, "event", list(PROMOS.values()))
promo["above_p95"] = promo["uplift"] > band[0.95]
promo["above_max"] = promo["uplift"] > ordinary.max()
promo.index = promo.index.strftime("%a %Y-%m-%d")
print(promo.round(2))
Output
712 ordinary days: median uplift 1.02, 5th-95th percentile 0.55 to 1.56, max 2.14
114 ordinary Nov-Dec days: median 1.16, 95th percentile 1.56
event orders base uplift rev_uplift above_p95 above_max
order_date
Tue 2023-07-11 summer sale 20 12.0 1.67 1.09 True False
Wed 2023-07-12 summer sale 29 18.0 1.61 0.84 True False
Fri 2023-11-24 Black Friday 92 22.5 4.09 7.41 True True
Sat 2023-11-25 BF weekend 56 26.5 2.11 2.59 True False
Sun 2023-11-26 BF weekend 41 29.5 1.39 1.49 False False
Mon 2023-11-27 Cyber Monday 35 15.0 2.33 1.33 True True
Tue 2024-07-16 summer sale 32 14.5 2.21 2.65 True True
Wed 2024-07-17 summer sale 38 21.0 1.81 1.60 True False
Fri 2024-11-29 Black Friday 130 32.5 4.00 4.51 True True
Sat 2024-11-30 BF weekend 87 37.5 2.32 1.76 True True
Sun 2024-12-01 BF weekend 66 32.0 2.06 1.94 True False
Mon 2024-12-02 Cyber Monday 84 24.0 3.50 2.05 True True

On ordinary days, the uplift centers near 1, as it should, but it is wide: one ordinary day in twenty is above 1.56×, and the largest reaches 2.14×. In November–December, ordinary days already sit above 1, because the trailing baseline lags the seasonal ramp. So read the promotions against the band, not against 1:

  • The two Black Fridays (about 4×) and Cyber Monday 2024 (3.5×) are far above anything an ordinary day reaches. Part of even their uplift is the season, so treat the numbers as upper bounds.
  • Half of the promotion days stay below the largest ordinary-day uplift, and one, the Sunday after Black Friday 2023, sits inside the band.
  • Revenue uplift is noisier than order uplift: one TV or laptop order moves a day’s revenue, so it ranges from 0.84× to 7.41×. That is why the chart uses orders.

Step 4 — Chart 4, the order uplift per promotion day.

sales_review.py (chart 4: promotion uplift)
fig, ax = plt.subplots(figsize=(8.5, 4.8))
colors = ["C0" if day.year == 2023 else "C1" for day in promo_days]
labels = [f"{d} {e}" for d, e in zip(promo.index, promo["event"])]
ax.axvspan(band[0.05], band[0.95], color="0.88", zorder=0)
ax.axvline(ordinary.max(), color="0.4", linestyle=":", linewidth=1.2)
ax.axvline(1, color="0.3", linestyle="--", linewidth=1)
bars = ax.barh(labels[::-1], promo["uplift"][::-1], color=colors[::-1], height=0.6)
ax.bar_label(bars, fmt="%.1f×", padding=3, fontsize=9)
ax.set_xlim(0, promo["uplift"].max() * 1.15)
within = (~promo["above_max"]).sum()
ax.set(title=f"Black Friday quadruples orders; {within} of {len(promo)} promotion days "
"stay within everyday range",
xlabel=f"Orders / median of the same weekday in the {WEEKS} weeks before")
handles = [plt.Rectangle((0, 0), 1, 1, color=c) for c in ["C0", "C1", "0.88"]]
handles.append(Line2D([], [], color="0.4", linestyle=":"))
ax.legend(handles, ["2023", "2024", "90% of ordinary days", "largest ordinary day"],
frameon=False, loc="upper center", bbox_to_anchor=(0.4, -0.13), ncol=4,
fontsize=9)
paths.append(save(fig, "4_promo_uplift"))
plt.show()
Horizontal bars of order uplift for the 12 promotion days. A grey band marks 90% of ordinary days, from about 0.55× to 1.56×, and a dotted line marks the largest ordinary day at 2.14×. Both Black Fridays reach about 4× and Cyber Monday 2024 3.5×; six days, including both summer sales of 2023, stay below the dotted line, and the Sunday after Black Friday 2023 sits inside the band.
Chart 4: order uplift on each documented promotion day, against the spread of the same measure on ordinary days.

Step 5 — What the promotion days cost. A promotion is worth its extra volume only if the gross margin holds up.

sales_review.py (promotion cost)
lines["promo"] = lines["order_date"].isin(promo_days)
promo_vs_rest = lines.groupby("promo").agg(
revenue=("revenue", "sum"), profit=("profit", "sum"),
mean_discount=("discount", "mean"),
share_20pct=("discount", lambda d: (d == 0.2).mean()),
)
promo_vs_rest["gross_margin"] = promo_vs_rest["profit"] / promo_vs_rest["revenue"]
promo_vs_rest["revenue_share"] = promo_vs_rest["revenue"] / kpi["revenue"].sum()
promo_vs_rest.index = ["other days", "promo days"]
promo_vs_rest["revenue"] = promo_vs_rest["revenue"].round().astype(int)
print(promo_vs_rest.drop(columns="profit").round(3))
gross_margin_gap = promo_vs_rest["gross_margin"].diff().iloc[-1] * 100
print(f"gross margin gap: {gross_margin_gap:+.1f} pp")
Output
revenue mean_discount share_20pct gross_margin revenue_share
other days 3433144 0.030 0.057 0.492 0.955
promo days 163380 0.101 0.349 0.445 0.045
gross margin gap: -4.7 pp

The 12 promotion days earn a few percent of the revenue at a gross margin several points lower. A third of their lines carry the deepest discount, 20%.

Reference solution — Milestone 5: online versus store order value

Step 1 — State the question before the test. The unit is one order: lines of the same order are not independent. The question is “is the mean order value different between online and store orders, and by how much?” The equivalence bound is ±10% of the store AOV: the smallest gap that would change the budget. Orders are also grouped by customer, because most customers order several times; step 2 checks that this does not change the answer.

sales_review.py (Welch test and effect size)
online = orders.loc[orders["channel"] == "online", "revenue"].to_numpy()
store = orders.loc[orders["channel"] == "store", "revenue"].to_numpy()
bound = 0.10 * store.mean()
welch = stats.ttest_ind(online, store, equal_var=False)
ci = welch.confidence_interval(confidence_level=0.95)
diff = online.mean() - store.mean()
# Cohen's d with the average of the two variances, which suits unequal variances
avg_sd = np.sqrt((online.var(ddof=1) + store.var(ddof=1)) / 2)
cohens_d = diff / avg_sd
print(f"orders: online {len(online):,}, store {len(store):,}")
print(f"AOV: online {online.mean():.2f}, store {store.mean():.2f}, diff {diff:+.2f}")
print(f"Welch 95% CI for the difference: {ci.low:+.2f} to {ci.high:+.2f} USD")
print(f"p-value {welch.pvalue:.3f}, Cohen's d {cohens_d:.3f}")
print(f"equivalence bound: +/-{bound:.2f} USD; CI inside it: "
f"{-bound < ci.low and ci.high < bound}")
Output
orders: online 6,270, store 8,607
AOV: online 242.34, store 241.32, diff +1.02
Welch 95% CI for the difference: -11.45 to +13.48 USD
p-value 0.873, Cohen's d 0.003
equivalence bound: +/-24.13 USD; CI inside it: True

The difference is about 1 USD on an AOV of about 240 USD. The confidence interval runs from about −11 to +13 USD, well inside the ±24 USD bound. So the data rules out any gap that would matter for the budget. Cohen’s d is close to 0: the two distributions overlap almost completely. It divides by the square root of the average of the two variances, not by the pooled SD, which assumes equal variances.

Step 2 — Robustness checks. Order values are right-skewed: a few TV and laptop orders are worth more than 1,000 USD. With 6,000 to 8,600 orders per group, the sample means are close to normal, so Welch is valid. Three checks confirm it from different angles. A customer bootstrap resamples whole customers with all their orders, so repeat customers cannot make the interval too narrow. A per-year check rules out a mix effect: the online share grew from 2023 to 2024, and the AOV changed between the years.

sales_review.py (robustness checks)
mw = stats.mannwhitneyu(online, store, alternative="two-sided")
superiority = mw.statistic / (len(online) * len(store))
log_test = stats.ttest_ind(np.log(online), np.log(store), equal_var=False)
log_ci = np.exp(log_test.confidence_interval())
rng = np.random.default_rng(42)
boot = stats.bootstrap(
(online, store),
lambda a, b, axis: np.median(a, axis=axis) - np.median(b, axis=axis),
n_resamples=2_000, method="percentile", vectorized=True, rng=rng,
)
median_diff = np.median(online) - np.median(store)
per_customer = orders.pivot_table(index="customer_id", columns="channel",
values="revenue", aggfunc=["sum", "size"],
fill_value=0)
picks = rng.integers(0, len(per_customer), size=(2_000, len(per_customer)))
boot_aov = {
ch_name: per_customer[("sum", ch_name)].to_numpy()[picks].sum(axis=1)
/ per_customer[("size", ch_name)].to_numpy()[picks].sum(axis=1)
for ch_name in ["online", "store"]
}
cust_ci = np.percentile(boot_aov["online"] - boot_aov["store"], [2.5, 97.5])
both = ((per_customer["size"] > 0).sum(axis=1) == 2).mean()
print(f"Mann-Whitney p {mw.pvalue:.3f}, "
f"probability of superiority (ties count half) {superiority:.3f}")
print(f"geometric-mean ratio online/store 95% CI: {log_ci[0]:.3f} to {log_ci[1]:.3f}")
print(f"median diff {median_diff:+.2f}, bootstrap 95% CI "
f"{boot.confidence_interval.low:+.2f} to {boot.confidence_interval.high:+.2f}")
year_cis = {}
for year, group in orders.groupby("year"):
a = group.loc[group["channel"] == "online", "revenue"]
b = group.loc[group["channel"] == "store", "revenue"]
low, high = stats.ttest_ind(a, b, equal_var=False).confidence_interval()
year_cis[year] = (low, high)
print(f"{year}: diff {a.mean() - b.mean():+6.2f}, 95% CI {low:+.2f} to {high:+.2f}")
print(f"{len(per_customer):,} customers, {len(orders) / len(per_customer):.2f} orders "
f"each, {both:.1%} use both channels")
print("customer bootstrap 95% CI for the AOV gap: "
f"{cust_ci[0]:+.2f} to {cust_ci[1]:+.2f}")
Output
Mann-Whitney p 0.753, probability of superiority (ties count half) 0.498
geometric-mean ratio online/store 95% CI: 0.956 to 1.033
median diff -2.01, bootstrap 95% CI -8.00 to +2.04
2023: diff +7.79, 95% CI -12.63 to +28.20
2024: diff -3.26, 95% CI -19.13 to +12.61
3,254 customers, 4.57 orders each, 58.4% use both channels
customer bootstrap 95% CI for the AOV gap: -10.89 to +13.20

Every check tells the same story. The probability of superiority, the chance that a random online order is larger than a random store order with ties counted as half, is about 0.5. The geometric means differ by a few percent at most. The median difference is a couple of dollars, and its interval contains 0. Within each year, the interval contains 0 too. Most customers order several times and many use both channels, yet the customer bootstrap gives almost the same interval as Welch.

Step 3 — Chart 5, the distributions and the intervals. An ECDF (empirical cumulative distribution function) shows, for each order value, the share of orders at or below it. On a log axis, the skewed values spread out evenly.

sales_review.py (chart 5: order value by channel)
fig, (left, right) = plt.subplots(1, 2, figsize=(10, 4),
gridspec_kw={"width_ratios": [3, 2]})
for i, (name, values) in enumerate([("store", store), ("online", online)]):
x = np.sort(values)
left.step(x, np.arange(1, len(x) + 1) / len(x), where="post", color=f"C{i}",
label=f"{name} (n = {len(x):,})")
left.set_xscale("log")
left.xaxis.set_major_formatter(FuncFormatter(lambda v, pos: f"{v:,.0f}"))
left.set(xlabel="Order value (USD, log scale)", ylabel="Share of orders at or below")
left.legend(frameon=False, loc="upper left")
for year_i, (_, group) in enumerate(orders.groupby("year")):
for i, name in enumerate(["store", "online"]):
values = group.loc[group["channel"] == name, "revenue"]
low, high = stats.t.interval(0.95, len(values) - 1, loc=values.mean(),
scale=stats.sem(values))
x = year_i + (i - 0.5) * 0.25
right.errorbar(x, values.mean(), yerr=[[values.mean() - low],
[high - values.mean()]], fmt="o", color=f"C{i}", capsize=4)
right.set_xticks([0, 1], labels=["2023", "2024"])
right.set_xlim(-0.6, 1.6)
right.set_ylim(0, 300)
right.set(ylabel="AOV with 95% CI (USD)")
dots = [Line2D([], [], marker="o", linestyle="", color=f"C{i}") for i in range(2)]
right.legend(dots, ["store", "online"], frameon=False, loc="lower center")
fig.suptitle(f"Online and store orders are worth about the same: gap {diff:+.0f} USD "
f"(95% CI {ci.low:+.0f} to {ci.high:+.0f})")
paths.append(save(fig, "5_order_value_by_channel"))
plt.show()
Left: the cumulative distributions of order value for store and online orders lie on top of each other from about 12 USD to several thousand USD on a log axis. Right: the mean order value with 95% intervals for each channel in 2023 and 2024; all four intervals overlap around 240 USD.
Chart 5: order value by channel. Left, the ECDF; right, the AOV with 95% confidence intervals per year.

The two curves are almost one line: the channels sell the same baskets. The right panel starts at 0, so the small gaps look as small as they are.

Reference solution — Milestone 6: cross-check with DuckDB and Polars

Step 1 — The growth bridge in SQL. DuckDB reads the three CSV files directly and detects the date columns. The query repeats the four driver rules, in the same order, with a CASE expression and pivots the years with FILTER. Nothing is shared with the pandas code except the files. The sums are not rounded in SQL, so the comparison sees the real values. np.allclose has a relative tolerance by default, which on 1.6 million USD would allow about 16 USD of difference; rtol=0, atol=0.005 demands agreement to the cent.

sales_review.py (DuckDB growth bridge)
bridge_sql = """
WITH labeled AS (
SELECT s.revenue,
YEAR(s.order_date) AS year,
CASE WHEN p.launch_date >= DATE '2023-01-01' THEN 'new product'
WHEN st.opened >= DATE '2023-01-01' AND s.channel = 'store'
THEN 'new store'
WHEN s.channel = 'online' THEN 'like-for-like online'
ELSE 'like-for-like in-store' END AS driver
FROM 'data/sales.csv' AS s
JOIN 'data/products.csv' AS p USING (product_id)
JOIN 'data/stores.csv' AS st USING (store_id)
)
SELECT driver,
SUM(revenue) FILTER (WHERE year = 2023) AS rev_2023,
SUM(revenue) FILTER (WHERE year = 2024) AS rev_2024
FROM labeled
GROUP BY driver
ORDER BY driver
"""
sql_bridge = duckdb.sql(bridge_sql).df().set_index("driver")
print(sql_bridge.to_string(float_format="{:,.2f}".format))
pandas_bridge = lines.pivot_table(index="driver", columns="year", values="revenue",
aggfunc="sum")
assert np.allclose(sql_bridge[["rev_2023", "rev_2024"]].to_numpy(),
pandas_bridge.loc[sql_bridge.index, [2023, 2024]].to_numpy(),
rtol=0, atol=0.005)
Output
rev_2023 rev_2024
driver
like-for-like in-store 938,707.19 849,256.86
like-for-like online 592,310.36 744,043.19
new product 78,549.12 314,516.37
new store 36,022.92 43,117.82

Step 2 — Yearly revenue, orders and AOV with two engines. COUNT(DISTINCT order_id) counts orders, not lines, in SQL. In Polars, n_unique does the same. The lazy query runs only at collect().

sales_review.py (DuckDB and Polars yearly KPIs)
yearly_sql = duckdb.sql("""
SELECT YEAR(order_date) AS year,
SUM(revenue) AS revenue,
COUNT(DISTINCT order_id) AS orders,
SUM(revenue) / COUNT(DISTINCT order_id) AS aov
FROM 'data/sales.csv'
GROUP BY year
ORDER BY year
""").df().set_index("year")
yearly_pl = (
pl.scan_csv("data/sales.csv", try_parse_dates=True)
.group_by(pl.col("order_date").dt.year().alias("year"))
.agg(pl.col("revenue").sum(), pl.col("order_id").n_unique().alias("orders"))
.with_columns((pl.col("revenue") / pl.col("orders")).alias("aov"))
.sort("year")
.collect()
)
print(yearly_sql.to_string(float_format="{:,.2f}".format))
for engine in [yearly_sql, yearly_pl.to_pandas().set_index("year")]:
assert np.allclose(engine[["revenue", "aov"]].to_numpy(),
kpi[["revenue", "aov"]].to_numpy(), rtol=0, atol=0.005)
assert (engine["orders"].to_numpy() == kpi["orders"].to_numpy()).all()
print("pandas, DuckDB and Polars agree on revenue, orders and AOV")
Output
revenue orders aov
year
2023 1,645,589.59 6721 244.84
2024 1,950,934.24 8156 239.20
pandas, DuckDB and Polars agree on revenue, orders and AOV

Three engines, written three ways, agree within half a cent. If a filter, a join or a group key were wrong in one of them, an assert would stop the script before the memo.

Reference solution — Milestone 7: the findings memo

Step 1 — Build the findings from variables. Each finding is a tuple of claim, evidence and caveat. The f-strings take every number from the results above, even the counts, so a data change updates the memo. Write the caveat first: if you cannot name the limit of a finding, you do not understand it yet. Keep claims descriptive: the data shows what happened, not what would have happened without a launch or a promotion.

sales_review.py (findings)
lfl_store = drivers.loc["like-for-like in-store"]
lfl_online = drivers.loc["like-for-like online"]
new = drivers.loc["new product"]
bf = promo.loc[promo["event"] == "Black Friday", "uplift"]
n_above_max, n_in_band = promo["above_max"].sum(), (~promo["above_p95"]).sum()
pv = promo_vs_rest.loc["promo days"]
change = kpi.loc[2024] / kpi.loc[2023] - 1
total = ch.loc["total"]
saturday = weekday["Saturday"] / daily["revenue"].mean()
years_with_zero = sum(low < 0 < high for low, high in year_cis.values())
findings = [
("The warehouse table is consistent with the POS export: no value differs.",
f"All {len(audit)} documented quirks found with the documented counts; "
f"{len(clean):,} clean lines matched sales.csv with "
f"{reconciliation['differ'].sum()} differing values.",
f"The export holds {len(clean):,} of {len(lines):,} lines "
f"({len(clean) / len(lines):.1%}), so the check is a sample. "
f"{gaps['customer_id']} customer ids and {gaps['channel']} channels are "
"missing in the export."),
("Revenue grew because we sold more orders, not bigger ones.",
f"Revenue {kpi.loc[2023, 'revenue']:,.0f} -> {kpi.loc[2024, 'revenue']:,.0f} USD "
f"({growth:+.1%}). Orders effect {total['orders_effect']:+,.0f} USD, AOV effect "
f"{total['aov_effect']:+,.0f} USD (orders {change['orders']:+.1%}, "
f"AOV {change['aov']:+.1%}).",
f"Two years only. S12 opened on {stores['opened'].max():%Y-%m-%d}, so 2023 "
"holds only part of its year."),
(f"Most of the measured growth sits in the {len(new_products)} new products.",
f"They added {new[2024] - new[2023]:,.0f} USD, "
f"{new['share_of_growth']:.0%} of the growth.",
"Some of it may be sales taken from older products (cannibalization); how "
"much is extra demand, this split cannot say."),
("The existing range grew only online; in the existing stores its in-store "
"sales fell.",
f"Like-for-like in-store {lfl_store[2023]:,.0f} -> {lfl_store[2024]:,.0f} USD "
f"({lfl_store['growth']:+.1%}; orders {lfl_store_orders_change:+.1%}). "
f"Like-for-like online {lfl_online['growth']:+.1%}. Online share of revenue "
f"{kpi.loc[2023, 'online_rev_share']:.1%} -> "
f"{kpi.loc[2024, 'online_rev_share']:.1%}.",
"The data cannot show whether store customers moved online or were lost. "
"Stores fulfill online orders, so regional totals mix both channels."),
("Online orders are not larger, so order size does not justify a separate "
"online basket budget.",
f"AOV gap {diff:+.2f} USD, 95% CI {ci.low:+.2f} to {ci.high:+.2f}, "
f"p = {welch.pvalue:.2f}, Cohen's d = {cohens_d:.3f}; the CI is inside the "
f"+/-{bound:.0f} USD equivalence bound. The CI contains 0 in {years_with_zero} "
f"of {len(year_cis)} years; a customer bootstrap gives {cust_ci[0]:+.2f} to "
f"{cust_ci[1]:+.2f}.",
"Observational data: customers choose their channel, so this compares orders; "
"it does not show what moving a customer online would do."),
("Black Friday lifts orders far beyond everyday variation; "
f"{len(promo) - n_above_max} of {len(promo)} promotion days do not, and "
"promotion days cost gross margin.",
f"Black Friday orders {bf.min():.1f}x to {bf.max():.1f}x the baseline. "
f"{n_above_max} of {len(promo)} promotion days beat the largest ordinary-day "
f"uplift ({ordinary.max():.2f}x); {n_in_band} stays inside the 5th-95th "
f"percentile band. Promotion days earn {pv['revenue_share']:.1%} of revenue at "
f"a gross margin {-gross_margin_gap:.1f} pp below other days.",
f"The baseline is the median of the {WEEKS} same weekdays before. It lags the "
f"November ramp (ordinary Nov-Dec days already show {late.median():.2f}x), and "
"promotions may pull sales forward."),
("Plan stock and staff for November-December and for Saturdays.",
f"Nov-Dec bring {nov_dec[2023]:.1%} (2023) and {nov_dec[2024]:.1%} (2024) of "
f"yearly revenue; Saturday is {saturday:.2f}x the average day.",
"Two seasons are a small sample for a yearly pattern."),
]
recommendations = [
f"Stores: explain the {lfl_store['growth']:.1%} like-for-like in-store decline "
"(by store, category and customer) before splitting the budget.",
"Online: the AOV argument does not justify a separate basket budget; judge any "
"online spend on order volume, which is where online growth came from.",
"Products: keep a launch pipeline; measure cannibalization of older products.",
"Promotions: keep Black Friday; before repeating a smaller promotion, check that "
"its extra orders clear the noise band and outweigh the lost gross margin.",
]

Step 2 — Print and save the memo, then check everything.

sales_review.py (memo and final checks)
def wrap(text: str, indent: str) -> str:
return textwrap.fill(text, width=96, initial_indent=indent,
subsequent_indent=" " * len(indent))
memo = ["MEMO: 2023-2024 sales performance review", ""]
for number, (claim, evidence, caveat) in enumerate(findings, start=1):
memo += [wrap(claim, f"{number}. "), wrap(evidence, " Evidence: "),
wrap(caveat, " Caveat: ")]
memo += ["", "Recommendations:"] + [wrap(r, "- ") for r in recommendations]
memo_text = "\n".join(memo)
print(memo_text)
(OUT / "memo.txt").write_text(memo_text + "\n", encoding="utf-8")
assert round(kpi["revenue"].sum(), 2) == 3596523.83
assert kpi["orders"].sum() == len(orders) == 14_877
assert -bound < ci.low < 0 < ci.high < bound
assert new["share_of_growth"] > 0.5 and lfl_store["growth"] < 0
assert bf.min() > promo.loc[promo["event"] != "Black Friday", "uplift"].max()
assert all(p.exists() for p in paths) and (OUT / "memo.txt").exists()
print()
for name in sorted(p.name for p in OUT.iterdir()):
print("saved", OUT / name)
Output
MEMO: 2023-2024 sales performance review
1. The warehouse table is consistent with the POS export: no value differs.
Evidence: All 17 documented quirks found with the documented counts; 1,164 clean lines
matched sales.csv with 0 differing values.
Caveat: The export holds 1,164 of 20,228 lines (5.8%), so the check is a sample. 23
customer ids and 17 channels are missing in the export.
2. Revenue grew because we sold more orders, not bigger ones.
Evidence: Revenue 1,645,590 -> 1,950,934 USD (+18.6%). Orders effect +351,350 USD, AOV effect
-46,005 USD (orders +21.4%, AOV -2.3%).
Caveat: Two years only. S12 opened on 2023-06-15, so 2023 holds only part of its year.
3. Most of the measured growth sits in the 4 new products.
Evidence: They added 235,967 USD, 77% of the growth.
Caveat: Some of it may be sales taken from older products (cannibalization); how much is
extra demand, this split cannot say.
4. The existing range grew only online; in the existing stores its in-store sales fell.
Evidence: Like-for-like in-store 938,707 -> 849,257 USD (-9.5%; orders -5.2%). Like-for-like
online +25.6%. Online share of revenue 37.8% -> 46.0%.
Caveat: The data cannot show whether store customers moved online or were lost. Stores
fulfill online orders, so regional totals mix both channels.
5. Online orders are not larger, so order size does not justify a separate online basket budget.
Evidence: AOV gap +1.02 USD, 95% CI -11.45 to +13.48, p = 0.87, Cohen's d = 0.003; the CI is
inside the +/-24 USD equivalence bound. The CI contains 0 in 2 of 2 years; a
customer bootstrap gives -10.89 to +13.20.
Caveat: Observational data: customers choose their channel, so this compares orders; it
does not show what moving a customer online would do.
6. Black Friday lifts orders far beyond everyday variation; 6 of 12 promotion days do not, and
promotion days cost gross margin.
Evidence: Black Friday orders 4.0x to 4.1x the baseline. 6 of 12 promotion days beat the
largest ordinary-day uplift (2.14x); 1 stays inside the 5th-95th percentile band.
Promotion days earn 4.5% of revenue at a gross margin 4.7 pp below other days.
Caveat: The baseline is the median of the 4 same weekdays before. It lags the November ramp
(ordinary Nov-Dec days already show 1.16x), and promotions may pull sales forward.
7. Plan stock and staff for November-December and for Saturdays.
Evidence: Nov-Dec bring 26.5% (2023) and 29.3% (2024) of yearly revenue; Saturday is 1.29x
the average day.
Caveat: Two seasons are a small sample for a yearly pattern.
Recommendations:
- Stores: explain the -9.5% like-for-like in-store decline (by store, category and customer)
before splitting the budget.
- Online: the AOV argument does not justify a separate basket budget; judge any online spend on
order volume, which is where online growth came from.
- Products: keep a launch pipeline; measure cannibalization of older products.
- Promotions: keep Black Friday; before repeating a smaller promotion, check that its extra
orders clear the noise band and outweigh the lost gross margin.
saved output/review/1_growth_bridge.png
saved output/review/2_orders_aov_by_channel.png
saved output/review/3_weekday_month_heatmap.png
saved output/review/4_promo_uplift.png
saved output/review/5_order_value_by_channel.png
saved output/review/memo.txt

How it works:

  1. Trust first. The quirk audit and the reconciliation turn “the data looks fine” into 17 matching counts and 0 differing values. Only then does the review switch to the full warehouse table.
  2. Validated joins and rules. Each merge checks its key. The rules catch broken reference tables, impossible dates and a revenue column that does not follow its formula.
  3. The right unit. Lines answer category questions; orders answer AOV questions. The orders table is built once and reused by the KPIs, the test and the cross-checks.
  4. Decomposition beats a single growth rate. The channel-aware driver label and the orders and AOV effects explain the +18.6%. The channel table alone shows store revenue up 3.1%; the drivers show that the existing stores sold less of the existing range in store.
  5. A stated baseline and a noise band. Promotion uplift is relative to the same weekday before the promotion, which removes the weekly pattern. It does not remove the seasonal ramp or day-to-day noise, so the same measure on ordinary days shows which promotions stand out.
  6. A decision-ready test. The equivalence bound is fixed before the test. The confidence interval, not the p-value, answers the online team: any gap that is plausible is too small to matter.
  7. Independent recomputation. SQL and Polars recompute the headline numbers from the raw files. The asserts tie the memo to them.

Alternative: split the script into a small package (load.py, kpis.py, charts.py, memo.py) with pytest tests for clean_raw and growth_by, as in Capstone 1. For a one-off review, one script with clear sections is easier to read and to rerun.

  1. Margin bridge. Rebuild chart 1 for gross profit instead of revenue. Do the new products bring the same share of profit growth as of revenue growth?
  2. Cannibalization check. Compare 2024 revenue of the other products in the categories of P005 and P007 (Electronics and Home) with their 2023 revenue. Did they shrink after the launches?
  3. Promo pull-forward and a seasonal baseline. Compare the 7 days after each Black Friday weekend with their own same-weekday baseline; a dip suggests that the promotion moved sales instead of creating them. Then build a baseline that follows the season, for example the same weekday in the same week of the other year, scaled by the yearly growth, and see how much of the November uplift remains.
  4. Equivalence test. Run two one-sided tests (TOST) for the AOV gap with the ±10% equivalence bound, using stats.ttest_ind(..., alternative=...) on shifted data. Report both p-values.
  5. Polars end to end. Rewrite milestones 2 and 3 with the lazy Polars API and compare the run time with pandas.
  6. A dashboard page. Combine the five charts in one plt.subplot_mosaic figure for a one-page handout.