Skip to content

Chapter 8 — CRSP daily transforms

Part II of the assayinganomalies tutorial. Prerequisite chapters: 1, 2, 3, 4, 5, 6. Python modules covered: transforms/crsp_daily.py.

What this chapter answers

  • How raw CRSP daily DSF rows become a normalized long panel, then monthly signals (rvol_*, amihud, maxret, idiovol, car3) merged into ccm_panel.
  • Why two different delisting paths exist: ret_adj on the stored daily panel versus raw ret, with dlret placed on the next calendar row, for the monthly aggregates.
  • What pandas nullable extension dtypes (Int64, Float64) do to numpy ufuncs, and why coerce_nullable_dtypes converts them first.
  • Why volatilities use the sample (n − 1) standard deviation (_matlab_std) rather than numpy.std's default.
  • How Gao–Ritter NASDAQ volume adjustment works, including the three date breakpoints and the month-end exchcd lookup.
  • Minimum-observation gates per measure, and how the stock-then-month loops are organized.

Where this sits in the pipeline

Stage transform-crsp-daily (Ch 4) reads staged DSF parquet, calls transform_daily, writes crsp_daily_panel, then builds monthly aggregates via aggregate_daily_to_monthly and left-joins them onto ccm_panel. Stage compute-car3 runs later (after COMPUSTAT quarterly is linked) and merges car3 separately.

flowchart LR
  DSF["crsp_daily_raw.parquet"]
  TD["transform_daily"]
  DP[("crsp_daily_panel")]
  INS["_insert_matlab_dlret_rows"]
  AGG["aggregate_daily_to_monthly"]
  CCM[("ccm_panel")]
  CAR3["compute_car3"]
  DSF --> TD --> DP
  DP --> INS --> AGG --> CCM
  DP --> CAR3 --> CCM

The daily data stays a long panel — one row per (permno, date) — from ingestion through aggregation; no nDays × nStocks matrix is ever built.

Return column for the monthly aggregates. Monthly RVOL / Amihud / IVOL / maxret are computed from raw ret plus synthetic rows that put each dlret on the trading day after the stock's last return (calendar index r+1), rather than compounding it into that last return. This follows the original MATLAB toolkit, which built its daily return matrix that way. The pipeline drops ret_adj and calls betas._insert_matlab_dlret_rows before aggregate_daily_to_monthly. That helper lives in betas.py but is part of the daily-derived contract; Ch 10 covers it in the beta context.

…and none of that happens under CIZ

The placement rows described above apply to the SIZ tape. They exist because SIZ dsf.ret stops at the last trading day and excludes the delisting payoff. CIZ writes that row itself, on stkdelists.deldlydt — on a 2019 CIZ build all 470 delisting returns were already present as their own daily row with dlyret == delret. Placing one again would double-count the payoff in every measure derived from the daily panel: RVOL, IVOL, maxret, VoV, the betas and CAR3.

So the four placement sites in pipeline.py — monthly aggregates, tcosts, betas, CAR3 — all route through _place_dlret_rows / _daily_dlret_events, which gate on ctx.source.apply_delisting_overlay (Ch 5):

def _daily_dlret_events(ctx, *, what):
    if not ctx.source.apply_delisting_overlay:
        ctx.logger.info(
            "%s: no MATLAB dlret placement — the %s tape carries the delisting "
            "payoff as its own daily row (DEV-035)", what, ctx.source.name,
        )
        return None
    return _load_daily_delist(ctx)

Note the log level. Under SIZ a missing delist file is a WARNING — a real input is absent. Under CIZ the same absence is INFO, because it is the design, not a failure. Getting that backwards would have trained every CIZ operator to ignore a warning.

transform_daily gets delist=None under CIZ for the same reason, so ret_adj == ret on 100.0000% of rows of that 2019 build, with 0 rows carrying the dlret-placement shape.

The daily panel is otherwise tape-blind: CIZSource.daily_sql() aliases dsf_v2 straight onto the pinned DAILY_COLUMNS (Ch 5), so the staged parquet, the DuckDB crsp_dsf table, and every function in this chapter see identical columns in identical order whichever tape produced them. prc is re-signed in SQL off dlyprcflg = 'BA', and neither dlyvol nor shrout needs rescaling — only monthly volume is 100×.

