Skip to content

Chapter 5 — Ingest: WRDS, CRSP, COMPUSTAT, FF, Chen-Zimmerman

Part II of the assayinganomalies tutorial. Prerequisite chapters: 1, 2, 3, 4. Python modules covered: ingest/wrds_client.py, ingest/crsp_source.py, ingest/crsp.py, ingest/crsp_daily.py, ingest/compustat.py, ingest/ff_factors.py, ingest/cz_anomalies.py, ingest/cz_release.py, ingest/ken_french.py, ingest/__init__.py.

What this chapter answers

  • How the package connects to WRDS, and how credentials resolve in interactive vs CI environments.
  • Which CRSP tape a build reads (SIZ vs CIZ), and how CRSPSource keeps every tape-specific table name, unit, and delisting convention in one module so the rest of the package never branches on it.
  • What demo (placeholder) mode is: an opt-in synthetic build (setup-database --demo) for trying the package and for tests. A normal build never falls back to it; a missing credential or failed download stops the run.
  • How CRSP monthly / aux / daily and COMPUSTAT annual / quarterly extracts are built (SQL, sample window, parquet staging).
  • How Fama–French factors are pulled from WRDS and keyed to month-ends.
  • How the Chen–Zimmerman catalog is downloaded from a release's Hugging Face branch (the newest release by default), checked against its checksums, what to do when the download fails, and how it is streamed into DuckDB.

Where this sits in the pipeline

Chapter 4 listed the 24 stages; this chapter is the body of every fetch-* stage plus the Ken French helper used outside the library build. Ingest writes staging parquet (or returns a DataFrame); load/transform stages (Ch 6–11) turn those into DuckDB tables and derived columns.

flowchart LR
  WRDS["WRDS PostgreSQL"]
  KF["Ken French / Hugging Face"]
  CLIENT["WRDSClient"]
  FETCH["fetch_* / write_cz_*"]
  PH["generate_placeholder_*"]
  STG["Data/staging/*.parquet"]
  DB[("aa.duckdb")]

  WRDS --> CLIENT
  CLIENT --> FETCH
  KF --> FETCH
  CLIENT -.->|"--demo only"| PH
  PH --> STG
  FETCH --> STG
  FETCH --> DB
  STG --> DB

Placeholder mode (read once)

The pipeline can run setup_database end-to-end without WRDS credentials, so pytest, CI and first-time users can exercise every stage. That mechanism is placeholder mode.

Trigger. Every fetch-* stage asks the pipeline context for a WRDS client. The context returns a live WRDSClient only if ensure_credentials succeeds. Otherwise a production build raises, naming the stage; a demo build gets None back, and the stage calls a placeholder generator — for CRSP through the tape source (ctx.source.placeholder_monthly, which wraps generate_placeholder_monthly on SIZ), elsewhere a generate_placeholder_* helper (or, for FF factors and CRSP aux, builds a tiny DataFrame / empty typed frame inline in pipeline.py).

def _stage_fetch_crsp_monthly(ctx: PipelineContext) -> None:
    dest = ctx.staging_dir / CRSP_RAW_FILE
    t0 = time.perf_counter()
    client = ctx.require_wrds_client("Fetching the CRSP monthly stock file")
    # Demo runs only: a deterministic synthetic stand-in for crsp.msf.
    if client is None:
        df = ctx.source.placeholder_monthly(ctx.config)
        df.to_parquet(dest, index=False)
        # ...
        return
    crsp_ingest.fetch_crsp_monthly(
        ctx.config, dest, wrds_client=client, source=ctx.source
    )

What placeholders are. Deterministic mini panels (fixed seeds where random noise is used) with the column names downstream transforms expect: two CRSP permnos, a few COMPUSTAT gvkeys, a handful of CZ signal columns, two months of FF factors. They are not a subsample of WRDS and are not suitable for research. They exist so DuckDB tables get created, transforms do not crash on empty schemas, and the public API smoke-tests.

When they are used. Only when you ask for them: aa setup-database --demo (or setup_database(demo=True)). A normal build with no WRDS credentials, or with a failed download, stops with an error instead. The Chen–Zimmerman download (which needs no WRDS account) is the one exception to stopping: a normal build never substitutes placeholder data for it either, but it finishes without cz_anomalies and says so (below). A demo database is stamped as synthetic, and the protocol refuses it unless you pass --allow-demo-data; see Known limitations for what the stamp does and does not guarantee.


ingest/wrds_client.py — WRDS without JDBC

The package connects through the wrds Python package (psycopg2 under the hood). There is no driver to install and no datasource to configure; all you need is a WRDS username and password.

WRDSClient

Signature

@dataclass
class WRDSClient:
    username: str | None = None
  • username — optional override; else WRDS_USERNAME env, else the user of the first WRDS line in ~/.pgpass, else an interactive prompt.

Returns — the dataclass itself; the connection comes from open_session() and is borrowed through connect().

What it does — thin credential + connection wrapper. Private helpers _get_username, _get_password, _can_prompt implement the priority chain: env password → ~/.pgpass (%APPDATA%\postgresql\pgpass.conf on Windows) → OS keyring service "wrds" → interactive input / getpass when safe, with one printed line first saying why it is asking. credential_source records which of these supplied the password (env, .pgpass, keyring, prompt). A keyring failure (no backend on a headless node) is logged at DEBUG only. _can_prompt returns False under ASSAYINGANOMALIES_NO_PROMPT / AA_NO_PROMPT, PYTEST_CURRENT_TEST, or common CI env vars, so tests never hang on a password prompt. A password typed at the prompt is stashed only in os.environ["WRDS_PASSWORD"] for the current process; it is never written to disk.

ensure_credentials(*, prompt: bool = True) -> bool

Signature

  • prompt — if True and _can_prompt(), ask for missing username/password.

Returns — True if both username and password are available after the call. It returns False rather than raising; the pipeline decides whether that is an error (production) or demo mode.

