Chapter 10 — Betas¶
Part II of the assayinganomalies tutorial. Prerequisite chapters: 1, 2, 3, 4, 5, 8. Python modules covered:
transforms/betas.py.
What this chapter answers¶
- How six Novy-Marx/Velikov (2022) beta variants are estimated from daily CRSP
returns and daily Fama–French factors, and merged into
ccm_panel. - Why
_insert_matlab_dlret_rowsruns before beta estimation (and before daily aggregates in Ch 8) even though the helper lives in this module. - How Frazzini–Pedersen beta splits correlation (5-year 3-day log returns) from volatility (1-year daily log returns), then shrinks toward 1.
- How OLS-family betas share one trailing-year window but differ in regression spec (Dimson lag), winsorization (Welch), and shrinkage (Vasicek, Standard).
- How all three of those regressions are solved as one batch of stacked normal
equations built from per-
(stock, month)sufficient statistics, and what that costs in floating-point agreement with a per-window loop. - Why the Frazzini–Pedersen leg sums those statistics with a carried rounding error while the OLS leg does not.
- What
_nanolsdoes locally versusanalytics/ols.py::nanols. - Which beta types are not implemented (e.g.
compute_downside_beta()).
Where this sits in the pipeline¶
Stage compute-betas (Ch 4) runs after daily CRSP and daily FF factors are
staged, and after ccm_panel exists (for month-end dates and the domestic-common
universe filter). It reads raw daily parquet (not ret_adj), optionally inserts
synthetic dlret rows, calls compute_betas, writes table betas, and
left-joins six columns onto ccm_panel.
"Optionally" is load-bearing: the insertion is gated on
ctx.source.apply_delisting_overlay (Ch 5) and does not happen under the CIZ
tape, which writes the delisting row itself. See the callout on
_insert_matlab_dlret_rows below.
It takes (permno, date, ret) from PipelineContext.daily_raw(), the one shared
copy of the staging parquet, so in a full build it re-reads nothing. Reading
the stored crsp_daily_panel instead would be a mistake. The panel's ret is
bit-identical to the parquet's on all 107,663,470 rows, but the column a reader
reaches for is ret_adj, which places each delisting return on its event date,
whereas beta estimation needs the payoff on the trading day after (r+1, below)
— the two differ on 27,346 cells by up to 36.0.
flowchart LR
DSF["crsp_daily_raw.parquet"]
FF["crsp_daily_factors.parquet"]
DEL["msedelist (daily dlret)"]
CCM[("ccm_panel dates + universe")]
INS["_insert_matlab_dlret_rows"]
CB["compute_betas"]
AGG["aggregate_betas_to_monthly"]
BT[("betas")]
OUT[("ccm_panel + bfp…bstd")]
DSF --> INS
DEL --> INS
FF --> INS
INS --> CB
FF --> CB
CCM --> CB
CB --> AGG --> BT --> OUT
AGG --> OUT
Everything stays on a long (permno, date) panel; calendar-aware merges, global
month-end gates and synthetic delisting rows give each estimator the same cells a
dense date × stock matrix would.
Sample start offsets. With sample_start = S, FP betas begin at month-end
S+3 (need 60 months of 3-day history); OLS-family betas begin at S+1 (need
12 trailing months). compute_betas splits month_ends accordingly.
The six estimators — math then code¶
Excess stock return is (xret = ret - rf); market excess is mktrf (stored as
dmkt after fillna(0)).
| Column | Estimator | Compact definition |
|---|---|---|
bfp |
Frazzini–Pedersen | (\tilde\beta = 0.6\,(\rho\,\sigma_s/\sigma_m) + 0.4) where (\rho) comes from 5y of 3-day log returns and (\sigma_s,\sigma_m) from 1y of daily log returns |
bols |
OLS benchmark | (\hat\beta) from (xret_t = \alpha + \beta\, dmkt_t + \varepsilon_t) over trailing 12 months (≥120 valid days) |
bdim |
Dimson | (\hat\beta = \hat\beta_{mkt} + \hat\beta_{L1}) from (xret_t = \alpha + \beta_1 dmkt_t + \beta_2 dmkt_{t-1} + \varepsilon_t) |
bsw |
Welch | Same as bols but (xret) winsorized to ([\min(-2m,4m), \max(-2m,4m)]) per day; non-trading stock-days filled at the lower bound on the dense factor calendar |
bvck |
Vasicek | (w_i = \sigma_T^2/(\sigma_T^2 + se_i^2)), (\beta_i^{vck} = w_i \hat\beta_i + (1-w_i)\bar\beta) with (\sigma_T^2 = \mathrm{Var}_{cs}(\hat\beta)) (sample var, ddof=1) |
bstd |
Standard | (0.6\,\beta^{dim} + 0.4) |
Shared eligibility (all six): finite excess return on the global last trading
day of the estimation month (not the stock’s last row in the month); minimum
daily/3-day counts as in the table above. Months are pd.Period("M") internally
and month-end timestamps aligned with ccm_panel on output.
Betas are second-pass statistics — rolling sums of logs, correlations from sufficient statistics, regressions, cross-sectional shrinkage — so they are more sensitive than raw returns to tiny differences in window membership (calendar, delisting placement, dropped −100% days). The gates above are what pin that membership down.
_insert_matlab_dlret_rows(daily, delist, factors)¶
SIZ only.
_stage_compute_betasobtains its events through_daily_dlret_events(ctx, what="beta estimation"), which returnsNoneon a tape whose daily file already carries the delisting payoff as its own row — so under CIZ this function is never called and the beta estimators see the raw daily returns unchanged. Placing a row there would double-count the payoff in all six estimators. CIZ-vs-SIZ betas on a matched 2019 window agree to rounding (correlation 1.0000, median relative difference 0–1e-6) acrossbols,bdim,bsw,bvckandbstd;bfpneeds three years of history, so that short window could not compare it.
Signature
daily— long panel withpermno,date,retorret_adj.delist— CRSP daily delist file (permno,dlstdt,dlret; optionaldlstcd).factors— daily FF factors (defines part of the trading calendar).
Returns — copy of daily with ret/ret_adj overwritten or new rows appended
at placement dates.
What it does — Builds the union calendar of factor dates and daily dates
(the union matters: CRSP daily has pre-1926 dates that the FF factors alone do
not). For each delist event, determines index r: if return on dlstdt is NaN
but the prior trading day is finite, r = dlstdt_idx; else
r = last_finite_idx + 1. Places dlret at r+1 on the trading-day grid.
Overwrites the return on existing (permno, date) keys; appends sparse rows with
NaN in other columns. Filters out the file-wide max dlstdt and dlstcd == 100
when dlstcd is present. This placement follows the original MATLAB toolkit,
which put each delisting return at calendar index r+1 of its daily return
matrix.
How it addresses rows — Every row is one packed integer,
permno * stride + calendar position, and every lookup is a searchsorted into
the sorted key array. The reason is scale, not elegance: three pipeline stages
run this over the ~100M-row daily panel to resolve about 20k placements, and a
(permno, date) MultiIndex built and probed for the same job accounted for 90s
of a 117s call. The stride is one past the last calendar slot so that undated
rows get a slot of their own that cannot collide with the next permno, which is
what makes the packed key sort exactly as sort_values(["permno", "date"]) would,
with NaT last.
Besides compute_betas, it is also called from _stage_aggregate_daily and
_stage_compute_car3 in pipeline.py (Ch 8). The result does not depend on
input row order.
_nanols(y, X)¶
Signature
y—(T,)response.X—(T, K)design matrix (include intercept column explicitly).
Returns — (beta, se) each shape (K,): OLS coefficients and standard errors
of coefficients (no t-stats or R²).
What it does — Masks rows with any non-finite value in y or X. Requires
n >= k + 1 observations, otherwise returns NaN. Solves the normal equations
with np.linalg.solve; residual variance (s^2 = e'e/(n-k));
se = sqrt(diag(s^2 (X'X)^{-1})).
compute_ols_betas does not call this — it builds the same normal equations from
cell sums and solves them in one stacked np.linalg.solve — so _nanols is the
specification the batched kernel is checked against rather than the code that
produces the shipped betas. It has no production caller left in the module:
compute_fp_beta computes its betas from correlations and standard deviations,
never a regression. compute_idiovol has its own kernel,
crsp_daily._nanols_resid_rms.
Relationship to analytics/ols.py::nanols
Both drop NaN rows then run OLS. The analytics version (Ch 14) returns a full
OlsRes dataclass, uses np.linalg.pinv for (X'X), and accepts pandas-like
inputs. _nanols is a minimal (beta, se) kernel; it is not imported from
analytics/ols.py. Consolidating to one implementation is an optimization
candidate — verify pinv vs solve and the n >= k+1 gate before swapping.
compute_fp_beta(daily, factors, month_ends, …)¶
Signature
daily,factors— as in module docstring;retorret_adj; factors needdate,mktrf,rf.month_ends— month-end timestamps at which to emit betas.corr_months=60,std_months=12,min_3day=750,min_daily=120,shrinkage=0.6— window lengths, count filters, and0.6*beta + 0.4*1.
Returns — DataFrame with date, permno, bfp (month-end dates).
What it does
Like the OLS family, every quantity FP needs is a sum over the window's daily
rows, so the shape is the same: reduce the daily panel once to per-(stock,
month) sufficient statistics, then sum each trailing window. Array code over the
whole panel does this — no per-stock loop — in about 159s on the full panel
(2,937,058 output rows).
-
Join to the trading calendar — Each daily row is placed by
searchsortedonto the deduplicated factor calendar and rows off it are dropped;xret = ret - rf,dmkt = mktrffilled with 0. -
3-day compounded returns — The rows are sorted by
(stock, calendar position), so the k-th previous row is the k-th previous trading day exactly when it belongs to the same stock and sits k positions back; any other lag is NaN, so a missing stock day yields NaN in the lag product. Compound:xret3 = (1+xret)(1+lag1)(1+lag2)-1(and same for market). -
Log-return validity — For both 3-day and daily series, keep days with finite returns and
ret > -1solog1pis real. A −100% delist day must drop from both stock and market columns in the daily std series. -
Monthly sufficient statistics — One cell per
(permno, month)holdingn,sx,sy,sxx,syy,sxyfor 3-day logs andn,sx,sxx,sy,syyfor daily logs. 82.8M daily rows collapse to ~3.93M cells; correlation and population std are recovered from the sums without storing every day. -
Global month-end gate — A cell is eligible only if the stock's last row of the month sits on the month's global last factor trading day and carries a finite
xret. This is also why the windows can be summed over observed cells rather than a dense per-stock month grid: a month the stock sat out has no row on that day, so it can never produce output, and it contributes nothing to any window either. -
Trailing windows —
_trailing_month_sumsadds each cell's own row plus the 59 (corr) or 11 (std) rows behind it, bounded by the stock and by the window's month span. Pearson (\rho) from sums; (\sigma_s,\sigma_m) as population std (sqrt(sxx/n - (sx/n)^2), ddof=0). -
Beta and shrinkage —
raw = rho * std_s / std_m;bfp = shrinkage * raw + (1-shrinkage). Keep rows withn3 >= 750,nd >= 120,has_last, finite result, anddateinmonth_ends.
Why FP carries a rounding error and the OLS family does not¶
Both legs sum the same kind of cell, but FP divides two of those sums and subtracts: (\sigma = \sqrt{sxx/n - (sx/n)^2}). For a stock whose excess return did not move all year — 252 identical values, which the real panel does contain — the exact answer is 0, and the subtraction has no significant digits left to give. A sum that is a few ULPs off the correctly rounded total puts ~1e-20 under that square root, and the root turns it into a (\sigma) of ~1e-10 and a beta of ~1e-9 where there should be none.
So both of FP's reductions carry the rounding error alongside the running total
(_segment_sums for the daily→cell step,
_trailing_month_sums(..., compensated=True) for the windows), which makes each
sum correctly rounded — what math.fsum returns. It costs 86s of the 159s. On
the full panel, plain summation and compensated summation disagree by more than
1e-12 relative on 8 of 2,937,058 stock-months; exact rational arithmetic puts the
compensated value on the nose and the plain one up to 1.9e-9 out. Six of the
eight are exactly this case — the compensated value is 0.4 to the last bit, the
shrinkage constant a zero beta shrinks to, and the plain one is not. The other
two are betas near 1e-5, where the relative gap is large only because the values
are: 4e-16 absolute. The OLS family needs none of this — its normal equations
have no cancelling subtraction of two sums — so compute_ols_betas uses the
plain np.add.reduceat reduction and the uncompensated window sum.
The output does not depend on input row order.
compute_ols_betas(daily, factors, month_ends, …)¶
Signature
lookback_months=12,min_daily=120— trailing window and count gate.
Returns — date, permno, bols, bdim, bsw, bvck, bstd.
What it does
Shared setup — Build a global dmkt_L1 = shift(mktrf, 1) on the factor
calendar, so each stock row on day (t) pairs with market (t-1) even across
stock-specific gaps. Welch bounds per day: lo = min(-2*m, 4*m),
hi = max(-2*m, 4*m).
All three regressions are one batched solve. Instead of a _nanols call per
regression per stock-month (which took ~76 minutes), a three-step reduction runs
21.9x faster and agrees with that loop to 2.7e-14 absolute on the full panel.
Every entry of every normal-equation system is a sum over the window's daily
rows, which is what makes the loop removable at all.
-
Reduce to
(stock, month)cells — Join daily rows to the factor calendar by position, drop rows off the calendar, and accumulate 18 sufficient statistics per cell withnp.add.reduceat: counts, first and second moments ofxret,dmkt,dmkt_L1and their cross-products, plus the two Welch terms. Thebolsandbdimdesigns get separate counts and sums because_nanolsdrops a row for a non-finite entry anywhere inyorX, and the Dimson design carries one column more. 82.8M daily rows collapse to ~3.93M cells. -
Sum each trailing window —
_trailing_month_sumsadds each cell's own row plus thelookback_months - 1rows behind it, bounded by the stock and by the window's month span. Shifted adds, deliberately not prefix-sum differences, which lose precision through cancellation. This is the uncompensated branch; FP asks the same function for the compensated one. -
Solve the stacks — Select eligible cells, then one
_batched_solveper regression.
-
Eligibility —
>= min_dailyfinite excess returns in the window, plus a finitexreton the global last trading day ofmonth_end. The gate reads the stock's last row of the month, not a window sum. -
bols— 2x2 stack forxret ~ [1, dmkt]. The standard error Vasicek needs would bes² · inv(X'X)[1,1], andnp.linalg.invon a 3.7M-deep stack costs 79s againstsolve's 1.6s — so the unit vector rides along as a second right-hand side and the inverse element comes out of the second solution column. The residual sum of squares comes from the same sums, as (y'y - 2\beta'X'y + \beta'X'X\beta). -
bdim— 3x3 stack forxret ~ [1, dmkt, dmkt_L1];bdim = beta[1] + beta[2]. -
bsw— Welch regresses on the dense factor calendar with the lower bound standing in for every day the stock did not trade, soX'Xand the lower-bound part ofX'ydepend only on the month and are computed once for all stocks. Only the traded days' deviation from that bound is stock-specific — two of the eighteen statistics. -
Singular windows —
_batched_solveruns the stack throughnp.linalg.solve, and on theLinAlgErrora singular member raises for the whole batch it retries the non-zero-determinant subset and leaves the rest NaN. That reproduces_nanols, which answers NaN rather than raising.
Because the sums are associated differently from a per-window regression, results
differ from a per-window _nanols loop by floating-point noise (order 1e-14
absolute); for betas very close to zero that can look large in relative terms.
Vasicek (bvck) — Cross-sectional sample variance of bols with ddof=1.
Weight (w = \sigma_T^2/(\sigma_T^2 + se_i^2)); shrink toward the cross-sectional
mean. When the pipeline passes universe_permnos (domestic common shares, shrcd
10/11), that is the cross-section.
The rows leave step 3 ordered by (stock, month), so one lexsort into
(month, stock) — which is the output order anyway — makes every month a
contiguous slice, and the per-month np.nanmean / np.nanvar read it without
materializing a group (1.70s, versus 2.26s for a groupby("date").apply()).
The reductions themselves are one per month over a few thousand stocks, and
nothing is gained by reassociating them into a grouped sum.
Standard (bstd) — 0.6 * bdim + 0.4.
The output does not depend on input row order.
compute_betas(daily, factors, month_ends, …)¶
Orchestrates the FP estimator, then the OLS family.
Signature
sample_start=1963— sets FP/OLS start offsets (+3/+1years).delist— optional; triggers_insert_matlab_dlret_rows.universe_permnos— restrict panel before estimation (Vasicek cross-section).
Returns — outer merge of FP and OLS columns on (date, permno), as one long
DataFrame.
What it does — Filter universe; insert dlret rows; split month_ends into
FP and OLS subsets; call compute_fp_beta and compute_ols_betas; outer-merge.
Pipeline wiring (_stage_compute_betas in pipeline.py) takes the shared raw
daily panel (raw ret plus placement rows, not ret_adj), daily delist,
domestic-common permnos when dom_com_eq, then writes betas and merges into
ccm_panel.
aggregate_betas_to_monthly(betas)¶
Signature — betas: output of compute_betas.
Returns — same columns; date forced to month-end via MonthEnd(0).
What it does — Pass-through normalization for DuckDB merge consistency.
Not implemented: compute_downside_beta() and other beta types¶
compute_downside_beta() (a conditional beta on market-down days only) is
out of scope. The production beta set is exactly the six columns above; there is
no seventh beta. There is likewise no coskewness or other "alternative beta".
Small helpers¶
LOGGER— module logger. Neither estimator has a stock loop to report progress from, so each logs the reduction's shape once (daily rows in, cells out, stocks) and the row count on the way out._batched_solve/_trailing_month_sums— the two kernels behind the batched OLS path. FP calls_trailing_month_sumsfor both of its windows, withcompensated=True.compute_idiovolis the remaining candidate for reuse._two_sum/_segment_sums— the compensated-summation pair FP needs and the OLS family does not._two_sumis Knuth's exact two-sum: the roundeda + band the rounding error it dropped._segment_sumsuses it to sum contiguous segments the waynp.add.reduceatdoes, carrying that error along; it walks lane by lane over full-width arrays rather than gathering each segment, which is what keeps the compensation affordable.__all__— exportscompute_betas,compute_fp_beta,compute_ols_betas,aggregate_betas_to_monthly,_insert_matlab_dlret_rows(helper exported for pipeline/Ch 8 reuse)._nanolsis internal.