Skip to content

Chapter 6 — CRSP monthly transforms

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

What this chapter answers

  • How raw MSF + aux tables become the CRSP half of ccm_panel (delisting-adjusted ret, me, nyse_flag, FF industries, momentum).
  • Exactly how _apply_matlab_delisting_adjustment places dlret (and why DLSTCD is not used).
  • Why there are two past-performance helpers, which one the live columns call, and exactly which months R12_2 / R6_1 cover.
  • Where momentum is computed: inside transform_monthly, via _cumret_window_global_months.

Where this sits in the pipeline

Stage transform-crsp-monthly (Ch 4) loads staged MSF + aux, calls transform_monthly, and writes the result into DuckDB. Later stages left-join COMPUSTAT, daily aggregates, tcosts, and betas onto that panel. Analytics and the assay protocol (Ch 13–17) read ret, me, nyse_flag, R12_2, and the FF industry columns from here.

flowchart LR
  MSF["staging MSF"]
  AUX["msedelist / mseexchdates / stocknames"]
  TM["transform_monthly"]
  CCM[("ccm_panel CRSP cols")]
  MSF --> TM
  AUX --> TM
  TM --> CCM

All of this work — filtering, delisting, ME, NYSE flag, industries, past performance — happens in one entry point on one long (date, permno) panel.

Schema note. The panel column dictionary lists iss_me / iss_shrout; this module emits issuance_delta / issuance_pct / shrout_adj. Annual issuance for the NMV anomaly is rebuilt in Ch 11 from shrout_adj.


Naming and the skip month (read before Ch 11 / 13 / 17)

_cumret_window_global_months(..., window, lag) cumulates gross returns (\prod(1+r)) over lags lag … lag+window-1 (inclusive) on a global monthly calendar, leaves the first lag+window-1 sample months as NaN, treats missing ret as 0% inside the product, then restores NaN wherever the contemporaneous ret was NaN.

Python column Lags at month t (stored) Live helper
R12_2 (t-1,\ldots,t-11) _cumret_window_global_months(..., window=11, lag=1)
R6_1 (t-1,\ldots,t-5) _cumret_window_global_months(..., window=5, lag=1)
R60_13 (t-12,\ldots,t-59) _cumret_window_global_months(..., window=48, lag=12)

Why R12_2? Portfolio sorts (Ch 13) lag every signal by one month before forming portfolios. The sort at t uses the value stored at t−1, whose product spans months t−12 … t−2. The column name describes that post-sort Jegadeesh–Titman 12–2 window. R6_1, by contrast, names the stored window (6 months ago through 1 month ago), not the post-sort t−6…t−2 effective window.

There is no top-level compute_momentum. Momentum is computed by the three groupby(...).apply(_cumret_window_global_months, ...) blocks inside transform_monthly.


Two tapes, one transform (read before the delisting sections)

Everything below describes the SIZ tape — Flat File Format 1.0, frozen by CRSP in January 2025. transform_monthly also runs on CIZ (Format 2.0), and three of its steps are gated on the CRSPSource object it is handed (Ch 5) rather than on a format string:

Step Gate SIZ CIZ
mseexchdates interval join for shrcd / exchcd / SIC source.needs_name_window joins, drop_outside=True skipped — msf_v2 carries the as-of codes on every row
Delisting source.apply_delisting_overlay _apply_matlab_delisting_adjustment _attach_informational_dlret
shrcd / exchcd values source.normalize_monthly (Ch 5) read from the tape derived from the security-info codes; unmapped → NaN

source defaults to crsp_source_for("siz") when omitted. Note this is a function-argument default, deliberately distinct from config.DEFAULT_CRSP_FORMAT, which is "ciz": the pipeline always passes ctx.source explicitly (Ch 1), so the argument default only ever applies to a direct call that says nothing about the tape.

Why CIZ must not run the overlay. CIZ's mthret is daily-compounded and already contains the delisting payoff — the payment arrives as an extra daily row on stkdelists.deldlydt and compounds into the month. Replacing ret with dlret on top of that would count the payoff twice.

_attach_informational_dlret is the no-overlay counterpart, and it is deliberately not a no-op:

  • ret ← ret_x_dl. This is an identity, not an adjustment — under this tape they are equal by construction — but stating it means no caller has to know which tape produced the panel. On the full 1925–2024 CIZ build, ret == ret_x_dl on 100.0000% of rows.
  • dlret is filled from stkdelists on the delisting month only, matched on (permno, yyyymm). Every other month stays NaN. It is never carried forward, never applied, never compounded. A permno delists once, so the match cannot fan out.

Contrast with the SIZ path below, where dlret is both an input and an output of the overlay: it can be moved to a neighbouring month, and it can create a whole new panel row. Under CIZ it is only ever an annotation on a row that already exists.