What it does

    def ensure_credentials(self, *, prompt: bool = True) -> bool:
        """
        Ensure credentials are available, optionally prompting the user.
        # ...
        """
        uname = self._get_username()
        pwd = self._get_password()
        if uname and pwd:
            return True

        if prompt and self._can_prompt():
            # Username: allow empty input to keep existing (env/config) if present.
            # ...
            if uname and not pwd:
                try:
                    pw = getpass.getpass("WRDS password: ")
                except EOFError:
                    return False
                if pw:
                    os.environ["WRDS_PASSWORD"] = pw
            # ...
        return False

open_session() / connect() / close() / run_query(sql, **kwargs)

Signature

  • open_session() — no args; logs in once and caches the connection on the client. Raises if wrds is missing, credentials are unavailable or the login fails.
  • connect() — a context manager yielding the cached connection; leaving the block does not close it.
  • close() / reconnect() — close the cached connection (and log in again).
  • save_pgpass() — write the current credentials to the password file.
  • run_query(sql, **kwargs) — conn.raw_sql(sql, **kwargs) on the borrowed connection.

Returns — wrds.Connection / a pandas DataFrame.

What it does — open_session builds wrds.Connection(autoconnect=False, wrds_username=..., wrds_password=...) and makes the engine with the library's private _Connection__make_sa_engine_conn(raise_err=True). The library's own connect() falls back to its Enter your password: and Create .pgpass file now [y/n]? prompts when a login fails, which a build must never show, so a failure raises instead; load_library_list is skipped because ingest only calls raw_sql. A test pins the private method against the installed wrds. connect checks the cached connection with SELECT 1 and reopens it once if that fails. setup_database and rebuild open the session in _preflight_credentials (so the one Duo push comes before stage 1) and close it in a finally. Most ingest code uses with client.connect() as conn: directly rather than run_query; the chunked CRSP daily pull asks the client to reconnect after a failed chunk. There is no row-count check before a download; the fetch helpers log the shape of what came back.


ingest/crsp_source.py — which CRSP tape, behind one interface

The problem this module solves

CRSP froze the legacy stock tape ("SIZ", Flat File Format 1.0) in January 2025; data after December 2024 exists only on the new one ("CIZ", Flat File Format 2.0). The two tapes disagree about table names, column names, units, the sign of prc, how share/exchange codes are encoded, and — most consequentially — whether the monthly return already contains the delisting payoff.

SIZ (Format 1.0) CIZ (Format 2.0)
Monthly stock file crsp.msf crsp.msf_v2 (= stkmthsecuritydata widened with security-info columns)
Daily stock file crsp.dsf crsp.dsf_v2 (= stkdlysecuritydata)
Delisting msedelist (monthly), dsedelist (daily) stkdelists
Name / exchange windows mseexchdates, stocknames, msfhdr stksecurityinfohist, stocknames_v2
Compustat link ccmxpf_lnkhist ccmxpf_lnkhist (unchanged)
Coverage 1925 → Dec 2024, frozen 1925 → present

The strategy pattern

The naive way to support a second tape would be an if config.crsp_format == "ciz": at each site that touches CRSP. The cleaner alternative is a strategy object: one class per tape, both exposing the same method names, and the pipeline holding whichever instance the config selected.

# ingest/crsp_source.py
class CRSPSource(ABC):          # the interface
    name: str
    apply_delisting_overlay: bool
    needs_name_window: bool
    @abstractmethod
    def monthly_sql(self, config) -> str: ...
    @abstractmethod
    def daily_sql(self) -> str: ...
    @abstractmethod
    def normalize_monthly(self, raw, *, aux=None): ...
    # ... aux_tables, delist_events, daily_delist_events, link_grid,
    #     placeholder_monthly, placeholder_daily, placeholder_aux_schemas

class SIZSource(CRSPSource): ...   # the two implementations
class CIZSource(CRSPSource): ...

def crsp_source_for(config) -> CRSPSource:   # the factory
    return {"siz": SIZSource, "ciz": CIZSource}[config.crsp_format]()

ABC is abc.ABC, Python's abstract base class: a class carrying @abstractmethod members cannot be instantiated, so a subclass that forgets a method fails loudly at construction instead of at the first call.

The payoff is the call site. ctx.source.monthly_sql(cfg) runs the SIZ version or the CIZ version depending only on which object was constructed: the pipeline never branches on the format and never spells a WRDS table name again. Adding a third tape is adding a subclass, and the SIZ behaviour is stated in exactly one place, so it cannot drift.

SIZSource — the legacy tape

Every literal in SIZSource was moved verbatim out of ingest/crsp.py, ingest/crsp_daily.py and pipeline.py, and introducing the abstraction left SIZ output byte-for-byte unchanged.

normalize_monthly is the identity function here: the SIZ column names are the canonical names. apply_delisting_overlay = True and needs_name_window = True.

CIZSource — the current tape

Every CIZ fact encoded in this class was verified by querying WRDS; nothing in the class assumes a CIZ column name, unit or code mapping that was not confirmed there.

The monthly rename map (CIZ_MONTHLY_RENAMES) covers the plain renames:

Raw msf_v2 Canonical
mthcaldt date
mthret ret
mthretx retx
mthcumfacpr cfacpr
mthcumfacshr cfacshr

Five columns are not plain renames, and normalize_monthly handles each:

  • prc — CIZ never writes a negative price. Where SIZ signed a bid/ask midpoint negative, CIZ flags it mthprcflg = 'BA' and leaves the price positive. The re-sign happens on normalize so every downstream prc.abs() and prc < 0 keeps meaning what it meant.
  • vol — mthvol is 100× SIZ's msf.vol, so it is divided by CIZ_MONTHLY_VOL_SCALE = 100.0. Daily volume is unchanged; only monthly moved.
  • shrcd / exchcd — CIZ has no such codes. derive_shrcd and derive_exchcd reconstruct them from the security-info columns (below).
  • siccd — msf_v2.siccd is the header SIC: it reports a 2025 industry for a 1975 observation. It is dropped and the as-of value is interval-joined from stksecurityinfohist. That join is a left join, deliberately: ~0.5% of monthly rows sit one day past secinfoenddt and have no window at all, and they are almost entirely delisting months — exactly the rows the no-overlay design depends on keeping.

