Chapter 20 — Validation and reproducibility¶
Part V of the assayinganomalies tutorial. Prerequisite chapters: 1–19. Python modules covered:
run_manifest.py,provenance.py.
What this chapter answers¶
- How to tell whether two databases, or two protocol runs, are the same experiment.
- What the demo-database stamp does, where it lives, and what it refuses.
- What a golden snapshot is, and how the package's own numbers are kept from drifting silently between releases.
- How the numbers were validated in the first place.
Where this sits in the pipeline¶
Chapters 1–19 describe what the package computes. This chapter is about the records that let you trust, compare and reproduce those computations. Three mechanisms do that work, each at a different point:
flowchart LR
BUILD["aa setup-database"]
DB[("aa.duckdb<br/>+ demo stamp")]
BM["aa.manifest.json"]
RUN["aa run-protocol"]
PKL["ACRONYM_Results.pkl + TeX"]
PM["ACRONYM_manifest.json"]
GOLD["golden snapshots<br/>(release testing)"]
BUILD --> DB
BUILD --> BM
DB --> RUN
RUN --> PKL
RUN --> PM
DB -.-> GOLD
PKL -.-> GOLD
- Run manifests travel with your outputs: every build and every protocol run writes a JSON receipt of what determined its numbers.
- The demo stamp travels with the database: a database built from synthetic data says so, and the protocol refuses it unless told otherwise.
- Golden snapshots are kept by the package's developers: frozen reductions of a reference build and a reference protocol run, used to check that a code change moves no number it was not meant to move.
Run manifests¶
The full field list is in Ch 2, Run manifests; this section is about using them.
| Command | Manifest |
|---|---|
aa setup-database / setup_database() |
Data/aa.manifest.json, beside the database |
aa run-protocol / test_signal() |
<out_dir>/<ACRONYM>_manifest.json, beside <ACRONYM>_Results.pkl |
Each manifest splits into a scientific block — everything that determines
the numbers: code version, tape, sample, warm-up windows, settings, seeds and
the SHA-256 of every input file — and blocks that are recorded but do not
define the experiment (data_vintage, environment, execution).
scientific_id is the SHA-256 of the scientific block in canonical JSON.
Comparing two runs¶
from assayinganomalies.run_manifest import read_manifest, verify_manifest
a = read_manifest("Data/aa.manifest.json")
b = read_manifest("/other/machine/Data/aa.manifest.json")
verify_manifest(a) # the id still matches the block
a["scientific_id"] == b["scientific_id"] # same code, settings and input bytes?
If the ids differ, diff the two scientific blocks to see why: a changed
setting shows up under settings, a re-pulled extract under inputs (same
name, different sha256), a different release under code. If the ids match
but the numbers do not, the difference is outside what the manifest records —
usually the environment block (a different numpy or scikit-learn) is the first
place to look.
For protocol runs, compare scientific.database.build.scientific_id rather
than scientific.database.file: the DuckDB file's own hash changes every time
the file is rewritten, even with identical data.
verify_manifest(manifest)¶
Recomputes scientific_id from the scientific block and returns whether it
matches the stored id. A False means the file was edited after it was
written.
read_manifest(path) / write_manifest(path, manifest)¶
Plain JSON I/O. write_manifest writes indented JSON atomically (a temporary
file, then a rename), so an interrupted write never leaves half a manifest.
database_manifest(...) / protocol_manifest(...)¶
Assemble the two manifest kinds. setup_database, rebuild and the protocol
call them for you; you need them only to write a manifest for work done
outside those entry points. build_manifest_path(db_path) and
protocol_manifest_path(out_dir, acronym) give the standard file names.
Input registration: note_input, recording_inputs, file_identity¶
Code that opens an input file outside the staging directory calls
note_input(path, role); inside a with recording_inputs(): block those calls
are collected, and the manifest builder hashes each one with
file_identity(path, role) (role, name, bytes, sha256). This is how the
Gibbs estimates, the high-frequency spreads and the Chen–Zimmerman files reach
scientific.inputs even though they do not live in Data/staging/.
note_cz_release does the same for the Chen–Zimmerman release a download
resolved to.
Identity helpers¶
code_identity() records the package version and, when the package is imported
from a git checkout, the commit and a dirty flag (null for an installed
wheel). environment() records the interpreter, the platform and the versions
of the numerical libraries. scientific_id(block) is the hash itself.
sha256_file, file_location, git_state, utc_now and wrds_pull_dates are
the small pieces the builders use.
The demo-database stamp¶
aa setup-database --demo (API: setup_database(demo=True)) builds a database
from deterministic synthetic data, for trying the package without a WRDS
subscription. Without --demo, a build with no credentials or a failed download
stops with an error rather than substituting synthetic rows.
A demo database is stamped: key demo_data is written to both the metadata
and the config table, because metadata is dropped and rewritten by
--full-refresh while config survives it. The protocol checks the stamp
before it starts; aa run-protocol and test_signal refuse a stamped database
unless you pass --allow-demo-data / allow_demo_data=True, and then every
report title and manifest carries SYNTHETIC DEMO DATA — NOT REAL RESEARCH
OUTPUT. The manifests record the flag under scientific.demo_data.
The stamp is a guard against the accidental demo build, not proof of provenance; its limits (it fails open, only the protocol checks it, only a full rebuild clears it) are in Known limitations.
database_is_demo(db_path)¶
True if either table carries a true demo_data value. A missing file, a
database with neither table, or any read error returns False — a database
that predates the stamp is treated as a production database.
mark_database_demo(db_path, demo)¶
Writes the stamp. metadata is created if absent; config is updated only if
it already exists (creating one would make an unconfigured database look like a
legacy-tape build, because load_config reads an existing config table as the
database's own settings). The pipeline stamps last, so the stamp reflects a
build that finished: a demo build writes True; a production build writes
False only after a full refresh from the first stage; a partial production
run over a stamped database keeps the stamp and logs a warning.
require_real_database(db_path, *, allow_demo=False, what=...)¶
Raises DemoDatabaseError for a stamped database unless allow_demo is set,
and returns the demo flag so the caller can label its own output.
label_title(title, demo) / provenance_payload(demo)¶
The labelling half: label_title prefixes a title with the demo banner;
provenance_payload returns the {"demo_data": ..., "data_provenance": ...}
fields every manifest-like output carries.
Errors¶
All refusals derive from ProvenanceError:
| Exception | Raised when |
|---|---|
MissingCredentialsError |
A production build needs WRDS and no credentials resolve (missing_credentials_error(purpose) builds the message, listing every way to supply them) |
DownloadFailedError |
A required download fails (download_failed_error(what, exc, hint=...)); the pipeline never substitutes synthetic data |
MissingInputError |
A required input file is missing — the Gibbs estimates, or the high-frequency spreads under tcosts_type='full' (trading-cost inputs) |
DemoDatabaseError |
Production code is pointed at a stamped database |
Golden snapshots¶
A golden snapshot is a frozen, compact reduction of a reference result, committed alongside the code so that any later change has to declare what it moved. The package's developers keep two kinds, one at each end of the pipeline:
- Panel snapshots freeze the inputs to every analysis: the derived
monthly panel
ccm_paneland the anomaly tablenmv_anomalies. For each column they store summary statistics (dtype, non-null, NaN and inf counts, mean, std, min, max) plus about ten thousand individual cells. Statistics catch distribution-wide drift; the sampled cells catch drift that cancels in aggregate, such as a sign flip on half the panel or rows shuffled between permnos. Cells are chosen by a hash of their own(permno, date), so adding rows elsewhere leaves the rest of the sample unchanged. - Protocol snapshots freeze the outputs: twenty-one tables reduced from the
reference MPE run's
MPE_Results.pkl, with a SHA-256 per table. Some are the numbers that reach the LaTeX report (the basic and robustness sorts, the close-anomaly tables, the alpha percentiles, the headline text scalars); the rest are the full-precision numbers behind them (sort grids, anomaly diagnostics, Fama–MacBeth coefficients, trading costs, the dendrogram linkage, the combination strategies). Label columns are kept as well as numbers: the close-anomaly selection, the dendrogram leaf order and the zoo's column order are positional keys that later tables inherit, so a reordering that leaves every number intact still shows up.
There is one snapshot tree per CRSP tape (SIZ and CIZ), chosen from the
database's own record of the tape it was built from, and both describe
reference builds over the default 1925–2024 sample with tcosts_type='full'.
Before a release, a fresh build and protocol run are checked against them; a
difference is either a bug or a deliberate change that is re-pinned and
recorded in the CHANGELOG.
The snapshot tools and trees live in the development repository and do not
ship with the package. To check your own work across machines or over time, use
the manifests above: equal scientific_ids mean the same code, settings and
input bytes, and a protocol run's ProtocolResult.summary (also copied into
the manifest's execution.summary) gives the headline numbers to compare.
How the numbers were validated¶
The package began as a Python port of the MATLAB toolkit that accompanies Novy-Marx and Velikov (2026). During the port, every database computation (the CRSP and Compustat derived variables, daily aggregates, trading costs, betas, the Fama–French factors) and every protocol builder was compared, number by number, against the MATLAB toolkit's output on the same CRSP extract, until all of them agreed within tolerance or the difference was a documented, intended change. The pytest suite in the development repository pins that behaviour on synthetic data, and the golden snapshots above took over as the reference once the port was complete.
One part of the package has since left that comparison on purpose. The univariate sort, the zoo strategies, the protocol and the Fama–French factor costs now hold their legs between trades (Ch 13, Ch 9b), so their trading costs, and the returns of signals that change once a year, no longer match the MATLAB toolkit; the appendix lists what differs. The held-leg calculation is checked against independent simulations in dollars in the test suite, not against MATLAB.
Because the MATLAB toolkit reads only the legacy CRSP tape (SIZ), that comparison was done on SIZ builds; the CIZ default was then checked against SIZ at the level of the research conclusion. If you are moving from the MATLAB toolkit, the appendix maps its functions to this package's and lists the differences that matter.