Letting dlret simply vanish under CIZ was the tempting alternative and the wrong one: a column that is silently all-NaN under one tape and populated under the other is the kind of difference that gets discovered by a broken regression six months later.


_apply_matlab_delisting_adjustment(...)

SIZ only. Under CIZ this function never runs; see the section above.

The placement rules below follow the original MATLAB toolkit, which stored returns in a balanced months×stocks matrix and wrote each delisting return into a cell of that matrix. That origin explains the rules that would otherwise look arbitrary: replacement rather than compounding, the dropped max-dlstdt row, file-order processing, and the synthetic rows.

Signature

  • df: pd.DataFrame — monthly panel already filtered to the sample, with permno, yyyymm, date, and ret_x_dl (raw MSF return).
  • msedelist: pd.DataFrame — CRSP monthly delisting file (permno, dlstdt, dlret, …).
  • months_yyyymm: pd.Series — global YYYYMM calendar for the panel (unique months after MSF filtering).

Returns — copy of df with ret (delisting-adjusted), dlret (placed value where an assignment happened), and possibly extra rows for (permno, yyyymm) cells that had no MSF row but received a delisting return.

What it does

Setup

  1. If msedelist is empty → ret = ret_x_dl, return.
  2. Build month_to_pos from the panel’s unique YYYYMM values only — do not extend the calendar with delist dates (nothing is ever assigned outside the panel’s months).
  3. Drop the row with dlstdt == max(dlstdt) (often a placeholder).
  4. Keep only permnos present in the panel.
  5. Map dlstdt → YYYYMM via month-of-date (not calendar month-end), then to a position in the global month vector. Drop rows missing permno, position, or dlret.
  6. Do not re-sort the delist table — records are processed in file order, so later assignments can overwrite earlier ones at the same cell.
    # MATLAB drops the max dlstdt row (often a placeholder).
    if d["dlstdt"].notna().any():
        max_dlstdt = d["dlstdt"].max()
        d = d[d["dlstdt"] != max_dlstdt]
    # ...
    d["dl_yyyymm"] = _date_yyyymm(d["dlstdt"])
    d["dl_pos"] = d["dl_yyyymm"].map(month_to_pos).astype("Int64")
    d = d.dropna(subset=["permno", "dl_pos", "dlret"])

DLRET vs DLSTCD (what is not in this path)

DLSTCD is never consulted. There is no Shumway-style “if dlret missing and code ∈ {500, 520, 551–574, 580, 584}, impute −30%” branch. The only return used is the file’s dlret column, written by replacement into ret (not (1+ret)×(1+dlret)−1).

Case Behaviour
dlret finite, assign rule picks a row assigned[(pn, pos)] = dlret_val, then overwrite ret / dlret
dlret NaN Row dropped before the loop (dropna on dlret)
dlstcd any value Ignored
Permno not in panel Dropped before the loop
Delist month outside the panel calendar dl_pos NaN → dropped
No finite return history for permno pn not in last_finite_pos → continue

Assignment rule

For each remaining delist record, with dl_pos the delisting month’s position and r_last = last_finite_month_pos + 1 (updated as assignments extend finiteness):

  1. if ret at dl_pos is NaN and ret the month before is finite → assign at dl_pos;
  2. else, if r_last is not the final month of the calendar → assign at r_last;
  3. else → no assignment.

The cap max_assign_pos = len(months_yyyymm) - 2 (0-based) is what keeps the final month of the calendar from ever receiving a fallback assignment:

        ret_dt = _cur_ret(pn, dl_pos)
        ret_prev = _cur_ret(pn, dl_pos - 1) if dl_pos - 1 >= 0 else float("nan")

        max_assign_pos = len(months_yyyymm) - 2  # last allowed 0-based position (MATLAB strict <)
        assign_pos: int | None
        if np.isnan(ret_dt) and np.isfinite(ret_prev):
            assign_pos = dl_pos
        elif r_last <= max_assign_pos:
            assign_pos = r_last
        else:
            assign_pos = None

        if assign_pos is not None:
            assigned[(pn, assign_pos)] = dlret_val
            if np.isfinite(dlret_val) and assign_pos > int(last_finite_pos.loc[pn]):
                last_finite_pos.loc[pn] = assign_pos

Worked cases:

  1. Gap at delist month, prior month finite → write dlret at the delist YYYYMM (even if that month had no MSF row — see synthetic rows below).
  2. Otherwise → write at the month after the last finite ret for that permno, but never into the last month of the global calendar.
  3. Otherwise → skip.
  4. Replacement, not multiply — if that cell already had a return, it is overwritten with dlret.

Synthetic rows