shrout needs no conversion (thousands of shares on both tapes), so me = |prc| * shrout / 1000 is unchanged.

Derived shrcd / exchcd — WRDS's documented approximation, cross-tabbed against the SIZ universe over the full 1963–2024 overlap:

  • shrcd: the common-stock screen is sharetype='NS' AND securitytype='EQTY' AND securitysubtype='COM' AND usincflg='Y', and within it issuertype ACOR → 10, CORP → 11. Agreement 99.9974%.
  • exchcd: gated on conditionaltype='RW' AND tradingstatusflg='A', then primaryexch N/A/Q → 1/2/3. The cross-tab is perfectly diagonal — the two tapes never name different listed exchanges.
  • Anything the screens do not recognise gets NaN, never a code. This is the deliberate part: SIZ's exchcd = 0 means "not on a listed exchange", which is a narrower claim than "this tape uses a venue SIZ never coded" (ARCA, BATS, …). Inventing a 0 would be a fabricated fact.

The daily query is an asymmetry worth understanding. The monthly path stages a faithful copy of the tape and renames in normalize_monthly; the daily path aliases in SQL, via CIZ_DAILY_SELECT — (raw expression, canonical name) pairs kept as data rather than one SQL string, so the ordering contract with crsp_daily.DAILY_COLUMNS is something a test can check instead of parse:

CIZ_DAILY_SELECT = (
    ("permno", "permno"),
    ("dlycaldt", "date"),
    ("dlyret", "ret"),
    ("dlyretx", "retx"),
    ("CASE WHEN dlyprcflg = 'BA' THEN -dlyprc ELSE dlyprc END", "prc"),
    ("dlybid", "bid"), ("dlyask", "ask"),
    ("dlylow", "bidlo"), ("dlyhigh", "askhi"),
    ("dlyvol", "vol"), ("shrout", "shrout"),
    ("dlycumfacpr", "cfacpr"), ("dlycumfacshr", "cfacshr"),
)

Two reasons for the asymmetry: the chunked fetch pins DAILY_SCHEMA and has no normalize hook, and carrying ~35 unused native columns through a 108M-row file is the one place where that would cost real disk. The payoff is that the staged daily parquet, the merge SQL, the manifest's columns list and the DuckDB crsp_dsf table are identical under both tapes, so every daily consumer downstream (Ch 8, 9, 10) is tape-blind.

Delisting semantics — the single most consequential difference, and the reason the class carries two flags rather than one method:

  • apply_delisting_overlay = False. CIZ's mthret already contains the delisting payoff: the payment arrives as an extra daily row on stkdelists.deldlydt and is compounded into the month. Applying the SIZ delisting overlay would double-count it. delist_events still returns stkdelists (renamed onto permno/dlstdt/dlret/dlstcd) so dlret can be reported, but nothing applies it — ret_x_dl == ret.
  • dlstcd is always NaN under CIZ. SIZ's one numeric delisting code is replaced by four categorical reasons (delactiontype, delstatustype, delreasontype, delpaymenttype); no mapping onto SIZ's integers has been verified, so the package does not invent one. The column is emitted anyway so the frame has one shape under both tapes, and the four reason columns ride along.
  • daily_delist_events returns None, always — there is nothing for betas._insert_matlab_dlret_rows to place (Ch 10).

needs_name_window = False. msf_v2 carries the as-of security-info columns on every row, so there is no separate window table to join, and — checked, not assumed — msf_v2 is not itself restricted to stksecurityinfohist windows. link_grid therefore applies the shrcd 10/11 screen but no window restriction: re-imposing one would silently drop the delisting months from the Gibbs expansion grid.

Not available under CIZ: msf_v2 has no monthly quote columns (bid/ask/bidlo/askhi), so the monthly spread cannot be built at all.

crsp_source_for(config) -> CRSPSource

The factory. Accepts an AssayConfig or a bare format string (which is what the tests and placeholder helpers use), lower-cases it, and raises ValueError on anything outside CRSP_FORMATS. A module-level assert keeps CRSP_FORMATS in step with config.VALID_CRSP_FORMATS — config.py validates the field without importing this module, so that reading a config never pulls in pandas, and the assert is what stops the two lists drifting.

How the pipeline holds it

PipelineContext.source is constructed once from the config and threaded through every CRSP stage, monthly and daily. Three guards keep a build from mixing tapes:

  1. setup_database compares the requested format against the crsp_format key in the database's metadata table and refuses unless --full-refresh.
  2. The chunked daily fetch stamps source.name into the resume manifest (MANIFEST_VERSION 1 → 2), so an interrupted pull cannot resume against the other tape.
  3. transform_monthly gates the mseexchdates join on needs_name_window and the delisting overlay on apply_delisting_overlay (Ch 6) — not on a format string.

The CIZ path has been checked end to end against a full CIZ build.


ingest/crsp.py — monthly CRSP + aux

Module constants

CRSP_MONTHLY_SQL selects * from crsp.msf with date BETWEEN '{start_date}' AND '{end_date}'. CRSP_AUX_TABLES maps logical names to unfiltered SELECT * queries, including dsedelist (daily delisting), which the daily pipeline needs for dlret placement.

Both names are now backwards-compatible aliases for SIZ_MONTHLY_SQL and SIZ_AUX_TABLES in crsp_source.py; the live code path asks source.monthly_sql(config) / source.aux_tables instead, so a CIZ build gets msf_v2 and stkdelists through the same functions. fetch_crsp_monthly and fetch_crsp_aux_table take an optional source: CRSPSource and fall back to crsp_source_for(config).

generate_placeholder_monthly(config) -> pd.DataFrame

Signature — config: AssayConfig (uses sample_start for two month-end dates).

Returns — 2-row DataFrame: date, permno, ret, me, prc, shrout, siccd, shrcd, exchcd.

What it does — builds two month-end timestamps from sample_start and two fixed permnos. Dates are real Timestamps (not yyyymm ints) so pd.to_datetime in transforms behaves like a real extract. Demo mode only; see Placeholder mode above.

