Skip to content

Chapter 9 — Transaction costs (stock-level spreads)

Part II of the assayinganomalies tutorial. Prerequisite chapters: 1, 2, 3, 4, 5, 6, 7, 8. Python modules covered: transforms/tcosts.py — this file covers the stock-level spread construction through make_trading_costs; the Fama–French factor trading-cost path is in 09b — FF factor trading costs.

What this chapter answers

  • How four low-frequency effective-spread estimators (Corwin–Schultz HL, Abdi–Ranaldi CHL, Kyle–Obizhaeva VoV, Hasbrouck Gibbs) plus optional TAQ/ISSM high-frequency spreads are built from daily CRSP and external CSVs, winsorized, exchange-filtered, averaged, and gap-filled into the monthly half-spread column tcost.
  • Why CPI inflation (CPIAUCNS) appears in a spread formula, why Gibbs estimates are expanded onto the full CRSP link grid, and why 3-month idiosyncratic volatility (idiovol_ff_3m) — not 1-month — drives the nearest-neighbour fill.
  • Which estimator conventions are kept on purpose (complex-log Corwin–Schultz propagation, raw-only nearest-neighbour donors, universe-restricted winsorization caps), and which exchange/date exclusions apply.
  • How _matlab_prctile_rows differs from NumPy’s default percentile rule — and that three copies of this helper exist in the package (the FF sort path uses the copy in this module and is covered in 09b).

Where this sits in the pipeline

Stage compute-tcosts (Ch 4) reads staged daily DSF, inserts next-row delisting return rows for VoV (same pattern as the Ch 8 aggregates), pulls ME / idiovol_ff_3m / exchcd from ccm_panel (preferring full-universe ivol from the daily aggregate parquet), locates crspgibbs*.csv and, under tcosts_type='full', hf_monthly.csv (where they come from, the lookup order and what a missing file does: Trading-cost inputs), then calls make_trading_costs. Results land in DuckDB table tcosts and are merged into ccm_panel as tcost (+ tcost_gibbs, the Gibbs-only filled half-spread). Stage compute-ff-tcosts runs later: it prices the Fama–French factors on held legs from these half-spreads and stores the costs in ts_data under both conventions (smb_tc … for "dollar", smb_tc_capital … for "capital", and smb_tc_capital_short … for the factors held short under "capital"). It is documented in 09b.

flowchart LR
  DSF["crsp_daily_raw"]
  DL["dlret placement rows"]
  LF["HL / CHL / VoV / Gibbs"]
  HF["HF TAQ optional"]
  WIN["winsorize 99.9%"]
  EX["exchange exclusions"]
  COMB["mean + HF overlay"]
  FILL["fill_missing_tcosts"]
  OUT[("tcosts / ccm_panel.tcost")]
  DSF --> DL --> LF
  LF --> WIN --> EX --> COMB
  HF --> COMB
  COMB --> FILL --> OUT

Each measure is a long (permno, date) panel from estimation through the fill; only the FF path (09b) pivots to dense months × stocks matrices.

Config knob: AssayConfig.tcosts_type — 'gibbs', 'lf_combo' (default), or 'full' (low-frequency estimators plus the TAQ/ISSM high-frequency spreads).

Under CIZ, the dlret placement rows box does not fire. The stage calls _place_dlret_rows(ctx, raw, factors, what="tcosts daily input"), which gates on ctx.source.apply_delisting_overlay (Ch 5, Ch 8) and returns the daily frame untouched on a tape whose daily file already carries the delisting payoff as its own row. Inserting one would double-count it inside VoV — and, through the combined mean, inside tcost. The absence is logged at INFO, not WARNING, because it is the design and not a missing input.

Everything else in this chapter is tape-blind: the daily columns arrive in the same names and order under both tapes (Ch 5), and the exchange exclusions read exchcd from ccm_panel whichever way it was produced. One caveat when comparing numbers across tapes — the exclusions are historical (NASDAQ Gibbs/VoV through 1982-12, HL/CHL through 1992-12), so a modern-window comparison never exercises them, and CIZ's derived exchcd leaves unmapped venues as NaN rather than 0. Recomputed lf_combo on the two tapes over a matched 2019 window agrees to 1e-6 on 99.54% of 90,467 stock-months (correlation 0.9946).


_matlab_prctile_rows — MATLAB percentile interpolation

NumPy’s percentile / pandas quantile use the (i-1)/(n-1) plotting rule by default. The package's breakpoints instead use midpoint plotting positions (i-0.5)/n with linear interpolation, following the original MATLAB toolkit's prctile. For quintile sorts the gap moves enough stocks across breakpoints to matter.

This module’s row-wise implementation:

def _matlab_prctile_rows(x: np.ndarray, pcts: np.ndarray) -> np.ndarray:
    """Row-wise MATLAB ``prctile``: plot positions ``(i-0.5)/n``, NaN dropped.
    ...
    """
    p = np.atleast_1d(np.asarray(pcts, dtype=float))
    ...
        pos = (np.arange(1, n + 1) - 0.5) * 100.0 / n
        out[i, :] = np.interp(p, pos, xs[i, :n])
    return out

