Skip to content

Chapter 18 — Results builders II: close anomalies, dendrogram, combination strategies, ML

Part IV of the assayinganomalies tutorial. Prerequisite chapters: 1–17, especially 11 (fill_var, check_fill_anomalies), 13 (SortResult.long_short, _ols, _matlab_prctile), 14 (run_fama_macbeth, _calendar_lag_panel), 16 (call order of the twelve builders), and 17 (resAnoms, resCorrels, resBasicSorts, make_fmb_res). Python modules covered: second half of analytics/results.py (from CloseAnomResult onward).

What this chapter answers

  • How the six closest zoo anomalies are chosen (tiedrank(span R̄²) + tiedrank(|ρ|)), with ties ranked by Series.rank(method="average", na_option="keep").
  • Why close-anomaly Fama–MacBeth uses 100*ret (percent), like Chapter 17’s per-anomaly FM — the original implementation used raw decimal ret here.
  • How Ward linkage on anomaly L/S returns is computed with SciPy.
  • The six combination methods — average rank, weighted average rank, Fama–MacBeth, PLS, IPCA and LASSO — all of which run.
  • How each ML predictor is estimated: scikit-learn LassoCV with seeded, shuffled folds (and why cv=5 alone would give a different estimator); a two-step OLS for PLS; and the Kelly/Pruitt/Su ALS algorithm for IPCA.

Where this sits in the pipeline

Chapter 16 is the driver. Chapter 17 produced resAnoms, resBasicSorts, and resCorrels. This chapter is stages 4–6 of that driver. Reporting (Chapter 19) reads the objects; it does not re-cluster or re-rank.

flowchart TD
  RTS["run_test_signal  Ch 16"]
  S1["make_anom_strat_results  Ch 17"]
  S2["make_basic_sorts_results  Ch 17"]
  S3["make_anom_benchmark_results  Ch 17"]
  DEND["make_dendrogram_results"]
  CLOSE["make_close_anom_results"]
  FILL["fill_var  Ch 11"]
  COMB["make_comb_strats"]
  PRT["make_res_to_print  Ch 19"]
  RTS --> S1
  RTS --> S2
  RTS --> S3
  S1 --> DEND
  S2 --> DEND
  S3 --> CLOSE
  S1 --> CLOSE
  S2 --> CLOSE
  S1 --> COMB
  S2 --> COMB
  FILL --> COMB
  DEND --> PRT
  CLOSE --> PRT
  COMB --> PRT

results.py is one large module. Chapter 17 cut after make_fmb_res. This chapter starts at CloseAnomResult.

Output Python object Builder
Dendrogram ProtocolResult.Z / .dendrogram_labels / .cutoff make_dendrogram_results
Close-anomaly FM CloseAnomResults.fmb (list[RegressionResult]) make_close_anom_results
Close-anomaly spanning CloseAnomResults.span (list[CloseAnomResult]) same
Close-anomaly labels CloseAnomResults.close_labels same
Combination strategies CombStratsResults make_comb_strats

The protocol passes the strat results (res_anoms.results from make_anom_strat_results) into both the dendrogram and the close-anom / comb-strat builders — the univariate VW-NYSE quintile L/S, not the conditional 5×5 from make_anom_benchmark_results. The type hints that accept AnomBenchmarkResults and then read .cond_sort are a footgun; the live path never takes it.


Specs at a glance

Close-anomaly ranking

Step Python
Skip long_short is None or xret is None
Pre-select OLS _nanols_span(y, [const, anom_ls]); store r2_adj
Correlation res_correls["pearson"] (positional fallback: column 2)
Combined rank _tiedrank(span_r2) + _tiedrank(anom_corr.abs())
Order sort_values(ascending=False, kind="mergesort", na_position="last"); missing ranks are never selected
n_close _CLOSE_N_ANOMS = 6
Per-close FM run_fama_macbeth(ret_sliced, [test_signal, anom_i]), with ret_sliced = 100 * ret
Per-close span _nanols_span on [const, anom_ls] + _resolve_factor_model(6) dropping rf
Joint row all six signals / all six L/S + FF6, appended as the 7th list entry

LHS of every spanning regression is the test-signal L/S basic[("vw_nyse_5", 1)].long_short.

