Skip to content

Chapter 2 — End-to-end tour: build, load, assay

Part I of the assayinganomalies tutorial. Prerequisite chapters: 1. Python modules covered: none (integrative; cites across the package).

What this chapter answers

  • The package's three jobs — build the database, analyze it interactively, assay a signal — and the CLI / API entry point for each.
  • What a full DuckDB build writes (tables, stages, sidecars), verified against pipeline.py and stage_registry.py.
  • What a protocol run leaves on disk (MPE_Results.pkl, printResults, TeX, figures, PDF).
  • Realistic wall-clock and disk expectations from a measured from-scratch run.
  • Which later chapter owns each layer when you need depth.

Where this sits in the pipeline

Chapter 1 covered config and the package front door. This chapter is the map of the whole system: build the warehouse, load panels, run analytics or the assay protocol, emit report artifacts. Later chapters zoom into one box at a time; nothing here is meant to replace them.

flowchart TB
  subgraph entry [Entry]
    CLI["aa CLI"]
    API["import assayinganomalies as aa"]
  end
  CFG["AssayConfig"]
  PIPE["setup_database<br/>24 stages"]
  DB[("DuckDB<br/>Data/aa.duckdb")]
  LOAD["aa.load / load_cz_anomalies"]
  SORT["sorts / FM / costs<br/>Ch 13-15"]
  PROT["test_signal / run_test_signal<br/>Ch 16-18"]
  REP["printResults → TeX / figures<br/>Ch 19"]
  OUT["Scratch/Assay/<br/>MPE_Results.pkl, MPE.tex, PDFs"]

  CLI --> CFG
  API --> CFG
  CLI --> PIPE
  API --> PIPE
  CFG --> PIPE
  PIPE --> DB
  CFG --> LOAD
  DB --> LOAD
  LOAD --> SORT
  LOAD --> PROT
  SORT --> PROT
  PROT --> REP
  REP --> OUT
  PROT --> OUT

The package does three jobs: setup_database builds the database, aa.load plus the analytics functions serve interactive work, and test_signal / aa run-protocol assay a signal.


The three jobs and their entry points

1. Build the database — setup_database

One function and one CLI command build the whole database. Settings come from AssayConfig (Ch 1); the stage list is the ordered STAGES tuple:

STAGES: List[PipelineStage] = [
    PipelineStage("initialize-database", _stage_initialize_database),
    PipelineStage("generate-field-catalog", _stage_generate_field_catalog),
    PipelineStage("fetch-crsp-monthly", _stage_fetch_crsp_monthly),
    PipelineStage("fetch-crsp-aux", _stage_fetch_crsp_aux),
    PipelineStage("fetch-ff-daily", _stage_fetch_ff_daily),
    PipelineStage("fetch-ff-factors", _stage_fetch_ff_factors),
    PipelineStage("fetch-compustat-annual", _stage_fetch_compustat_annual),
    PipelineStage("fetch-compustat-quarterly", _stage_fetch_compustat_quarterly),
    PipelineStage("fetch-crsp-daily", _stage_fetch_crsp_daily),
    PipelineStage("load-crsp-msf", _stage_load_crsp_msf),
    PipelineStage("transform-crsp-monthly", _stage_transform_crsp_monthly),
    PipelineStage("load-crsp-aux", _stage_load_crsp_aux),
    PipelineStage("load-crsp-dsf", _stage_load_crsp_dsf),
    PipelineStage("transform-crsp-daily", _stage_transform_crsp_daily),
    PipelineStage("load-compustat", _stage_load_compustat),
    PipelineStage("transform-compustat", _stage_transform_compustat),
    PipelineStage("validate-bm-hml", _stage_validate_bm_hml),
    PipelineStage("compute-tcosts", _stage_compute_tcosts),
    PipelineStage("compute-ff-tcosts", _stage_compute_ff_tcosts),
    PipelineStage("compute-betas", _stage_compute_betas),
    PipelineStage("compute-car3", _stage_compute_car3),
    PipelineStage("compute-nmv-anomalies", _stage_compute_nmv_anomalies),
    PipelineStage("fetch-cz-anomalies", _stage_fetch_cz_anomalies),
    PipelineStage("finalize", _stage_finalize),
]

A full build with the settings of the measured run in Runtime and disk expectations:

import assayinganomalies as aa

