Chapter 3 — The DuckDB storage layer¶
Part II of the assayinganomalies tutorial. Prerequisite chapters: 1, 2. Python modules covered:
db/__init__.py,db/manager.py,db/reader.py,db/writer.py,db/cache.py,db/migrations.py.
What this chapter answers¶
- Why the package stores data as long DuckDB tables keyed by
(date, permno)rather than one densenMonths × nStocksmatrix per variable (the layout of much empirical-finance code). - How to picture the same return observation in both layouts (every later chapter assumes this translation).
- How
DuckDBManager,write_table, andbuild_select_statementfit between the pipeline writers andaa.load. - What the month-end date invariant is, where writers enforce it, and what
migrate_ts_data_monthly_dates_to_month_endrepairs on existing databases. - Where the SQL injection surface lives in
_quote_identifierandwrite_table.
Where this sits in the pipeline¶
Chapter 2 showed that setup_database fills Data/aa.duckdb and that everyday
analytics call aa.load. This chapter is the thin storage API those stages and
loaders share: open a DuckDB file, write a DataFrame as a table, compose a
SELECT, optionally migrate dates, and keep a JSON field-alias sidecar.
flowchart LR
PIPE["pipeline stages<br/>Ch 4–11"]
W["write_table<br/>db/writer.py"]
MIG["migrate_ts_data_...<br/>db/migrations.py"]
DB[("Data/aa.duckdb")]
CAT["aa.catalog.json<br/>db/cache.py"]
R["build_select_statement<br/>db/reader.py"]
M["DuckDBManager<br/>db/manager.py"]
LOAD["aa.load<br/>Ch 12"]
PIPE --> W
PIPE --> MIG
PIPE --> CAT
W --> M
MIG --> M
M --> DB
LOAD --> R
R --> M
M --> LOAD
Storage philosophies: wide matrices vs panels¶
The wide-matrix layout¶
A common way to hold a stock panel is one dense matrix per variable, with
rows = months, columns = stocks, aligned to shared dates (YYYYMM
integers) and permno vectors. Over a 1925–2024 CRSP sample that is a
1189 × 26746 matrix for ret, another for me, and so on. Missing
stock-months are NaN cells inside the rectangle — the matrix is dense in
memory even when most cells are empty early in the sample.
A single observation — permno 10006 in July 1963 returning 0.012 — is cell
(i, j) where dates[i] == 196307 and permno[j] == 10006.
What the package stores¶
The same observation is one row of a panel (primarily ccm_panel):
| date | permno | ret | me | … |
|---|---|---|---|---|
| 1963-07-31 | 10006 | 0.012 | 450.2 | … |
| 1963-07-31 | 10030 | −0.003 | 12.1 | … |
| 1963-08-31 | 10006 | 0.045 | 460.0 | … |
Keys are (date, permno). date is a calendar month-end timestamp, not a
YYYYMM int (see below). Only stock-months that exist are stored; there is no
all-NaN padding for stocks that were not listed yet.
Time series such as the Fama–French factors are rows of ts_data, keyed by
the same month-end date (no permno).
The pivot at read time¶
Analytics that want a months × stocks matrix call aa.load(..., wide=True),
which (after the SQL fetch) does a pandas pivot: index = date, columns =
permno (Ch 12). Until then, every pipeline stage and most analytics work on
the long form. Idiom map:
| Wide matrix | Long panel (df from aa.load) |
|---|---|
ret[t, :] — cross-section at month t |
df.xs(date, level='date') or groupby(level='date') |
ret[:, j] — one stock’s history |
df.xs(permno, level='permno') |
| row-wise NaN-mean over stocks | df.groupby(level='date')['ret'].mean() |
| one matrix per variable | aa.load(['ret', 'me']) → MultiIndex (date, permno) |
Hold this picture: a dense layout pays storage/IO up front for alignment; the panel layout stores only existing stock-months and pays a pivot only when matrix layout is needed.
The month-end date invariant¶
Monthly data uses month-end dates; returns are decimals.
The canonical monthly key is a timestamp at the last calendar day of the month
(1963-07-31 00:00:00), not an integer YYYYMM (196307). DuckDB/pandas joins
and BETWEEN filters are natural on dates, and every monthly table
(ccm_panel, ts_data, cz_anomalies, …) shares one clock. User-facing
arguments still accept YYYYMM integers and convert them.
Where it is enforced (writers, later chapters):
| Site | Role |
|---|---|
transforms/crsp_monthly.py |
After MSF filtering, date = yyyymm → MonthEnd |
ingest/ff_factors.py::_to_month_end |
WRDS FF dates (often month-start) coerced to month-end before ts_data load |
db/reader.py::_yyyymm_to_date_literal |
User dates=(196307, 201212) → SQL '1963-07-31' … '2012-12-31' |
db/migrations.py |
Idempotent repair if an older ts_data still has month-start keys |
analytics/sorts.py::_to_month_end |
YYYYMM timePeriod args → month-end Timestamps (Ch 13) |
Returns as decimals: every table stores 0.01 for a 1% return, not 1.0.
Package export: db/__init__.py¶
from .manager import DuckDBManager
from .cache import FieldCatalog, load_field_catalog, save_field_catalog
__all__ = ["DuckDBManager", "FieldCatalog", "load_field_catalog", "save_field_catalog"]
Re-exports the connection manager and the field-catalog helpers. write_table,
build_select_statement, and the migration are imported from their submodules
directly by pipeline.py / data_access.py and are not in this __all__.
db/manager.py — connection lifecycle¶
DuckDBManager¶
Signature
__init__(self, path: Path)— storepath; do not connect yet.- Context manager:
__enter__/__exit__. connection— lazyduckdb.DuckDBPyConnection.execute(sql, *params)— run SQL, discard result.query_df(sql)— run SQL, returnpandas.DataFrame.
Returns — the manager itself from __enter__; DataFrames from query_df.
What it does
Construction only records the path:
class DuckDBManager:
def __init__(self, path: Path):
self.path = Path(path)
self._con: duckdb.DuckDBPyConnection | None = None
Entering the context opens a file-backed connection and returning leaves it closed:
def __enter__(self) -> "DuckDBManager":
self._con = duckdb.connect(str(self.path))
return self
def __exit__(self, exc_type, exc, tb) -> None:
if self._con is not None:
self._con.close()
self._con = None
The connection property also connects on first use if nothing opened it yet
(lazy path used by some call sites that hold a manager without with):
@property
def connection(self) -> duckdb.DuckDBPyConnection:
if self._con is None:
self._con = duckdb.connect(str(self.path))
return self._con
def execute(self, sql: str, *params: Any) -> None:
self.connection.execute(sql, params)
def query_df(self, sql: str) -> pd.DataFrame:
return self.connection.execute(sql).df()
execute forwards *params to DuckDB’s parameterized API. query_df does
not take parameters — callers who need binds must use connection.execute
themselves (or interpolate carefully, as build_select_statement does today).
Concurrent access. DuckDB’s default file locking allows multiple readers
or one writer. Each with DuckDBManager(...) opens its own connection to the
same path. Pipeline stages run sequentially, so they do not collide. Two
processes writing Data/aa.duckdb at once will fail with a lock error — there
is no retry or pool in this class. Closing on __exit__ matters: a leaked
writer connection blocks the next stage.
db/writer.py — DataFrame → table¶
write_table(path, table, df, *, mode="append")¶
Signature
path— DuckDB file path.table— SQL table name (interpolated raw into SQL; see injection note).df—pandas.DataFramewhose columns become table columns.mode—"replace"(drop + create) or default"append"(create-if-missing empty clone, thenINSERT).
Returns — None.
What it does
def write_table(path: Path, table: str, df: pd.DataFrame, *, mode: str = "append") -> None:
with DuckDBManager(path) as manager:
manager.connection.register("tmp_df", df)
if mode == "replace":
manager.execute(f"DROP TABLE IF EXISTS {table}")
manager.execute(f"CREATE TABLE {table} AS SELECT * FROM tmp_df")
else:
manager.execute(f"CREATE TABLE IF NOT EXISTS {table} AS SELECT * FROM tmp_df WHERE 0")
manager.execute(f"INSERT INTO {table} SELECT * FROM tmp_df")
register("tmp_df", df) exposes the DataFrame as a temporary DuckDB relation
without a round-trip through Parquet. Replace mode is what the pipeline uses
for ccm_panel, ts_data, crsp_msf, and friends (Ch 4). Append mode’s
WHERE 0 trick creates an empty table with the same schema when the table does
not exist yet, then inserts.
Injection surface. table is not passed through _quote_identifier and is
not restricted to a allowlist inside write_table. Pipeline callers pass
constant strings ("ccm_panel", "ts_data", …). Do not thread unsanitized user
input into table.
mode="replace" rebuilds the whole relation: writing one column means
rewriting every column of that table.
db/reader.py — composing SELECTs¶
This module does not open DuckDB itself. aa.load (Ch 12) calls
build_select_statement, then DuckDBManager.query_df. The helpers below are
the entire SQL-construction surface.
Small helpers (grouped)¶
_yyyymm_to_date_literal(val)¶
What it does — parse 196307 → calendar month-end → SQL date literal
'1963-07-31', using calendar.monthrange so February is correct:
def _yyyymm_to_date_literal(val: int | str) -> str:
"""Convert a YYYYMM integer (e.g. 196307) to a SQL date literal like '1963-07-31'.
Uses month-end convention consistent with the rest of the codebase.
"""
import calendar
val = int(val)
year, month = divmod(val, 100)
day = calendar.monthrange(year, month)[1]
return f"'{year:04d}-{month:02d}-{day:02d}'"
This is the read-side half of the month-end invariant: user-facing APIs take YYYYMM integers; SQL speaks month-end dates.
_quote_identifier(name) and SQL_RESERVED_WORDS¶
def _quote_identifier(name: str) -> str:
"""Quote an identifier if it's a SQL reserved word."""
if name.lower() in SQL_RESERVED_WORDS:
return f'"{name}"'
return name
COMPUSTAT’s at (total assets) must become "at" or DuckDB parses AT TIME
ZONE. The SQL_RESERVED_WORDS frozenset is intentionally incomplete — enough for
CRSP/COMPUSTAT column names that collide with SQL keywords (date, order,
index, …).
SQL injection surface. Quoting is not escaping. If name is not in the
reserved set, it is spliced into SQL unchanged. A hostile field string such as
ret; DROP TABLE ccm_panel;-- would not be quoted and would break out of the
identifier position. Safe use today relies on trusted field names from the
catalog / caller. Parameterized identifiers are not available the way bound
values are; hardening would mean allowlisting [A-Za-z_][A-Za-z0-9_]* (and
always quoting) before interpolation.
_normalize_field_expr(expr)¶
def _normalize_field_expr(expr: str) -> str:
"""
Backward-compat field aliases for SQL expressions.
This keeps example code stable while the API settles.
"""
alias_map = {
"dates": "date",
"NYSE": "nyse_flag",
}
return alias_map.get(expr, expr)
The legacy names dates and NYSE map to the DuckDB columns date and
nyse_flag; this follows the original MATLAB toolkit, which used those
variable names. This is separate from FieldCatalog (below): the loader path
uses this hard-coded map, not the JSON sidecar.
build_select_statement(...)¶
Signature
fields— iterable of column names, orMapping[str, str]ofalias -> expression(expression is a column name today after normalize).filters— optional{column: value | sequence}→=orIN (...).lag— accepted, currently unused in the body.universe— accepted, currently unused in the body.dates— optional(yyyymm_lo, yyyymm_hi)→ month-endBETWEEN.panel— defaultTrue; chooses default table and key columns.common_shares_only— defaultTrue; addsshrcd IN (10, 11)onccm_panel.table— override source table; defaultccm_panelifpanelelsets_data.
Returns — a single SQL string (not executed here).
What it does (execution order)
- Normalize and quote selected expressions. Mapping form emits
expr AS alias; list form emits bare identifiers.
selected: list[str] = []
if isinstance(fields, Mapping):
for alias, expr in fields.items():
norm_expr = _normalize_field_expr(expr)
quoted_expr = _quote_identifier(norm_expr)
selected.append(f"{quoted_expr} AS {alias}")
else:
for f in fields:
norm_f = _normalize_field_expr(f)
selected.append(_quote_identifier(norm_f))
-
Pick the source table —
tableargument, elseccm_panel/ts_data. -
Ensure key columns for index construction in
aa.load. Panel tables (ccm_panel,cz_anomalies) always getdateandpermnoprepended if missing; pure time-series getsdateonly.
# Always include date and permno for panel data so we can set the index.
# Track unquoted names for membership check
selected_unquoted = {s.strip('"') for s in selected}
if panel or is_panel_table:
for key_col in ("date", "permno"):
if key_col not in selected_unquoted:
selected.insert(0, _quote_identifier(key_col))
else:
# For time-series tables, always include date for alignment.
if "date" not in selected_unquoted:
selected.insert(0, _quote_identifier("date"))
- Build
WHERE. Default common-share filter; then equality/INfilters (values via Pythonrepr); then dateBETWEENmonth-end literals.
# Default: US ordinary common shares only (shrcd 10 or 11)
if common_shares_only and panel and source_table == "ccm_panel":
clauses.append("shrcd IN (10, 11)")
if filters:
for key, value in filters.items():
quoted_key = _quote_identifier(key)
if isinstance(value, (list, tuple, set)):
values = ", ".join(repr(v) for v in value)
clauses.append(f"{quoted_key} IN ({values})")
else:
clauses.append(f"{quoted_key} = {repr(value)}")
if dates:
lo, hi = dates
lo_date = _yyyymm_to_date_literal(lo)
hi_date = _yyyymm_to_date_literal(hi)
clauses.append(f"{_quote_identifier('date')} BETWEEN {lo_date} AND {hi_date}")
if clauses:
sql_parts.append("WHERE " + " AND ".join(clauses))
return " ".join(sql_parts)
Example: build_select_statement(["ret", "me"], dates=(196307, 196308))
produces (whitespace collapsed):
SELECT date, permno, ret, me FROM ccm_panel
WHERE shrcd IN (10, 11)
AND "date" BETWEEN '1963-07-31' AND '1963-08-31'
That result set is the panel form of the matrix slice "rows 196307–196308 of
ret (plus me)", without NaN padding for absent listings. aa.load(..., wide=True) would then pivot toward the dense
matrix shape.
Filter values and injection. Column keys go through _quote_identifier
(same reserved-word-only behavior). Values use repr, which for strings emits
single-quoted Python literals that happen to be valid SQL strings in common
cases, but this is still not a bound parameter. Prefer trusted filter keys;
for hostile input, switch to connection.execute(sql, params).
Dead parameters. lag and universe are part of the public signature
(mirrored on aa.load) but never referenced in the function body. Lag/universe
logic, if any, belongs elsewhere today or is unfinished API.
Common-share filter at two levels. The build already filters to share
codes 10/11 at transform time when dom_com_eq is set; the default
shrcd IN (10, 11) at read time is a second, belt-and-suspenders filter on
ccm_panel. Pass common_shares_only=False to drop the read-time filter.
Every aa.load call goes through this function, so changing identifier
quoting, date literal conversion, or the default shrcd filter changes what
every loader returns.
db/cache.py — field catalog sidecar¶
FieldCatalog¶
Signature — @dataclass with fields: Mapping[str, str] (alias → column /
expression).
What it does — plain data holder. No methods.
cache_path(db_path)¶
Returns — db_path.with_suffix(".catalog.json"), so
Data/aa.duckdb → Data/aa.catalog.json.
Not in cache.py’s __all__, but used by load/save.
load_field_catalog(db_path) / save_field_catalog(db_path, catalog)¶
What they do
def load_field_catalog(db_path: Path) -> FieldCatalog:
path = cache_path(db_path)
if path.exists():
with path.open("r", encoding="utf-8") as fh:
data = json.load(fh)
return FieldCatalog(fields=data)
return FieldCatalog(fields={})
def save_field_catalog(db_path: Path, catalog: FieldCatalog) -> None:
path = cache_path(db_path)
with path.open("w", encoding="utf-8") as fh:
json.dump(catalog.fields, fh, indent=2)
The pipeline stage generate-field-catalog writes a small alias map (ret,
me, dates→date, NYSE→nyse_flag, …) via save_field_catalog (Ch 4).
When it goes stale / who reads it. aa.load does not call
load_field_catalog; aliases for loading live in _normalize_field_expr. As of
this writing, nothing under src/assayinganomalies/ calls load_field_catalog
except re-exporting it. The JSON file is therefore a write-mostly sidecar:
useful for a reader, but not on the numeric path today. If the catalog and
_normalize_field_expr drift apart, loaders follow the hard-coded map.
db/migrations.py — month-end repair for ts_data¶
_month_end_expr(col)¶
What it does — DuckDB expression: truncate to month start, add one month, subtract one day → last calendar day of the month.
def _month_end_expr(col: str) -> str:
"""
DuckDB SQL expression that converts a DATE/TIMESTAMP to the month-end date (same month).
"""
# date_trunc('month', ts) gives the first day of month at 00:00; then add 1 month and subtract 1 day.
return f"(date_trunc('month', {col}) + INTERVAL '1 month' - INTERVAL '1 day')"
Worked example: 1963-07-01 → 1963-07-31; 1963-07-31 → 1963-07-31
(idempotent).
migrate_ts_data_monthly_dates_to_month_end(db_path)¶
Signature — db_path: str | Path → None.
What it does
- Open the DB; no-op if
ts_datais missing or has nodatecolumn. UPDATE ts_data SET date = <month-end expr>.- If any month-end now has
count(*) > 1, raiseValueErrortelling the user to--full-refresh(both month-start and month-end rows collapsed onto one key).
with DuckDBManager(path) as manager:
exists = manager.connection.execute(
"SELECT count(*) FROM information_schema.tables WHERE table_name = 'ts_data'"
).fetchone()[0]
if not exists:
return
# ...
manager.execute(f"UPDATE ts_data SET date = {_month_end_expr('date')}")
# Detect collisions (e.g., both month-start and month-end rows existed and now collide).
dup = manager.connection.execute(
"SELECT date, count(*) AS c FROM ts_data GROUP BY date HAVING c > 1 LIMIT 1"
).fetchone()
if dup:
raise ValueError(
"Migration created duplicate ts_data rows for the same month-end date. "
"Please run a full refresh (aa setup-database --full-refresh) to rebuild ts_data cleanly."
)
Called from _stage_initialize_database on every setup_database run (Ch 4),
so old warehouses that ingested WRDS month-start factor dates get repaired
before later stages join ts_data to ccm_panel on date. Incorrect month
keys would break every join of the factors to the panel, which is why the
invariant matters more than this small function.