After collecting assignments, the function merges them onto existing rows, then appends rows for (permno, yyyymm) keys that were missing in the long panel, filling ret/dlret and inheriting shrcd so domestic-common filters still see the name.

    # Add rows for assignment months that didn't exist in the raw long data (MATLAB balanced matrix effect).
    out_key = out[["permno", "yyyymm"]].dropna()
    missing = assigns_df.merge(out_key, on=["permno", "yyyymm"], how="left", indicator=True)
    missing = missing[missing["_merge"] == "left_only"].drop(columns=["_merge"]).reset_index(drop=True)
    if not missing.empty:
        new_rows = pd.DataFrame({col: pd.NA for col in out.columns}, index=range(len(missing)))
        # ...
        new_rows["date"] = pd.to_datetime(new_rows["yyyymm"].astype(str) + "01", format="%Y%m%d", errors="coerce") + pd.offsets.MonthEnd(0)
        new_rows["ret_x_dl"] = pd.NA
        new_rows["ret"] = pd.to_numeric(missing["__dlret_assign"], errors="coerce").to_numpy()
        new_rows["dlret"] = pd.to_numeric(missing["__dlret_assign"], errors="coerce").to_numpy()

_merge_on_interval(...)

Signature

  • base, aux — left panel and interval table, both with permno.
  • start_col, end_col — usually namedt / nameendt (fallback begexchdate / endexchdate).
  • cols — fields to bring across (shrcd, exchcd, siccd, …).
  • drop_outside: bool — if True, drop base rows with no covering interval (MSEEXCHDATES behavior).

Returns — base with cols filled; at most one aux match per base row (latest __start wins when intervals overlap).

What it does — merge on permno, keep rows where base.date ∈ [start, end] at day granularity, clear non-matching merges, dedupe by latest start.

    # Exact day-level date comparison (MATLAB date ∈ [namedt, nameendt]).
    mask = (merged["__date_dt"] >= merged["__start"]) & (merged["__date_dt"] <= merged["__end"])

    if drop_outside:
        # ...
        mask = mask.loc[keep].copy()

    # For remaining non-matching rows (including NaT bounds), clear merged values.
    merged.loc[~mask, cols] = pd.NA
    merged.loc[~mask, "__start"] = pd.NaT

    # Deduplicate: for each original row, keep the record with the latest valid start date
    merged = merged.sort_values("__start", ascending=False, na_position="last")
    merged = merged.drop_duplicates(subset=["__row_id"], keep="first")

The comparison is day-level: an interval ending 2020-01-15 does not cover 2020-01-31 (a YYYYMM compare of 202001 would have kept it).


Past performance: _cumret_window vs _cumret_window_global_months

_cumret_window(group, window, lag, col)

A simpler per-series variant that works on the observed row index only (no global calendar).

Signature — one-permno group; window = number of months in the product; lag = how many months to skip; col = return column name.

Returns — Series aligned to group.index: gross product, NaN where contemporaneous col was NaN.

What it does — fillna(0) on returns → shift(lag) → rolling(window).apply(np.prod) → restore NaNs. It does not NaN out the first lag+window-1 months of the global sample — only whatever the rolling window naturally misses on the sparse series.

Live use — none. No caller in this module; all stored momentum columns use the global-month helper.

_cumret_window_global_months(...)

Signature

  • group — one permno, sorted by date inside the function.
  • window, lag, col — as above (from = lag + window).
  • start_year, start_month, n_months — global calendar from AssayConfig.sample_start…sample_end (Jan–Dec).
  • data_start_pos — offset of the first month that actually has CRSP data (CRSP starts at 1925-12, not necessarily January of SAMPLE_START).

Returns — Series on the group’s index: gross cumret on the global grid, projected back to observed rows.

What it does

  1. Scatter observed returns onto a length-n_months vector.
  2. Treat NaN as 0% via log1p; lag by lag; rolling sum of length window; exp → gross return.
  3. Force NaN for the first data_start_pos + (lag+window) - 1 months, anchored at the first data month — e.g. R12_2 is NaN through 1926-10 when data start at 1925-12.
  4. Restore NaN wherever the grid ret was NaN; map back to observed dates.
    from_ = int(lag + window)
    rr[: int(data_start_pos) + from_ - 1] = np.nan

    gross = np.exp(rr)
    gross[is_nan] = np.nan

Which columns use which

Column Helper window lag
R12_2 _cumret_window_global_months 11 1
R6_1 _cumret_window_global_months 5 1
R60_13 _cumret_window_global_months 48 12
(none) _cumret_window — —

_assign_ff_buckets and the FF range tables

_assign_ff_buckets(sic, ranges)

Signature — sic: Series; ranges: list[(lo, hi, bucket_id)].

Returns — nullable Int64 Series; unmatched → <NA>.

What it does — for each (lo, hi, code), mask = sic ∈ [lo, hi] and out.mask(mask, code). Later ranges overwrite earlier ones on overlap (the published Fama–French ranges are mutually exclusive in practice).

