Skip to content

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 table nmv_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_var and check_fill_anomalies prepare 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 — long ccm_panel-like DataFrame with date, permno, and upstream derived columns (ret, me, bm, R12_2, ff49, …).
  • funda — unused; kept for API compatibility. All inputs now come from ccm_panel (Ch 7 merge), where quarterly/annual fields are pre-merged.
  • factors — optional monthly DataFrame with date, mktrf, rf for 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

  1. Normalizes input: if the index is a MultiIndex, reset; coerce date to datetime; sort by (permno, date). _enforce_annual_validity then blanks any annual Compustat value that is not on the row of its availability June (be/bm against be_avail_date, the others against comp_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.
  2. Precomputes FF49 industry value-weighted returns once via _compute_ff49_industry_returns — shared by signals 18–20 and 23.
  3. Calls each _signal_* in NMV_LABELS order and assembles columns.
  4. 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

  1. Builds nine binary indicators with (x > 0)*1 semantics — NaN comparisons contribute 0, not NaN.
  2. F_EQ uses June-only log growth of split-adjusted shares (shrout_adj, from the Ch 6 issuance plumbing), placed via _june_only.
  3. Sums indicators; sets score to NaN unless all nine availability flags are 1 (finiteness of the underlying differences).
  4. 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 with me, ret, idiovol, prc, quarterly fundamentals.
  • factors — monthly FF factors for EXRET; if missing, EXRETAVG is NaN and the linear combination propagates NaN (no fillna(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

  1. Early exit if CRSP core columns are missing or niq/ltq are all NaN.
  2. NIMTAAVG — exponentially weighted quarterly NIMTA with c = 2^(-1/3).
  3. EXRETAVG — lag-1 weight 1, then c^j for j=2..12 on log excess returns; market total return from mktrf + rf mapped by month.
  4. SIGMA — sqrt(252) * idiovol.
  5. RSIZE — log(me / cross-sectional sum of me).
  6. 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_key reindex), so it is held for the next 11 months and a stock with no row in that June has none.
  7. PRICE — min(|prc|, 15), NaN if < 1.
  8. Accumulates coef[k] * winsorize_xs(component) with plain + — any NaN component NaNs the sum (no nansum). 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 with date, permno, ret, me, ff49.
  • iret — (date × industry) VW returns from calc_ptf_rets.
  • ireta — each stock's contemporaneous industry return.

Returns

  • _compute_ff49_industry_returns → (iret, ireta) or (None, NaN series) if no ff49 column.
  • _industry_momentum_raw → rank-based industry momentum scaled to [0,1] per month.

What it does

  1. Builds MultiIndex (date, permno) series and calls calc_ptf_rets(ret, ind, me, holding_period=1, weighting="v") (Ch 13) — a value-weighted "sort" on industry codes.
  2. Maps each stock-month to its industry's contemporaneous return via stacked (date_code, ff49) keys.
  3. Industry momentum: iret.rank(axis=1, method="max") + 1 assigned 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

  1. Cross-sectional rank of ireta - ret via _cross_rank (average ranks for ties).
  2. 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

  1. 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.
  2. 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

  1. Starts from _signal_industry_relative_reversal.
  2. Computes the NYSE-only cross-sectional median of idiovol_ff_3m using _matlab_prctile(..., [50]) — a two-bin NYSE-breakpoint sort.
  3. NaN's IRR where ivol >= median (high-vol bin 2). Stocks with NaN idiovol_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

  1. Ranks momentum, _gp_at(p, monthly=True), and BM; sums.
  2. gp, at and bm are on the June rows of ccm_panel only (Ch 7). GP/AT and bm are 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_mom does the same with bm alone.

_signal_pead_sue(p) / _signal_pead_car3(p)

Signature — panel; CAR3 depends on Ch 8 daily stage populating car3.

Returns

  • _signal_pead_sue — sue2 if any non-null, else sue.
  • _signal_pead_car3 — car3 column 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_panel stores 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 with monthly=True carried through the following May.
  • _filled(values, p) — aa.fill_months with 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__ — exports NMV_LABELS, compute_nmv_anomalies only; _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)-indexed Series.

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

  1. 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).
  2. Tied rank → (rank-1)/(max-1) - 0.5.
  3. Fills NaN ranks with 0 where mcap is 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 after fill_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.