Two exchange-gated paths in this chapter are historical, so a modern CIZ window never exercises them: the Gao–Ritter volume divisors stop in 2003 and the tcost exchange exclusions in 1992. On historical dates they behave the same on CIZ-derived exchcd as on SIZ exchcd.


Nullable dtypes — mechanism and the int64 failure

WRDS parquet exports often use pandas nullable extension dtypes: capital- letter Int64 / Float64 (NA-aware, backed by Arrow), not numpy int64 / float64. Two failure modes matter here:

  1. .values / .to_numpy() without dtype= on an extension column can yield an object array of boxed scalars. Then np.isfinite(x) raises TypeError because ufuncs do not run on object dtype.
  2. In-place assignment into nullable integer columns rejects floats. This has broken a full run: Fama–MacBeth winsorization in regressions.py (not this module) failed because a signal column stayed Int64, and Series.clip tried to write a float bound (-0.62…) into integer storage → TypeError: Invalid value '…' for dtype Int64. Daily-derived columns loaded from DuckDB can propagate the same dtype if ingestion never normalized them.

The fix pattern used throughout daily work is coerce_nullable_dtypes:

def coerce_nullable_dtypes(df: pd.DataFrame) -> pd.DataFrame:
    """
    Convert pandas nullable extension dtypes to numpy dtypes in-place.
    ...
    """
    for col in df.columns:
        if pd.api.types.is_extension_array_dtype(df[col]):
            if pd.api.types.is_float_dtype(df[col]):
                df[col] = df[col].astype("float64")
            elif pd.api.types.is_integer_dtype(df[col]):
                if df[col].isna().any():
                    df[col] = df[col].astype("float64")
                else:
                    df[col] = df[col].astype("int64")
    return df

Rules: floats → float64; integers with any NA → float64 (numpy integers have no NA); clean integer columns → int64. _normalize_daily calls this immediately after parsing dates; compute_idiovol repeats it on the factors frame. Pipeline stages that re-read parquet also call it.

Takeaway for optimization: any new path that reads WRDS/parquet and feeds numpy should coerce first. Downstream analytics (aa.load, FMB, sorts) should assume float64 signal columns unless explicitly categorical.


Daily → monthly: windowed reductions without a dense matrix

Every monthly measure is a function of the daily rows that fall in a window of calendar months ending at month t (one month for maxret and 1-month IVOL, up to 60 for rvol_60m). The package never materializes a dense days × stocks matrix. Instead:

Measure Python strategy
RVOL Daily rows reduced to one (stock, month) cell, windows merged pairwise; complete-window gate
Amihud Daily ratios reduced to one (stock, month) cell, 11 lagged cells added
maxret groupby(["permno","ym"]).max() on the return series
idiovol Per-stock month blocks; slice daily rows
car3 (permno, calendar position) packed into one ascending key

The RVOL and Amihud reductions are written by hand rather than with pandas rolling windows. A window's standard deviation is NaN if any trading day in the window lacks a finite return for that stock, and the trading-day count is taken from the global calendar, not the stock's own rows. A naive groupby.rolling().std() would reproduce neither the global denominator nor the all-finite gate without extra code. compute_monthly_rvol precomputes cal_cum — cumulative trading days on the global calendar (from all panel rows, including NaN returns) — and turns it into a per-window required table, which the finished window count has to hit exactly.

Month-end timestamps use ym_int = year*12 + month internally, then _month_ends_from_ym_int / _month_end_from_period to align with ccm_panel.


_matlab_std — the sample standard deviation

Volatilities use the sample standard deviation: divide by N-1 (ddof=1). NumPy’s np.std defaults to population ddof=0. A second edge case: with one finite observation the helper returns 0, where NumPy returns NaN. The helper's name and the single-observation rule follow the original MATLAB toolkit's std(x, 0).