Dendrogram

Step Python
Columns SortResult.long_short of each anomaly, plus the signal L/S
Window the signal's return months inside [start, end]: from its first return (not before the sample's second month) to its last (dendrogram_signal_window)
Drop an anomaly with any NaN/Inf in the window; the dropped names are logged. The signal is always a leaf
Stop DendrogramSignalError if the signal has a month without a return inside its window
Layout linkage(rets.T.values, method="ward") — observations = series, features = months
Z shape (n-1) × 4, 0-based (SciPy)
Cutoff _matlab_prctile(Z[:,2], [75])
Signal label "\\color{red}{MPE}"

Combination strategies

Rows 1–6, each run inside its own try/except.

Row Key Python default
1 avg_rank make_avg_rank
2 weighted_avg_rank make_weighted_avg_rank
3 fama_macbeth make_fmb_res (Ch 17)
4 pls make_pls_res
5 ipca make_ipca_res
6 lasso make_lasso_res

All six rows produce forecasts. The original MATLAB toolkit reported IPCA and LASSO as N/A because it ran out of memory building a dense (nMonths, nStocks, nAnoms) array, not because the methods do not apply; this package works from the long panel and runs both.

Each method is run twice: baseline (filled_anoms only) and enhanced (filled_anoms plus the filled test signal as an extra column). Downstream sorts consume eret / eret_enh as characteristics. fill_var has already mapped every column to [-0.5, 0.5] (Chapter 11), so “average rank” is a sum of filled ranks, not a fresh tiedrank.

When the test signal is used. A month has data when the filled signal has a non-zero value in it (fill_var gives every stock the median, 0, in a month without data).

Method Uses the signal in a month when
Average rank the month has data
The other five each of the previous signal_window months (120) has data

In a month in which a method does not use the signal, both eret and eret_enh are NaN, so the strategy with the signal and the one without it start in the same month. For IPCA the signal's keep flag follows the same rule; MATLAB marks the signal as kept in every month, which makes a window in which it has no data impossible to solve. The report starts the figure in the signal's first month and names the period each panel compares.


Two implementation details

_tiedrank versus MATLAB tiedrank

_tiedrank reproduces tiedrank from MATLAB’s Statistics Toolbox, which the close-anomaly ranking was originally written against: average ranks for ties, and NaNs left as NaN (they do not consume a rank). The pandas call is exactly:

x.rank(method="average", na_option="keep")

method="average" is the tie rule (1.5 / 2.5, not "min", "max", "first", or "dense"). na_option="keep" is the default and is spelled out so a future na_option="bottom" cannot silently change close-set selection.

The ranking order is the second detail. The combined rank is sorted descending with na_position="last", and only anomalies with a finite combined rank are eligible. An anomaly with no spanning R̄² or no correlation has no overlap measurement at all, so it is never called “closely related.” If fewer than n_close anomalies have a finite rank, the builder selects the ones it has and logs a warning; if none do, it raises ValueError.

fill_var (Chapter 11) uses the same pandas call — groupby(level="date").rank(method="average") — then maps to [-0.5, 0.5]. That is a cross-sectional rank of the raw signal, not this chapter’s span/correlation rank.

SciPy linkage layout

SciPy scipy.cluster.hierarchy.linkage(X, method="ward") returns (n-1) × 4: [cluster_a, cluster_b, distance, n_in_cluster], 0-based ids (leaves 0..n-1, merged cluster n+i). Ward is minimum-variance with Euclidean distances on the raw observation matrix (series × months). fcluster would cut the tree; this builder does not call it, and it does not cap the number of clusters.

make_dendrogram_results stores SciPy Z. A linkage matrix produced by the original MATLAB toolkit is 1-based with three columns; reporting/figures.py::_matlab_linkage_to_scipy (Chapter 19) converts one to SciPy layout and returns a SciPy Z unchanged. Distances agree between the two layouts; cluster numbers do not.

The cutoff uses _matlab_prctile (Chapter 13), not np.percentile.


Shared constants