Three copies in the package:

Location Name Scope
transforms/tcosts.py _matlab_prctile_rows 2-D matrix, keeps ±Inf (needed for OpProf = OP/BE)
analytics/sorts.py _matlab_prctile 1-D cross-section, drops non-finite via isfinite
transforms/nmv_anomalies.py _matlab_prctile 1-D winsorization helper, drops non-finite

On finite-only inputs the three agree numerically, including single-element edge cases. They diverge when ±Inf is present: tcosts keeps infinities in the sort key for RMW breakpoints; sorts/nmv drop them. Consolidation must preserve that distinction or RMW tertiles drift.

The FF sort helpers that call _matlab_prctile_rows are covered in 09b.


transforms/tcosts.py — spread construction

_cs_spread(hi, lo, lhi, llo)

Corwin–Schultz daily spread: equations (7), (10), (18)/(14), Section II.C zeroing.

Signature

  • hi, lo, lhi, llo: 1-D float64 arrays (same length), split-adjusted daily high/low and lags.

Returns — same shape, daily Corwin–Schultz spread s (non-negative real).

What it does

  1. Detect the complex dtype path when negative price ratios force complex logs. Complex values propagate through the monthly mean, and the real part is taken only at month aggregation. This follows the original MATLAB toolkit, whose log of a negative ratio silently returned a complex number.
  2. Zero or NaN gates on non-positive highs/lows.
  3. Compute beta, gamma, alpha, spread s; zero negative real parts.

compute_corwin_schultz(daily, min_days=12)

Signature

  • daily: long panel with permno, date, prc, askhi, bidlo; optional cfacpr.
  • min_days: minimum valid daily spreads per month (default 12).

Returns — DataFrame: permno, month-end date, hl.

What it does

  1. Sort by (permno, date); set askhi/bidlo NaN when prc < 0.
  2. Overnight adjustment (Section II.A of Corwin–Schultz).
  3. Lag adjusted hi/lo with split factors.
  4. Apply _cs_spread per day; rerun in complex arithmetic for stocks with negative ratios after the overnight adjustment.
  5. Monthly mean of finite daily spreads; require min_days valid days.

compute_abdi_ranaldi(daily, min_days=12)

Signature

  • daily: permno, date, prc, askhi, bidlo.

Returns — permno, month-end date, chl.