def _matlab_std(values: np.ndarray) -> float:
    """
    Match MATLAB ``std(x, 0)``: sample std (ddof=1), with the 1-element
    special case returning 0 (MATLAB does; NumPy returns NaN).
    """
    x = values[np.isfinite(values)]
    n = len(x)
    if n == 0:
        return np.nan
    if n == 1:
        return 0.0
    return float(np.std(x, ddof=1))

This is the scalar statement of the rule compute_monthly_rvol applies to every window that clears the complete-window gate. The production path computes it with an array reduction rather than calling the helper cell by cell, so the helper serves as the reference definition. Every rvol_* column depends on this convention: replacing it with np.std or pandas.Series.std defaults would change the numbers.


adjust_nasdaq_volume — Gao–Ritter breakpoints

NASDAQ share volume double-counts dealer trades, so NASDAQ listings (exchcd == 3) get share volume divided by regime-specific factors. Exchange codes are monthly, so each daily row needs one: month-end trading days carry that month’s exchcd, and each interior day inherits the previous month-end’s code. The lookup uses searchsorted on the panel’s unique trading dates:

Calendar dates Divisor
before 2001-02-01 2.0
2001-02-01 – 2001-12-31 1.8
2002-01-01 – 2003-12-31 1.6
from 2004-01-01 none

Days before the first month-end in the sample get no exchcd → no adjustment (no forward-fill across missing months). Used by compute_amihud (and by tcosts) when the pipeline passes monthly exchcd from ccm_panel.


Minimum-observation thresholds (quick reference)

Measure Window Gate
rvol_Wm W calendar months Finite return on every global trading day in window
amihud 12 months ≥ 200 finite daily |ret|/dollar-vol ratios and monthly |prc| > 5
idiovol / idiovol_ff 1 month Complete month: row count = factor calendar days in month, all finite xret
idiovol_3m / idiovol_ff_3m 3 months Same completeness on concatenated window (no partial months in CAPM/FF3 stack)
maxret within month none (max daily return)
car3 3 calendar days around RDQ RDQ must be a trading day; neighbors on global calendar

Amihud’s price filter uses monthly CRSP prc when monthly_prc is passed. A NaN monthly price passes the filter, because the exclusion test |prc| <= 5 is false for NaN. Amihud has no 1e6 scaling (despite common textbook convention).


transforms/crsp_daily.py

transform_daily(...)

Builds the stored daily panel. Monthly derived variables are not computed here.

Signature

  • raw: pd.DataFrame — staged DSF (WRDS or placeholder).
  • config: AssayConfig — sample_start / sample_end year window.
  • delist: pd.DataFrame | None — daily delist file (permno, dlstdt, dlret). None under CIZ, where the payoff is already its own daily row, so ret_adj == ret.
  • factors: pd.DataFrame | None — accepted for call-site compatibility; ignored inside this function (factors used at aggregate / CAR3 / beta stages).

Returns — long daily panel: normalized columns, ret_adj, optional me (|prc| * shrout), adjustment factors dropped. No monthly measure columns.

What it does

  1. _normalize_daily(raw, config) — lowercase, dates, sample filter, nullable dtype coercion, sort by (permno, date).
  2. ret_adj = compute_daily_delisting_adj(...) — same-day compound/substitute (see below); this is not the next-row placement the monthly aggregates use.
  3. If prc and shrout present: me = |prc| * shrout, unscaled (thousand-dollar units from raw shrout; no further /1000 at this stage).
  4. Drop cfacpr, cfacshr.

aggregate_daily_to_monthly(...)

Builds every daily-derived monthly measure except CAR3 (separate stage).

Signature

  • daily: pd.DataFrame — should carry ret, not ret_adj, with the next-row dlret rows already inserted when delist + factors are available.
  • factors: pd.DataFrame | None — daily FF factors for idiovol.
  • exchcd: pd.DataFrame | None — monthly (permno, date, exchcd) for Gao–Ritter.
  • monthly_prc: pd.DataFrame | None — monthly CRSP prices for Amihud filter.