# Number of closely-related anomalies to include in the spanning / FM regressions.
# MATLAB hard-codes this to 6.
_CLOSE_N_ANOMS: int = 6
# Factor model used for the spanning-test RHS. MATLAB uses `ff6(s:e, 2:end)`
# (all 6 FF factors ex-rf), so the default here is 6.
_CLOSE_SPAN_FACTOR_MODEL: int = 6

span_factor_model=6 goes through _resolve_factor_model, which loads smb2 (Ken French five-factor SMB) and renames it to smb in the returned frame:

    df = factors[cols].copy()
    if "smb2" in df.columns:
        df = df.rename(columns={"smb2": "smb"})
    if "rf" in factors.columns:
        df["rf"] = factors["rf"]
    return df

The builder then drops rf, so the spanning RHS is the six factors excluding the risk-free rate. It is not the plain smb that Chapter 17’s gen-α block uses: the package uses two different SMBs.

Combination-strategy labels, display strings, and LaTeX explanations are module-level tuples/dicts (COMB_STRAT_LABELS, COMB_STRAT_DISPLAY_LABELS, COMB_STRAT_EXPLANATIONS). The explanation text is reproduced verbatim from the original toolkit, including the trailing spaces and \\citet{...} markup. _LASSO_ROLL_WINDOW = 120 is the LASSO training window in months.


CloseAnomResult

One spanning regression in the close-anomaly panel. The FM side of each pair is a RegressionResult (Chapter 14), not this dataclass.

Signature — dataclass fields, not a constructor you call by hand.

Field Contents
beta Series, index = RHS names (const, anom_ls or close-anom names, then FF6 factors)
tstats same index; classical OLS t (not White, not NW)
r2 unadjusted R²
r2_adj adjusted R²; this is what the pre-select step ranks on
n_obs complete-case rows
metadata anom, rank, factor_model on the per-close rows; anom="all_close" on the joint row

CloseAnomResults

The full output of make_close_anom_results: FM results, spanning results and labels in one object.

Signature — dataclass fields.

Field Contents
fmb list[RegressionResult], length n_close+2. Entry 0 is ret ~ [testSignal] alone (labels ["Const", "test_signal"]; not in the MATLAB original), entry i (1..n_close) is ret ~ [testSignal, close_i], the last entry is the joint FM. metadata["fmb_layout"] names them in order. Results saved before this entry existed have length n_close+1.
span list[CloseAnomResult], length n_close+1. Last entry is joint spanning.
close_labels {"short": [...], "long": [...]}, length n_close (or fewer when fewer anomalies have a finite combined rank)
close_indices 0-based positions in the input zoo order
span_r2 per-anomaly pre-select R̄²; NaN if skipped
anom_corr signal correlation used in the combined rank: Spearman by default, Pearson with rank_correlation="pearson" (NaN if unavailable)
metadata n_close, n_close_requested, close_names, fmb_layout, combined_rank, rank_missing, span_factor_model, …

span_r2, anom_corr and close_indices are kept so the close-set selection can be replayed and audited after the fact.


_nanols_span(y, X)

Signature

  • y — date-indexed Series (the test-signal L/S).
  • X — date-indexed DataFrame, including const. The helper does not add an intercept; the caller must.

Returns — CloseAnomResult.

What it does — concat + dropna (complete-case row drop, no imputation). If n ≤ k, all-NaN coefficients. Otherwise sorts._ols(y, X, robust=False) (classical SEs, lstsq) and

    if pd.notna(r2) and n > k:
        r2_adj = 1.0 - (1.0 - r2) * (n - 1) / (n - k)
    else:
        r2_adj = np.nan

Local import of _ols avoids a cycle with sorts.py.

This is a fifth OLS kernel in the package (Chapter 14 counted four: analytics.ols.nanols / pinv, betas._nanols / solve, sorts._ols / lstsq for factor regs, _ols_beta_rbar in make_fmb_res). Pre-select and spanning both go through this one. Its r2_adj is the ranking input, so changing the kernel moves the close set.


_tiedrank(x)

Signature — x: pd.Series → pd.Series of average ranks, NaN preserved.

What it does — one line:

def _tiedrank(x: pd.Series) -> pd.Series:
    """MATLAB `tiedrank`: average rank, NaNs kept as NaN.

    Python equivalent of MATLAB `tiedrank(x)` — ascending average rank with
    NaN preserved. Pandas `rank(method='average')` already averages ties; by
    default NaNs are kept (``na_option='keep'``), which mirrors MATLAB.
    """
    return x.rank(method="average", na_option="keep")

Ascending: larger span_r2 / |corr| → larger rank → the descending sort puts them first. Ties share the mean of the occupied ranks. NaN ordering is handled by the subsequent sort, not here.


make_close_anom_results(res_correls, res_anoms, anoms, labels, test_signal, res_basic_sorts, *, returns, ...)

Data (returns, factors, time period) is passed in as arguments rather than loaded inside the builder.

Signature

Parameter Shape / dtype
res_correls DataFrame, rows = anomaly names, columns spearman / pearson
res_anoms dict[str, SortResult] from strat results, or AnomBenchmarkResults (then .cond_sort — not the protocol path)
anoms DataFrame / dict / (nMonths, nStocks, nAnoms) ndarray of raw signals (not filled ranks)
labels {"short": [...], "long": [...]} aligned to anoms
test_signal Series (date, permno)
res_basic_sorts BasicSortsResults; spanning LHS from ("vw_nyse_5", first factor model)
returns Series, decimals; the function multiplies them by 100 for the FMs
mcap unused; kept for signature symmetry
time_period (start, end) YYYYMM or Timestamp; windows FM and spanning
n_close default _CLOSE_N_ANOMS (6)
span_factor_model default 6 (FF6 excluding rf)
basic_sort_row default BASIC_SORT_LABELS[0] (vw_nyse_5)
anom_labels required only for ndarray anoms
factors optional factor table for the spanning RHS

Returns — CloseAnomResults.

What it does

  1. Normalize. Coerce anoms via _coerce_anoms_to_dict (Chapter 17). Take the ranking correlation from res_correls["pearson"] (falling back to the second column, then the only column).

  2. Slice y. Test-signal L/S to time_period.

  3. Pre-select. For each zoo column with a usable L/S, OLS of y on [1, anom_LS] (no FF factors). Need len(df) ≥ 3. Store r2_adj and the correlation.

  4. Rank and take six. Combined rank _tiedrank(span_r2) + _tiedrank(anom_corr.abs()), sorted descending with kind="mergesort" (pandas’ stable sort, so remaining ties break by original position) and na_position="last". Only finite ranks are eligible; see the ranking order above.

  5. FF6-ex-rf. _resolve_factor_model(y.index, 6) then drop(columns=["rf"]).

  6. Per-close FM + span. FM runs on percent returns (ret_sliced = 100.0 * _slice_panel_by_time(returns, time_period)):

        fmb_i = run_fama_macbeth(
            ret_sliced,
            rhs,
            time_period=time_period if isinstance(time_period, tuple) else None,
            print_results=False,
            labels=["Const", "test_signal", name],
        )

Chapter 17’s benchmark FM scales returns by 100 the same way. The original MATLAB toolkit used raw ret here, which made the report's coefficients too small to read at two decimals; the t-statistics and R² are the same either way. Coefficients remain in units of the raw signals, so signals such as Illiquidity or DolVol still give large ones. Each regression records the number of monthly cross-sections it averaged in metadata["n_months"], which the report prints as the # months row.

Spanning RHS is [1, anom_LS, FF6_ex_rf].

  1. Joint row. FM on [testSignal, close_1, …, close_6]; spanning on [1, six L/S, FF6_ex_rf]. The printed spanning alpha (bps) is this last intercept × 10,000.

Tie-break jitter does not enter the FM step, which uses raw signals. Spanning uses L/S series that were jittered upstream in make_anom_strat_results (Chapter 17), so spanning cells on tie-heavy signals (Price, Illiquidity, DolVol) depend on those draws — see The random seed is part of the specification.


DendrogramResults

Field Contents
Z ndarray (n_leaves-1, 4) SciPy linkage, 0-based
labels list of shorts plus "\\color{red}{signal}"
cutoff 75th percentile of Z[:, 2] via _matlab_prctile
metadata dropped columns, missing xret, n_months, …

_to_month_end(x)

Signature — Timestamp | int → month-end Timestamp.