fetch_crsp_monthly(config, destination, *, wrds_client=None) -> Path

Signature

  • config — sample_start / sample_end / wrds_username.
  • destination — parquet path (pipeline: Data/staging/crsp_msf.parquet).
  • wrds_client — optional reuse; else WRDSClient(config.wrds_username).

Returns — destination after df.to_parquet(..., index=False).

What it does — pulls every column of the monthly stock file for the sample window (the date filter is in the SQL), and stages it as parquet.

    sql = CRSP_MONTHLY_SQL.format(
        start_date=f"{config.sample_start}-01-01",
        end_date=f"{config.sample_end}-12-31",
    )
    # ...
    with client.connect() as conn:  # pragma: no cover - requires live WRDS access
        df = conn.raw_sql(sql)
    # ...
    df.to_parquet(destination, index=False)
    # ...
    return destination

The SELECT * column set follows the live WRDS schema.

fetch_crsp_aux_table(table, destination, *, wrds_client=None) -> Path

Signature — table must be a key of CRSP_AUX_TABLES (msfhdr, msedelist, dsedelist, mseexchdates, stocknames, ccmxpf_lnkhist).

Returns — parquet path.

What it does — SELECT * with no date filter, write parquet. One function, parameterized by table name, serves all six tables; the fetch-crsp-aux stage pulls dsedelist along with the monthly tables so the daily transforms need no second WRDS round-trip for delistings. The demo-mode placeholder path writes empty typed frames in pipeline.py, not in this module.


ingest/crsp_daily.py — daily stock file

generate_placeholder_daily(config) -> pd.DataFrame

Signature — config: AssayConfig.

Returns — 2 permnos × 22 business days; columns match CRSP_DAILY_SQL (permno, date, ret, retx, prc, bid, ask, bidlo, askhi, vol, shrout, cfacpr, cfacshr). Seed np.random.default_rng(44). Demo mode only.

plan_daily_chunks

Signature — plan_daily_chunks(sample_start, sample_end, years_per_chunk=1) -> list[DailyChunk].

Returns — consecutive year ranges covering the sample window, the last one truncated at sample_end so the union is exactly the window the single query used to cover. Each DailyChunk knows its start_date / end_date for the SQL and its part_name for staging.

fetch_crsp_daily(config, destination, *, wrds_client=None) -> Path

Signature — config, destination, plus keyword-only wrds_client, connect, years_per_chunk=1, resume=True, keep_parts=False, max_attempts=3, retry_wait=30.0, sort_output=True, merge_memory_limit="4GB".

Returns — parquet path. 1925–2024 is ~108M rows / ~2 GB and takes the best part of an hour, essentially all of it network.

What it does — one dated query per year range, each staged as its own parquet part under <destination stem>_parts/, then merged into destination. Only one year is in memory at a time, and a pull that dies part way through keeps its finished parts: rerunning skips them and resumes at the first missing chunk. Parts land through a temp name and os.replace, so a killed process never leaves a part that looks complete. A manifest.json records the plan the parts were fetched under; parts written for a different sample window, chunk size or query — or by a fetch that already finished and stamped completed_at — are discarded rather than merged.

Each chunk is coerced onto a pinned arrow schema (DAILY_SCHEMA: permno int64, date string, the other eleven float64) instead of letting each year's dtypes be inferred, because an early year with no quotes at all would otherwise produce a part that will not concatenate with its neighbours. The merged file is sorted by (permno, date): chunks arrive year-major, which is not the order the single-shot pull happened to return, and every consumer sorts on those keys anyway. The sort runs in DuckDB under a 4 GB memory_limit and spills into the parts directory — unbudgeted it sorts all 108M rows in memory and peaks at 28 GB, which would undo the point of chunking.

        sql = sql_template.format(start_date=chunk.start_date, end_date=chunk.end_date)
        LOGGER.debug("CRSP DSF SQL (chunk %s): %s", chunk.label, sql.strip())
        t0 = time.perf_counter()
        df = _run_chunk_query(
            session, sql, chunk, max_attempts=max_attempts, retry_wait=retry_wait
        )
        table = _chunk_to_arrow(df)
        del df
        _write_part(table, part)

The query does not fetch openprc or numtrd; no daily transform uses them. Delistings arrive via the aux dsedelist table, not this module. The staged file has the same schema and contents a single-query pull would produce; this was confirmed at full scale against the real 107,663,470-row extract.


ingest/compustat.py — funda / fundq

The fetch helpers read the variable names from the CSV named by AssayConfig.compustat_variables (default: the packaged ingest/data/compustat_variables.csv, generated from the constants ANNUAL_VARS / QUARTERLY_VARS: 82 annual and 40 quarterly names), validate them against information_schema, and add a datadate BETWEEN sample window to the SQL. 'All' selects *. The list is MATLAB's COMPUSTAT Variable Names.csv plus a few names it lacks, among them noncontrolling interest (mib, mibq) and quarterly R&D (xrdq), which the panel carries for your own signals (Ch 7).

_validate_columns / _get_table_columns / _build_*_query

Signatures

  • _validate_columns(requested, available, table_name) -> set[str] — logs and drops missing names.
  • _get_table_columns(conn, schema, table) -> set[str] — lowercased information_schema names.
  • _build_annual_query(config, variables=None, available_cols=None) -> str
  • _build_quarterly_query(...) — same idea; always forces gvkey, datadate (and rdq quarterly).

Returns — SQL strings with sorted column lists and INDL/STD/C/D filters.

What it does — intersects the requested names with the table's columns. The fetch stages resolve AssayConfig.compustat_variables with resolve_variables_file, read it with read_variables_file (columns Annual,Quarterly; blanks dropped, names trimmed and lower-cased) and pass the list as variables=; variables='All' builds SELECT *. Calling fetch_compustat_* without variables= still uses the constants. Names that match no column are dropped with a warning rather than failing the fetch. To change the list, copy the packaged CSV, edit it, and point compustat_variables at the copy (aa set-params --compustat-variables PATH).

fetch_compustat_annual / fetch_compustat_quarterly