aa.set_params(
    sample_start=1925,
    sample_end=2024,
    dom_com_eq=True,
    tcosts_type="full",  # AssayConfig default is lf_combo
)
aa.setup_database(full_refresh=True, verbose=True)
# or: aa setup-database --full-refresh --verbose

Stage-by-stage internals, restartability, and rebuild(...) are Ch 4. Ingest and transform details are Ch 5–11.

2. Everyday analytics — aa.load + sorts / FM

Interactive work follows one pattern: load long panels from DuckDB, then pass MultiIndex Series into the analytics functions. run_univariate_sort takes the signal Series directly; bin assignment and the one-month lag happen inside (Ch 13).

import assayinganomalies as aa

df = aa.load(["ret", "me", "nyse_flag", "R12_2", "bm", "tcost"])
# df: MultiIndex (date, permno) long panel

res = aa.run_univariate_sort(
    df["ret"],
    -df["me"],          # size sort: low ME in bin 1
    df["me"],
    n_bins=5,
    breaks="NYSE",
    nyse_flag=df["nyse_flag"].astype(bool),
    factor_model=6,
    print_results=True,
)

aa.run_fama_macbeth(
    100 * df["ret"],
    [aa.log(df["me"]), df["R12_2"]],
    time_period=(196307, None),
)

Bivariate sorts, portfolio costs, generalized alpha, and anomaly decay are Ch 13–15.

3. Assay a signal — test_signal / aa run-protocol

test_signal takes a signal CSV and its SignalInfo, compares the signal with the Chen–Zimmerman anomaly zoo, and writes its outputs under Scratch/Assay/:

from pathlib import Path
import assayinganomalies as aa

signal = Path("mpe.csv")
info = aa.default_mpe_signal_info(file_link=signal)
result = aa.test_signal(
    signal,
    info,
    out_dir=Path("Scratch/Assay"),
    save=True,
    make_print_results=True,
    print_tex=True,
    emit_figures=True,
)
# result.path → Scratch/Assay/MPE_Results.pkl
# result.tex_path → Scratch/Assay/tex/MPE.tex

The same run from the command line:

aa run-protocol --signal mpe.csv --out-dir Scratch/Assay

Compile the PDF yourself (latexmk -pdf MPE.tex in Scratch/Assay/tex/). Protocol orchestration is Ch 16; result builders Ch 17–18; TeX/figures Ch 19.

Job Entry point Chapter
Build the database aa.setup_database / aa setup-database 4–11
Everyday analytics aa.load + analytics APIs 12–15
Assay a signal aa.test_signal / aa run-protocol 16–19

DuckDB table inventory

Source of truth for writers: write_table calls in pipeline.py, cross-checked with TABLE_WRITER_CHAIN in stage_registry.py. Row counts below are from a full from-scratch build in September 2026.

Primary tables (full build)

Table First / last writer stage Fresh-run rows × cols Role
crsp_msf load-crsp-msf 5,153,763 × 21 Raw CRSP monthly stock file
crsp_dsf load-crsp-dsf 107,663,470 × 13 Raw CRSP daily stock file
crsp_daily_panel transform-crsp-daily 107,663,470 × 13 Daily panel with derived fields
ccm_panel transform-crsp-monthly → … → compute-car3 3,890,902 × 94 Unified monthly firm panel (multi-writer)
ts_data fetch-ff-factors → compute-ff-tcosts 1,182 × 15, plus the five _capital and the five _capital_short factor-cost columns Monthly factors + FF factor tcosts under both conventions (smb_tc … for "dollar", smb_tc_capital … for "capital", smb_tc_capital_short … for the factors held short under "capital"; Ch 9b)
ts_data_daily transform-crsp-daily 25,901 × 6 Daily FF factors
tcosts compute-tcosts 3,933,565 × 4 Stock-level trading costs
betas compute-betas 3,667,529 × 8 Six beta variants
nmv_anomalies compute-nmv-anomalies 3,890,376 × 25 23 Novy-Marx/Velikov signals
cz_anomalies fetch-cz-anomalies 4,109,578 × 214 Chen–Zimmerman signal panel
cz_signal_info fetch-cz-anomalies 212 × 30 CZ signal documentation
validation_bm_hml validate-bm-hml 1,182 × 3 BM/HML sanity check summary
compustat_funda load-compustat 585,826 × 80 Raw annual fundamentals
compustat_fundq load-compustat 2,051,259 × 38 Raw quarterly fundamentals
ccm_link transform-compustat ~34,000 × 7 (the LC/LU links with a permno) Cleaned CRSP-Compustat link (Ch 7); read by compute-ff-tcosts and compute-car3