What it does — YYYYMM → last day of that month. A Timestamp that is already month-end is left alone; a month-start or mid-month is snapped with MonthEnd(0). Monthly data in this package is always keyed by month-end dates.

Duplicates exist in sorts.py, ingest/ff_factors.py, ingest/cz_anomalies.py, and transforms/anomaly_fill.py. Dendrogram and weighted-average rank use this copy.


make_dendrogram_results(res_anoms, signal_label, labels, res_basic_sorts, time_period, *, ...)

Signature

Parameter Shape / dtype
res_anoms dict of strat SortResults (protocol); list; or AnomBenchmarkResults → .cond_sort
signal_label plain string ("MPE"); wrapped in the output
labels list[str], one short label per anomaly, same order
res_basic_sorts test-signal L/S from ("vw_nyse_5", first fm)
time_period optional; the protocol always passes it
linkage_method default "ward"
cutoff_percentile default 75.0

Returns — DendrogramResults.

What it does

  1. The window. Inside [start, end], the first month is never used (MATLAB's s+1). The window then runs from the signal's first return month to its last (dendrogram_signal_window). A signal with a month without a return inside that window raises DendrogramSignalError, and the protocol stops. Anomaly L/S series are reindexed to the window.

  2. Build dates × (n_anoms+1). Missing xret → a column of NaN (so the drop step reports it). Signal column last.

  3. Drop any-non-finite anomalies. A single NaN or Inf in an anomaly's series over the window drops it; there is no pairwise-complete distance. The dropped names are logged with their first and last return month, and metadata["window"], ["n_anoms_kept"] and ["dropped_detail"] keep the record. The signal is always a leaf.

  4. Labels. Kept column names, with the signal wrapped "\\color{red}{...}". When res_anoms is a dict, those names are the acronyms; the labels argument is length-checked and then not used for output. Protocol keys match labels.short, so leaves print correctly; a dict keyed by DuckDB lowercase names would print lowercase leaves.

  5. Ward linkage + cutoff.

    # MATLAB: Z = linkage(rets', 'ward')
    # SciPy's `linkage` expects observations as rows (n x m), so we pass
    # rets.T.values (rows = anomalies, cols = months).
    from scipy.cluster.hierarchy import linkage  # type: ignore

    obs_matrix = rets.to_numpy(dtype="float64").T  # (n_anoms_kept, n_months)
    Z = linkage(obs_matrix, method=linkage_method)

    # ---- Cutoff: percentile of linkage distances -------------------------
    # MATLAB: cutoff = prctile(Z(:,3), 75)
    from .sorts import _matlab_prctile

    cutoff = float(_matlab_prctile(Z[:, 2], [cutoff_percentile])[0])

scipy is imported inside the function and is declared in the [analytics] extra. A protocol run without scipy installed fails this stage; the orchestrator’s inner try/except (Chapter 16) logs it and leaves Z is None.


CombStratResult / CombStratsResults

CombStratResult fields

Field Contents
eret forecast-return panel, (date, permno); all-NaN on failure
eret_enh same, with the test signal concatenated as an extra column
label short key from COMB_STRAT_LABELS
display_label "Average rank" or "Average rank - N/A"
explanation LaTeX blurb; "" on failure
error the exception, or None

CombStratsResults — strats: dict[str, CombStratResult] in row order 1–6; metadata with n_success / n_failed and the LASSO tuning settings. Display strings feed Chapter 19’s Fig_CombStrat["ttl"]. Each CombStratResult also has signal_start (the first month whose forecast uses the test signal, None if never) and info (the rule's signal_window; for IPCA the months its solver skipped). metadata repeats them as signal_start, signal_first_month and ipca_skipped.


_nan_eret_like(returns)

Signature — returns: Series → all-NaN Series on the same index, dtype=float64, name="eret".

What it does — the N/A panel. A failed method gets it in both eret and eret_enh, so downstream sorts see a well-shaped empty characteristic.


make_comb_strats(filled_anoms, filled_signal, keep_roll_anoms, res_anoms, res_basic_sorts, returns, *, ...)

Signature

Parameter Shape / dtype
filled_anoms filled ranks, [-0.5, 0.5] (Chapter 11)
filled_signal fill_var(test_signal, me)
keep_roll_anoms (date × anomaly) bool; IPCA only. None ok
res_anoms strat L/S for weighted-average weights
res_basic_sorts test-signal L/S for the enhanced weighted-avg pret column
returns panel shape for NaN fallbacks; also the FMB/PLS/LASSO LHS
time_period forwarded to FMB / PLS / IPCA / weighted-avg
avg_rank_fn … lasso_fn injection hooks; None → default adapter
rf IPCA only
n_jobs worker count for IPCA and LASSO; speed only (None → AA_PROTOCOL_N_JOBS, then config, then cpu_count - 1, capped by RAM)
checkpoint_dir per-method checkpoints, so a killed run can resume. A checkpoint is used only if it was written for the same signal, database, window, anomalies and toolkit version; otherwise the method is computed again and the log names what differs
checkpoint_identity the caller's part of what a checkpoint belongs to (signal, signal_sha256, database_scientific_id, window); the protocol passes it
lasso_cv_mode / lasso_random_state forwarded to make_lasso_res; recorded in metadata
signal_window months of data the test signal needs before the five methods other than the average rank use it (default 120; the protocol passes n_roll)

Returns — CombStratsResults.

What it does

  1. Default adapters. Each *_fn is a small closure so _run_one can call fn(**kwargs) uniformly, and all six adapters take the keyword names the call site passes:
    strats["lasso"] = _run_one(
        "lasso",
        base_kwargs={
            "filled_anoms": base_dict,
            "ret": returns,
            "time_period": time_period,
        },
        # ...
        fn=lasso_fn,
    )

Because _run_one turns any exception into an N/A row, an adapter whose parameter names do not match the call site fails with a TypeError before the method is ever entered — and in the report that looks exactly like a method that genuinely does not apply. When writing your own *_fn, accept the keyword names shown above (plus **kwargs for anything you ignore).

  1. Enhanced panel. Copy base_dict, add "__test_signal__" (with underscores appended on collision). For IPCA, append an always-True column to keep_roll_anoms, so the test signal is always eligible.

  2. _run_one. try: call base + enhanced; unwrap FMBRes / LassoRes / PLSRes / IPCARes to .eret. except Exception: N/A panel, empty explanation, and a " - N/A" suffix on the display label.

  3. Row order. Avg rank, weighted-avg (assembles pret from each anomaly’s long_short plus the test-signal L/S), FMB, PLS, IPCA, LASSO. The result always has six keys.

  4. me substitution. Default avg-rank / weighted-avg adapters pass me=returns. Weighted-avg uses me only as the output index. Avg-rank also masks eret where me is NaN, so the mask is “missing return” rather than “missing market cap.” Protocol’s returns and mcap share a (date, permno) index; cells with ME but no return (or the reverse) can differ.

  5. rf. Taken as a keyword and forwarded to IPCA alone, which needs excess returns. run_test_signal supplies it from the factor table. Omitting it makes IPCA fit on raw returns.


make_avg_rank(filled_anoms, me=None, *, ...)

Signature

  • filled_anoms — filled ranks (dict / DataFrame / nMonths × nStocks × nAnoms ndarray).
  • me — optional mask; None skips masking. Also supplies signal_index for ndarray input.
  • anom_labels / signal_index — ndarray plumbing.

Returns — Series named "eret" (no dataclass). make_comb_strats accepts a Series directly.

What it does — stack to a DataFrame, sum(axis=1, skipna=False) so NaN propagates. Then eret.where(me.notna()). No rolling window. The “rank” is already in the input: fill_var mapped each signal with rank(method="average") to [-0.5, 0.5] and put 0 (median) where ME is finite but the signal is missing.

    # MATLAB: eret = sum(filledAnoms, 3);
    # Use skipna=False so NaN propagates — matches MATLAB default `sum`.
    eret = anoms_df.sum(axis=1, skipna=False)
    eret.name = "eret"

    # ---------------- Apply the `me` NaN mask -----------------------------
    # MATLAB: eret(isnan(me)) = nan;
    if me is not None:
        me_aligned = pd.to_numeric(me, errors="coerce").reindex(eret.index)
        eret = eret.where(me_aligned.notna(), other=np.nan)

Through the protocol adapter, me is returns, so the mask is missing-return, not missing-ME.


make_weighted_avg_rank(filled_anoms, pret, me, *, time_period, lookback=120, ...)

Signature

Parameter Shape / dtype
filled_anoms filled ranks
pret date × anomaly L/S returns (each anomaly’s long_short, assembled by the orchestrator)
me output panel shape only. Values are not a mask here
time_period first filled month is start + lookback
lookback months, default 120

Returns — Series on me.index, NaN outside the rolling window.

What it does — for each month i in range(s_idx + lookback, e_idx + 1):

  1. weights = mean(pret[i-lookback+1 : i+1, :], axis=0) — NaN-propagating mean (np.mean, not nanmean). An anomaly with any missing L/S in the window gets weight NaN and drops out.
  2. Negative weights → 0 (no shorting a historically losing predictor); NaNs stay NaN.
  3. Divide by nansum(weights). If the denominator is 0, leave the month empty.
  4. eret[t] = X_t[:, ok] @ weights[ok] — contemporaneous filled ranks, NaN propagates through the matmul.

make_comb_strats builds pret as a DataFrame keyed by anomaly name before calling this, including the test-signal L/S on the enhanced pass. Its adapter passes returns as me; only the index is used.


LassoRes

Field Contents
eret forecast panel aligned to the original returns index
betas date × anomaly coefficients; NaN outside fit months
metadata roll_window, random_state, cv_mode, …

make_lasso_res(filled_anoms, returns, *, time_period, roll_window=120, random_state=0, ...)

Python library: sklearn.linear_model.LassoCV. This is not a hand-rolled coordinate descent. scikit-learn is imported inside the function and is declared in the [analytics] extra.

Signature

Parameter Shape / dtype
filled_anoms filled ranks
returns decimals, (date, permno)
time_period (start, end) window
roll_window months, default 120
random_state CV fold seed, default 0. At ~500k observations per window the choice of seed is immaterial
cv_mode "shuffled" (default) or "month_grouped" — see step 4
n_jobs months fitted in parallel; speed only, default 1

Returns — LassoRes.

What it does

  1. Lag X with _calendar_lag_panel(..., 1). Forecast uses contemporaneous X.
  2. Loop for i in range(roll_window, n_months). Training window eval_dates[i-roll_window+1 : i+1] includes month i. First fit at eval_dates[roll_window].
  3. Drop columns with no finite mass (nansum(|x|)==0). Mean-impute remaining NaNs in X before fitting (rather than dropping any column that contains a NaN).
  4. Fit LassoCV(cv=KFold(5, shuffle=True, random_state=random_state)). The fold object matters more than it looks. Passing the bare integer 5 to LassoCV gets an unshuffled KFold(5), and since the training panel is sorted by (date, permno) that makes each fold a contiguous ~24-month block — a time-series CV. Holding out whole regimes pushed the selected penalty 9–43x higher (20 non-zero betas against 149 in the 2005–2015 window), a materially different estimator. Shuffled observation folds follow the original MATLAB toolkit, whose lasso(x, y, 'CV', 5) partitions observations at random. cv_mode="month_grouped" is a sensitivity alternative: every observation from one calendar month lands in the same fold, and the imputation is refitted inside each training fold. Shuffled folds put stocks from the same month on both sides of the split, so the hold-out shares that month’s common shock and the penalty tends to come out too weak; month-grouped folds remove that dependence and can select a different penalty. It changes the estimator and is never the default.
  5. scikit-learn picks alpha_ by CV MSE over its own λ grid, and does not standardize X — near-neutral here because the inputs are uniform ranks.
  6. Forecast X_now @ coef — no intercept. The panel is therefore off by a monthly constant and averages near zero; harmless, because eret is only consumed as a sort signal.

PLSRes

Field Contents
eret forecast panel, original ret index
lambdas date × anomaly step-1 slopes
metadata n_anoms, names, time_period

_nanols_univariate_beta(y, x)

Signature — two 1-d arrays → float slope ∑xy / ∑x² over complete cases, NaN if < 2 rows or zero denominator. A single regressor with no constant.

What it does — the Light/Maslov/Rytchkov slope. Not sklearn.cross_decomposition.PLSRegression.


make_pls_res(filled_anoms, ret, *, time_period, ...)

Light, Maslov, Rytchkov (2017) two-step procedure.

Python library: none. This is a hand-rolled pair of cross-sectional OLS loops, not scikit-learn PLS.

Signature — filled_anoms, ret (decimals), optional time_period. No roll_window: every month is its own pair of cross-section OLS fits.

Returns — PLSRes.

What it does — for each month t in the window:

  1. Step 1. For each anomaly j, λ_t[j] = _nanols_univariate_beta(ret_t, X_{t-1}[:,j]).
  2. Step 2. For each stock s, eret[t,s] = _nanols_univariate_beta(X_t[s,:], λ_t).

Lag is _calendar_lag_panel on the full panel, then slice, so the first month of the window can use the previous month’s X from outside the window. Progress logs every 120 months. No intercept in either step.

There is no ten-year wait despite the comb-strat explanation string saying so; that sentence is shared with the FMB/LASSO/IPCA blurbs, and PLS starts at the first month of the window.


IPCARes

Field Contents
eret forecast panel, (date, permno); NaN outside the window
gamma_beta per-month (nKept+1) × K loading matrix, constant row last
lambda_ per-month mean(F, 2), one row per forecast month
diagnostics per-month kept-anomaly count, cross-section size, ALS iterations, tolerance reached
metadata time period, anomaly names, solver settings, fit-month count

Keeping the loadings and diagnostics is what makes the ALS auditable — diagnostics.n_iter against the 10,000-iteration cap is the difference between "converged" and "gave up".


make_ipca_res(filled_anoms, keep_roll_anoms, ret, rf, *, time_period, roll_window=120, ...)

Python library: none, by choice. Not scikit-learn, not the PyPI ipca package. The Kelly/Pruitt/Su (2019) alternating-least-squares algorithm needs only basic linear algebra, so it is implemented directly.

For each forecast month i (with T = roll_window = 120), if any anomaly is kept in month i-1:

  1. Slice the filled characteristics for months i-T … i-1 (kept anomalies only) and excess returns ret - rf for months i-T+1 … i. Note the offset: month j's characteristics are matched to month j+1's return.
  2. Per window: keep complete cases, append a constant characteristic, build W_t = Z'Z/N_t and X_t = Z'r/N_t, take K=5 factors with an SVD initial guess, and iterate ALS until tol=1e-6 or 10,000 iterations (Γ orthonormal, F positive-mean).
  3. Lambda = mean(F, 2); forecast [X_i; 1]' * GammaBeta * Lambda.

The code is split as make_ipca_res (the month loop) → _ipca_fit_window (the ALS loop) → _ipca_als_step (one sweep), with _ipca_month_moments for W_t / X_t. Loop bounds are 0-based offsets from the sample start: range(roll_window, n_months - 1): the first forecast is in the same month as the other rolling methods' (MATLAB starts one month later).

Two structural choices:

  • Moments are hoisted. W_t and X_t depend only on the month, so they are computed once per month and the kept-anomaly subset is sliced out of the cache, instead of being rebuilt inside each of the up to 120 windows that contain the month. This is valid only if the complete-case mask is independent of which anomalies are kept — true because fill_var gives every filled signal the market cap's own missingness pattern. The invariant is checked per month and raises if violated.
  • No dense cube. A (nMonths, nStocks, nAnoms) array is ~19 GiB for a 157-anomaly zoo. The code works from the long panel one month at a time.

The initial guess is np.linalg.svd(X)[:, :K]; the ALS re-normalizes sign each sweep, so only the starting point depends on it. A month whose moments are non-finite is skipped with a warning.

On the MPE example, the IPCA forecast has a mean cross-sectional Spearman correlation with next month's return of +0.078 (t = 13.6).


Small helpers

Name Role
LOGGER module logger (Chapter 17).
_CLOSE_N_ANOMS / _CLOSE_SPAN_FACTOR_MODEL Shared constants.
_LASSO_ROLL_WINDOW 120; LASSO training window in months.
COMB_STRAT_LABELS / _DISPLAY_LABELS / _EXPLANATIONS Shared constants.