FF10_RANGES / FF17_RANGES / FF49_RANGES

Module-level constants holding the Fama–French SIC range definitions for the 10-, 17- and 49-industry schemes. After bucketing, transform_monthly fills every unmatched row with the scheme’s "Other" bucket:

Scheme Catch-all after assign
FF10 .fillna(10)
FF17 .fillna(17)
FF49 .fillna(49)

Because the fill runs on <NA>, stocks with missing SIC also land in "Other", not in a separate missing category.


transform_monthly(raw, config, *, aux=None)

Signature

  • raw — MSF frame from ingest (Ch 5).
  • config: AssayConfig — sample_start / sample_end, dom_com_eq.
  • aux — dict with optional msedelist, mseexchdates, stocknames (SIZ) or stkdelists, stksecurityinfohist (CIZ). raw has already been through source.normalize_monthly, so its columns are canonical either way.
  • source: CRSPSource | None — which tape raw came from. Defaults to crsp_source_for("siz").

Returns — long DataFrame, one row per (date, permno) after filters, with the column set in wanted: identifiers, ret / ret_x_dl / dlret, prices, me, nyse_flag, ff10/ff17/ff49, R12_2/R60_13/R6_1, issuance fields, etc. Index is a plain RangeIndex; keys are columns.

What it does (execution order)

  1. Normalize date, cast permno, build yyyymm; filter to [sample_start*100+1, sample_end*100+12].
  2. Interval-merge mseexchdates with drop_outside=True for shrcd / exchcd / SIC — gated on source.needs_name_window, so CIZ skips it.
  3. SIC fallbacks: hsiccd, then stocknames interval merge.
  4. Optional dom_com_eq filter shrcd ∈ {10, 11}.
  5. Collapse date to calendar month-end from yyyymm (one row per permno-month).
  6. ret_x_dl ← ret; then gated on source.apply_delisting_overlay: either _apply_matlab_delisting_adjustment (SIZ) or _attach_informational_dlret (CIZ).
  7. me = |prc| * shrout / 1000 (millions of USD), then me==0 → NaN.
  8. Momentum via _cumret_window_global_months for R12_2, R60_13, R6_1.
  9. Issuance: month-over-month change in shrout * cfacshr (12-month issuance is rebuilt in Ch 11).
  10. nyse_flag = (exchcd == 1).fillna(False) — a missing exchcd counts as not-NYSE, so the column is a plain bool.
  11. FF buckets + fillna Other defaults.
  12. Project to wanted columns.
    # Market equity: compute if not already present.
    # makeCRSPDerivedVariables.m:132-133 -- shrout is in thousands of shares,
    # so divide by 1000 to express me in millions of USD; then map me==0 to
    # NaN (MATLAB treats zero market-cap as missing).
    if "me" not in df.columns:
        df["me"] = (df["prc"].abs() * df["shrout"] / 1000.0).astype("float64")
    else:
        df["me"] = df["me"].astype("float64")
    df.loc[df["me"].eq(0), "me"] = np.nan
    # Exchange flag: NYSE = exchcd==1.
    # MATLAB NYSE = (exchcd == 1)*1 on a dense (T,N) double matrix where
    # NaN == 1 evaluates to False (0), not NaN. Collapse the pandas nullable
    # boolean {True, False, NA} to plain bool by mapping NA -> False.
    if "exchcd" in df.columns:
        exch = df["exchcd"]
    else:
        exch = pd.Series(False, index=df.index)
    df["nyse_flag"] = (
        pd.to_numeric(exch, errors="coerce").eq(1).fillna(False).astype(bool)
    )

    # Industry buckets (FF10/17/49) using SIC ranges per attached MATLAB mappings.
    df["ff10"] = _assign_ff_buckets(df["sic"], FF10_RANGES).fillna(10).astype("Int64")
    df["ff17"] = _assign_ff_buckets(df["sic"], FF17_RANGES).fillna(17).astype("Int64")
    df["ff49"] = _assign_ff_buckets(df["sic"], FF49_RANGES).fillna(49).astype("Int64")

Not in this module

Item Status
Gao–Ritter NASDAQ volume adjustment Not applied; vol_x_adj is split-adjusted volume only
Investment universes (FF / Russell / mep) Not built; no universe column on ccm_panel
Fama–French factors Ch 5 ingest
12-month log share issuance Ch 11 NMV iss rebuilds annual log growth from shrout_adj

Small helpers

_month_end(ts)

Normalizes timestamps to calendar month-end midnight via MonthEnd(0).

Live use — unused inside this module; transform_monthly builds month-end dates from yyyymm instead. Duplicate of helpers in ingest (Ch 5).

_date_yyyymm(dt)

Computes 100*year + month.

Returns — nullable Int64 YYYYMM.

Live use — panel yyyymm and delist dl_yyyymm.