What it does

  1. Build global trading calendar from all dates in daily.
  2. Per permno, reindex to the calendar span from first month start through last month end, so prices carry across trading days on which the stock has no row. This explicit reindex changes the numbers; do not drop it.
  3. Forward-fill close/high/low on days without a row.
  4. Midpoint and lead-by-one calendar day; at span end use the carried value.
  5. sqrt(fmax(4*(c-η)(c-η'), 0)) with np.fmax, so NaN inputs contribute 0 to the monthly mean.
  6. Gate: ≥ min_days with raw prc > 0, finite hi/lo, hi ≠ lo.

compute_kyle_obizhaeva(daily, cpi=None, min_vol_days=5, min_ret_days=11, exchcd=None)

Signature

  • daily: permno, date, ret or ret_adj, prc, vol. Pipeline passes raw ret after dlret placement (Ch 8 / pipeline stage).
  • cpi: optional month-end Series; default load_cpi_aucns().
  • min_vol_days / min_ret_days: FHT filters (≥5 positive volume days, ≥11 non-zero return days).
  • exchcd: monthly exchange codes for Gao–Ritter volume (via crsp_daily.adjust_nasdaq_volume).

Returns — permno, month-end date, vov.

What it does

  1. Dollar volume dvol = vol_adj * |prc|.
  2. Per (permno, month): ret_std with ddof=1 (sample std, NaN omitted); vol_mean includes zero-volume days.
  3. CPI normalize: CPIAUCNS / CPIAUCNS(Jan-2000).
  4. VoV formula 8 * ret_std^(2/3) / vol_mean^(1/3) when gates pass.

Exchange exclusions are applied later, in make_trading_costs, not here.


load_cpi_aucns(cache_path=None)

Signature

  • cache_path: optional CSV path; otherwise tries Data/CPIAUCNS.csv under the project root (and a legacy-toolkit input folder, if present), then downloads FRED CPIAUCNS and caches it to Data/CPIAUCNS.csv.

Returns — month-end indexed Series, or None if unavailable (VoV skips CPI scaling with a warning rather than failing).

What it does

Read CSV, normalize column names, coerce month-end index, dedupe.


load_gibbs(filepath)

Signature

  • filepath: path to crspgibbs*.csv with columns permno, year, c. The package ships it at inputs/gibbs/crspgibbs.csv; see Trading-cost inputs.

Returns — yearly panel: permno, year, gibbs where gibbs = 2*c (full effective spread).

What it does

Read CSV, average duplicate (permno, year) rows, multiply c by 2. Does not merge onto crsp_link — that is _expand_gibbs_to_monthly.


_expand_gibbs_to_monthly(gibbs_yearly, me)

Merges the yearly Gibbs estimates onto a monthly grid.

Signature

  • gibbs_yearly: output of load_gibbs.
  • me: expansion grid — the pipeline passes link_keys mimicking crsp_link (name-window + shrcd filter), not bare ccm_panel keys. The grid matters: it decides which stock-months receive a Gibbs value.

Returns — (permno, date, gibbs) monthly panel.


load_hf_spreads(filepath)

Signature

  • filepath: hf_monthly.csv with WRDS-style columns, built on WRDS Cloud by hf-spreads-all; see Trading-cost inputs.

Returns — permno, month-end date, hf_ave, hf_monthend, hf_n (hf_ave in decimal, not percent).


fill_missing_tcosts(tcosts_raw, me, ivol=None, universe_permnos=None)

Signature

  • tcosts_raw: (permno, date, tcost) — pre-fill half-spreads.
  • me: market equity panel.
  • ivol: optional; prefers column idiovol_ff_3m.
  • universe_permnos: restrict the grid to the domestic common-stock universe (shrcd 10–11).

Returns — filled (permno, date, tcost).

What it does

  1. Union universe from tcost rows, finite ME, finite ivol keys, so ranks include stocks without a raw tcost.
  2. Sort (date, permno) for stable rank and tie order.
  3. Pass 1: donors = raw finite tcost only; fill targets with finite ME+ivol; Euclidean distance on rank(me), rank(idiovol) (pandas ranks, method='average').
  4. Pass 2: donors still raw finite only (not pass-1 fills); ME rank only.

Ties among donors with indistinguishable ranks are broken by sort order, so for a target whose idiosyncratic volatility is numerically degenerate (~1e-20 regression round-off) the chosen donor is sensitive to floating-point noise. A handful of stock-months in the full CRSP sample are affected.


_winsorize(s, upper_pct=99.9)

Signature

  • s: numeric Series; upper cap only (lower unchanged).

Returns — capped copy.


combine_lf_spreads(hl=None, chl=None, vov=None)

Convenience wrapper for the low-frequency mean only; does not include Gibbs/HF. The production path uses make_trading_costs.

Signature

  • Optional panels for hl, chl, vov columns.

Returns — eff_spread (mean of available), tcost = eff_spread/2.

What it does

Winsorize each leg at 99.9%, outer-merge, row-wise mean skipping NaN.


_apply_exchange_exclusions(measures, exchcd)

Signature

  • measures: dict name → panel (mutated in place).
  • exchcd: monthly exchcd panel.

What it does

YYYYMM integer thresholds on merged rows:

Measure Exchange Through
all AMEX (2) 1961-12
gibbs, vov NASDAQ (3) 1982-12
hl, chl NASDAQ (3) 1992-12

NASDAQ stock-months from 1983 to 1992 therefore get Gibbs and VoV estimates but no HL/CHL.


make_trading_costs(...)

Signature

  • daily, me, optional ivol, exchcd, tcosts_type ('full' | 'lf_combo' | 'gibbs'), gibbs_path, hf_path, cpi, universe_permnos, link_keys, demo.
  • A missing gibbs_path raises MissingInputError; with demo=True it only warns and the Gibbs measure is omitted.

Returns — permno, date, tcost (filled half-spread); plus tcost_gibbs (filled Gibbs-only half-spread) when Gibbs path present.

What it does (execution order)

  1. Coerce nullable dtypes on daily.
  2. Load Gibbs; expand to monthly on link_keys or me.
  3. Pre-winsorize Gibbs fill: fill_missing_tcosts(gibbs/2) → tcost_gibbs.
  4. Compute HL, CHL, VoV when not 'gibbs' only.
  5. Load HF when 'full'.
  6. Restrict all measures to universe_permnos before winsorization, so the 99.9% cap is computed on the domestic common-stock pool.
  7. Winsorize each leg at 99.9%.
  8. Exchange exclusions unless 'gibbs' only.
  9. Combine: mean of LF (+ Gibbs in average); HF outer-merge overlay where finite.
  10. Half-spread tcost; fill_missing_tcosts on combined.
  11. Attach tcost_gibbs column.

Small helpers (grouped)

Name Role
LOGGER Module logger (assayinganomalies.transforms.tcosts).
FF_TC_COLS, FF_TC_CAPITAL_COLS, FF_TC_CAPITAL_SHORT_COLS, FF_TC_STORED_COLS, FF_TC_ANNUAL_COLS, FF_TC_RECORD_KEY, FF_TC_HELD, FF_TC_RECORD_VERSION, _FF_TC_MOM_ALIASES Constants for FF path — see 09b.
_row_lag, _nanmatsum, _matlab_prctile_rows, _assign_to_ptf, _make_univ_sort_ind, _make_biv_sort_ind, _month_rows, _wide, _ff_tcosts_or_zeros Matrix/sort helpers for the FF factor trading costs — 09b.