ccm_panel is the only multi-writer table that matters day to day. Later stages DROP+CREATE the whole table when they merge new columns; skipping a cascade after a scoped rebuild silently drops columns. The writer chain:

TABLE_WRITER_CHAIN: Dict[str, List[str]] = {
    # ccm_panel is built by transform-crsp-monthly and re-written (merge)
    # by every downstream enrichment stage. Each re-write is a DROP+CREATE,
    # so the last writer wins — skipping cascade rots columns.
    "ccm_panel": [
        "transform-crsp-monthly",
        "transform-crsp-daily",
        "transform-compustat",
        "compute-tcosts",
        "compute-betas",
        "compute-car3",
    ],

CRSP aux tables (load-crsp-aux)

pipeline.py writes these under the short names in CRSP_AUX_RAW, the names stage_registry.TABLE_WRITER_CHAIN uses too (only the staging parquets carry the crsp_ prefix):

CRSP_AUX_RAW = {
    "msfhdr": "crsp_msfhdr_raw.parquet",
    "msedelist": "crsp_msedelist_raw.parquet",
    "dsedelist": "crsp_dsedelist_raw.parquet",
    "mseexchdates": "crsp_mseexchdates_raw.parquet",
    "stocknames": "crsp_stocknames_raw.parquet",
    "ccmxpf_lnkhist": "crsp_ccmxpf_lnkhist_raw.parquet",
}
DuckDB table Stage Fresh-run rows
msfhdr load-crsp-aux 38,843
msedelist load-crsp-aux 38,843
dsedelist load-crsp-aux 38,872
mseexchdates load-crsp-aux 117,859
stocknames load-crsp-aux 83,280
ccmxpf_lnkhist load-crsp-aux 123,388

Metadata / plumbing tables

Table / file Produced by Notes
metadata initialize-database (+ persist_metadata) Key/value including JSON stage_history, and the records annual_layout (Ch 7) and ff_tcosts (Ch 9b) that later readers check
config aa.save_config / set_params Not a pipeline stage; Ch 1
rebuild_state pipeline.rebuild Journal for scoped rebuilds; Ch 4
Data/aa.catalog.json generate-field-catalog Field-alias sidecar; not a DuckDB table
Data/aa.manifest.json setup_database / rebuild (end of run) Run manifest; see Run manifests

Fetch stages (fetch-*) write Parquet under Data/staging/ and do not create DuckDB tables themselves. finalize only logs completion.


Protocol artifact inventory

From a full MPE protocol run in September 2026. Defaults assume acronym MPE and out_dir=Scratch/Assay.

Artifact Path Size (fresh run)
Results pickle Scratch/Assay/MPE_Results.pkl ~7.55 GB (contains ResStruct pack + printResults)
TeX source Scratch/Assay/tex/MPE.tex ~37 KB
Compiled PDF Scratch/Assay/tex/MPE.pdf ~1.4 MB, 24 pages
Figure PDFs (8) Scratch/Assay/tex/MPE_figure*.pdf SignalDescription, SharpeDist, Ibbots, AlphaPrctl, Correl, Dendrogram, CondStrats, CombStrats
Protocol log Scratch/Assay/mpe_full_run.log ~37 KB
Run manifest Scratch/Assay/MPE_manifest.json a few KB; see Run manifests

printResults is the reporting struct assembled by make_res_to_print (Ch 19). It is stored inside the pickle (and available on ProtocolResult.print_results); there is no separate file for it.

The close-anomaly spanning table (tab:closeAnomSpan) breaks ties among equal signal values with a tiny seeded random jitter, so it is identical across reruns with the default seed; a different seed can move tie-heavy anomalies slightly (Ch 17).


Run manifests

Every database build and every protocol run that writes outputs leaves a JSON receipt beside them (module assayinganomalies.run_manifest):

Command Manifest Written when
aa setup-database / setup_database() Data/aa.manifest.json (the database name with .manifest.json) at the end of every build, including --start-from resumes; a scoped rebuild() rewrites it
aa run-protocol / test_signal() <out_dir>/<ACRONYM>_manifest.json, next to <ACRONYM>_Results.pkl whenever the run saves the pickle or writes TeX (save=True or print_tex=True)

Both commands print the manifest path. Writing one never changes a number, and a failure to write one is logged rather than raised.

To read one, call assayinganomalies.run_manifest.read_manifest(path); any JSON reader works too.

Layout

Block What it answers In the id?
scientific What determines the numbers: code, tape, sample, warm-up windows, settings, seeds, input hashes (it is the identity)
scientific_id SHA-256 of scientific in canonical JSON (sorted keys, no whitespace) —
data_vintage When the data were pulled: WRDS fetch dates, file modification times, CZ release requested no
environment Python, platform, key package versions no
execution Start/finish times, paths, flags, stage history (build) or the run's summary (protocol) no

Two runs with the same scientific_id used the same code, the same settings and the same input bytes. Rerunning on identical files (even after a re-pull from WRDS that returns identical bytes) keeps the id; changing one input byte or one setting moves it. verify_manifest(m) checks that the id still matches the block. Timestamps and library versions are kept out of the id on purpose: they are recorded so a difference can be diagnosed, but "same experiment" is defined by code, settings and data.

Anything not known is written as null or "unknown", never inferred: an installed wheel has no git checkout, so git_sha is null; a configured CZ release of null means "latest", and which release that resolved to is not recorded by the download. No credential is ever written; configuration is copied field by field from an allowlist and wrds_username is not on it.

Common fields

Field Meaning
manifest_version Format version (currently 1)
kind "database" or "protocol"
scientific.code.package_version Installed assayinganomalies version
scientific.code.git_sha / git_dirty Commit of the checkout the package was imported from, and whether tracked files were modified (untracked files do not count); both null outside a checkout
scientific.code.package_sha256 Protocol manifests only: SHA-256 over the installed package's files as the distribution's RECORD lists them (path and hash of every assayinganomalies/ file, sorted). The same for a wheel and every installation of it; null for an editable install
environment.python, .platform, .machine Interpreter and OS
environment.packages Versions of numpy, pandas, scipy, scikit-learn, statsmodels, duckdb (null = not installed)
execution.started_at / finished_at UTC, ISO 8601

Database build (aa.manifest.json)

Field Meaning
scientific.crsp_format Tape: "ciz" or "siz"
scientific.sample start_year, end_year from the config; end_year is the resolved year when sample_end is latest
scientific.warmup null: the build has no warm-up of its own; every stage reads the full sample
scientific.settings The config fields that change what is computed: crsp_format, sample_start, sample_end, dom_com_eq, tcosts_type, compustat_variables, cz_release_version, cz_signal_doc_path, cz_signals_path
scientific.seeds {}: no build stage draws random numbers
scientific.demo_data true if the database is stamped as synthetic (--demo)
scientific.inputs[] One record per input: role, name, bytes, sha256. Every file directly in Data/staging/ (the WRDS extracts and the CZ download cache, role "staging extract"), plus inputs read from elsewhere and registered by the code that opens them: Gibbs estimates, HF effective spreads, CPIAUCNS, the Davis-Fama-French book equity, the CZ signal documentation and signed predictors. An input fetched straight from a URL is listed with its url and sha256: null
data_vintage.crsp_format Tape again, for reading without the identity block
data_vintage.cz_release_requested Configured CZ release, or "latest (the newest release on Hugging Face when the build ran)"
data_vintage.cz_release_resolved The release each CZ file was read from: {"signals": "2025.10", "signal_doc": "2025.10"}; unknown (...) for a file you supplied; unknown if no CZ stage ran
data_vintage.cz_release_source The Hugging Face branch and commit of each CZ file read from a release: {"signals": {"release": "2026.10", "branch": "Data-Release-2026.10", "commit": "dd10…"}, ...}; the commit is unknown for a file read from the cache
data_vintage.sample_end_requested / sample_end_resolved / sample_end_source latest or the configured year; the year built through; wrds, metadata, demo, explicit or clamped-siz
data_vintage.crsp_tape_max_date / compustat_max_datadate Last month on the CRSP monthly file and last Compustat datadate when the year was looked up; unknown otherwise
data_vintage.wrds_pulls Latest successful time of each fetch-* stage, from stage_history, kept across --start-from resumes; "unknown" if none is recorded
data_vintage.files Path and modification time of each input
execution.command "setup-database" or "rebuild"
execution.database_path, staging_dir Where the build ran
execution.full_refresh, start_from, rebuild_id How it was invoked
execution.stage_history The same records persist_metadata stores in the metadata table

Hashing the staging directory of a full build (~13 GB) takes on the order of a minute.

Protocol run (<ACRONYM>_manifest.json)

Field Meaning
scientific.signal_acronym From summary
scientific.crsp_format Tape of the database the run read (from summary, which reads it from the database's own record)
scientific.cz_release Chen-Zimmerman release of the zoo the run read ("2026.10"), from the database's metadata; null when the database does not record it
scientific.factor_source Where the factor bundle came from (from summary)
scientific.demo_data Whether the database is stamped synthetic
scientific.stages, max_anoms, compute_gen_alpha From summary
scientific.sample.time_period [YYYYMM, YYYYMM] evaluation window
scientific.warmup Rolling windows in months that must fill before output appears: anomaly_coverage_window_months (n_roll), comb_fmb_window_months, comb_lasso_window_months, comb_ipca_window_months
scientific.settings factor_models, n_close, mcap_thresh, tcosts_type, make_print_results, compute_alpha_prctl, compute_comb_sorts (null = the default was used)
scientific.seeds anomaly_tiebreak_jitter_seed, benchmark_tiebreak_jitter_seed, anomaly_fill_jitter_seed (the 1e-12 tie-break jitter) and tiebreak_jitter_stream (how each anomaly's random stream is keyed: by its name), lasso_random_state, lasso_cv_mode, read from the defaults of the functions the protocol calls
scientific.signal.file Identity record of the signal CSV (null when the signal was passed in memory)
scientific.signal.content_sha256 Hash of the resolved signal panel (index and values), present either way
scientific.database.file Identity record of the DuckDB file, hashed before the run opens it (~1 min for 14 GB); null when every panel was passed in memory
scientific.database.build The database's own scientific_id, sample and settings, read from aa.manifest.json beside it, or "unknown"
scientific.in_memory_inputs Names of panels passed in memory (returns, mcap, factors, ...): used, but not hashed
data_vintage.database Path and modification time of the database file
execution.outputs Paths of results_pickle and tex
execution.n_jobs Pool size (does not change numbers)
execution.summary The run's ProtocolResult.summary (minus the stage log): stage outcomes, counts, headline Sharpe, elapsed time

The database file's hash changes whenever the file is rewritten, even with identical data, because DuckDB stores its own metadata (including the build time) in it. Two protocol runs on two rebuilds of the same data therefore have different ids; scientific.database.build.scientific_id is the field that says whether the two databases were built from the same inputs.


Runtime and disk expectations

Numbers from a from-scratch run on 2026-09-17 (CIZ tape, sample 1925–2024, tcosts_type=full, 16 cores with 15 protocol workers). Expect similar magnitudes on a comparable machine; WRDS latency and the Chen–Zimmerman download dominate the variance.

Phase Wall clock Notes
Full setup_database 2 h 45 m Dominated by fetch-crsp-daily (~1 h, server-side) and transform-crsp-daily (~48 min); then compute-tcosts and fetch-cz-anomalies (~12–13 min each)
CZ re-ingest alone ~11 min Streaming the wide CSV
MPE test_signal (core) ~2 h (7,042 s) The combination strategies take ~77 min of it
aa run-protocol, including the PDF 1 h 58 m
Disk object Approx size
Data/aa.duckdb ~16 GB
Chen–Zimmerman input files ~10–11 GB while building
MPE_Results.pkl ~350 MB
TeX + 8 figures + PDF small (few MB)

Without WRDS credentials a build stops with an error. aa setup-database --demo builds a synthetic database instead: fine for trying the API and for tests, useless for research (see Known limitations).


Where do I look for X?

Want to understand… Chapter
Package layout, AssayConfig, CLI, AssayClient 1
DuckDB connections, aa.load SQL, field catalog, month-end dates 3
STAGES, setup_database, rebuild, stage history 4
WRDS / CRSP / COMPUSTAT / FF / CZ ingest 5
CRSP monthly transforms → ccm_panel core 6
COMPUSTAT derived vars and CCM merge 7
CRSP daily transforms and monthly aggregates 8
tcosts (stock + FF factor) 9
Beta variants 10
23 NMV anomalies + fill helpers 11
aa.load, CZ loaders, signal CSV I/O 12
Univariate / bivariate sorts and factor regs 13
Fama–MacBeth and nanols / prt 14
Portfolio costs, gen alpha, anomaly decay 15
test_signal / run_test_signal orchestrator 16
Result builders: basic sorts, zoo, FMB 17
Close anomalies, dendrogram, combo / ML 18
printResults, LaTeX, eight figures 19
Pytest and the path to PyPI 20
Run manifests (what a build or protocol run records about itself) this chapter