Chapter 11 — The 23 Novy-Marx/Velikov anomalies¶
Part II of the assayinganomalies tutorial. Prerequisite chapters: 1, 2, 3, 4, 5, 6, 7, 8, 10. Python modules covered:
transforms/nmv_anomalies.py,transforms/anomaly_fill.py.
What this chapter answers¶
- How the 23 Novy-Marx & Velikov (2016) benchmark signals are built from
ccm_panel, written to DuckDB tablenmv_anomalies, and loaded back for sorts and the assay protocol. - Which signals are thin column reads versus multi-step constructions (Piotroski, distress, industry momentum, PEAD, seasonality, etc.).
- How shared plumbing (
_lag_panel,_cross_rank,_june_only, percentile breakpoints, winsorization) keeps lags and cross-sectional ranks right on a long panel with gaps. - How
fill_varandcheck_fill_anomaliesprepare benchmark anomalies for combination-strategy tests (Chapter 18).
Where this sits in the pipeline¶
Stage compute-nmv-anomalies (Ch 4) runs after ccm_panel exists and after
monthly FF factors are in ts_data (needed for the distress signal's market
return). It reads the full panel, optionally passes mktrf/rf, calls
compute_nmv_anomalies, and replaces table nmv_anomalies.
flowchart LR
CCM[("ccm_panel")]
TS[("ts_data mktrf rf")]
DRV["compute_nmv_anomalies"]
FF49["calc_ptf_rets via _compute_ff49_industry_returns"]
OUT[("nmv_anomalies")]
LOAD["aa.load_nmv_anomalies (Ch 12)"]
PROTO["run_test_signal → check_fill_anomalies (Ch 16–18)"]
CCM --> DRV
TS --> DRV
CCM --> FF49 --> DRV
DRV --> OUT --> LOAD
OUT --> PROTO
Everything stays on the long (date, permno) panel produced upstream; each
signal is one value per (month, stock) cell.
Signal catalog (all 23)¶
All signals are signed so higher values predict higher returns (long side).
Column order matches NMV_LABELS.
| # | Signal | One-line definition | Primary inputs | Python |
|---|---|---|---|---|
| 1 | size |
Negative market equity, June only | me |
_signal_size |
| 2 | value |
Book-to-market, June only | bm |
_signal_value |
| 3 | grossProfitability |
GP/AT, excl. financials, June only | gp, at, fin_firm |
_signal_gross_profitability |
| 4 | valProf |
rank(GP/AT) + rank(BM), June only | gp, at, bm, fin_firm |
_signal_val_prof |
| 5 | accruals |
Sloan accruals, sign-flipped, scaled by AT, June only | act, che, lct, dlc, txp, dp, at |
_signal_accruals |
| 6 | assetGrowth |
−AT/lag(AT,12), excl. financials, June only | at, fin_firm |
_signal_asset_growth |
| 7 | investment |
−(ΔPPEGT+ΔINVT)/lag(AT,12), excl. financials, June only | ppegt, invt, at, fin_firm (or inv_capital) |
_signal_investment |
| 8 | piotroski |
Piotroski F-score (9 binaries) + BM tiebreaker | ib, cfo, at, dltt, act, lct, revt, cogs, shrout_adj, bm |
_signal_piotroski |
| 9 | issuance |
−log annual growth of split-adjusted shares | shrout_adj |
_signal_issuance |
| 10 | roe |
IBQ / lag(BEQ, 3 months) | ibq, beq |
_signal_roe |
| 11 | distress |
−Campbell–Hilscher–Szilagyi failure probability | me, ret, idiovol, prc, niq, ltq, cheq, be, FF mktrf/rf |
_signal_distress |
| 12 | valMomProf |
rank(R12_2) + rank(GP/AT) + rank(BM), monthly | R12_2, gp, at, bm, fin_firm |
_signal_val_mom_prof |
| 13 | valMom |
rank(R12_2) + rank(BM), monthly | R12_2, bm |
_signal_val_mom |
| 14 | idiosyncraticVolatility |
−3-month FF3 idiosyncratic vol | idiovol_ff_3m |
_signal_idio_vol |
| 15 | momentum |
12–2 month past return | R12_2 |
_signal_momentum |
| 16 | peadSUE |
Standardized unexpected earnings (SUE2) | sue2 (fallback sue) |
_signal_pead_sue |
| 17 | peadCAR3 |
3-day CAR around earnings announcement | car3 |
_signal_pead_car3 |
| 18 | industryMomentum |
Rank of FF49 industry VW return | ret, me, ff49 |
_signal_industry_momentum |
| 19 | industryRelativeReversal |
Rank of (industry return − stock return), scaled | ret, ff49, industry returns |
_signal_industry_relative_reversal |
| 20 | highFrequencyCombo |
IRR + industry momentum | industry machinery + ret |
_signal_high_freq_combo |
| 21 | reversals |
−monthly return | ret |
_signal_reversals |
| 22 | seasonality |
Heston–Sadka: sum ret at lags 11,23,35,47,59 | ret |
_signal_seasonality |
| 23 | industryRelativeReversalLowVol |
IRR for low-IffVOL3 (NYSE median) stocks | idiovol_ff_3m, nyse_flag, industry IRR |
_signal_irr_low_vol |
Signals 1–7, 9–10, 13–15, 21 are mostly column arithmetic plus optional
_june_only / _lag_panel. The sections below give full template treatment for
the machinery signals; simple ones are defined entirely by the table above.
compute_nmv_anomalies(panel, funda=None, factors=None)¶
Signature
panel— longccm_panel-like DataFrame withdate,permno, and upstream derived columns (ret,me,bm,R12_2,ff49, …).funda— unused; kept for API compatibility. All inputs now come fromccm_panel(Ch 7 merge), where quarterly/annual fields are pre-merged.factors— optional monthly DataFrame withdate,mktrf,rffor distress EXRET.
Returns — DataFrame with columns date, permno, and the 23 NMV_LABELS
signals. Rows where every signal is NaN are dropped.
What it does
- Normalizes input: if the index is a MultiIndex, reset; coerce
dateto datetime; sort by(permno, date)._enforce_annual_validitythen blanks any annual Compustat value that is not on the row of its availability June (be/bmagainstbe_avail_date, the others againstcomp_avail_date). On a panel the build wrote this changes nothing, because annual columns are stored on the June row only (Ch 7); on a panel filled June to May, or an edited one, it logs a warning with the count. - Precomputes FF49 industry value-weighted returns once via
_compute_ff49_industry_returns— shared by signals 18–20 and 23. - Calls each
_signal_*inNMV_LABELSorder and assembles columns. - Logs per-signal non-null counts.
Pipeline wiring (pipeline.py) reads ccm_panel, loads mktrf/rf from
ts_data when present, and writes nmv_anomalies; load_nmv_anomalies
(Ch 12) reads it back. The stage stops on a database built before annual
columns were stored in June only (no metadata.annual_layout record and
annual values in the panel) and names the rebuild,
aa setup-database --start-from transform-compustat; the stage
validate-bm-hml does the same.
Annual inputs. The annual Compustat columns arrive with values in June
only. Signals 1–7 and the other June-based ones (the valProf ranks, the
Piotroski tiebreaker, the distress MB, 12-month lags of June values) use
them where they are. Two signals need annual values every month: valMom
and valMomProf carry the June bm and GP/AT through the following May with
_filled, which is aa.fill_months(…, 11) (MATLAB's FillMonths), and rank
them each month. validate-bm-hml fills bm the same way before its monthly
sort. A stock with no panel row in the June of a record has no value from it,
so it is missing from those two signals and from validation_bm_hml until
its next June; MATLAB, and versions that stored the columns filled June to
May, kept it.
Machinery signals (full template)¶
_signal_piotroski(p)¶
Signature
p— panel DataFrame with profitability, leverage, and efficiency inputs listed in the catalog table.
Returns — pd.Series aligned to p.index: integer F-score 0–9 plus a
June-only BM tiebreaker in (0, 1), ranked cross-sectionally within the
month.
What it does
- Builds nine binary indicators with
(x > 0)*1semantics — NaN comparisons contribute 0, not NaN. F_EQuses June-only log growth of split-adjusted shares (shrout_adj, from the Ch 6 issuance plumbing), placed via_june_only.- Sums indicators; sets score to NaN unless all nine availability flags are 1 (finiteness of the underlying differences).
- Adds the BM tiebreaker via
_cross_rank_unit(_june_only(bm, p), p)— a tied rank across the month's stocks divided by one more than the number ranked, so it stays inside(0, 1)and orders stocks within an F-score level rather than across levels.
The tiebreaker differs from the original MATLAB toolkit, whose
tiedrank(bm)/1000 ranked each stock against its own full-sample BM history (the
wrong axis, and forward-looking); piotroski values and their sort returns
therefore differ from that toolkit's.
_signal_distress(p, factors=None)¶
Signature
p— panel withme,ret,idiovol,prc, quarterly fundamentals.factors— monthly FF factors for EXRET; if missing, EXRETAVG is NaN and the linear combination propagates NaN (nofillna(0)).
Returns — -DISTRESS where DISTRESS is the Campbell et al. (2008) linear
index with 5% cross-sectional winsorization on each of eight components.
What it does
- Early exit if CRSP core columns are missing or
niq/ltqare all NaN. - NIMTAAVG — exponentially weighted quarterly NIMTA with
c = 2^(-1/3). - EXRETAVG — lag-1 weight 1, then
c^jfor j=2..12 on log excess returns; market total return frommktrf + rfmapped by month. - SIGMA —
sqrt(252) * idiovol. - RSIZE — log(me / cross-sectional sum of me).
- MB — June-only
adjBE = 0.9*BE + 0.1*me, lag(me,6)/adjBE; each month then looks up the value on the stock's row of the June that opens its June-to-May window (a_month_keyreindex), so it is held for the next 11 months and a stock with no row in that June has none. - PRICE —
min(|prc|, 15), NaN if< 1. - Accumulates
coef[k] * winsorize_xs(component)with plain+— any NaN component NaNs the sum (nonansum). Winsorization uses_matlab_prctile/_winsorize_xs(see Shared plumbing).
The distress signal needs ts_data (monthly mktrf/rf) for full coverage.
_compute_ff49_industry_returns(p) and _industry_momentum_raw(p, iret, ireta)¶
Signature
p— panel withdate,permno,ret,me,ff49.iret—(date × industry)VW returns fromcalc_ptf_rets.ireta— each stock's contemporaneous industry return.
Returns
_compute_ff49_industry_returns→(iret, ireta)or(None, NaN series)if noff49column._industry_momentum_raw→ rank-based industry momentum scaled to [0,1] per month.
What it does
- Builds MultiIndex
(date, permno)series and callscalc_ptf_rets(ret, ind, me, holding_period=1, weighting="v")(Ch 13) — a value-weighted "sort" on industry codes. - Maps each stock-month to its industry's contemporaneous return via stacked
(date_code, ff49)keys. - Industry momentum:
iret.rank(axis=1, method="max") + 1assigned by industry, zero or NaN industry assignment → NaN, divide by monthly max (_scale_to_unit).
_signal_industry_momentum(p, iret, ireta)¶
Signature — passes through to _industry_momentum_raw.
Returns — industry momentum signal (catalog #18).
What it does — Thin wrapper around _industry_momentum_raw.
_signal_industry_relative_reversal(p, ireta)¶
Signature
ireta— contemporaneous FF49 industry return per stock-month.
Returns — tied rank of ireta - ret divided by the month's max rank.
What it does
- Cross-sectional rank of
ireta - retvia_cross_rank(average ranks for ties). - Divide by monthly max rank.
_signal_high_freq_combo(p, iret, ireta)¶
Signature — industry return tensors plus panel.
Returns — IRR + IMOM (catalog #20).
What it does — Sums _signal_industry_relative_reversal and
_industry_momentum_raw.
_signal_seasonality(p)¶
Signature — panel with ret.
Returns — sum of lag(ret, 12*i - 1) for i=1..5 (lags 11, 23, 35, 47, 59).
What it does
- Accumulates five calendar lags via
_lag_panel. With plain+, any missing lag NaNs the sum, so the first 59 months of each stock are NaN. - Sets exact zeros to NaN after the sum.
_signal_irr_low_vol(p, ireta)¶
Signature — panel with idiovol_ff_3m, optional nyse_flag; industry IRR
inputs via ireta.
Returns — industry-relative reversal with high-volatility stocks NaN'd.
What it does
- Starts from
_signal_industry_relative_reversal. - Computes the NYSE-only cross-sectional median of
idiovol_ff_3musing_matlab_prctile(..., [50])— a two-bin NYSE-breakpoint sort. - NaN's IRR where
ivol >= median(high-vol bin 2). Stocks with NaNidiovol_ff_3m, and months without a breakpoint, keep their IRR.
_signal_val_mom_prof(p)¶
Signature — panel with R12_2, gp, at, bm, fin_firm.
Returns — sum of three cross-sectional ranks; monthly (not June-only).
What it does
- Ranks momentum,
_gp_at(p, monthly=True), and BM; sums. gp,atandbmare on the June rows ofccm_panelonly (Ch 7). GP/AT andbmare carried through the following May with_filled(aa.fill_months, 11 months) and ranked every month. GP/AT is filled before financial firms are dropped, so the flag is each month's own._signal_val_momdoes the same withbmalone.
_signal_pead_sue(p) / _signal_pead_car3(p)¶
Signature — panel; CAR3 depends on Ch 8 daily stage populating car3.
Returns
_signal_pead_sue—sue2if any non-null, elsesue._signal_pead_car3—car3column or all NaN with info log.
What it does — Column reads with fallback. SUE is computed upstream in Ch 7;
CAR3 is merged by pipeline stage compute-car3 before the NMV stage. If
compute-car3 was skipped, signal 17 is all NaN but the other signals still
export (rows are dropped only when all 23 are NaN).
Shared plumbing (Small helpers)¶
These utilities appear across many _signal_* functions. First use in this chapter
is documented here; later signals refer back.
_cross_rank(s, panel)¶
Cross-sectional tied rank within each date using rank(method="average").
_month_key(panel) / _lag_panel(s, panel, months)¶
_month_key encodes permno * 10^5 + (year*12 + month) for calendar-aware joins.
_lag_panel reindexes by key - months so a lag is always calendar months,
not row shifts — critical when permno rows have gaps, where a positional shift
would silently reach back too far.
_matlab_prctile(values, pcts) / _winsorize_xs(s, panel, pct=5.0)¶
This module’s 1-D percentile and cross-sectional winsorization helpers. The
percentile follows the original MATLAB toolkit's prctile interpolation rather
than numpy's default; the rule and the three package copies are in
Ch 9,
and the sorts 1-D version is in Ch 13.
Used here by distress and _signal_irr_low_vol. Drops non-finite values (unlike
tcosts’ _matlab_prctile_rows, which keeps ±Inf).
_scale_to_unit(s, panel)¶
Divide by the monthly max.
_safe_col(p, col) / _june_only(sig, p) / _gp_at(p)¶
_safe_col— missing column → NaN series._june_only— NaN outside June.ccm_panelstores annual columns on the June row only, so for a signal built from them alone the mask changes nothing; it matters where a monthly column enters (me,shrout_adj,fin_firm). This follows the original MATLAB toolkit, whose annual signals exist only in June._gp_at(p, *, monthly=False)— GP/AT with financials masked; June rows only, or withmonthly=Truecarried through the following May._filled(values, p)—aa.fill_monthswith 11 months on a series aligned to the panel's rows: a June value runs through the following May._enforce_annual_validity(p)— see the driver above.
Other grouped items¶
NMV_LABELS— canonical column order.LOGGER— info-level progress in driver and distress/CAR3 branches.__all__— exportsNMV_LABELS,compute_nmv_anomaliesonly;_signal_*are internal.
Simple _signal_* functions (size, value, momentum, reversals, etc.) — see the
catalog table.
anomaly_fill.py — benchmark signal preparation¶
These functions are not used when building nmv_anomalies. They run inside
run_test_signal (Ch 16) when the "fill" stage is enabled, before combination
strategy builders (Ch 18) consume a standardized, coverage-screened anomaly set.
fill_var(var, mcap)¶
Signature
var,mcap—(date, permno)-indexedSeries.
Returns — cross-sectional ranks mapped to [-0.5, 0.5], with stocks that have market cap but missing signal set to 0 (median rank); no-cap → NaN.
What it does
- Infers update frequency from the median gap between months with observations (not from signal metadata); if not monthly, forward-fills within permno with limit 11 (annual), 5 (semi-annual), or 2 (quarterly).
- Tied rank →
(rank-1)/(max-1) - 0.5. - Fills NaN ranks with 0 where
mcapis finite.
Ch 18 combination strategies assume this scale.
check_fill_anomalies(anoms, mcap, time_period, mcap_thresh=0.40, n_roll=120, seed=0)¶
Signature
anoms— dict or DataFrame of raw signals (NMV + Chen–Zimmerman in protocol).mcap— market cap MultiIndex series.time_period—(start, end)as YYYYMM ints or timestamps.mcap_thresh— 0.40 average coverage vs ME universe.n_roll— 120-month rolling window (~10 years).seed— seed for the tie-break noise (randn*1e-12) added before sorting, so results are reproducible run to run.
Returns — (filled, keep, keep_roll):
filled— dict of kept anomalies afterfill_var.keep— bool Series over anomaly names (average coverage test).keep_roll—(date × anomaly)bool, rolling coverage for combination tests.
What it does
Per anomaly: add noise; mask to mcap finite; find sample window; require more
than n_roll months inside window; require the sample mean of
n_obs / n_finite_me to exceed mcap_thresh; if kept, fill_var and rolling
mask. Prints progress per anomaly.
Protocol fallback when zero anomalies pass: analytics/protocol.py fills all
raw signals anyway so smoke tests still run.