A reproducible Python analysis workflow: notebooks, scripts and tests
TL;DR
Difficulty: Intermediate
A report you cannot rerun is an opinion with a chart attached. Explore in notebooks, but put the monthly report into a few plain Python functions run by one command.
- Lock the libraries (uv.lock or pinned requirements), seed every random step with default_rng, and keep every business number in one configuration file.
- Freeze the inputs: keep each raw export untouched, named by its download date, with its SHA256 hash in a run log. Late refunds legitimately change last month's numbers, and the as at date explains why.
- A validation gate (plain checks and a pandera schema) stops the run on a broken export, and one pytest test pins each written business rule.
- Keep data and secrets out of git. Schedule the run once it stops itself on bad data.
A notebook that produced last month's report is not yet a report you can produce next month. This closing chapter of the foundations series turns an example shop's monthly channel report into a small Python project: one command, a lock file, a validation gate, six tests and a run log. Along the way it shows why the same month can rightly give different numbers, and how to prove which ones are which.
The question this chapter answers
You have a notebook that produced last month's channel report. It worked. Áine, the founder, read it, moved some budget, and asked for the same report next month. Now it is the third of November, the new exports are sitting in your downloads folder, and you open the notebook again. Which cells do you run? In what order? Was the test order filter the one in cell 14 or the one you deleted? Why does September's revenue no longer match the number in the email you sent?
This is the closing chapter of the foundations series, and it answers one question: how do you turn notebooks into an analysis that someone else can rerun next month and get the same answer? Everything in the eleven chapters before it (loading, cleaning, joining, grouping, time, charts, models) only pays off if it can be repeated without you standing next to it.
The example is the same invented shop as in every chapter: Ardmore Home in Sligo (ardmorehome.example), an online homeware shop with about 1,200 products, 48,000 orders a year from about 21,000 customers, an average order value of €66 and a gross margin of 52%. Áine is the founder. Darragh is the analyst. His standing question: "Which channel really pays back, and what should we do with next month's budget?" By the end of this chapter his monthly channel report is a small Python project with one command, a validation gate, six tests and a run log, and you will have built every file of it.
If you only read one section
For the person who commissions this, here is the whole chapter in five sentences.
- A report you cannot rerun is an opinion with a chart attached. Ask for the one command that rebuilds it.
- Most "the numbers changed" moments are not bugs in the code. The data under the code changed: refunds arrived, an export was restated, a channel was renamed. So every number in the report should carry the date its data was downloaded, and the raw file should be kept unchanged.
- Notebooks are where the analysis is discovered. The monthly report itself belongs in plain Python files that run from top to bottom with no hidden state.
- Before any number reaches you, a set of written checks should be able to stop the run. A report that refuses to run on a broken export is worth more than one that always produces something.
- The time saved is real (in the illustrative example below, from about two and a half hours a month to about half an hour), but the bigger gain is trust: the number in March means the same thing as the number in November.
If you want the reasoning, read on. If you want the code, every block below runs, in order, on data the first block generates.
The rerun test: three kinds of "the same answer"
"Reproducible" sounds like one property. In a business report it is three, and they fail for different reasons. I find it useful to name them, because each one has its own fix.
| Rerun | What should happen | What usually breaks it | The fix in this chapter |
|---|---|---|---|
| Same data, same code, another person or machine | Identical numbers, to the penny | Hidden notebook state, unpinned library versions, unseeded randomness | Scripts, a lock file, seeds |
| Same code, next month's data | Correct numbers, or a loud stop | The export changed shape, a filter no longer matches, a time zone edge | Validation checks and tests |
| Same month, a later export | Different numbers, and a record of why | Refunds and restated data arriving after the month closed | Raw snapshots, an as at date, a run log |
The third row is the one tutorials skip, and it is the one that costs trust. A September report produced on 3 October and a September report produced on 3 December should not match, because two months of refunds have arrived in between. What must match is the explanation: same code, different input, here is the input's fingerprint and the day it was downloaded.
Example: Ardmore's October report, run twice. The tables later in this chapter come from the code you will write. Here is the punchline first. Darragh runs the October channel report on 3 November with the export downloaded that morning. Paid social returns €2.34 of gross margin for every euro spent, paid search €2.32. Paid social looks slightly better. He reruns exactly the same code on 3 December with a fresh export of the same October orders. Now paid social returns €2.18 and paid search €2.26. The ranking has flipped. Nothing in the code changed. Paid social's refunds for October orders went from €1,384.97 to €4,030.24 as late returns came in. In this invented example, customers who arrive from social ads send more of their orders back.
If Darragh had only the notebook, he would have two contradictory numbers and no way to show why. With the setup in this chapter he has two report folders, each with the fingerprint of its input file and its as at date, and a sentence for Áine: "October is provisional until early December, because refunds keep arriving. Here is the final view."
Why notebooks drift: hidden state and order
A Jupyter notebook keeps every variable you create in memory until the kernel restarts. You can run cells in any order, run one cell five times, edit a cell and not rerun the cells below it, or delete a cell whose result is still in memory. Each of these leaves the notebook showing code that no longer produces the numbers on screen. Researchers call this hidden state.
It is not a rare problem. Pimentel and colleagues collected more than 1.1 million notebooks from GitHub and tried to execute the 863,878 that had a clear execution order. Only 24.11% ran without errors, and only 4.03% produced the same results as the ones saved in the file1. Of the notebooks whose execution order could be read unambiguously, 36.36% had cells that had been run out of order. Fewer than 2% imported any testing module, and only 13.72% declared their dependencies in a file such as requirements.txt. Their recommendations read like the outline of this chapter: move code into functions and modules and test them, declare dependencies and pin their versions, and check them in a clean environment.
Those were mostly research and teaching notebooks, not business reports. That makes the result more worrying, not less: a business notebook is rerun by a different person, on different data, with money attached.
Example: the deleted filter. Darragh's notebook has a cell that removes test orders, which come from the shop's own domain.
import pandas as pd
orders = pd.DataFrame({
"order_id": ["A1", "A2", "A3"],
"email": ["a@mail.example", "darragh+test@ardmorehome.example", "b@mail.example"],
"amount": [40.0, 10.0, 60.0],
})
# Cell 14: remove test orders
orders = orders[~orders["email"].str.endswith("@ardmorehome.example")]
print(orders["amount"].sum()) # 100.0
Later he tidies up and deletes cell 14, because the filter "has been done". The orders variable in memory is still filtered, so every cell below still shows €100. The notebook on disk no longer contains the filter. The next person who opens it, or Darragh after a kernel restart, gets €110 and a different report, with nothing on screen to explain the difference. The fix is not more care. The fix is a format that cannot hold hidden state: a script that always runs from the first line to the last, in a fresh process.
Notebooks to explore, scripts to report
I do not tell anyone to stop using notebooks. They are the best tool there is for the exploring part of analysis: looking at a column, trying a chart, checking a hunch. The rule is about where things live once they matter.
- Exploration lives in notebooks, in a
notebooks/folder, numbered and dated. They may be messy. - Anything the report depends on lives in plain Python files in a package (a folder of
.pyfiles Python can import). Functions take data in and return data out. Nothing reads a variable that was created somewhere else. - The notebook imports those functions instead of copying them. When the exploration finds a new rule, the rule moves into the package, with a test.
McKinney makes a related point in the appendix on IPython in Python for Data Analysis: Python imports a module once per session, so edits to a module do not reach a running notebook until you reload it, and he favours flat code and a few cohesive modules over many tiny files2. Both observations shape the layout below. In a notebook, IPython's autoreload extension saves you from restarting after every edit to the package3.
# First cell of an exploration notebook: pick up edits to the package automatically
%load_ext autoreload
%autoreload 2
from ardmore_report import pipeline
The % lines are notebook commands, not Python, so they belong only in a notebook. Everything else in this chapter is plain Python.
Example: Ardmore's project folder. This is the whole monthly report project. It follows the layout that Wilson and colleagues recommend for research projects (raw data in its own folder, code in src, generated results apart from both, documents next to the code)4, adapted to a monthly business report.
ardmore-report/
pyproject.toml what the project needs (names and version ranges)
uv.lock the exact versions that were installed (generated)
.python-version which Python to use
.gitignore what must never be committed
README.md how to run it, in five lines
ASSUMPTIONS.md every business rule, in words, with a date
config/
report.toml every number a person might change
src/
ardmore_report/
__init__.py
pipeline.py load, clean, summarise
checks.py the validation gate
__main__.py the one command
tests/
test_pipeline.py one test per business rule
notebooks/
2025-10-explore-refunds.ipynb
data/ never committed
raw/2025-10/
orders_asat_2025-11-03.csv
orders_asat_2025-12-03.csv
spend_2025-10.csv
reports/ never committed, rebuilt from data and code
2025-10/asat_2025-11-03/
channel_report.csv
audit_sample.csv
run_log.json
Three choices are deliberate. The raw files are named by the date they were downloaded (orders_asat_2025-11-03.csv), so two exports of the same month can live side by side. The reports folder mirrors that, so every report knows which input made it. And there are only three Python files in the package, because a monthly report does not need a framework.
Environments and lock files: the same libraries next month
Your code is only half of what runs. The other half is pandas, NumPy and the rest, and they change. On the date of this chapter (5 November 2025) the current releases are Python 3.14 (released 7 October 2025)5, pandas 2.3.3, NumPy 2.3.4, pandera 0.26.1 and pytest 8.4.2. The pandas team has also announced that pandas 3.0 will switch on a dedicated string type by default and make copy on write the only behaviour6. Both changes are improvements, and both can change what existing code does. If your report installs "the latest pandas" every month, one morning it will install 3.0, and a report that ran yesterday may behave differently today without a single line of yours changing.
The answer is two files. A short one says what the project needs, in ranges a person chose. A long one, generated by a tool, records the exact version of every package that was actually installed, including the packages your packages depend on. That second file is called a lock file.
There are three common ways to do this, as of this chapter's date:
| Tool | What you write | What gets locked | When I would use it |
|---|---|---|---|
| pip and venv (built into Python) | requirements.in or a short list | pip freeze > requirements.txt, exact pins, no hashes by default | The smallest setup, already on every machine |
| uv | pyproject.toml | uv.lock, exact versions and hashes for every platform | My default for new projects: fast, one tool for Python versions, environments and locks |
| conda (or mamba) | environment.yml | conda env export, or conda lock as a separate tool | When you need non Python libraries that conda packages well |
Example: locking Ardmore's environment with uv. Chapter one of this series set up Python and a virtual environment (why Python for data analysis, and how to set it up). Here the project gets its declaration of needs. The version ranges allow bug fix releases but no new feature release, and certainly no pandas 3.0 until Darragh has tested it.
# pyproject.toml
[project]
name = "ardmore-report"
version = "0.1.0"
description = "Monthly channel report for Ardmore Home"
requires-python = ">=3.13"
dependencies = [
"numpy>=2.3,<2.4",
"pandas>=2.3,<2.4",
"pandera>=0.26,<0.27",
]
[dependency-groups]
dev = ["pytest>=8.4,<9", "jupyterlab>=4.4"]
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[tool.pytest.ini_options]
testpaths = ["tests"]
Then three commands create the lock file, install from it and check that it is current:
uv python pin 3.13 # writes .python-version
uv lock # resolves every package and writes uv.lock
uv sync --locked # installs exactly what uv.lock says, fails if it is out of date
uv run also locks and syncs before it runs anything, so uv run pytest on a new laptop builds the same environment first7. The --locked flag is the one to use on a scheduled run: if somebody changed pyproject.toml without updating the lock file, the run stops instead of quietly installing something new. If a colleague insists on pip, uv export --format requirements.txt writes the same pins in the older format.
I pinned Python 3.13 rather than 3.14 here. That is not a judgement on 3.14. It is a rule: a new Python version is its own change, made on purpose, with the tests run, not something the monthly report picks up by accident.
Seeds: randomness you can repeat
A monthly report rarely needs randomness, but it often contains some: a sample of orders for a manual check, a bootstrap interval, a train and test split for a model. Random numbers on a computer come from a generator that starts from a seed. Same seed, same numbers. No seed, new numbers every run, and therefore a report that cannot be reproduced. Sandve and colleagues list this as one of ten rules for reproducible computational work: note the seeds of any analysis that includes randomness8.
NumPy's current advice is to create a Generator with np.random.default_rng(seed) and pass it to whatever needs randomness, instead of setting the old global np.random.seed9. McKinney's NumPy chapter works the same way and points out that such a generator is isolated from other code that uses numpy.random10. Many older tutorials still set the global seed. That seed is shared by every piece of code in the process, so one library drawing a random number changes every draw after it. A generator you pass around is local and explicit. Chapter three covered how NumPy works (NumPy explained). Here is the habit.
Example: a fixed audit sample. Each month Darragh picks 20 October orders and checks them by hand against the shop's admin screen, as a sanity check on the export. With a seeded generator the same 20 orders come out on every rerun, so a second person can repeat his check, no bother.
import numpy as np
import pandas as pd
# The data generator for this whole chapter: Ardmore's order export
rng = np.random.default_rng(seed=1105)
# About 131 orders a day (48,000 a year), 31 August to 2 November 2025, in UTC
days = pd.date_range("2025-08-31", "2025-11-02", freq="D", tz="UTC")
n_per_day = rng.poisson(131, size=len(days))
n = int(n_per_day.sum())
seconds = rng.integers(0, 24 * 3600, size=n)
created = (pd.to_datetime(np.repeat(days.values, n_per_day), utc=True)
+ pd.to_timedelta(seconds, unit="s"))
channels = ["organic_search", "paid_search", "paid_social", "email", "direct", "referral"]
channel = rng.choice(channels, size=n, p=[0.30, 0.24, 0.16, 0.12, 0.13, 0.05])
# Order values: right skewed, about €66 on average
value = np.round(rng.lognormal(mean=np.log(59.17), sigma=0.45, size=n), 2)
orders = pd.DataFrame({
"order_id": [f"AH{100000 + i}" for i in range(n)],
"created_at": created,
"customer_id": rng.integers(1, 21_000, size=n),
"email": [f"customer{c}@mail.example" for c in rng.integers(1, 21_000, size=n)],
"channel": channel,
"amount": value,
"currency": "EUR",
"row_type": "order",
}).sort_values("created_at", ignore_index=True)
print(n) # 8470
The audit sample itself is two lines. The second run gives the same orders as the first:
october = orders[orders["created_at"].dt.strftime("%Y-%m") == "2025-10"]
first = october.sample(n=20, random_state=np.random.default_rng(2025))["order_id"]
again = october.sample(n=20, random_state=np.random.default_rng(2025))["order_id"]
print(first.equals(again)) # True
(Here the month is taken in UTC to keep the demonstration short. The real pipeline below takes it in Irish time, for a reason you will see.)
Freeze the inputs, not just the code
A lock file freezes the libraries. Nothing in Python freezes the data. The shop's order export is not a document, it is a query: download it today and again in a month, and the rows for the same orders differ, because refunds are separate rows that arrive later, orders get cancelled, and sometimes a platform restates history. Wilson and colleagues put it simply: save raw data as it was originally generated, and treat it as read only4. For a business report I add two things: the download date in the file name, and a fingerprint of the file in the run log.
A fingerprint here is a SHA256 hash: a 64 character code computed from every byte of the file. Change one character in the file and the hash changes completely. If the hash in December's run log matches the file on disk, you know the report was built from exactly that file.
Example: finishing the export and taking two snapshots. The generator continues with the three traps of a real shop export (test orders, staff orders, refunds as separate rows) and writes the file the shop would have produced on 3 November and on 3 December. Refund rates differ by channel, and in this example paid social customers return the most.
from pathlib import Path
# Trap 1: test orders placed from the shop's own domain
test_idx = rng.choice(n, size=9, replace=False)
orders.loc[test_idx, "email"] = "darragh+test@ardmorehome.example"
# Trap 2: staff orders with the staff discount code
orders["discount_code"] = ""
orders.loc[rng.choice(n, size=24, replace=False), "discount_code"] = "STAFF30"
# Trap 3: refunds are separate rows, 2 to 40 days after the order
refund_rate = orders["channel"].map({
"organic_search": 0.040, "paid_search": 0.045, "paid_social": 0.085,
"email": 0.025, "direct": 0.035, "referral": 0.040,
})
refunds = orders[rng.random(n) < refund_rate].copy()
refunds["created_at"] += pd.to_timedelta(rng.integers(2, 41, size=len(refunds)), unit="D")
refunds["amount"] = -refunds["amount"]
refunds["row_type"] = "refund"
all_rows = pd.concat([orders, refunds], ignore_index=True)
def export_as_at(as_at: str) -> pd.DataFrame:
"""What the shop export returns when downloaded on a given day."""
rows = all_rows[all_rows["created_at"] < pd.Timestamp(as_at, tz="UTC")].copy()
rows["created_at"] = rows["created_at"].dt.strftime("%Y-%m-%dT%H:%M:%SZ")
return rows.sort_values(["created_at", "order_id"], ignore_index=True)
raw = Path("data/raw/2025-10")
raw.mkdir(parents=True, exist_ok=True)
export_as_at("2025-11-03").to_csv(raw / "orders_asat_2025-11-03.csv", index=False)
export_as_at("2025-12-03").to_csv(raw / "orders_asat_2025-12-03.csv", index=False)
pd.DataFrame({"channel": ["paid_search", "paid_social", "email"],
"spend": [14_110.00, 8_990.00, 400.00]}
).to_csv(raw / "spend_2025-10.csv", index=False)
The spend file stands in for the Google Ads and Meta exports and the newsletter tool's fee, already reduced to one row per channel (loading business data into pandas shows how to get there from the real files, header blocks and totals rows included).
Then a three line function gives the fingerprint:
import hashlib
def file_sha256(path) -> str:
"""Fingerprint of the raw export, so we can prove which file was used."""
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
print(file_sha256(raw / "orders_asat_2025-11-03.csv")[:16]) # 19aaff992ef96313
The 3 November file has 8,741 rows (8,470 orders and 271 refunds). The 3 December file has the same orders and more refunds. Both stay on disk, untouched, for as long as the reports built from them matter.
Configuration: every number a person might change, in one file
Somewhere in every notebook there is a line like margin = 0.52 and, forty cells later, another one like df[df.code != "STAFF30"]. Those are business rules disguised as code. When the margin changes or a second staff code appears, someone has to find every place they occur.
The fix is a configuration file: a plain text file that holds every value a non programmer might reasonably change, separate from the code that uses them. Python has read TOML files (a simple, readable configuration format) with the built in tomllib module since Python 3.1111. Secrets are the exception. API keys and database passwords never go in the configuration file, because the configuration file is committed to version control. They live in environment variables, or in a .env file that is never committed.
Example: Ardmore's configuration.
# config/report.toml: every number a person might change lives here
[report]
timezone = "Europe/Dublin"
gross_margin = 0.52
audit_sample_size = 20
audit_seed = 2025
[exclusions]
test_domain = "ardmorehome.example"
staff_codes = ["STAFF30"]
[checks]
max_order_change = 0.30 # stop if orders move more than 30% month on month
Reading it takes three lines:
import tomllib
with open("config/report.toml", "rb") as f: # tomllib needs the file in binary mode
cfg = tomllib.load(f)
print(cfg["report"]["gross_margin"]) # 0.52
When Áine's accountant revises the margin to 51%, Darragh changes one line, commits it with a message that says why, and every later report uses the new figure. The old reports keep the old one, and the history shows exactly when it changed.
The pipeline as plain functions
Now the heart of the project. A pipeline here simply means a fixed sequence of steps: load, clean, validate, compute, write. Each step is a function that takes data in and returns data out. No function reads a global variable, prints a number someone has to copy, or depends on having been run after another cell. That is what makes the steps testable one by one.
Three rules from earlier chapters become code here:
- Read with explicit types rather than letting pandas guess (pandas Series and DataFrames explains types, cleaning data in pandas the test and staff orders).
- Take the month in the shop's own time zone, not in UTC (time series in pandas).
- Count refunds against the month of the original order, so a channel is charged for the returns its own customers made (group by and pivot tables in pandas).
Example: pipeline.py. Save this block as src/ardmore_report/pipeline.py. In a notebook you can also run it as it is, and it simply defines the functions.
# src/ardmore_report/pipeline.py
# Load, clean and summarise the shop's order export. Pure functions:
# data in, data out, no hidden state, nothing read from the notebook.
import hashlib
from pathlib import Path
import pandas as pd
def file_sha256(path: Path) -> str:
"""Fingerprint of the raw export, so we can prove which file was used."""
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def load_orders(path: Path) -> pd.DataFrame:
"""Read the export with explicit types instead of letting pandas guess."""
df = pd.read_csv(
path,
dtype={"order_id": "string", "email": "string", "channel": "string",
"currency": "string", "row_type": "string",
"discount_code": "string"},
keep_default_na=False,
)
df["created_at"] = pd.to_datetime(df["created_at"], utc=True, format="ISO8601")
return df
def clean_orders(df: pd.DataFrame, test_domain: str, staff_codes: list[str]) -> pd.DataFrame:
"""Drop test and staff orders, together with their refunds."""
is_test = df["email"].str.endswith("@" + test_domain)
is_staff = df["discount_code"].isin(staff_codes)
excluded = set(df.loc[is_test | is_staff, "order_id"])
return df[~df["order_id"].isin(excluded)].reset_index(drop=True)
def add_local_month(df: pd.DataFrame, tz: str) -> pd.DataFrame:
"""The month an order belongs to, in the shop's own time zone."""
out = df.copy()
out["month"] = out["created_at"].dt.tz_convert(tz).dt.strftime("%Y-%m")
return out
def channel_report(df: pd.DataFrame, spend: pd.DataFrame, month: str,
gross_margin: float) -> pd.DataFrame:
"""Orders, net revenue and margin payback per channel for one month.
Refunds count against the month of the ORIGINAL order (cohort view),
so a month's figures can still fall while late refunds arrive.
"""
orders = df[(df["row_type"] == "order") & (df["month"] == month)]
refunds = df[(df["row_type"] == "refund") & df["order_id"].isin(orders["order_id"])]
report = (
orders.groupby("channel")
.agg(orders=("order_id", "nunique"), gross_revenue=("amount", "sum"))
.join(refunds.groupby("channel").agg(refunds=("amount", "sum")))
.fillna({"refunds": 0.0})
)
report["net_revenue"] = report["gross_revenue"] + report["refunds"]
report["avg_order_value"] = report["gross_revenue"] / report["orders"]
report = report.join(spend.set_index("channel"))
report["margin_payback"] = report["net_revenue"] * gross_margin / report["spend"]
return report.sort_index().round(2)
clean_orders removes a staff order and its refund together, by order number, because removing only the order row would leave an orphan refund that quietly reduces revenue. On the 3 November export it removes 33 rows (9 test orders and 24 staff orders, none of which had a refund yet), leaving 8,708.
The time zone trap at the month boundary
The shop export stores times in UTC. Ardmore's month is an Irish month. On 1 October 2025 Ireland was on summer time (legally Irish Standard Time), one hour ahead of UTC, so an order placed at 00:30 on 1 October in Sligo is stored as 23:30 on 30 September. Clocks went back on 26 October, so at the end of the month UTC and Irish time agree again.
Example: counting October two ways. Taking the month in UTC gives 4,039 October orders. Taking it in Irish time, as add_local_month does, gives 4,044. Five orders sounds trivial, and in money it is. In trust it is not: the shop's admin screen shows Irish time, so a UTC report never matches the number Áine sees when she logs in, and every mismatch invites the question "which of these numbers is wrong?" The test further down pins this rule so nobody "simplifies" it away.
The metric: margin payback
The report's key number is the gross margin a channel returns for each euro spent on it. It answers Áine's question in her own terms: above 1, the channel pays for itself before overheads. It is a ratio of two amounts (Foundations: ratios and rates):
where is the margin payback of channel , is the channel's net revenue for the month (orders minus the refunds of those orders), is the gross margin (0.52) and is the channel's spend for the month.
Worked through for paid social as at 3 November, with net revenue of €40,372.25 and spend of €8,990:
So : every euro spent on social ads brought back €2.34 of gross margin, as far as anyone knew on 3 November. As at 3 December the net revenue for the same orders is €37,726.98, and the same formula gives 2.18. The email figure of about 37 looks spectacular, and it is not comparable: Ardmore's "spend" on email is only the tool's monthly fee, not the time it takes to write the newsletter. Write that in the assumptions file, or someone will move the ad budget to email.
Validation: a gate the data must pass
Code can be perfect and the report still wrong, because the data changed. Ad platforms rename channels, exports add columns, a download stops halfway. Tests (next section) check that the code does what you meant. Validation checks that this month's data is what the code expects. It runs on every run, on the real data, and it stops the run when something is off.
There are three levels, and you should use them in this order:
- Plain checks in Python. A line that raises an error with a clear message. One warning: do not use
assertfor checks that must always run. Python removesassertstatements entirely when it runs with optimisation switched on (python -O)12.assertis fine in a notebook and in tests. In the pipeline, raise an error. - A schema library. pandera lets you declare, once, what each column must look like (type, allowed values, ranges, uniqueness) and validates a DataFrame against it, reporting every failure at once instead of stopping at the first13. Since version 0.24 the recommended import for pandas is
pandera.pandas, and that is what the code below uses. - A data quality platform. Great Expectations does the same job at a larger scale, with stored expectations, data documentation and many data sources14. It earns its setup cost when several teams share many sources. For one shop's monthly report it is more machinery than the problem needs.
Example: Ardmore's validation gate. Save as src/ardmore_report/checks.py.
# src/ardmore_report/checks.py
# The gate between cleaning and reporting: if a check fails, no report.
import pandas as pd
import pandera.pandas as pa
CHANNELS = ["organic_search", "paid_search", "paid_social", "email", "direct", "referral"]
orders_schema = pa.DataFrameSchema(
{
"order_id": pa.Column("string"),
"created_at": pa.Column("datetime64[ns, UTC]"),
"channel": pa.Column("string", pa.Check.isin(CHANNELS)),
"amount": pa.Column(float, pa.Check(lambda s: s != 0, error="amount is zero")),
"currency": pa.Column("string", pa.Check.eq("EUR")),
"row_type": pa.Column("string", pa.Check.isin(["order", "refund"])),
},
checks=[
# An order is positive, a refund is negative
pa.Check(lambda d: (d["amount"] > 0) == (d["row_type"] == "order"),
error="sign of amount does not match row_type"),
# Each order appears once as an order row
pa.Check(lambda d: ~d.loc[d["row_type"] == "order", "order_id"].duplicated().any(),
error="duplicate order rows"),
],
strict=False, # extra columns in the export are allowed
)
def check_volume(this_month: int, last_month: int, max_change: float) -> None:
"""Stop if the number of orders moved more than we believe is possible."""
change = (this_month - last_month) / last_month
if abs(change) > max_change:
# raise, not assert: "python -O" silently skips assert statements
raise ValueError(
f"Order count changed by {change:.0%} against last month "
f"({last_month} to {this_month}). Check the export before reporting."
)
The volume check catches the failure no schema can see: a file that is perfectly shaped and half empty, because the download timed out. It compares this month's order count with last month's as a percentage change (Foundations: percentages):
where is the relative change, is the number of orders this month and the number last month. The run stops when is above the limit in the configuration file, 0.30.
For October, with 4,044 orders against 3,983 in September:
With , a rise of 1.5%, October passes. Thirty per cent is a business judgement, not a statistical one: Ardmore's busiest month, December, is well within that of November, and a genuine move bigger than that is something Darragh wants to look at before he reports it anyway.
Example: the gate catching a renamed channel. Suppose next month the ad platform's naming changes and paid social arrives as "meta", and a glitch duplicates one order row. The schema reports both problems at once:
import pandera.pandas as pa
clean = add_local_month(clean_orders(load_orders(raw / "orders_asat_2025-11-03.csv"),
"ardmorehome.example", ["STAFF30"]), "Europe/Dublin")
bad = clean.copy()
bad["channel"] = bad["channel"].replace({"paid_social": "meta"})
bad = pd.concat([bad, bad.iloc[[100]]], ignore_index=True)
try:
orders_schema.validate(bad, lazy=True) # lazy: collect every failure, not just the first
except pa.errors.SchemaErrors as e:
print(e.failure_cases.groupby("check", dropna=False).size())
# duplicate order rows 1
# isin(['organic_search', 'paid_search', 'paid_social', 'email', ...]) 1389
Without the gate, those 1,389 rows would have dropped out of the group by silently, and paid social would have shown as a channel with spend and no revenue. Áine would have cut it. The rule I give everyone: when a check fails, fix the export or fix the rule, never the number.
Tests: pin every business rule with pytest
Validation checks the data. Tests check the code. A test is a small function that runs a piece of your code on a tiny, hand made input whose right answer you know, and fails if the answer differs. pytest is the standard tool for this in Python: any function whose name starts with test_ in a file whose name starts with test_ is found and run. The test driven development in Django chapter of the testing series covers pytest in depth for web applications. Data functions are easier to test than web pages, because they are pure: same input, same output.
The best tests for a report are not about Python. Each one pins a business rule that someone could plausibly break while "tidying up". Write the rule in the test's name, so a failing test reads like a sentence.
Example: Ardmore's tests. Save as tests/test_pipeline.py. parametrize runs one test with several inputs15, which suits time zone edges perfectly.
# tests/test_pipeline.py
# Each test pins one business rule the report depends on.
import pandas as pd
import pytest
from ardmore_report import checks, pipeline
def make_rows(rows):
"""Small hand made export: (order_id, created_at UTC, channel, amount, row_type, email, code)."""
df = pd.DataFrame(rows, columns=["order_id", "created_at", "channel", "amount",
"row_type", "email", "discount_code"])
df["created_at"] = pd.to_datetime(df["created_at"], utc=True)
df["currency"] = "EUR"
return df.astype({c: "string" for c in ["order_id", "channel", "row_type",
"email", "discount_code", "currency"]})
@pytest.mark.parametrize("utc_time, expected_month", [
("2025-09-30 23:30", "2025-10"), # 00:30 on 1 October in Ireland (summer time)
("2025-10-31 23:30", "2025-10"), # still October: clocks went back on 26 October
("2025-11-01 00:30", "2025-11"),
])
def test_month_is_taken_from_irish_time(utc_time, expected_month):
df = make_rows([("A1", utc_time, "email", 40.0, "order", "a@mail.example", "")])
assert pipeline.add_local_month(df, "Europe/Dublin")["month"].iloc[0] == expected_month
def test_test_and_staff_orders_are_removed_with_their_refunds():
df = make_rows([
("A1", "2025-10-02 10:00", "email", 40.0, "order", "a@mail.example", ""),
("T1", "2025-10-02 11:00", "direct", 10.0, "order", "darragh+test@ardmorehome.example", ""),
("S1", "2025-10-03 09:00", "direct", 30.0, "order", "b@mail.example", "STAFF30"),
("S1", "2025-10-09 09:00", "direct", -30.0, "refund", "b@mail.example", "STAFF30"),
])
clean = pipeline.clean_orders(df, "ardmorehome.example", ["STAFF30"])
assert list(clean["order_id"]) == ["A1"]
def test_refund_counts_against_the_month_of_the_original_order():
df = make_rows([
("A1", "2025-10-20 10:00", "paid_social", 100.0, "order", "a@mail.example", ""),
("A1", "2025-11-04 10:00", "paid_social", -100.0, "refund", "a@mail.example", ""),
("A2", "2025-10-21 10:00", "paid_social", 60.0, "order", "b@mail.example", ""),
])
df = pipeline.add_local_month(df, "Europe/Dublin")
spend = pd.DataFrame({"channel": ["paid_social"], "spend": [52.0]})
report = pipeline.channel_report(df, spend, "2025-10", gross_margin=0.52)
row = report.loc["paid_social"]
assert row["orders"] == 2
assert row["net_revenue"] == pytest.approx(60.0)
assert row["margin_payback"] == pytest.approx(60.0 * 0.52 / 52.0)
def test_volume_check_stops_a_half_empty_export():
with pytest.raises(ValueError, match="changed by"):
checks.check_volume(this_month=1_900, last_month=4_000, max_change=0.30)
Run them from the project folder:
uv run pytest -q
# ...... [100%]
# 6 passed in 1.18s
Six tests, because the first one runs three times. Notice what the tests do not do: they do not read the real export. Tests on tiny hand made data run in a second, never contain customer data, and fail for exactly one reason. pytest.approx compares money amounts with a small tolerance, because floating point sums of pennies are rarely exact to the last bit.
A fair question is how many tests a report needs. My rule of thumb: one test for every sentence in the assumptions file. If a rule matters enough to write down, it matters enough to pin.
The main script: one command
Now the pieces come together in the file that runs them. __main__.py lets the package run with python -m ardmore_report. It reads the configuration, runs the steps in order, refuses to write anything if validation fails, and writes three files: the report, the audit sample and a run log that says exactly how the report was made. Sandve's first rule is "for every result, keep track of how it was produced"8. The run log is that rule as a file.
Example: src/ardmore_report/__main__.py.
# src/ardmore_report/__main__.py
# The monthly channel report in one command:
# uv run python -m ardmore_report --month 2025-10 --as-at 2025-11-03
# Without arguments it reports last month, from an export downloaded today.
import argparse
import json
import platform
import tomllib
from datetime import datetime, timezone
from pathlib import Path
import numpy as np
import pandas as pd
from ardmore_report import checks, pipeline
def main() -> None:
parser = argparse.ArgumentParser(description="Ardmore Home monthly channel report")
parser.add_argument("--month", help="report month, e.g. 2025-10 (default: last month)")
parser.add_argument("--as-at", help="date the export was downloaded (default: today)")
parser.add_argument("--config", default="config/report.toml")
args = parser.parse_args()
with open(args.config, "rb") as f:
cfg = tomllib.load(f)
today = pd.Timestamp.now(tz=cfg["report"]["timezone"])
args.month = args.month or (today.to_period("M") - 1).strftime("%Y-%m")
args.as_at = args.as_at or today.strftime("%Y-%m-%d")
raw_dir = Path("data/raw") / args.month
orders_file = raw_dir / f"orders_asat_{args.as_at}.csv"
out_dir = Path("reports") / args.month / f"asat_{args.as_at}"
# 1. Load: the raw file is read, never edited
raw = pipeline.load_orders(orders_file)
spend = pd.read_csv(raw_dir / f"spend_{args.month}.csv")
# 2. Clean
clean = pipeline.clean_orders(raw, cfg["exclusions"]["test_domain"],
cfg["exclusions"]["staff_codes"])
clean = pipeline.add_local_month(clean, cfg["report"]["timezone"])
# 3. Validate: stop here if anything is off
checks.orders_schema.validate(clean, lazy=True)
is_order = clean["row_type"] == "order"
this_month = (is_order & (clean["month"] == args.month)).sum()
prev = (pd.Period(args.month, freq="M") - 1).strftime("%Y-%m")
last_month = (is_order & (clean["month"] == prev)).sum()
checks.check_volume(int(this_month), int(last_month),
cfg["checks"]["max_order_change"])
# 4. Compute
report = pipeline.channel_report(clean, spend, args.month,
cfg["report"]["gross_margin"])
# 5. A fixed audit sample: the same 20 orders on every rerun
rng = np.random.default_rng(cfg["report"]["audit_seed"])
audit = (clean[is_order & (clean["month"] == args.month)]
.sample(n=cfg["report"]["audit_sample_size"], random_state=rng)
.sort_values("order_id"))
# 6. Write the outputs and a run log that says how they were made
out_dir.mkdir(parents=True, exist_ok=True)
report.to_csv(out_dir / "channel_report.csv")
audit[["order_id", "created_at", "channel", "amount"]].to_csv(
out_dir / "audit_sample.csv", index=False)
run_log = {
"month": args.month,
"as_at": args.as_at,
"input_file": str(orders_file),
"input_sha256": pipeline.file_sha256(orders_file),
"rows_raw": len(raw),
"rows_clean": len(clean),
"python": platform.python_version(),
"pandas": pd.__version__,
"numpy": np.__version__,
"run_at_utc": datetime.now(timezone.utc).isoformat(timespec="seconds"),
}
(out_dir / "run_log.json").write_text(json.dumps(run_log, indent=2))
print(report[["orders", "net_revenue", "spend", "margin_payback"]])
if __name__ == "__main__":
main()
The output directory is created only after every check has passed, so a failed run leaves no half finished report behind that someone might send by mistake.
Example: running October, twice. On 3 November:
uv run python -m ardmore_report --month 2025-10 --as-at 2025-11-03
# orders net_revenue spend margin_payback
# channel
# direct 485 31283.85 NaN NaN
# email 450 28593.35 400.0 37.17
# organic_search 1263 80953.76 NaN NaN
# paid_search 1000 62956.22 14110.0 2.32
# paid_social 635 40372.25 8990.0 2.34
# referral 211 13323.41 NaN NaN
October has 4,044 orders, €263,390.63 of gross revenue, €5,907.79 of refunds known so far and €257,482.84 of net revenue. The run log next to the report reads:
{
"month": "2025-10",
"as_at": "2025-11-03",
"input_file": "data/raw/2025-10/orders_asat_2025-11-03.csv",
"input_sha256": "19aaff992ef96313419683d6b3c801be80289288cad20e7a6544dc518a844df7",
"rows_raw": 8741,
"rows_clean": 8708,
"python": "3.13.3",
"pandas": "2.3.3",
"numpy": "2.3.4",
"run_at_utc": "2025-11-03T08:14:05+00:00"
}
Run the same command again on the same file and the report is identical, byte for byte. I checked it the blunt way, by hashing the two output files: the same 64 characters both times. That is the first row of the rerun test passed.
On 3 December, with --as-at 2025-12-03, the same 4,044 orders and the same gross revenue come back, but refunds have grown to €13,867.84 and net revenue has fallen to €249,522.79, 3.1% lower. Paid search is at 2.26 and paid social at 2.18. Two folders, two run logs, two different hashes, one explanation. That is the third row.
Version control: what goes into git, and what never does
Git records every change to a set of files, who made it and why, and lets you go back to any earlier state. For a report that means you can still say, months later, exactly what the code looked like on the day the September numbers were produced. Sandve's fourth rule is to put every custom script under version control8. If git is new to you, learn four commands first: git init once, then git add, git commit -m "why" and git log for the rest of your life.
What goes in: the code, the tests, pyproject.toml, uv.lock, .python-version, the configuration, the README and the assumptions file. What stays out: the data, the generated reports, the virtual environment and every secret. A file called .gitignore lists what git should never pick up.
Example: Ardmore's .gitignore.
# Data stays out of git: it holds customer emails and it is large
data/
reports/
# Secrets and local settings
.env
# Environments and caches
.venv/
__pycache__/
.ipynb_checkpoints/
The data rule is not only about size. The order export contains customer email addresses, which are personal data. The GDPR asks you to keep personal data to what is necessary for the purpose and to protect it properly16. The Data Protection Commission (DPC), Ireland's regulator, explains these principles in plain terms17. A copy of every customer's email in a git repository, cloned to every laptop that ever worked on the report and possibly pushed to a hosted service, fails both tests. Store the raw exports where access is controlled, and keep only what the report needs. This is general information, not legal advice.
The trap is that git never forgets. A file that was committed once stays in the history even after you delete it. If a secret is committed, treat it as exposed: revoke or rotate it first, then clean the history. GitHub's guidance recommends exactly that order, with the git filter repo tool for the clean up18. If customer data was committed and pushed, rewriting history is necessary but not sufficient, because every existing clone still has it. Prevention is a one line .gitignore entry, written before the first commit.
Notebooks have one more git problem: they are JSON files full of outputs, so a diff of two versions is unreadable, and saved outputs can contain customer rows. Two tools help, named fairly. Jupytext pairs each notebook with a plain .py or Markdown file that diffs cleanly19. papermill runs a notebook from the command line with parameters, if you decide a notebook really must be part of a scheduled job20. For a monthly report I prefer the package and the plain script. Notebooks stay for exploration, and I clear their outputs before committing them.
Scheduling the monthly run
Once the report runs with one command and stops itself when the data is wrong, scheduling it is the easy part. The default arguments in __main__.py already mean "last month, from an export downloaded today".
The question is not how but when. Two business facts decide it. The exports must exist (if the order export is downloaded by hand, the schedule waits for a person, and that is fine). And the month must be settled enough to be useful. Ardmore's refunds keep arriving for about six weeks, so the 3 November run is provisional and the 3 December run is final. Put both in the calendar: a provisional report early in the month for quick budget decisions, a final one a month later for anything that is compared over time.
Example: a cron line on the machine that holds the data. Cron is the scheduler built into macOS and Linux. This line runs the report at 7am on the 3rd of every month (in the machine's local time) and keeps a log:
# crontab -e, then add:
0 7 3 * * cd /srv/ardmore-report && /usr/local/bin/uv run --locked python -m ardmore_report >> logs/monthly.log 2>&1
If the export is not there yet, the run fails with a clear "file not found" in the log, and nothing is written to reports/. If you schedule in a hosted service instead, read its small print. GitHub Actions, for example, runs scheduled workflows in UTC, may delay them at busy times and can drop queued jobs under high load, and switches scheduled workflows off in public repositories after 60 days without activity21. A scheduled job also needs access to the data, which, for the reasons above, is not in the repository.
A test suite that runs on every change belongs on the same machine or service: a test suite you can trust explains continuous integration for web projects, and the same idea applies here at a smaller scale.
Write down the assumptions
The code says what the report does. It does not say why. Every report rests on decisions that someone made and someone else will question: why refunds count against the order's month, why the month is an Irish month, why email's payback is not comparable. Write them down in plain words, with a date, in a file next to the code. Six months later, when Darragh is on holiday and Áine asks why paid social's October figure went down, the answer is in the repository.
Example: Ardmore's ASSUMPTIONS.md.
# Assumptions behind the monthly channel report
* A month is a calendar month in Europe/Dublin time, as in the shop admin. (2025-10-12)
* Test orders: any order from an @ardmorehome.example address. Excluded. (2025-10-12)
* Staff orders: discount code STAFF30. Excluded with their refunds. (2025-10-12)
* Refunds count against the month of the original order, so each channel
carries the returns of its own customers. A month is provisional until the
run on the 3rd of the month after next. (2025-11-03)
* Margin payback uses gross margin 0.52, from the finance team's 2025 figure. (2025-10-12)
* Email spend is the tool's fee only, not writing time. Email payback is not
comparable with paid channels. (2025-11-03)
* The volume check stops the run if orders move more than 30% month on month. (2025-10-12)
Each line has a test or a check behind it, which is the point. An assumption that only lives in a document drifts away from the code. An assumption that lives in a document and in a test cannot.
Before and after: what the monthly run costs
The time saving is the easiest benefit to explain to whoever pays for the work, so here is an honest picture. The numbers below are illustrative, not measured: a plausible split of a monthly notebook report against the same report run as a script with checks. Your own will differ, and it is worth timing them once.
About 150 minutes against about 31. Building the project costs a few days once, so it pays back within the first year on time alone. The larger effect does not fit on a bar chart: the 31 minutes produce a number that can be defended, and the 150 minutes produce one that has to be believed. The writing up still takes a quarter of an hour, because explaining what the numbers mean is the part that should never be automated. The chart that goes with it should come from the report file by code too, following the house rules from a chart style guide for your business and the workflow in tools and workflow for good charts.
The checklist: the whole foundations series in one table
This table is the series in one place. Each line is a check you can tick for any analysis that will be rerun, with the chapter that teaches the skill behind it.
| Check | Why it matters | Where it is taught |
|---|---|---|
| The project has its own environment, Python version and lock file | Next month installs the same libraries | Setting up Python |
| Logic lives in functions with clear inputs and outputs | Functions can be tested and reused, cells cannot | Python basics for analysts |
Every random step uses a seeded default_rng | The same sample on every rerun | NumPy explained |
| Columns are read with explicit types | No silent change when pandas guesses differently | pandas Series and DataFrames |
| Raw exports are saved untouched, named by download date, hashed | Later exports can be compared with earlier ones | Loading business data into pandas |
| Test orders, staff orders and refunds follow written rules | Revenue means the same thing every month | Cleaning data in pandas |
Every join states what it expects, for example validate="many_to_one" | A duplicate key stops the run instead of doubling revenue22 | Joining and reshaping data |
| Totals after grouping reconcile with the cleaned total | Nothing fell out of the group by | Group by and pivot tables |
| Months and days are taken in the business's time zone | The report matches the shop's own screens | Time series in pandas |
| Charts are drawn by code from the report file | The chart cannot disagree with the table | Charts in Python |
| Models record their inputs, seed and fitted values | A refit next month can be compared with this one | Statistical models in Python |
| A validation gate stops the run on bad data | A broken export never becomes a decision | This chapter |
| One test per written assumption | Nobody tidies a business rule away | This chapter |
| A run log records input hash, as at date and versions | Every number can be traced to its source | This chapter |
My view
My view: the most valuable line in the whole project is not a line of code. It is the as at date in the folder name. Most of the arguments I see about "the numbers changed" are about data that legitimately moved, refunds above all, presented as if it were fixed. Printing the download date next to every number, and keeping the file it came from, turns an argument into a sentence.
I would also start smaller than most guides suggest. Plain checks and a pandera schema cover almost every failure a monthly shop report will meet. Three Python files, six tests and one command are enough. I would add a data quality platform, an orchestration tool or a dashboard layer only when a real problem asks for one, because each one is another thing to keep running next month. The goal is not a sophisticated pipeline. The goal is that Áine can ask "where does this number come from?" and get an answer in under a minute.
And keep the notebooks. They are where Darragh found out that paid social refunds more than the other channels. The discipline is only that once a finding matters, it moves out of the notebook and into a function with a test.
Data storytelling, analytics dashboards and data science are a core part of the work I do for clients, and this is the shape I give every recurring analysis: one command, checks that can stop it, and the client owns the code, the accounts and the data. If you want to see what that would look like on your own exports, my Data Science service describes the work, and my prices are published in full on the pricing transparency page.
Conclusion
A reproducible analysis is not a stricter notebook. It is a different shape: exploration in notebooks, the report as plain functions in a small package, one configuration file, a lock file for the libraries, a seed for every random step, raw exports frozen with their download date and fingerprint, a validation gate that can stop the run, a test for every business rule, and a run log next to every result. Ardmore's monthly channel report now runs in one command, refuses to run on a broken export, gives identical numbers on identical data, and explains why October looked different on 3 December than on 3 November.
That closes the foundations series. You can load the exports a business really has, clean, join, group and chart them, fit a model, and now hand the whole thing to someone else and trust what comes back next month. The next series builds every model of the Marketing Analytics series in Python on exactly these foundations, starting with the descriptive statistics every marketer needs.
