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 throughmake_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_rowsdiffers 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-Dfloat64arrays (same length), split-adjusted daily high/low and lags.
Returns — same shape, daily Corwin–Schultz spread s (non-negative real).
What it does
- 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
logof a negative ratio silently returned a complex number. - Zero or NaN gates on non-positive highs/lows.
- Compute
beta,gamma,alpha, spreads; zero negative real parts.
compute_corwin_schultz(daily, min_days=12)¶
Signature
daily: long panel withpermno,date,prc,askhi,bidlo; optionalcfacpr.min_days: minimum valid daily spreads per month (default 12).
Returns — DataFrame: permno, month-end date, hl.
What it does
- Sort by
(permno, date); setaskhi/bidloNaN whenprc < 0. - Overnight adjustment (Section II.A of Corwin–Schultz).
- Lag adjusted hi/lo with split factors.
- Apply
_cs_spreadper day; rerun in complex arithmetic for stocks with negative ratios after the overnight adjustment. - Monthly mean of finite daily spreads; require
min_daysvalid days.
compute_abdi_ranaldi(daily, min_days=12)¶
Signature
daily:permno,date,prc,askhi,bidlo.
Returns — permno, month-end date, chl.
What it does
- Build global trading calendar from all dates in
daily. - 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.
- Forward-fill close/high/low on days without a row.
- Midpoint and lead-by-one calendar day; at span end use the carried value.
sqrt(fmax(4*(c-η)(c-η'), 0))withnp.fmax, so NaN inputs contribute 0 to the monthly mean.- Gate: ≥
min_dayswith rawprc > 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,retorret_adj,prc,vol. Pipeline passes rawretafter dlret placement (Ch 8 / pipeline stage).cpi: optional month-endSeries; defaultload_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 (viacrsp_daily.adjust_nasdaq_volume).
Returns — permno, month-end date, vov.
What it does
- Dollar volume
dvol = vol_adj * |prc|. - Per
(permno, month):ret_stdwith ddof=1 (sample std, NaN omitted);vol_meanincludes zero-volume days. - CPI normalize:
CPIAUCNS / CPIAUCNS(Jan-2000). - 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 triesData/CPIAUCNS.csvunder the project root (and a legacy-toolkit input folder, if present), then downloads FREDCPIAUCNSand caches it toData/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 tocrspgibbs*.csvwith columnspermno,year,c. The package ships it atinputs/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 ofload_gibbs.me: expansion grid — the pipeline passeslink_keysmimickingcrsp_link(name-window + shrcd filter), not bareccm_panelkeys. 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.csvwith WRDS-style columns, built on WRDS Cloud byhf-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 columnidiovol_ff_3m.universe_permnos: restrict the grid to the domestic common-stock universe (shrcd 10–11).
Returns — filled (permno, date, tcost).
What it does
- Union universe from tcost rows, finite ME, finite ivol keys, so ranks include stocks without a raw tcost.
- Sort
(date, permno)for stable rank and tie order. - Pass 1: donors = raw finite tcost only; fill targets with finite ME+ivol;
Euclidean distance on
rank(me),rank(idiovol)(pandas ranks,method='average'). - 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: numericSeries; 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,vovcolumns.
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: monthlyexchcdpanel.
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, optionalivol,exchcd,tcosts_type('full'|'lf_combo'|'gibbs'),gibbs_path,hf_path,cpi,universe_permnos,link_keys,demo.- A missing
gibbs_pathraisesMissingInputError; withdemo=Trueit 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)
- Coerce nullable dtypes on daily.
- Load Gibbs; expand to monthly on
link_keysorme. - Pre-winsorize Gibbs fill:
fill_missing_tcosts(gibbs/2)→tcost_gibbs. - Compute HL, CHL, VoV when not
'gibbs'only. - Load HF when
'full'. - Restrict all measures to
universe_permnosbefore winsorization, so the 99.9% cap is computed on the domestic common-stock pool. - Winsorize each leg at 99.9%.
- Exchange exclusions unless
'gibbs'only. - Combine: mean of LF (+ Gibbs in average); HF outer-merge overlay where finite.
- Half-spread
tcost;fill_missing_tcostson combined. - Attach
tcost_gibbscolumn.
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. |