Signature — config, destination, optional wrds_client, optional variables list.

Returns — parquet path.

What it does — connect → _get_table_columns → build SQL → raw_sql → parquet, reusing one connection for the schema probe and the fetch. Logging reports row/col counts and elapsed time.

fetch_compustat_columns / parse_variable_names

Signatures

  • parse_variable_names(text) -> list[str] — "xrd, MIB" → ["xrd", "mib"]: split on commas and spaces, lower-cased, de-duplicated; a name that is not a letter followed by letters, digits or _ raises ValueError.
  • fetch_compustat_columns(config, destination, *, wrds_client, freq, columns) -> Path — freq is "annual" (comp.funda) or "quarterly" (comp.fundq).

What it does — downloads only columns plus the identifiers (ANNUAL_KEY_COLS = gvkey, datadate, fyear, fyr; QUARTERLY_KEY_COLS = gvkey, datadate, rdq, fyearq, fqtr), with the same row filters and sample window as the build's fetch (_select_from). Unlike the build's fetch, which drops unknown names with a warning, a name the table does not have raises ValueError before anything is downloaded. Used by aa add-compustat-vars (next section).

generate_placeholder_annual / generate_placeholder_quarterly

Signature — config: AssayConfig.

Returns — small deterministic frames (seeds 42 / 43; mib, mibq and xrdq draw from their own seeds 142 / 143, so adding them left the other columns' values unchanged): 2 gvkeys × up to 3 years annual; 2 gvkeys × 4 quarters. Enough columns for transform smoke tests, not the full ANNUAL_VARS set.

Adding your own Compustat variables after the build

The build fetches a fixed list of Compustat columns and carries a fixed set of them onto ccm_panel (Ch 7). To use another one, say R&D expense xrd for your own signal, you do not need to rebuild the database:

aa add-compustat-vars --annual xrd
aa add-compustat-vars --annual xrd,dvt --quarterly xrdq   # several at once
import assayinganomalies as aa
aa.add_compustat_vars(annual="xrd")          # returns an AddVarsReport
xrd = aa.load(["xrd"])                       # an annual column: values in June only
xrd_m = aa.load(["xrd"], fill_annual=True)   # each June value through the next May

What happens (compustat_extras.add_compustat_vars):

  1. Checks, offline. The database must be built (ccm_panel). Each name is checked against ccm_panel and against what the build writes (RESERVED_PANEL_COLUMNS: the annual and quarterly panel columns, every column in stage_registry.COLUMN_TO_STAGE, fin_firm and the Compustat identifiers). A name already there is refused: names are kept as they are in Compustat (--annual xrd gives a column xrd), so the column would overwrite one the build wrote. The exception is a name an earlier run of the command added: it is downloaded again and replaced. xrdq, mib and mibq are already on the panel (Ch 7). An annual name also needs a database with the June-only annual layout (Ch 7): on one built before it the command stops with aa.AnnualLayoutError and names the rebuild, aa setup-database --start-from transform-compustat. A quarterly name is still added.
  2. The sample. The rows are the build's: the years sample_start..sample_end, with "latest" read from metadata.sample_end_resolved, so the new column ends where the panel does.
  3. One WRDS login (one Duo push), then a check of every name against the funda / fundq column lists. An unknown name stops the command before any download.
  4. Download only those columns and the identifiers into Data/staging/compustat_extra_funda_raw.parquet / compustat_extra_fundq_raw.parquet (a few minutes; the files hold every column the command has added, not only this run's).
  5. Align like the build's own columns, through the ccm_link table: annual columns like at (available at the end of June after the fiscal year and stored on that June row only, missing in the other eleven months and in a year without a filing; aa.load(..., fill_annual=True) or aa.fill_months gives the June-to-May values, Ch 12), quarterly columns like ibq (placed at the RDQ month, forward-filled until two months past the last announcement).
  6. Write the columns onto the end of ccm_panel in one DuckDB transaction (db.writer.add_columns_from_frame); every other column and the row count are unchanged.
  7. Record the names in the database's config table (compustat_extra_vars), what this run added in metadata.compustat_extra_vars_applied, and rewrite the run manifest (execution.command = "add-compustat-vars"; scientific.settings.compustat_extra_vars, so the database's scientific_id changes; it is absent for a database with no added columns).

The recorded names are not a set-params setting, and aa show-config lists them under its settings. A later aa setup-database, also with --full-refresh, fetches them with the build's own Compustat columns and transform-compustat carries them onto the panel again; a rebuild that does not refetch takes them from the command's staging files. Columns of other types than numbers (names, codes) are refused. Do not run the command while a build or another command writes the database: DuckDB has one writer.


ingest/ff_factors.py — Fama–French factors

Factors come from WRDS (ff.factors_monthly, ff.fivefactors_monthly, ff.factors_daily), already in decimals, rather than from the zip files on the Ken French website. The series are the same, but WRDS can lag the website by a few months at the end of the sample. The monthly factors land in DuckDB ts_data; read them with, e.g., aa.load(['mktrf'], panel=False, table='ts_data').

_to_month_end(ts) -> pd.Series

Signature — ts: pd.Series date-like.

Returns — month-end normalized datetimes (MonthEnd(0) then .normalize()).

What it does — WRDS often stores factor months as month-start, so the date key is moved explicitly to the month-end Timestamp that ccm_panel uses.

def _to_month_end(ts: pd.Series) -> pd.Series:
    dt = pd.to_datetime(ts, errors="coerce")
    return (dt + pd.offsets.MonthEnd(0)).dt.normalize()

fetch_ff_monthly(config, *, wrds_client=None) -> pd.DataFrame

Signature — config supplies the sample window; optional wrds_client.

Returns — DataFrame columns date, mktrf, smb, hml, rf, umd, smb2, rmw, cma (decimals, month-end date). mktrf is the excess market return. Pipeline writes this to DuckDB ts_data.

What it does

  1. Query FF3+UMD from ff.factors_monthly.
  2. Query FF5 as smb AS smb2, rmw, cma from ff.fivefactors_monthly.
  3. _to_month_end both sides; merge(..., how="left") so FF3 dates win and pre-1963 RMW/CMA stay NaN.
  4. Sort / drop duplicate months (keep="last").

The FF3 smb and the FF5 smb2 are kept as distinct columns.

    with client.connect() as conn:  # pragma: no cover - requires WRDS
        # Fetch FF3 + momentum
        sql_ff3 = FF3_MONTHLY_SQL.format(start_date=start_date, end_date=end_date)
        df_ff3 = conn.raw_sql(sql_ff3)

        # Fetch FF5 (rmw, cma)
        sql_ff5 = FF5_MONTHLY_SQL.format(start_date=start_date, end_date=end_date)
        df_ff5 = conn.raw_sql(sql_ff5)
    # ...
    df_ff3["date"] = _to_month_end(df_ff3["date"])
    df_ff5["date"] = _to_month_end(df_ff5["date"])
    df = df_ff3.merge(df_ff5, on="date", how="left")
    df = df.sort_values("date").drop_duplicates(subset=["date"], keep="last").reset_index(drop=True)

Only the factor columns are stored; regression helpers assemble factor matrices later.

Placeholder path for FF monthly lives in pipeline._stage_fetch_ff_factors (inline two-row DataFrame), not in this module.

fetch_ff_daily(config, *, wrds_client=None) -> pd.DataFrame

Signature — same pattern as monthly.

Returns — date, mktrf, smb, hml, rf, umd (calendar dates, not month-end).

What it does — single WRDS query to ff.factors_daily; sort / dedupe by date. Does not pull daily RMW/CMA/smb2: the current daily consumers (betas, daily transforms) only need FF3+UMD.


ingest/ken_french.py — FF 5×5 portfolios

Not part of setup_database. Used for FF replication examples via aa.load_ff25.

FF25_URL / load_ff25(url=FF25_URL, cache=None) -> pd.DataFrame

Signature

  • url — zip URL on the Ken French library.
  • cache — optional local path; read if present, else download and optionally write the raw CSV bytes.

Returns — DataFrame indexed by month-end date, columns = 25 portfolio names, returns as decimals; -99.99 codes masked to NaN.

What it does — download/unzip → scan for the monthly value-weighted block (header row with empty first cell and >20 names; data rows with 6-digit yyyymm) → stop at the first non-month row (annual block) → /100.

    for line in lines:
        cells = [c.strip() for c in line.split(",")]
        if header is None:
            if len(cells) > 20 and not cells[0]:
                header = [c for c in cells[1:] if c]
            continue
        if len(cells[0]) == 6 and cells[0].isdigit():
            # ...
        elif rows:
            break                      # end of the monthly value-weighted block
    # ...
    return out.mask(out <= -99.98) / 100.0

ingest/cz_anomalies.py — Chen–Zimmerman catalog

The catalog is downloaded from a Chen–Zimmerman release on Hugging Face; the run manifest records which release, branch and commit each file came from. The package streams the wide signal panel (a parquet file) into DuckDB cz_anomalies and keeps the signal documentation in cz_signal_info.

The download half lives in its own module, ingest/cz_release.py; this module decides which local file to read and caches downloads.

Releases: CZ_RELEASES / parse_release_label / resolve_release

Chen and Zimmermann publish every release as a branch of the public Hugging Face dataset OpenSourceAP/CrossSection (they moved off Google Drive, which could not handle the download volume). CZ_RELEASES maps a release label to its branch, oldest first:

Label Branch Notes
2022.03 2022.03 Oldest
2022.04 2022.04
2023.08 2023.08
2024.08 2024.08
2024.10 2024.10
2025.10 2025.10
2026.10 Data-Release-2026.10 Newest the package knows

config.cz_release_version picks one, and must be in the table. parse_release_label accepts 2025.10, 2025-10 (the legacy 2022-03 label older configs and databases persist), 2025_10 and 202510, as text or integer, plus a bare year when only one release has it (2023) and 2022 for 2022.03 (as openassetpricing reads it). An unknown or ambiguous label raises ValueError listing the known ones.

None (the default) means the newest release on Hugging Face, which only the network can say. resolve_release(None) reads the branch list (GET https://huggingface.co/api/datasets/OpenSourceAP/CrossSection/refs, which gives each branch's commit) and takes the newest branch named YYYY.MM or Data-Release-YYYY.MM that is 2022.03 or later (releases_on_branches). Other branches (main, upload-test, Test-Data-2026.10, which holds mixed-vintage test data) and the older 2020–2021 layouts never qualify. A release newer than the table is used too, and logged as such. If the branch list cannot be read or holds no release, the newest entry of the table is used with a warning, so a build can still find that release's cache offline. Because the default follows Hugging Face, a rebuild after a new release reads the new one; pin a release for anything you want to reproduce.

resolve_release(label) returns a CZRelease (label, branch, the commit the branch points to, and how the label was chosen). For an explicit label, a branch missing from Hugging Face raises NotFoundError. list_release_files reads the release's file list at that commit from the tree API (/api/datasets/…/tree/<commit>?recursive=true, paged through the Link header) and returns, per path, the size and the checksum: the sha256 for a Git LFS file such as the parquet (lfs.oid), the git blob sha1 for a plain file such as SignalDoc.csv (oid). This follows openassetpricing 0.1.0 (urls.py, hf_parse.py), reimplemented so the toolkit needs no extra dependency.

Downloads: download_file / download_release_file / verify_file

A file is downloaded from https://huggingface.co/datasets/OpenSourceAP/CrossSection/resolve/<commit>/<path>. No token is needed. For the large parquet, huggingface.co answers with a redirect to its CDN (*.hf.co), which requests follows, so both hosts must be reachable. Both files come from the same commit, so a signal panel and its SignalDoc never come from two states of a branch.

open_download classifies each response: HTTP 404, or 401/403 (the dataset is public, so a refusal means the file is gone), raises NotFoundError; HTTP 429 or 5xx raises RetryableDownloadError; any other error, or an HTML page where the file should be (a proxy or captive portal), raises DownloadError. All are DownloadErrors, and a production build never substitutes data for a failed download.

download_file then streams the file to <name>.part and renames it once complete, so an interrupted download never leaves a file that looks complete. On the way it:

  • retries a dropped connection, a timeout, a broken chunked transfer, HTTP 429/5xx and a body that ends short of its Content-Length — five attempts in all, waiting 5, 15, 45 and 120 s (each ±20 %) in between and logging each retry at WARNING. A not-found answer is never retried;
  • resumes: each retry sends Range: bytes=N-, where N is the size of the .part. A 206 whose Content-Range starts at N is appended; a 200 means the server ignored the range, so the .part starts over. The .part survives a network failure, even after the last attempt, so the next run picks it up; it is deleted only when the answer is rejected (not found, a web page), the final size check fails or the checksum does not match;
  • logs progress at INFO about every 256 MB (MB done / total, MB/s), so a 2 GB download shows signs of life.

download_release_file passes verify_file as the check run on the complete .part before the rename: the size must match the tree API's, then the sha256 (LFS) or the git blob sha1 (the sha1 of b"blob <size>\0" followed by the bytes, which is what git hash-object computes). A mismatch raises ChecksumError and leaves nothing behind; it is not retried.

There is no support for tokens or mirrors: the file comes from the release's public Hugging Face branch or from you (below).

CZReleaseChoice: one release per stage

fetch-cz-anomalies creates one CZReleaseChoice and passes it to both write_cz_anomalies_table and fetch_cz_signal_info. It settles the release the first time it is needed and then keeps it: a configured label is known offline; with none, the newest release is looked up the first time its label is needed, which is only when no pinned or hand-placed file was found. The commit and the file list are fetched once, the first time either file must be downloaded, so the two downloads cannot straddle a change to the branch.

Local files and caches: find_local_cz_signals / find_local_signal_doc / download_cz_signals / ensure_cz_signal_doc

File Where Who writes it Release
signed_predictors_dl_wide*.parquet searched (below) you, by hand (from Hugging Face) not known from the file
signed_predictors_dl_wide*.csv searched you, by hand (unzipped, older releases) not known from the file
signed_predictors_dl_wide*.zip searched you, by hand (Google Drive era) not known from the file
cz_firm_char.zip searched you, by hand (older name) not known from the file
SignalDoc*.csv searched you, by hand not known from the file
cz_firm_char_<release>.parquet staging/ a download in the name
cz_firm_char_<release>.zip staging/ a download by an older version in the name
cz_signal_doc_<release>.csv staging/ a download in the name

A hand-downloaded file is searched for, recursively, in the same directories as the Gibbs file: <database dir>/staging/, <database dir>/, inputs/ of a source checkout, then the current directory. The first directory with a usable file wins; within one, a parquet beats a CSV, which beats a zip. A parquet must have PAR1 at both ends (an interrupted download does not), a signals CSV must be over 1 MB, a zip must open, and a SignalDoc's header must start with Acronym; anything else is skipped with a warning. Release caches are matched by exact name only, so a cache of another release is never read; with no release configured, the cache is looked for only once the stage has settled the release.

Downloads are cached under release-labelled names, so a signal panel and a SignalDoc from two different releases are never paired by accident. download_cz_signals downloads the parquet to the cache, verified. ensure_cz_signal_doc returns the release's cached SignalDoc or downloads it, verified, and checks its header.

resolve_cz_signals_source(config, db_path, *, source=None, download=True, release=None) -> Path

Preference order — explicit source → config.cz_signals_path (raises if the file is missing) → a hand-downloaded file (searched as above) → staging/cz_firm_char_<release>.parquet (or a .zip cached by an older version) → download when download=True. Steps 2–4 are find_local_cz_signals. A file you supply wins over the cache because supplying one is what the download error tells you to do. Its release cannot be read off the file, so the log says so.

find_local_signal_doc applies the same order to the SignalDoc: config.cz_signal_doc_path → a hand-downloaded SignalDoc*.csv → staging/cz_signal_doc_<release>.csv; fetch_cz_signal_info downloads the release's when it finds none.

The run manifest records the release each file came from (data_vintage.cz_release_resolved; unknown (...) for a file you supplied) and, for a file from a release, its branch and commit (data_vintage.cz_release_source; the commit is unknown for a file read from the cache, whose commit this run did not look up).

When the download fails: the preflight and the resume

fetch-cz-anomalies is stage 23 of 24, just before finalize, so on a fresh build it runs hours after the first WRDS query, and nothing after it depends on it. setup_database runs a CZ preflight (pipeline._preflight_cz) before stage 1, and it is offline: when fetch-cz-anomalies is planned and the run is not --demo, it calls cz_release_label, which raises on a bad cz_release_version (a config error, so the run stops there), and logs, for the signals and the SignalDoc, the local file it found (Found CZ signals file: …) or that the stage will read the release cache or download one. A pin naming a missing file raises there too. It never touches Hugging Face, not even to find the newest release; the stage does that itself. pipeline.rebuild runs the same preflight.

If the download fails at stage 23, the stage raises NonFatalStageError (Ch 4): it is recorded as failed-nonfatal, no cz_anomalies table is left behind, and the SignalDoc step is skipped. A SignalDoc failure after the zoo has loaded is non-fatal the same way and drops the zoo as well: the database never holds cz_anomalies without cz_signal_info, or the reverse. finalize still runs, and the build ends with

Build finished; 1 stage(s) did not complete: fetch-cz-anomalies.
- fetch-cz-anomalies: Could not download the CZ 2026.10 signals: ... timed out ...
  To continue: download signed_predictors_dl_wide.parquet (under 'Firm Level
  Characteristics/') from
  https://huggingface.co/datasets/OpenSourceAP/CrossSection/tree/Data-Release-2026.10
  ... If a firewall blocked the download, allow huggingface.co and *.hf.co ...
  Then resume without repeating the WRDS stages:
  `aa setup-database --start-from fetch-cz-anomalies`.
Everything else in the database is usable.

and exit code 0. A failure to read a file already on disk (a pinned path, a file placed in staging, the zip extraction) is reported as Could not read the local C-Z file … with a hint to check the file and the free space in staging, not to download it again. Until the stage completes, aa.load_cz_anomalies and the protocol stop with cz_anomalies is not in <db>; the C-Z stage did not complete. Fetch it with aa setup-database --start-from fetch-cz-anomalies.

Every CZ download error names the ways out (cz_manual_hint):

  • save signed_predictors_dl_wide.parquet (from the release's Hugging Face branch, under Firm Level Characteristics) under its own name in any of the searched directories, or keep it anywhere and pin it with aa set-params --cz-signals-path <file> (for the SignalDoc: save SignalDoc.csv the same way, or --cz-signal-doc-path <file>);
  • or, if a firewall blocked the download, allow huggingface.co and *.hf.co;
  • then resume without repeating the WRDS stages: aa setup-database --start-from fetch-cz-anomalies. Since the stage is now 23 of 24, that runs only fetch-cz-anomalies and finalize.

_cz_file_for_duckdb(source, staging) -> Path

A context manager that yields a parquet or plain CSV DuckDB can read. A parquet or CSV source is yielded as is. For a zip, it picks the first .csv member, checks that staging has room for its uncompressed size (~8 GB; shutil.disk_usage), streams it to staging/.cz_extract_<zip stem>.csv with ZipFile.open + shutil.copyfileobj, and deletes that file on exit, whether the load worked or not. DuckDB's own zip:// paths are not used: they need the community zipfs extension, which a build does not install, and without it DuckDB reports "No files found that match the pattern".

_cz_read_sql(source) -> str

Returns — DuckDB read_parquet(...) fragment for a parquet, read_csv(...) for a plain CSV; the path is written with forward slashes and single quotes doubled, so Windows paths and paths with a ' work.

Why it matters — production loads never materialize the panel in pandas.

write_cz_anomalies_table(...) -> dict

Signature — config, db_path, optional source, download, release (the stage's CZReleaseChoice).

Returns — stats dict (rows, permnos, columns, signals, date span, source path).

What it does

  1. Resolve source; for a zip, extract the CSV with _cz_file_for_duckdb (the extraction spans both DuckDB statements); DESCRIBE columns; lowercase map; require permno and yyyymm or date.
  2. Skip keys and any pre-existing price/streversal/size (always rebuilt).
  3. CREATE TABLE cz_anomalies AS — filter sample yyyymm, restrict to ccm_panel permnos, TRY_CAST signals to DOUBLE, LEFT JOIN ccm_panel for -abs(prc), -ret, -me.

The result is a long table, one row per (date, permno) and one column per signal, built by streaming the parquet (or CSV) through DuckDB rather than loading it into memory. Price, STreversal and Size are not distributed in the Chen–Zimmerman release (they are built from CRSP, which is WRDS-licensed), so they are always rebuilt from ccm_panel with the signs shown below.

        CREATE TABLE cz_anomalies AS
        WITH raw AS (
            SELECT * FROM {read_sql}
        ),
        filtered AS (
            SELECT
                {date_expr} AS date,
                TRY_CAST(raw."{pcol}" AS BIGINT) AS permno,
                {signal_select}
            FROM raw
            WHERE {date_filter}
              AND TRY_CAST(raw."{pcol}" AS BIGINT) IN (
                    SELECT DISTINCT permno FROM ccm_panel WHERE permno IS NOT NULL
              )
        )
        SELECT
            f.date,
            f.permno,
            ...
            -abs(c.prc) AS price,
            -CAST(c.ret AS DOUBLE) AS streversal,
            -CAST(c.me AS DOUBLE) AS size
        FROM filtered f
        LEFT JOIN ccm_panel c
          ON f.permno = c.permno
         AND f.date = last_day(CAST(c.date AS DATE))

fetch_cz_anomalies(config, db_path) -> pd.DataFrame

What it does — the pandas path, for small and test sources. If the source is

200MB, it delegates to write_cz_anomalies_table and returns a schema-only empty frame (LIMIT 0); else pandas read → month-end dates → sample filter → permno filter → _add_crsp_derived_signals. Prefer write_cz_anomalies_table in production (the pipeline does).

_add_crsp_derived_signals / _get_ccm_panel_permnos / _month_end

Pandas-path helpers: pull prc/ret/me from ccm_panel, form price = -abs(prc), streversal = -ret, size = -me, merge on month-end (date, permno). The DuckDB writer inlines the same expressions in SQL.

generate_placeholder_cz_anomalies(config, db_path) -> pd.DataFrame

Returns — up to 10 ccm_panel permnos × 3 months × a short list of NA signal columns (bm, mom12m, size, …).

fetch_cz_signal_info / _normalize_signal_info / _generate_placeholder_signal_info

What they do — optional config.cz_signal_doc_path pin → else the configured release's own SignalDoc.csv (ensure_cz_signal_doc: cached as staging/cz_signal_doc_<release>.csv, else downloaded) → rename dotted columns → keep Cat_Signal == 'Predictor' → lowercase acronym plus acronym_cased → ensure Price/STreversal/Size metadata rows exist. The result is one normalized table, cz_signal_info. acronym_cased keeps the CamelCase acronym, which orders and labels signals in the anomaly zoo even though DuckDB column names are lowercase.


ingest/__init__.py

Re-exports WRDSClient, submodules cz_anomalies and compustat, and FF25_URL / load_ff25. CRSP / FF factor fetchers are imported by the pipeline directly from their modules, not via package __all__.


Small helpers

Name Module Note
_get_username / _get_password / _can_prompt wrds_client.py Credential resolution; see WRDSClient
_month_end cz_anomalies.py Same month-end idea as ff_factors._to_month_end
_staging_dir / _cached_cz_parquet_path / _cached_signal_doc_path / _find_cached_signals / _find_cached_signal_doc cz_anomalies.py Staging paths (release-labelled caches)
cz_release_label / cz_manual_hint cz_anomalies.py The configured release as a label; the "what to do" text every CZ download error carries
_generate_placeholder_signal_info cz_anomalies.py Five-row docs stub when a --demo download fails