Returns — one row per (permno, month-end date) with outer-merged columns: rvol_1m … rvol_60m, amihud, maxret, idiovol, idiovol_3m, idiovol_ff, idiovol_ff_3m (subset empty if inputs missing).

What it does — calls compute_monthly_rvol, compute_amihud, compute_maxret, compute_idiovol sequentially; outer-merges on (permno, date). The numeric gates are those in the quick-reference table above.


coerce_nullable_dtypes(df)

Signature — df: pd.DataFrame, modified in place and returned.

Returns — same frame with extension dtypes converted (see dedicated section above).

What it does — iterates columns; extension float → float64; extension int → int64 or float64 if NA present. Critical for runtime stability when reading WRDS parquet.


compute_daily_delisting_adj(df, delist=None)

Signature

  • df — columns permno, date, ret.
  • delist — optional permno, dlstdt, dlret.

Returns — pd.Series aligned to df.index: adjusted returns.

SIZ only. The pipeline passes delist=None under CIZ, so this reduces to ret_adj = ret.

What it does — left-merge delist events on (permno, date==dlstdt). If both ret and dlret finite: compound (1+ret)*(1+dlret)-1. If ret NaN and dlret finite: substitute dlret. This is a same-day compound, unlike the next-row placement used for the monthly aggregates. No DLSTCD filter here: dropping dlstcd==100 and the max-dlstdt placeholder happens only on the aggregate path, in betas._insert_matlab_dlret_rows.


adjust_nasdaq_volume(daily, exchcd=None)

Signature

  • daily — permno, date, vol.
  • exchcd — optional monthly panel with exchcd.

Returns — pd.Series of float64 volume, index aligned to daily.

What it does — documented in the Gao–Ritter section: build applicable month-end per row, merge exchcd, apply piecewise divisors for NASDAQ.


compute_monthly_rvol(daily, windows_months=RVOL_WINDOWS_MONTHS)

Signature

  • daily — permno, date, and ret or ret_adj (via _ret_col).
  • windows_months — default (1, 3, 6, 12, 36, 60) matching RVOL_WINDOWS_MONTHS.

Returns — permno, month-end date, columns rvol_{W}m.

What it does

  1. Build global calendar day counts per ym_int, and from them a required trading-day count for every (window, calendar month) pair.
  2. Drop rows with NaN returns before counting (finite returns only in slices).
  3. Lay out one grid cell per (stock, month) from each stock's first observed month to its last, silent months included, and reduce the daily rows onto it: observation count, month mean, and month sum of squared deviations about that mean — a genuine two-pass, so a one-month window is numpy.std's own answer.
  4. For each window W, merge the W trailing cells of every grid position pairwise (Chan/Golub/LeVeque), and keep the result only where the merged observation count equals required.
  5. Filter output to months present in the global all_ym list.

Step 4 merges deviations forward rather than differencing a running sum of squares backward out of the stock's history. The cheaper form is wrong at the precision this package holds itself to: a stock that goes quiet for a month inside an otherwise volatile life has a window variance ~1e12 below its lifetime sum of squares, and differencing prefix sums to find it costs six significant figures. Roughly 4,800 real stock-months on the CRSP panel land there.


compute_realized_volatility(daily, window=1, min_obs=None)

Single-window wrapper around the RVOL computation.

Signature — window interpreted as calendar months; min_obs unused (API compat).

Returns — single-column rvol_{window}m plus keys.

What it does — delegates to compute_monthly_rvol(daily, windows_months=(window,)). Prefer compute_monthly_rvol.


compute_amihud(daily, *, window_months=12, min_obs=200, min_prc=5.0, exchcd=None, monthly_prc=None)

Signature — see defaults above; exchcd for Gao–Ritter volume; monthly_prc for the monthly CRSP price filter.

Returns — permno, month-end date, amihud.

