Chapter 17 — Results builders I: basic sorts, anomaly zoo, FMB¶
Part IV of the assayinganomalies tutorial. Prerequisite chapters: 1–16, especially 13 (
run_univariate_sort,SortResult), 14 (run_fama_macbeth,_calendar_lag_panel), 15 (calc_tcosts,calc_gen_alpha), and 16 (call order of the twelve builders). Python modules covered: first half ofanalytics/results.py(everything up to and includingmake_fmb_res).
What this chapter answers¶
- What each of the four
make_*builders writes intoProtocolResult, field by field — these dataclasses are the substructures the reader will look up. - Which sort each builder actually runs: number of portfolios, weighting,
breakpoint universe, whether costs are applied, and whether
time_periodwindows the sort or only a downstream statistic. - How
_panel_correlscomputes the signal–anomaly correlations, and which of the two columns ofres_correlsthe close-anomaly ranking reads. - What
_winsorize_xs_1pct/_drop_highly_correlateddo inmake_fmb_res, and which partner the collinearity screen drops. - How the
1e-12tie-break jitter in the anomaly sorts is drawn and seeded.
Where this sits in the pipeline¶
Chapter 16 is the driver. This chapter is the first three stages it calls,
plus the Fama–MacBeth combination helper that Chapter 18’s make_comb_strats
invokes. Reporting (Chapter 19) reads these objects; it does not recompute
sorts.
flowchart TD
RTS["run_test_signal Ch 16"]
S1["make_anom_strat_results"]
S2["make_basic_sorts_results"]
S3["make_anom_benchmark_results"]
FMB["make_fmb_res"]
C18["make_comb_strats / make_close_anom_results Ch 18"]
PRT["make_res_to_print Ch 19"]
RTS --> S1
RTS --> S2
RTS --> S3
S1 --> C18
S2 --> C18
S3 --> C18
C18 --> FMB
S1 --> PRT
S2 --> PRT
S3 --> PRT
results.py is one long module. The cut is after make_fmb_res.
Everything from CloseAnomResult onward is Chapter 18.
ProtocolResult attribute |
Python object | Builder |
|---|---|---|
res_anoms |
AnomStratResults |
make_anom_strat_results |
res_basic_sorts |
BasicSortsResults (.basic + .gen_alpha) |
make_basic_sorts_results |
res_cond_me_sorts |
BasicSortsResults.conditional |
same |
res_correls |
AnomBenchmarkResults.correls |
make_anom_benchmark_results |
res_cond_sort |
AnomBenchmarkResults.cond_sort |
same |
res_fmbs |
AnomBenchmarkResults.fmbs |
same (per-anomaly run_fama_macbeth of 100*ret) |
comb_strats FMB row |
FMBRes.eret |
make_fmb_res, called from make_comb_strats (Ch 18) |
res_fmbs and make_fmb_res are different Fama–MacBeths. The first is a
bivariate characteristic regression of the test signal against one zoo
anomaly at a time. The second is a rolling combination signal: 120-month
mean of cross-sectional slopes, dotted into this month’s filled anomalies,
then sorted as if it were a characteristic. Chapter 14’s
run_fama_macbeth is used only by the first.
Sort specifications at a glance¶
Every sort the four builders run, as a run_univariate_sort call or a
hand-built ind + calc_held_ptfs (the zoo strategies) or calc_ptf_rets
(the conditional 5×5 strategies, which stay on monthly value weights and
carry no cost).
make_basic_sorts_results — five rows × five models, plus size-conditional¶
The builder loops over FACTOR_MODELS = (1, 3, 4, 5, 6). run_univariate_sort
is not given time_period; only the generalized-α step sees the window.
| Python key | Bins | Breaks | Weight | Costs | time_period to the sort |
|---|---|---|---|---|---|
("vw_nyse_5", f) |
5 | NYSE | VW | yes | no (full sample) |
("ew_nyse_5", f) |
5 | NYSE | EW | yes | no |
("vw_name_5", f) |
5 | name | VW | yes | no |
("vw_cap_5", f) |
5 | cap (portfolio_mass=mcap) |
VW | yes | no |
("vw_nyse_10", f) |
10 | NYSE | VW | yes | no |
Conditional-on-size (BasicSortsResults.conditional):
| Step | Python |
|---|---|
| ME bins | _bin_by_cross_section(me_cond, 5, breaks="nyse") on raw, contemporaneous ME (not run_univariate_sort, which would lag) |
| Mask | test_signal.where(me_bins.eq(i)) |
| Inner sort | breaks="name", no nyse_flag |
| Weight / model / costs | VW, weights reset to last month's market capitalization every month (reweighted_sort), f ∈ {1,3,4,5,6}, no tcosts |
make_anom_strat_results — zoo L/S, one spec¶
| Python | |
|---|---|
| Bins | quintiles, keep bins 1 and 5, remap to {1,2} |
| Breaks | NYSE if nyse_flag else name |
| Weight | VW |
| Model | factor_model=1 (CAPM) |
| Costs | held legs (calc_held_ptfs, Ch 13): the cost of the trades of the two extreme legs after the first purchase, whose cost is reported separately (entry_cost) and not charged; convention sets the legs’ size after a trade |
| Window | full sample; time_period accepted and ignored (make_res_to_print windows later) |
| Jitter | seeded, one stream per anomaly, unless noise_seed=None |
make_anom_benchmark_results — three products per zoo column¶
| Product | Python |
|---|---|
| Correlations | _panel_correls on the window, after _slice_panel_by_time |
| 5×5 → 2-leg | conditional outer (anomaly) + inner (test-signal) quintile bins, remapped to two legs, calc_ptf_rets on the sliced panel; CAPM, no tcosts, VW |
| Fama–MacBeth | run_fama_macbeth(100.0 * ret_sliced, [test_signal, anom_i]) |
When nyse_flag is supplied (and run_test_signal always supplies it), the
double sort uses NYSE breaks on the outer (anomaly) leg and name breaks
on the inner (test-signal) leg; without it, both legs use name breaks.
The tie-break jitter¶
Before every zoo quintile sort — in make_anom_strat_results and in the
conditional double sort of make_anom_benchmark_results — each anomaly gets
noise of order 1e-12 added to it. Tied signal values — binary event
dummies (IndIPO, DivOmit, ExchSwitch, …), and discrete characteristics
such as Price = −|prc| — are then split at random across the quintile cut
instead of by row order. This follows the original MATLAB toolkit, which
breaks ties the same way.
The draw is seeded. Each anomaly gets its own stream, keyed by its name
(assayinganomalies.tiebreak.anomaly_noise_rng: default_rng([noise_seed, key]),
where key is the first 8 bytes of the SHA-256 of the name), attached to the
(date, permno)-sorted index. An anomaly therefore has the same strategy
whatever the other anomalies in the zoo and whatever its place among them:
if noise_seed is None:
return {name: None for name in anoms_dict}
return {
name: anomaly_noise_rng(noise_seed, name).standard_normal(len(anom))
* _ANOM_NOISE_SCALE
for name, anom in anoms_dict.items()
}
The default seed is _ANOM_NOISE_SEED = 20231201. Pass noise_seed=None to
skip jitter entirely.
Downstream. make_close_anom_results (Ch 18) ranks the zoo by how
closely each anomaly relates to the test-signal L/S, then runs spanning
regressions on the six closest. Tie-heavy close names (Price,
Illiquidity, DolVol) move with the jitter; tie-free names (Size,
IntanBM, SP) agree across seeds to ~1e-16. Across eight seeds the
printed cells of the close-anomaly spanning table spread by 0.09–0.57. See
Known limitations: the random seed is part of the specification.
FM regressions and panel correlations use the raw signal. They are not jittered.
Shared constants¶
# Factor-model codes mirrored from runUnivSort.m / makeBasicSortsResults.m.
FACTOR_MODELS: tuple[int, ...] = (1, 3, 4, 5, 6)
# Labels for the 5 basic-sort rows (matches MATLAB resBasicSorts(i,:) row index).
BASIC_SORT_LABELS: tuple[str, ...] = (
"vw_nyse_5", # row 1: VW quintiles, NYSE breaks
"ew_nyse_5", # row 2: EW quintiles, NYSE breaks
"vw_name_5", # row 3: VW quintiles, name breaks
"vw_cap_5", # row 4: VW quintiles, cap (portfolio-mass) breaks
"vw_nyse_10", # row 5: VW deciles, NYSE breaks
)
run_univariate_sort has its own default factor_model (Ch 13); these
builders always pass the model explicitly. BASIC_SORT_LABELS[0] (vw_nyse_5) is what
Chapter 18 takes as the test-signal L/S
(res_basic_sorts.basic[("vw_nyse_5", 1)].long_short).
_slice_time_period(test_signal, time_period)¶
Signature
test_signal—pd.Series, unused. Present so a caller could pass the panel whose index defines the calendar; the body never reads it.time_period—(start, end)as YYYYMM ints or Timestamps, orNone.
Returns — time_period unchanged, or None.
What it does — a documented pass-through: “run_univariate_sort already
parses YYYYMM or Timestamps.” Nothing in the package calls it. Windowing in
this module goes through _slice_panel_by_time. Dead as of this writing.
BasicSortsResults¶
The output of make_basic_sorts_results: 5 sort specifications × 5 factor
models of univariate sorts (with generalized α), plus 5 ME quintiles × 5
models of size-conditional sorts.
Signature — dataclass fields, not a constructor you call by hand.
| Field | Contents |
|---|---|
basic |
dict[(row_label, factor_model), SortResult]. 5 × 5 = 25 entries at default. row_label ∈ BASIC_SORT_LABELS, factor_model ∈ FACTOR_MODELS. Each SortResult is the Chapter 13 object: leg_returns, long_short, xret/alpha/sharpe (percent / annualized), and when tcosts was passed, tcosts_ts / netpret / ptf_costs (held-leg costs; ptf_costs is each portfolio's own cost, and entry_cost the cost of the first purchase, which is not in tcosts_ts; Ch 13). |
conditional |
dict[(me_quintile, factor_model), SortResult]. me_quintile in 1..5. No cost fields — these sorts are run without tcosts. |
gen_alpha |
dict[(row_label, factor_model), dict]. Keys of the inner dict: |
anom_ret — L/S series, already sliced to time_period |
|
anom_tcosts — SortResult.tcosts_ts aligned to that series (zeros if missing) |
|
factor_rets / factor_tcosts — frames from factor_matrix_for_gen_alpha (plain smb, not smb2; Ch 15) |
|
anom_tcosts_short / factor_tcosts_short — the costs charged on short positions (SortResult.tcosts_ts_short and the factors' short costs; Ch 15). None unless the run is under "capital" |
|
alpha_res — OlsRes (Ch 14); intercept is the generalized α, percent |
|
w_x_y, w_x — net-MVE weights from calc_gen_alpha |
|
metadata |
time_period, factor_models, n_me_ptfs, has_factor_tcosts, compute_gen_alpha, convention, capital_restarts (sort label → number of trades at which the strategy’s capital was zero or negative; "capital" only, and only the sorts where it happened), entry_cost (sort label → cost of the sort's first purchase, decimal; not in the cost series) |
gen_alpha stores the aligned inputs as well as alpha_res, so net α can be
rebuilt from a saved result without rerunning the sorts.
ProtocolResult.res_cond_me_sorts is a pointer at .conditional, not a
copy. Chapter 19’s Tab_BasicSort / Tab_RobustSort / Tab_CondSizeSort
read these three maps.
make_basic_sorts_results(test_signal, returns, mcap, *, ...)¶
All panels are passed in as arguments; run_test_signal injects them.
Signature
| Parameter | Shape / dtype / notes |
|---|---|
test_signal |
Series, (date, permno) |
returns |
Series, (date, permno), decimals |
mcap |
Series, (date, permno); VW weights, cap breaks, default ME-conditional |
nyse_flag |
Series of bool/0-1, same index. Required for NYSE rows. |
tcosts |
optional per-stock half-spread panel |
factor_tcosts |
date-indexed frame of factor trading costs under the plain names mkt_tc … umd_tc; missing columns treated as 0. In a protocol run these are the costs stored for the run’s convention, and under "capital" the frame also has smb_tc_short … umd_tc_short, the costs of the factors held short (Ch 16, Ch 9b) |
factors |
date-indexed factor returns; omitted → load from DuckDB. Gen-α uses plain smb. |
time_period |
(start, end) YYYYMM or Timestamp. Windows gen-α only. |
convention |
"dollar" (default) or "capital": the size of the two legs after a trade, passed to every run_univariate_sort call |
factor_models |
default FACTOR_MODELS |
me_for_conditional |
ME used for the size-conditional bins; default mcap |
n_me_ptfs |
int, default 5 |
compute_gen_alpha |
default True; False skips the net-MVE search (useful for quick smoke runs) |
verbose |
progress logging, default True |
Returns — BasicSortsResults.
What it does
- Five univariate variants per factor model.
time_period=is not passed torun_univariate_sort: the sorts span the full sample, and windowing them would shorten the sample and move the NYSE breakpoints. This follows the original MATLAB toolkit, which windows only the generalized α; Chapter 19 windows Table 1 and the Ibbotson figure itself.
for f in factor_models:
# Row 1: VW, NYSE breakpoints, 5 bins
res.basic[("vw_nyse_5", f)] = run_univariate_sort(
returns, test_signal, mcap,
n_bins=5,
breaks="nyse",
nyse_flag=nyse_flag,
weighting="v",
factor_model=f,
tcosts=tcosts,
print_results=False,
plot_results=False,
)
Rows 2–5 are the same call with weighting="e", breaks="name",
breaks="cap" + portfolio_mass=mcap, and n_bins=10 (see the spec
table). run_univariate_sort forms bins on the contemporaneous signal; the
portfolios are held legs whose returns start the month after formation
(Ch 13).
- Generalized α, windowed. For each cell,
factor_matrix_for_gen_alphabuilds the factor returns and factor costs for modelf; the L/S return and its cost series are sliced totime_period, then passed tocalc_gen_alpha:
# The sorts run on the full sample (MATLAB passes no
# 'timePeriod' to runUnivSort); only gen-alpha is windowed.
anom_ret = _slice_panel_by_time(anom_ret, time_period)
anom_tc = _slice_panel_by_time(anom_tc, time_period)
try:
f_df, tc_df = factor_matrix_for_gen_alpha(
f,
anom_ret.index,
factors=factors,
factor_tcosts=factor_tcosts,
)
alpha_res, w_x_y, w_x = calc_gen_alpha(
anom_ret.to_numpy(),
anom_tc.to_numpy(),
f_df.to_numpy(),
tc_df.to_numpy(),
print_res=False,
)
Under convention="capital" the call also gets anom_tcosts_short
(SortResult.tcosts_ts_short, sliced the same way) and factor_tcosts_short
(factor_short_tcosts_for_gen_alpha), so that a short position in the net
MVE portfolio is charged its own cost
(Ch 15). Under
"dollar" neither is passed.
_slice_panel_by_time on a date-indexed Series uses
index.get_level_values(0), which is the DatetimeIndex itself — it does
not require a MultiIndex. A failed calc_gen_alpha is logged and stored as
alpha_res=None rather than aborting the remaining 24 cells. The gen-α
factor list is mkt smb hml rmw cma [umd] — plain smb, not the smb2
used by est_factor_regs (Ch 13 / 15).
- ME-conditional sorts. The ME quintiles are formed on contemporaneous
(unlagged) ME.
run_univariate_sortwould lag, so the builder rebuilds the bins with_bin_by_cross_sectionon raw ME. The test signal is then masked to NaN outside ME quintilei, followed by a name-break VW quintile sort with no costs, reweighted every month (reweighted_sort).
me_bins = _bin_by_cross_section(
me_cond,
n_me_ptfs,
breaks="nyse" if nyse_flag is not None else "name",
nyse_flag=nyse_flag,
mcap=me_cond,
)
# `me_quintile_sort` is captured only to keep a reference to the ME
# quintile boundaries for downstream reporting; not used directly.
del me_quintile_sort
for i in range(1, n_me_ptfs + 1):
# Mask the test signal outside ME quintile i, matching
# `tempSignal(indME ~= i) = nan` in MATLAB.
mask = me_bins.eq(i)
masked_signal = test_signal.where(mask.reindex(test_signal.index).fillna(False))
res.conditional.update(
{
(i, f): sr
for f, sr in reweighted_sort(
returns, masked_signal, mcap,
factor_models=factor_models,
factors=factors,
).items()
}
)
reweighted_sort forms the five portfolios, on name breakpoints, in the
months in which the masked signal has values, carries them to the next such
month, and weights them by last month's market capitalization every month
(calc_ptf_rets). These 25 portfolios are therefore not held legs: the
report's double-sort table says "value-weighted, with weights reset every
month". One SortResult per factor model, all on the same returns, with no
cost fields and no convention in the metadata ("weights": "reset
monthly" instead).
The run_univariate_sort that is immediately del’d is wasted work.
AnomBenchmarkResults¶
The output of make_anom_benchmark_results: correlations, conditional
double sorts and bivariate Fama–MacBeths of the test signal against each
zoo anomaly.
| Field | Contents |
|---|---|
correls |
DataFrame, rows = anomaly names, columns spearman, pearson (from _panel_correls). Close-anomaly ranking (Ch 18) reads the pearson column. |
cond_sort |
dict[str, SortResult]. Each value is a 2-leg VW sort: leg 1 = lowest test-signal quintile within each anomaly quintile, leg 2 = highest. L/S = 2 − 1. CAPM stats. No tcosts. |
fmbs |
dict[str, RegressionResult] (Ch 14). Bivariate FM of 100*ret on [test_signal, anom_i] plus intercept. Labels ["Const", "test_signal", name]. |
metadata |
time_period, n_anoms, anom_names, factor_model, noise_seed, noise_scale |
Fig_Correls (Ch 19) plots both columns.
_panel_correls(var1, var2)¶
Signature — two pd.Series (any aligned index; protocol passes
(date, permno)).
Returns — (rho_spearman, rho_pearson) as Python floats, in that order.
What it does
df = pd.concat({"v1": var1, "v2": var2}, axis=1, join="inner").dropna()
if df.empty or df["v1"].nunique() < 2 or df["v2"].nunique() < 2:
return (np.nan, np.nan)
v1 = df["v1"].astype(float)
v2 = df["v2"].astype(float)
rho_s = v1.corr(v2, method="spearman")
finite = np.isfinite(v1) & np.isfinite(v2)
v1f, v2f = v1[finite], v2[finite]
if len(v1f) < 2 or v1f.nunique() < 2 or v2f.nunique() < 2:
rho_p = np.nan
else:
rho_p = v1f.corr(v2f, method="pearson")
return (float(rho_s), float(rho_p))
concat(..., join="inner") then dropna() drops cells that are NaN in
either panel. dropna() keeps ±Inf: the Spearman correlation uses those
cells (an infinite value is simply the extreme rank), while the Pearson
correlation is computed on the finite subsample, since a single infinite
cell would otherwise make it NaN. A constant series (nunique < 2) returns
(nan, nan) instead of letting pandas emit a divide-by-zero warning.
_slice_panel_by_time(s, time_period)¶
The window filter every builder in this module uses.
Signature
s— Series or DataFrame. MultiIndex(date, permno)or a plain DatetimeIndex (gen-α’s L/S series).time_period—(start, end)YYYYMM ints or Timestamps, orNone.
Returns — the same type, rows with start ≤ date ≤ end (inclusive).
None → s unchanged.
What it does — YYYYMM ints become month-end Timestamps via
Timestamp(year, month, 1) + MonthEnd(0) (the package date invariant), so
197501 → 1975-01-31. Filter is get_level_values(0), which on a
non-MultiIndex DatetimeIndex is the index itself.
if time_period is None:
return s
start, end = time_period
if isinstance(start, int):
start = pd.Timestamp(year=start // 100, month=start % 100, day=1) + pd.offsets.MonthEnd(0)
if isinstance(end, int):
end = pd.Timestamp(year=end // 100, month=end % 100, day=1) + pd.offsets.MonthEnd(0)
dates = s.index.get_level_values(0)
mask = (dates >= start) & (dates <= end)
return s[mask]
Used by: gen-α windowing, the benchmark builder (all three products),
make_fmb_res’s pre-loop subset. Not used by make_anom_strat_results
or the basic sorts themselves. A wrong conversion here would shift every
windowed statistic.
_coerce_anoms_to_dict(anoms, *, signal_index, labels)¶
The adapter that lets callers pass the anomaly zoo as a DataFrame, a
{name: Series} dict, or a 3-D array.
Signature
anoms— DataFrame(date, permno) × anomaly columns, ordict[str, Series], orndarrayof shape(nMonths, nStocks, nAnoms).signal_index— MultiIndex used only for the ndarray path, to recover dates and permnos.labels— required for the ndarray path; length must equalanoms.shape[2].
Returns — dict[str, pd.Series], insertion order = DataFrame column
order / dict order / labels order. Anything that indexes anomalies by
position (res_correls rows, the dendrogram Z)
depends on this order; Chapter 16’s CamelCase zoo sort is what fixes it.
What it does — three branches, then TypeError. The ndarray path builds
MultiIndex.from_product([unique dates, unique permnos]) and
reshape(-1) each slice — C-order flatten of an (nMonths, nStocks) block
is date-slowest if the array is laid out months × stocks. Production code
passes the DataFrame; the ndarray path is a bridge for wide-matrix inputs.
make_anom_benchmark_results(anoms, test_signal, returns, mcap, *, ...)¶
Signature
| Parameter | Notes |
|---|---|
anoms |
DataFrame / dict / ndarray (see _coerce_anoms_to_dict) |
test_signal |
Series (date, permno) |
returns |
decimals; FM multiplies by 100 |
mcap |
VW weights |
nyse_flag |
if present, NYSE breaks on the outer (anomaly) leg of the double sort |
time_period |
applied to correlations, the 2-leg sort, and the FM |
anom_labels |
ndarray path only |
factor_model |
default 1 (CAPM) |
noise_seed |
default 20231201; None skips jitter |
verbose |
progress logging |
Returns — AnomBenchmarkResults.
What it does — slice once, then per anomaly:
-
Correlations on the window (
_panel_correls). -
Jitter + 5×5 conditional + collapse to 2 legs. The jittered anomaly is binned into quintiles (outer), the test signal into quintiles within each anomaly quintile (inner). Leg 1 is inner bin 1 in every outer quintile; leg 2 is inner bin 5. Python does this without building a 25-portfolio id:
anom_ok = bins_anom.notna()
cond_lo = (anom_ok & (bins_ts == 1)).fillna(False).astype(bool)
cond_hi = (anom_ok & (bins_ts == 5)).fillna(False).astype(bool)
ind = pd.Series(0, index=bins_ts.index, dtype="Int64")
ind = ind.mask(cond_lo, 1)
ind = ind.mask(cond_hi, 2)
.fillna(False) is required because Int64 == 1 is <NA> where bins_ts
is NA, and Series.mask treats NA as True. Then calc_ptf_rets on {ret,
ind, mcap} (one-month lag + carry-forward, Ch 13), CAPM via
_run_factor_regs / _matlab_style_sort_outputs, no trading costs. The
bins are formed on the already-sliced panel; cross-sectional breakpoints at
month t do not depend on months outside the window, so binning first and
slicing later would give the same in-window bins.
- Fama–MacBeth of
100 * reton the test signal and the anomaly:
rhs = pd.concat(
{"test_signal": ts_sliced, name: anom_sliced}, axis=1
)
fmbs[name] = run_fama_macbeth(
100.0 * ret_sliced,
rhs,
time_period=time_period if isinstance(time_period, tuple) else None,
print_results=False,
labels=["Const", "test_signal", name],
)
run_fama_macbeth lags the RHS itself (_calendar_lag_panel, Ch 14).
Coefficients are percent per month.
AnomStratResults¶
The output of make_anom_strat_results: one long/short sort per zoo anomaly.
| Field | Contents |
|---|---|
results |
dict[str, SortResult]. 2-leg VW NYSE quintile (extremes only). long_short = high − low. When tcosts is passed: tcosts_ts, netpret (= long_short_net), tcosts (mean of tcosts_ts over the months in which the strategy has a return), netxret / tnetxret from nanols(100*netpret, 1). |
metadata |
n_anoms, factor_model, time_period (recorded even though ignored), noise_scale, convention, capital_restarts (anomaly name → number of trades at which its capital was zero or negative; "capital" only, and only the anomalies where it happened), entry_cost (anomaly name → cost of its first purchase, decimal; not in tcosts_ts). Does not record noise_seed. |
tcosts_ts / netpret live on each SortResult, not in metadata;
Fig_AlphaPrctl reads the zoo costs from there when it calls
calc_gen_alpha.
make_anom_strat_results(anoms, returns, mcap, *, ...)¶
Signature
| Parameter | Notes |
|---|---|
anoms |
DataFrame / dict / ndarray |
returns / mcap |
decimals / VW weights |
tcosts |
optional per-stock half-spreads; priced on the held legs’ trades |
nyse_flag |
NYSE breaks if given |
time_period |
accepted, stored, ignored |
anom_labels |
ndarray path |
factor_model |
default 1 (CAPM) |
noise_seed |
default 20231201; None skips jitter |
verbose |
progress logging |
convention |
"dollar" (default) or "capital": the size of the two legs after a trade |
Returns — AnomStratResults.
What it does
# MATLAB `makeAnomStratResults` takes no timePeriod: every zoo strategy runs
# on the full sample, and the windowing happens later in `makeResToPrint`
# (Fig_Ibbots uses s:e; Fig_AlphaPrctl uses each anomaly's own finite span).
ret_sliced = returns
mcap_sliced = mcap
nyse_sliced = nyse_flag
tc_sliced = tcosts
Per anomaly: add jitter, NYSE-quintile contemporaneous bins, keep legs 1
and 5 remapped to {1,2}, then calc_held_ptfs (VW): the two legs are
bought in a month in which the anomaly has values and left alone until the
next such month (Ch 13). An anomaly with
values every month trades every month; one with values each June trades each
June (Ch 13). CAPM stats follow,
and, if tcosts is present, the cost of the two legs' trades, the first
purchase included.
# MATLAB: ind = 1*(ind==1) + 2*(ind==5)
ind = pd.Series(0, index=bins.index, dtype="Int64")
ind = ind.mask((bins == 1).fillna(False), 1)
ind = ind.mask((bins == 5).fillna(False), 2)
held = calc_held_ptfs(
ret_sliced, ind_aligned, mcap_sliced, tc_sliced,
weighting="v", convention=convention, label=name,
)
...
tcosts_ts = held.costs["cost"].rename(None)
netpret = long_short - tcosts_ts
tcosts_ts is 0 in a month without a trade, so netpret is defined wherever
the long/short return is. The first purchase is not in tcosts_ts; it is the
SortResult's entry_cost. Under "capital" the SortResult also has
tcosts_ts_short. A strategy whose capital is zero or negative at a
trade restarts with $1 in each leg (convention="capital"); the count is in
its metadata["capital_restarts"], the parent process logs a warning per
such strategy, and AnomStratResults.metadata["capital_restarts"] collects
them by name. The dendrogram (Ch 18) and Fig_AlphaPrctl / Fig_SharpeDist
consume this dict. Results for tie-heavy anomalies depend on the jitter
seed (see The tie-break jitter).
FMBRes¶
The output of make_fmb_res.
| Field | Contents |
|---|---|
eret |
Series, (date, permno), float64, name "eret". Forecast excess return. NaN outside time_period, in the first roll_window-1 months of the window, and where any used anomaly is NaN for that stock (a NaN in the dot product poisons it). Reindexed to the original returns index. |
betas |
DataFrame, dates × anomaly names. One row per month’s cross-sectional slopes (no intercept). NaN if the anomaly was unused / dropped / rank-deficient that month. |
metadata |
time_period, roll_window (120), corr_threshold (0.90), winsor_pct (1.0), n_anoms, anom_names |
make_comb_strats (Ch 18) unwraps FMBRes.eret the same way it unwraps
LassoRes / PLSRes.
_winsorize_xs_1pct(x, pct=1.0)¶
Clips each anomaly cross-sectionally, per month, at its pct and
100 - pct percentiles.
Signature — x is stocks × anomalies (DataFrame, one column per anom)
for a single month. pct default _FMB_WINSOR_PCT = 1.0.
Returns — a copy, same shape; x is not modified.
What it does
if x.empty:
return x
from .sorts import _matlab_prctile
out = x.astype(float).copy()
for col in out.columns:
s = out[col]
if s.notna().sum() == 0:
continue
lo, hi = _matlab_prctile(s.to_numpy(dtype=float), [pct, 100.0 - pct])
out[col] = s.clip(lower=lo, upper=hi)
return out
The percentiles come from _matlab_prctile
(Ch 13;
Ch 9
for the three copies), not Series.quantile. This follows the original
MATLAB toolkit, whose percentile interpolation differs from numpy’s; using
quantile would move the clip points and the FM slopes. This is a different
winsorization from the one in Ch 14.
_drop_highly_correlated(x, threshold)¶
Signature — x is the already-winsorized stocks × anomalies frame for
one month. threshold default 0.90.
Returns — a list of column names to drop, in x.columns order.
What it does
if x.shape[1] < 2:
return []
x_cc = x.dropna(how="any")
if x_cc.shape[0] < 2:
return []
# drop columns that are constant in the complete-case sample — corrcoef
# on them is NaN in MATLAB (any(NaN>0.9)==false) so they should be kept.
# We handle by filling pairwise correlations involving such columns with 0.
corr = x_cc.corr().abs()
# Keep only strictly lower triangle (MATLAB `tril` includes the diagonal
# but the next line zeros it out — equivalent to strictly lower).
lower = np.tril(corr.to_numpy(), k=-1)
lower = np.nan_to_num(lower, nan=0.0)
# MATLAB `any(... > 0.90)` operates column-wise. A column k is flagged if
# *any* row of the lower triangle in that column exceeds the threshold —
# and rows below the diagonal in column k are the later columns i > k, so
# this drops k whenever some *later* column i had |corr(i, k)| > threshold.
mask = (lower > threshold).any(axis=0)
return [c for c, drop in zip(x.columns, mask) if drop]
Complete-case rows (dropna(how="any")). Pearson (DataFrame.corr()
default). Strictly lower triangle (np.tril(..., k=-1)). Column-wise any
(axis=0). Strict >, not >=. Constant columns have a NaN correlation,
which nan_to_num turns into 0, so they are kept. One-shot, not iterative.
Ordering — what actually gets dropped. The rule drops the earlier
column of a highly correlated pair. Worked example, columns [A, B] with
|corr|=0.95:
corr = [[1, 0.95], [0.95, 1]]
tril k=-1 = [[0, 0], [0.95, 0]]
any(axis=0) = [True, False] → drop A (column 0), keep B
If A–B and A–C are both high, A is dropped and B–C is then checked in the
same one-shot matrix: if |corr(B,C)|>0.90, B (earlier of B,C) is also
flagged. Changing the rule to drop the later partner would silently change
which anomaly survives in a collinear pair.
A second channel for silent changes is column order.
_coerce_anoms_to_dict preserves DataFrame column order, and Chapter 16’s
CamelCase zoo sort fixes that order. If a caller built filled_anoms with a
different column permutation, a different member of each collinear pair
would be kept and eret would move. That is an input-order contract, not a
bug.
make_fmb_res(filled_anoms, returns, *, ...)¶
Called from make_comb_strats (the default _fmb_adapter, Ch 18), not from
run_test_signal directly.
Signature
| Parameter | Notes |
|---|---|
filled_anoms |
filled zoo (Ch 11 fill_var); DataFrame / dict / ndarray |
returns |
decimals; not scaled by 100 (this is a combination signal, not a printed FM table) |
time_period |
subset before the monthly loop; output reindexed to full returns |
anom_labels |
ndarray path |
roll_window |
default 120 |
corr_threshold |
default 0.90 |
winsor_pct |
default 1 |
verbose |
progress logging every roll_window months |
Dates come from the MultiIndex.
Returns — FMBRes.
What it does — month by month, skipping the first month of the window (no lag available):
-
Lag the anomalies one month on the calendar grid with
_calendar_lag_panel(anoms_sliced, 1)(the same helper asrun_fama_macbeth). A stock absent att-1is NaN, not its previous finite value. -
Keep columns with at least one finite nonzero value this month. Intentionally lenient.
-
Winsorize the survivors (
_winsorize_xs_1pct). -
Drop earlier members of
|corr|>0.90pairs (_drop_highly_correlated); re-winsorize on the reduced set. -
Regress returns on a constant and the lagged anomalies: complete-case
np.linalg.lstsq, skipped ifn_obs <= n_params. Slopes (no intercept) are stored inbetas.loc[d, a]. -
Once 120 months are available, average the last 120 rows of
betas(ignoring NaN) and formeret_t = X_t @ bMeanusing the raw contemporaneousfilled_anomsatt(not lagged, not winsorized) and only columns with a finite mean slope.eval_dates[i-roll_window:i]is the 120-row inclusive window (enumerate(..., start=1)).
# Pre-shift anoms by 1 month so that, when we select rows at date t, we are
# reading X_{t-1} — mirroring MATLAB's `lagX = filledAnoms(i-1, :, :)`,
# which is a row of the rectangular grid (a stock absent at t-1 is NaN, not
# its last observed value).
anoms_lagged = _calendar_lag_panel(anoms_sliced, 1)
The output is a full-index Series of NaN with the window filled in.
run_fama_macbeth is not called here.
Small helpers¶
| Name | Role |
|---|---|
LOGGER |
logging.getLogger("assayinganomalies.analytics.results"). Progress lines. |
_ANOM_NOISE_SEED |
20231201. Default seed for both jitter sites. |
_ANOM_NOISE_SCALE |
1e-12. Jitter scale. |
_FMB_ROLL_WINDOW |
120. |
_FMB_CORR_THRESHOLD |
0.90. |
_FMB_WINSOR_PCT |
1.0. |