Chapter 12 — Data access and signal I/O¶
Part III of the assayinganomalies tutorial. Prerequisite chapters: 1, 2, 3, 4, 5–11. Python modules covered:
data_access.py,signal_io.py.
What this chapter answers¶
- What happens when you call
aa.load(['R12_2'])— from the field name throughbuild_select_statement, DuckDB, and the post-query index reshape — and how that long panel compares to a widenMonths × nStocksmatrix. - When to use
panel=True(default,ccm_paneland other(date, permno)tables) versuspanel=False(ts_dataand other date-only series), and whatwide=Truedoes if you want a matrix layout back. - Why an annual Compustat column comes back with values in June only, and how
fill_annual=Trueandaa.fill_monthsturn it into monthly values. - How Chen–Zimmerman and NMV anomaly tables are loaded and documented
(
load_cz_anomalies,get_cz_signal_info,load_nmv_anomalies, …). - How proposed-signal CSVs become
(date, permno)panels (get_anomaly_signals, a left join onto the library's stock-month grid), and whatSignalInfoholds. - Where
yyyymmintegers (thedatescolumn of a signal CSV) meet month-endTimestamps (storage) and why both directions must stay consistent.
Where this sits in the pipeline¶
Chapters 4–11 write DuckDB tables (ccm_panel, ts_data, cz_anomalies,
nmv_anomalies, tcosts, …). This chapter is the everyday read API:
analytics and the assay protocol pull data through here.
flowchart TB
subgraph writers ["Pipeline stages (Ch 4–11)"]
P["ccm_panel / ts_data / cz_anomalies / nmv_anomalies"]
end
DB[("Data/aa.duckdb")]
R["build_select_statement<br/>db/reader.py"]
M["DuckDBManager.query_df"]
L["aa.load<br/>data_access.py"]
subgraph consumers
AN["analytics sorts / FM (Ch 13–15)"]
PROTO["run_test_signal (Ch 16)<br/>get_anomaly_signals"]
end
P --> DB
L --> R --> M --> DB
AN --> L
PROTO --> L
PROTO --> SIG["signal_io.py"]
Each variable is a column of a SQL table; aa.load fetches one or more of them
by name.
Worked trace: aa.load(['R12_2']) end to end¶
12–2 month momentum, R12_2, is a column of ccm_panel.
Step 1 — call load.
aa.load(['R12_2']) passes no database path, so config defaults apply
(load_config().database_path, typically <project folder>/Data/aa.duckdb;
see Ch 1, Finding the project folder).
A missing or settings-only database raises DatabaseNotFoundError here rather than
being created empty.
Step 2 — load builds SQL.
With all defaults (panel=True, table=None, common_shares_only=True):
cfg = load_config()
db_path = Path(path) if path else cfg.database_path
stmt = build_select_statement(
fields,
filters=filters,
lag=lag,
universe=universe,
dates=dates,
panel=panel,
common_shares_only=common_shares_only,
table=table,
)
build_select_statement (in db/reader.py) resolves:
source_table = "ccm_panel"(becausepanel=Trueand no explicittable).- Selected columns:
date,permno(auto-prepended),R12_2. WHERE shrcd IN (10, 11)(US ordinary common shares filter onccm_panel).
Effective SQL (whitespace elided):
SELECT date, permno, R12_2
FROM ccm_panel
WHERE shrcd IN (10, 11)
Step 3 — DuckDB executes.
with DuckDBManager(db_path) as manager:
df = manager.query_df(stmt)
DuckDBManager.query_df runs the string and returns a pandas DataFrame (Ch 3).
Step 4 — index normalization (panel path).
if isinstance(df.index, pd.MultiIndex):
df.index = df.index.set_names(["date", "permno"])
elif {"date", "permno"}.issubset(df.columns):
df = df.set_index(["date", "permno"])
# ...
if wide and {"date", "permno"}.issubset(df.index.names):
return df.reset_index().pivot(index="date", columns="permno")
return df
Result shape: long panel, MultiIndex (date, permno), one column R12_2,
float64 values, date as month-end timestamps (pipeline invariant, Ch 3–6).
Matrix mental model: in a dense dates × permno matrix, R(t, i) is month
t, stock i. aa.load(['R12_2'])['R12_2'] holds the same cell as
panel.loc[(date_t, permno_i)]. To get a matrix:
wide = aa.load(["R12_2"], wide=True) # index=date, columns=permno
Or unstack: panel["R12_2"].unstack("permno").
data_access.py¶
load(fields, *, path=None, filters=None, panel=True, wide=False, lag=None, universe=None, dates=None, common_shares_only=True, table=None)¶
Signature
fields— column name(s) toSELECT, orMapping[alias, expr]forexpr AS alias. Shape: list/set ofstr, or dict. The legacy namesNYSEanddatesare accepted and mapped tonyse_flaganddate.path— DuckDB file; default fromAssayConfig.database_path.filters—{column: value}or{column: [values]}→ SQL=/IN.panel—True(default): read from panel tables, return MultiIndex(date, permno).False: read fromts_data(unlesstable=overrides), return date-indexed or flat DataFrame.wide— ifTrueand index is(date, permno), pivot todate × permnocolumns (matrix layout).lag,universe— accepted in the signature and forwarded tobuild_select_statement, but not implemented in SQL yet. Callers should lag in pandas.dates—(start_yyyymm, end_yyyymm)inclusive, translated to month-endBETWEENliterals in SQL.common_shares_only— defaultTrueaddsshrcd IN (10, 11)onccm_panelonly. PassFalsefor the full universe.table— override source table (cz_anomalies,nmv_anomalies,tcosts,ts_data, …).fill_annual(not in the heading above; keyword-only, defaultFalse) —Falsereturns annual Compustat columns as stored, with values in June only;Truefills them June to May. See the next section.
Returns
panel=True:DataFramewith MultiIndex["date", "permno"](names enforced even if DuckDB returns flat columns). Requested fields as columns; dtypes from DuckDB (typicallyfloat64for signals,datetime64[ns]dates,int64permno when present as column).panel=False: ifdatecolumn exists, coerce to datetime,set_index("date"), sort; else flat DataFrame with reset index.wide=True: pivoted matrix as above.
What it does
- Resolve config and database path.
- On the stock panel, check the fields against the annual columns
(
_annual_fields): a database without the June-only layout record is refused when any field reads one (AnnualLayoutError, next section), and withfill_annual=Truethe query goes through_load_filledinstead of the plain path below. - Call
build_select_statement— field normalization (dates→date,NYSE→nyse_flag), quote reserved words like"at", pick table, inject keys and filters. - Open DuckDB, run query, close (context manager).
- Branch on
panelfor index handling.
Column existence is not pre-validated in Python; unknown fields fail at SQL execution with a DuckDB error.
The long panel holds only the (date, permno) rows that exist in the table, so
it may omit stock-months that a dense matrix would carry as NaN; wide=True
reintroduces them as NaN only for dates and permnos that appear somewhere in the
result.
Annual Compustat columns and fill_annual¶
In ccm_panel an annual Compustat column (at, be, bm, gp, …, and any
column added with aa add-compustat-vars --annual;
data_access.annual_columns() lists them for a database) has a value only on
the row of the June in which its record becomes available. The other eleven
months are missing (Ch 7). aa.load returns
them that way unless asked otherwise:
d = aa.load(["gp", "at"]) # values in June only
m = aa.load(["gp", "at"], fill_annual=True) # each June value through the next May
signal = d["gp"] / d["at"] # a June-only signal
monthly = aa.fill_months(signal) # the same signal, every month June to May
The choice matters beyond convenience: a sort trades in every month in which its signal has values. A signal built from the default load trades each June and holds for the year; a filled signal is sorted and traded every month (Ch 13).
aa.fill_months(x, months=11) (analytics/sorts.py; MATLAB's
FillMonths) takes a Series or DataFrame indexed by (date, permno) and, for
each stock, lets a missing cell take the most recent non-missing value if that
value is at most months calendar months older.
- The limit counts calendar months, not rows: a month in which the stock has no row still counts.
- Only rows that exist are filled; no row is added. Values that are present are never changed. A DataFrame is filled column by column.
months=11is the annual case (June reaches the following May and stops, so a value never stands in for a later year without a record);2suits a quarterly value;0returns the input.- Numeric columns only (
TypeErrorotherwise); duplicate keys or dates that are not month-ends raiseValueError.
fill_annual=True applies aa.fill_months(…, 11) to each annual column
among fields. With no annual column among them it does nothing; for another
table, or with panel=False, it raises ValueError. Its rules:
- Plain column names are filled, expressions are not. A plain annual
column is filled, also under an alias (
{"assets": "at"}). An SQL expression that mentions an annual column ({"gpa": "gp / at"}) raisesValueErrorwithfill_annual=True; load the columns and compute in pandas, or load with the default and applyaa.fill_monthsto the result. With the default, expressions go to SQL as before and are evaluated on the June-only values. - The provenance columns are not filled.
comp_datadate,comp_avail_date,be_sourceandbe_avail_datestay on the June row. - Order.
common_shares_onlyis part of the query, so it applies before the fill.filtersare applied after the fill, and withdates=the query starts 11 months before the window and is trimmed afterwards. So neither a filter nor the window changes a filled value: a filter on a column that changes within the year (sayexchcd) does not remove the June value the later months are filled from, and the first months of a window are filled from the June before it.
What a fill cannot recover. A stock with no panel row in the June of a record has no value from that record, filled or not, until its next June. This is rare (for example a stock that enters the panel a few months after the June). MATLAB, and versions of this package that stored the columns filled June to May, gave such a stock the record's values from its first month.
Quarterly columns (beq, ibq, sue, …) are stored filled month by
month and are not affected by fill_annual.
aa.AnnualLayoutError. A database built before annual columns were stored
in June only holds them filled June to May, and it carries no record of its
layout (metadata.annual_layout). Reading such a column as if it were
June-only would make an annual signal trade every month without any sign of
it, so aa.load raises AnnualLayoutError when a field is an annual or
provenance column, an expression that mentions one, or *, whatever
fill_annual is. Fields that involve no annual column load as before. The
message names the fix:
aa setup-database --start-from transform-compustat
which reruns the build from the Compustat merge on, from the extracts already
in Data/staging/ (no WRDS login). The same error stops
aa add-compustat-vars --annual on such a database, and the stages
compute-nmv-anomalies and validate-bm-hml stop with a RuntimeError that
names the same command. SQL you write yourself against
ccm_panel is not checked.
load_cz_anomalies(signals=None, *, path=None, dates=None, wide=False)¶
Signature
signals— iterable of column names, orNonefor all non-key columns frominformation_schema.dates— optional(start_yyyymm, end_yyyymm)passed through toload.wide— pivot to matrix layout.
Returns — MultiIndex panel (date, permno) with requested CZ signal columns.
What it does
- If the database has no
cz_anomaliestable (the build's C-Z stage did not complete, which no longer stopsaa setup-database), raiseMissingCZAnomaliesError: "cz_anomalies is not in; the C-Z stage did not complete. Fetch it with aa setup-database --start-from fetch-cz-anomalies." The protocol's zoo loader goes through here, so it stops with the same message. - If
signals is None, introspect thecz_anomaliescolumn list. - Delegate to
load(..., table="cz_anomalies", panel=True, common_shares_only=False)— the CZ table has noshrcd.
The table must already have been built by the pipeline; nothing is downloaded at
load time. Signal column names are lower-case. WRDS-restricted signals (price,
streversal, size) are added at ingest time (Ch 5), not in this loader.
list_cz_signals(*, path=None)¶
Signature — optional path for DuckDB file.
Returns — sorted list[str] of signal column names in cz_anomalies.
What it does — queries information_schema.columns, excludes date and
permno, orders by name.
get_cz_signal_info(signal=None, *, path=None)¶
Signature
signal— optional acronym (case-insensitive);Nonereturns all rows.
Returns — DataFrame with documentation columns (acronym, Acronym,
Authors, Year, Journal, LongDescription, SampleStartYear,
SampleEndYear, StockWeight, LSQuantile, PortfolioPeriod, …) as loaded
from table cz_signal_info. A single-signal query returns a one-row DataFrame.
What it does
- Verify
cz_signal_infoexists; else raise with setup hint. - Filter by lowercase acronym or
SELECT * ORDER BY acronym.
describe_cz_signal(signal, *, path=None)¶
Signature — signal str, optional path.
Returns — multi-line human-readable str (acronym, description, citation,
sample years, weighting, LS quantile).
What it does — calls get_cz_signal_info(signal) and formats the non-null
fields.
load_nmv_anomalies(signals=None, *, path=None, dates=None, wide=False)¶
Signature — same pattern as load_cz_anomalies; default 23 NMV columns when
signals is None.
Returns — MultiIndex panel from table nmv_anomalies (built by the Ch 11
stage).
What it does — column discovery on nmv_anomalies, then load(..., table="nmv_anomalies", common_shares_only=False).
Merging your own gvkey data¶
Data keyed by Compustat gvkey (ESG scores, analyst data, hand-collected
firm characteristics) reaches the CRSP panel through the same link the build
uses. The build stores the cleaned CRSP-Compustat link as the ccm_link
table (columns gvkey, permno, permco, linkdt, linkenddt, linktype,
linkprim; LC/LU links only, open links closed at the end of the sample; see
Ch 7). It has no date column, so read it directly rather than through
aa.load, which always selects date:
import duckdb
import pandas as pd
import assayinganomalies as aa
db = aa.load_config().database_path
with duckdb.connect(str(db), read_only=True) as con:
link = con.execute("SELECT * FROM ccm_link").df()
mine = pd.read_csv("my_esg_scores.csv", dtype={"gvkey": str}, parse_dates=["score_date"])
linked = aa.merge_on_link(mine, link, date_col="score_date")
merge_on_link keeps the rows whose score_date falls inside a link window
(linkdt <= score_date <= linkenddt, both ends inclusive), adds an int
permno, and drops rows no link covers. Your own columns are left as they are,
and none of the link's columns are added. A gvkey linked to two permnos on the
same date gives one row per permno. gvkey_col= names a gvkey column with
another name; gvkeys are compared as strings, so keep their leading zeros (the
dtype={"gvkey": str} above).
To put the result on the monthly panel, map score_date to the month-end
your signal should first be usable in, then index on (date, permno):
linked["date"] = linked["score_date"] + pd.offsets.MonthEnd(0)
signal = linked.drop_duplicates(["date", "permno"], keep="last").set_index(["date", "permno"])["esg"]
A raw ccmxpf_lnkhist frame (from WRDS) can be cleaned first with
aa.clean_ccm_link(raw, config); the result is what ccm_link holds.
signal_io.py¶
SignalInfo (dataclass)¶
Signature — dataclass fields (defaults empty string unless noted):
| Field | Notes |
|---|---|
Authors |
author names |
email |
contact email |
PaperTitle |
paper title |
SignalName |
long signal name |
SignalAcronym |
acronym |
fileLink |
path/URL to signal CSV |
extras |
bag for unknown form keys |
The PascalCase field names are kept because the LaTeX/report templates use them.
Properties (read-only aliases): authors, paper_title, name, acronym,
file_link — snake_case views of the PascalCase fields.
Methods
to_dict()—asdictplus merge ofextrasinto top level.from_mapping(data)— normalize dict/SignalInfo; accepts nested{"info": {...}}fromSignalTester; maps snake_case and legacy key spellings; unknown keys →extras.
Returns — SignalInfo instance.
What it does — holds protocol metadata carried through run_test_signal /
reporting (Ch 16–19). One SignalInfo describes one signal per run; to test
several, loop in Python.
MPE_DEFAULT_SIGNAL_INFO¶
Signature — module-level constant SignalInfo(...).
Returns — frozen default metadata for the Monetary Policy Exposure example
(Authors, email, paper title, signal name, acronym MPE, fileLink='mpe.csv').
Report and LaTeX labels are built from these strings, so changing them changes the generated report text (not any numbers).
default_mpe_signal_info(file_link=None)¶
Signature — optional file_link str or Path.
Returns — new SignalInfo copy with overridden fileLink when provided.
get_signal_info(source=None, *, file_link=None)¶
Signature
source—None→ MPE defaults; path to form CSV →_parse_form_csv; mapping orSignalInfo→from_mapping; bare str path that is not a file → treated asfileLinkonly.file_link— override after resolve.
Returns — SignalInfo.
What it does — dispatches on the type of source; always applies the
file_link override when supplied. The CSV parser is best-effort: it accepts a
wide one-row layout or a two-column key/value layout, and an empty CSV yields
the MPE defaults.
_parse_form_csv(path)¶
What it does — read CSV; if one row with known headers → from_mapping row;
elif ≥2 columns → zip col0/col1 as key/value dict; else defaults with
file_link=str(path).
Grouped in Small helpers below; behavior summarized here because it defines real parsing logic.
yyyymm_to_month_end(yyyymm)¶
Signal CSVs and dates= arguments use YYYYMM integers; storage uses month-end
timestamps. This function converts the former to the latter.
Signature — yyyymm int, float, or str coercible to int.
Returns — pd.Timestamp at month-end (e.g. 197501 → 1975-01-31).
What it does — split year/month, validate month 1–12, Timestamp(day=1) +
MonthEnd(0). Matches _yyyymm_to_date_literal in db/reader.py for SQL
bounds. Any CSV signal aligned to the library grid depends on this conversion.
month_end_to_yyyymm(ts)¶
Signature — any value parseable by pd.Timestamp.
Returns — int YYYYMM (year * 100 + month), the inverse of
yyyymm_to_month_end.
get_anomaly_signals(file_name, permno_column="permno", dates_column="dates", *, anomaly_names=None, dates_format="yyyymm", panel_index=None)¶
Signature
file_name— local CSV path (URLs are not supported).permno_column,dates_column— header names or zero-based column indices.anomaly_names—None/empty → all non-key columns; int → column index; str → single column; sequence of ints → indices; sequence of str → names.dates_format—"yyyymm"(default) orstrftimepattern forpd.to_datetime.panel_index— optional full(date, permno)MultiIndex; result is left-reindexed onto it (NaN outside CSV support).
Returns — tuple (panel, labels):
panel— DataFrame, MultiIndex(date, permno), month-end dates, float signal columns.labels— list of column name strings in order.
What it does
- Validate file exists.
- Resolve column names from header.
- Determine anomaly column list.
- Read CSV subset; convert dates via
yyyymm_to_month_endor custom format + month-end snap. - Coerce permno to int64; drop bad rows; sort; keep last on duplicate
(date, permno). - Build one Series per signal,
concatto panel. - If
panel_indexgiven,reindexonto the fulldates × permnogrid (a left join).
The output stays in long format — one column per signal, not a 3-D month × stock × signal array; analytics consume the Series directly.
load_signal_csv(file_name, *, signal_column=None, permno_column="permno", dates_column="dates", dates_format="yyyymm", panel_index=None)¶
Convenience wrapper for loading a single signal (the typical mpe.csv
workflow).
Signature — same column/date options as above; optional signal_column name.
Returns — pd.Series with MultiIndex (date, permno), named after the signal.
What it does — calls get_anomaly_signals with one column; if
signal_column is None, requires exactly one non-key column in the file.
Small helpers¶
_parse_form_csv(path)¶
Best-effort form CSV → SignalInfo; described under get_signal_info. Falls
back to MPE defaults rather than raising on unrecognizable layouts.
Thinking in panels versus matrices¶
The storage picture (dense nMonths × nStocks matrices vs the DuckDB (date, permno) panel) is in Ch 3. aa.load is the read-time side of that picture:
panel=True(default) → MultiIndex(date, permno)panel, matchingccm_panel.wide=True→ pivot to date × permno (the matrix layout).panel=False→ date-indexed DataFrame fromts_data(factors:mktrf,smb, …), a vector aligned with the month-end dates.