What it does

  1. Daily ratio |ret| / (|prc| * |vol_adj|) with zero volume masked NaN.
  2. Lay out one grid cell per (stock, month) from each stock's first observed month to window_months-1 months past its last, and reduce the daily ratios onto it: finite count, non-NaN count, non-NaN sum.
  3. Add the window_months-1 lagged cells of each stock to get the trailing window, then apply the min_obs (finite count) and min_prc gates and divide sum by non-NaN count — so a ±Inf ratio, which does not count toward min_obs, still enters the average.
  4. Keep only cells at or past the 12th month of the global calendar. Values do extend up to window_months-1 months past the last daily row, because every (month, stock) cell of the calendar is computed.

The window's first month is the twelfth-previous month present in the panel, not calendar month t − 11. Summing month totals is safe here in a way it is not for RVOL (see that function's note): the ratios are non-negative, so a window sum has nothing to cancel, and no prefix total is ever differenced.


compute_maxret(daily)

Signature — daily panel with a return column (via _ret_col).

Returns — permno, month-end date, maxret (max daily return, the Bali/Cakici/Whitelaw 2011 MAX signal).

What it does — groupby(["permno","ym"]).max() on the return series; month-end from _month_end_from_period.


compute_idiovol(daily, factors=None, *, windows_months=(1, 3))

Signature

  • daily — returns column via _ret_col.
  • factors — daily mktrf, optional smb, hml, rf.
  • windows_months — which of 1- and 3-month windows to fill.

Returns — permno, month-end date, four idiovol columns.

What it does

  1. Inner-merge daily returns with factors; xret = ret - rf (rf missing → 0).
  2. Per stock, split into calendar months; complete-month gate: a month is eligible only if its row count equals the factor-calendar day count and all xret are finite.
  3. 1-month: _nanols_resid_rms on [const, mktrf] (CAPM) and FF3 if columns present. 3-month: concatenate daily rows from me-2 … me (calendar months).

Idiosyncratic volatility is the residual RMS with ddof=0, sqrt(mean(resid^2)), not a degrees-of-freedom-corrected standard error.


compute_car3(daily, fundq, factors=None)

Signature

  • daily — permno, date, raw ret with the next-row dlret placement rows.
  • fundq — linked quarterly with rdq, datadate.
  • factors — daily mktrf, rf for abnormal return 1 + ret - (mktrf + rf).

Returns — monthly panel permno, month-end date, car3.

What it does

  1. Build the global trading calendar, then pack each daily row’s (permno, calendar position) into one ascending int64 key.
  2. Announcement filter: drop announcements without datadate (the fiscal-quarter marker is datadate, not Compustat fqtr); one row per (permno, rdq-month) keeping latest (rdq, datadate).
  3. For every RDQ on a trading day, one binary search finds the announcement row; the two window days are the adjacent rows, taken only when their key is exactly one position away. car3 = left * center * right - 1, so a stock with no row on one of those calendar days yields NaN rather than falling back to its nearest observed day. Missing daily returns are not zero-filled.
  4. Forward-fill along one stacked month grid: each stock runs from its first non-NaN announcement to at most QUARTERLY_FILL_HORIZON (=2) months past its last finite value, capped by the calendar’s last month.
  5. After the merge into ccm_panel, the pipeline sets car3 to NaN wherever the monthly ret is NaN.

Small helpers

_normalize_daily(raw, config)

Encapsulates ingest normalization also described under transform_daily. Calls coerce_nullable_dtypes.

_ym_int_to_period(x), _month_ends_from_ym_int(ym_int),

_month_end_from_period(ym)

Encode/decode ym_int = year*12+month and convert to month-end Timestamp for ccm_panel alignment. _month_ends_from_ym_int adds MonthEnd(0) after Period.to_timestamp(how="end").

_ret_col(df)

Returns "ret_adj" if present else "ret". The aggregate path must pass frames without ret_adj so the measures see raw ret plus placement rows — the call-site convention matters, not the helper itself.

_matlab_std(values)

Covered in dedicated section above.

_nanols_resid_rms(y, X)

OLS on the finite rows of y and X, returning the residual RMS sqrt(mean(resid^2)); used by compute_idiovol.

RVOL_WINDOWS_MONTHS

Tuple (1, 3, 6, 12, 36, 60) — the RVOL windows, in calendar months.

LOGGER, __all__

Module logger and export list.