Chapter 13 — Portfolio sorts and factor regressions¶
Part III of the assayinganomalies tutorial. Prerequisite chapters: 1–12. Python modules covered:
analytics/sorts.py,analytics/__init__.pyre-export block.
What this chapter answers¶
- What
run_univariate_sortandrun_bivariate_sortdo and what each keyword controls. - Where portfolio formation (contemporaneous signal binning) ends and
holding begins (returns accrue from the month after formation) — and the
calendar-lag trap that a naive
groupby().shift(1)falls into. - What a held leg is: a univariate sort buys each portfolio at a trade and leaves it alone until the next trade (Held legs).
- When a sort trades: in every month in which the signal has values, and in no other. The data decide, not an argument (When a sort trades).
- What
SortResult/BivariateSortResultcontain. - The four semantics most often gotten wrong: conditional vs unconditional bivariate sorts, NYSE-only breakpoints, value vs equal weighting, and which step drops NaN signals.
- How factor regressions, GRS tests, and the print/plot formatters work.
- That
run_bivariate_sortreports gross returns only (see Known limitations).
Where this sits in the pipeline¶
Chapter 12 loads (date, permno) panels from DuckDB. This chapter is the first
analytics layer most anomaly assays touch: bin stocks into portfolios, compute
monthly portfolio returns, regress them on Ken French factors, optionally net
trading costs.
flowchart TD
LOAD["aa.load ret, me, signal, nyse_flag"]
BIN["_bin_by_cross_section / _conditional_bin_by_cross_section"]
IND["portfolio id ind (0 = unassigned)"]
HELD["univariate: calc_held_ptfs (held legs, costs)"]
CPR["bivariate, holding_period > 1: calc_ptf_rets (1-mo lag + carry-forward)"]
EFR["est_factor_regs / _matlab_style_sort_outputs"]
OUT["SortResult / BivariateSortResult"]
LOAD --> BIN --> IND
IND --> HELD --> EFR
IND --> CPR --> EFR
EFR --> OUT
TS["load_factors → ts_data"] --> EFR
Returns, portfolio ids and market caps are long (date, permno) Series. The
portfolio calculations must behave as if they were a rectangular months ×
stocks grid. calc_held_ptfs builds that grid from the labels (a complete
monthly calendar by the stocks that are ever assigned) and hands it to the
core in analytics/held.py. calc_ptf_rets reconstructs the grid's lag with
_calendar_lag_positions + _take_lagged.
Four semantics that matter¶
The rest of the chapter assumes these four choices.
1. Conditional vs unconditional bivariate sorting¶
| Mode | Python |
|---|---|
| Unconditional | sort_type="unconditional" — _bin_by_cross_section on signal1 and signal2 separately |
| Conditional | sort_type="conditional" — _conditional_bin_by_cross_section bins signal2 within each bins1 group |
Portfolio id formula (row-major, var1 first): (bin1 - 1) * n2 + bin2. A stock
must have both bin assignments; otherwise ind = 0.
Conditional strategies (high minus low within the other dimension) are
computed after the grid exists:
cond_var2_given_var1 = column-wise L/S within each var1 row;
cond_var1_given_var2 = row-wise L/S within each var2 column.
2. NYSE-only breakpoints¶
With breaks="nyse", breakpoints come from NYSE stocks only, but all
stocks are then assigned using those breakpoints. _get_breakpoints:
- Coerces
nyse_flagto boolean (handles DuckDB float NaNs and nullableboolean). - Computes percentiles on
sig.where(nyse_mask).dropna()only. - If the filter selects no stocks, returns empty breakpoints →
_assign_binsyields all NA →fillna(0)→ no assignments that month. There is no fallback to all-stock breakpoints.
Any boolean panel works as a breaks filter (e.g. exchcd == 3 for NASDAQ breaks).
3. Value vs equal weighting¶
Both schemes flow through calc_ptf_rets:
weighting="v"— weights = lagged market cap (lmcap).weighting="e"— weights = ones, but a stock still needs a finite lagged mcap and a finite return to be held:finite_ok = isfinite(ret) & isfinite(lmcap). Equal weighting does not bypass the lagged-cap filter. This follows the original MATLAB toolkit, which applies the same filter to both weighting schemes.
Portfolio return at date (t): (\sum_i w_i r_i / \sum_i w_i) over stocks held in the portfolio after lag and carry-forward.
4. Where NaN signals are dropped¶
| Step | NaN signal effect |
|---|---|
_get_breakpoints |
Excluded from percentile / cap-mass calculation (sig.dropna() or NYSE subset) |
_assign_bins |
Stock keeps NA bin → later fillna(0) → not held |
run_univariate_sort concat |
No dropna(subset=["ret","signal"]) before binning — stocks with missing returns but finite signals still enter breakpoints |
calc_ptf_rets |
Requires finite return and finite lagged mcap to contribute to a portfolio that month; zero lagged ind → not held |
NaN signals never receive a bin; NaN returns can still affect who is eligible for breakpoints but cannot contribute to realized portfolio returns.
Worked example (hand-verifiable)¶
Two month-ends, four stocks, NYSE breakpoints, value weights, n_bins=2.
Panel (month 1 = formation, month 2 = returns):
| permno | NYSE | signal (M1) | mcap (M1) | ret (M2) |
|---|---|---|---|---|
| 1 | yes | 1 | 10 | 0.05 |
| 2 | yes | 2 | 20 | 0.04 |
| 3 | no | 3 | 30 | 0.03 |
| 4 | no | 4 | 40 | 0.02 |
Step A — breakpoints (M1). NYSE signals {1, 2}. For 2 bins, cut at 50th
percentile. _matlab_prctile on [1, 2]: plot positions 25 and
75 → interpolate at 50 → 1.5.
Step B — assign all stocks (M1). Bin 1: signal < 1.5 → permno 1. Bin 2:
≥ 1.5 → permnos 2, 3, 4 (non-NYSE stocks use NYSE-derived cuts).
Step C — returns (M2 uses the M1 portfolios). Month 1 is the trade month and has no return → portfolio returns NaN. In month 2 each portfolio holds what it bought in month 1, with month-1 mcap as VW weights:
- Bin 1: (0.05) (only permno 1).
- Bin 2: ((0.04 \times 20 + 0.03 \times 30 + 0.02 \times 40) / 90 = 0.03111\ldots)
Long–short (bin 2 − bin 1) at M2: (0.03111 - 0.05 = -0.01889\ldots)
Held legs¶
run_univariate_sort computes the returns and the trading costs of portfolios
that are bought at a trade and then left alone until the next trade. The
calculation is in analytics/held.py, whose module docstring has the
definitions; calc_held_ptfs is the entry on (date, permno) Series.
For one portfolio (a "leg"):
- Trade months are the months in which any stock has a portfolio assignment.
- At a trade the leg is set to its target weights: market cap (
"v") or 1 ("e") over its stocks that have a market cap in the trade month, scaled to sum to 1. - Between trades a position grows with the stock's total return (
ret). A dividend is reinvested in the stock that paid it, and that purchase is not charged. A stock without a return in a month earns the average of the leg's other stocks. A return of −100% or less makes the position worthless from that month on. The value of a stock that loses its market cap becomes cash, which earns nothing until the next trade. - Leg return = the month's P&L over the leg's value entering the month.
With no missing data this is the buy-and-hold return of the target weights.
For a signal that is traded every month it is the return
calc_ptf_retsgives (monthly rebalanced portfolios). - A portfolio with no stocks at a trade holds nothing until the next trade: its return is missing in those months, and the trade that empties it pays to sell what it held.
For the long/short pair (the top portfolio minus the bottom one):
- Gross return = the long leg's return minus the short leg's, each on its own value.
-
conventionis the size the two legs are given at a trade."dollar"(the default): each leg goes back to $1. What it gained is taken out and what it lost is put back. The cost is the same whichever leg is long."capital": both legs are set to the strategy's capitalK = 1 + long P&L − short P&Lsince the previous trade. The legs are equal again, and their size grows or shrinks with the strategy. The cost depends on which leg is long.
The gross return is the same under both. Only costs and turnover differ. - Cost of a leg at a trade =
sum(|s × target − holding| × half-spread)over the leg's value entering the month, wheresis the leg's new size. Turnover is the same sum without the half-spread. A stock without a market cap in the trade month is not traded, and a stock without a half-spread is traded for free. - The entry cost is the cost of the first purchase,sum(target × half-spread)per leg, the same under both conventions. It is reported as one number (entry_cost) and is not in the cost series, the turnover or the net returns: the month of the first trade has no return to charge it to. Every later trade is booked in its own month. -K ≤ 0("capital"only): if the pair lost at least everything since the previous trade, the strategy starts again with $1 legs, the trade is charged as the move from what is held to those legs, and a warning is logged.SortResult.metadata["capital_restarts"]counts these trades. - The strategy held short is the same two portfolios with the legs exchanged. Under"dollar"it costs what the strategy costs. Under"capital"it has its own capital,K' = 1 + short P&L − long P&L, and therefore its own cost, which istcosts_ts_short. The generalized alpha charges it on a short position (Ch 15). - The last month with a return: withfthe usual gap between trades, returns run throughf + 1months after the last trade when the data go that far (13 for an annual sort), as incalc_ptf_rets.
A three-stock example. A and C are the long leg, equal-weighted, $0.50 each; B is the short leg, $1. Bought in June of year 1 and sorted again, into the same legs, in June of year 2. Every half-spread is 1%. In July A earns 30%, C 10% and B 10%; in January A earns 10%; all other returns are zero.
| Long (A, C) | Short (B) | Strategy | |
|---|---|---|---|
| July return | ½·30% + ½·10% = 20% | 10% | 10% |
| January return | 0.065 / 1.20 = 5.42% | 0 | 5.42% |
| Value entering the second June | 1.265 (A 0.715, C 0.55) | 1.10 | K = 1 + 0.265 − 0.10 = 1.165 |
"capital": targets |
A, C 0.5825 each | 1.165 | |
"capital": traded |
0.1325 + 0.0325 = 0.165 | 0.065 | cost 0.01 · (0.165/1.265 + 0.065/1.10) |
"dollar": targets |
A, C 0.50 each | 1.00 | |
"dollar": traded |
0.215 + 0.05 = 0.265 | 0.10 | cost 0.01 · (0.265/1.265 + 0.10/1.10) |
In January the long leg holds $0.65 of A in a leg worth $1.20, so A's 10% is 5.42% of the leg: the leg was not rebalanced after July. The first purchase costs 1% of $1 per leg, so the entry cost is 0.02 under both conventions. It is in no month: the cost series is zero in July and holds the second June's cost only.
Held on its own under "capital", the long portfolio rolls its value of 1.265
over: A and C go to 0.6325 each, 0.165 is traded, and its cost in the second
June is 0.01 · 0.165/1.265. The short portfolio holds one stock and trades
nothing. Under "dollar" each portfolio's own cost is its part of the
strategy's cost in the table.
What the cost fields hold (with a per-stock tcosts panel):
| Field | Content |
|---|---|
tcosts_ts |
Cost of the two extreme legs' trades in the month, decimal, the first purchase excluded. 0, never NaN, in a month without a trade, so netpret == long_short − tcosts_ts wherever there is a return |
netpret, netxret, tnetxret |
Net long-short return; its mean (%/mo) and t-statistic |
ptf_costs, ptf_to |
Every portfolio's own cost, and its traded dollars over its value, as a portfolio held by itself. 0 in a month without a trade. "dollar": each portfolio goes back to $1 at a trade, and the two extreme columns of ptf_costs add up to tcosts_ts. "capital": each portfolio rolls its own value over (1 plus its P&L since the previous trade; nothing is put in or taken out), and the two extreme columns are not the parts of tcosts_ts, whose legs are both set to K |
to_ts |
Turnover of the two extreme legs as legs of the pair |
tcosts, turnover |
Averages over the months in which the long-short portfolio has a return. Mean gross return (%/mo) less 100 × tcosts equals netxret. turnover is both legs' traded dollars over leg value, divided by 4 |
entry_cost, ptf_entry_costs |
Cost of the first purchase of the two extreme legs (decimal, per $1 in each leg), and the same for every portfolio (a Series indexed by portfolio). In none of the fields above |
tcosts_ts_short |
"capital" only: cost per month of the strategy held short (the legs exchanged). None under "dollar", where it equals tcosts_ts |
For a signal traded once a year, tcosts and turnover average over all
twelve months, so turnover is about a twelfth of the June figure, not the
June figure.
What is not a held leg. run_bivariate_sort, and run_univariate_sort
with holding_period > 1, use calc_ptf_rets: every month each portfolio
earns the return of fresh target weights, and no cost is computed. A per-stock
tcosts panel together with holding_period > 1 raises ValueError.
MATLAB. runUnivSort pairs calcPtfRets with calcTcosts. For a signal
with values every month the gross returns here equal MATLAB's; the costs do not
under either convention (positions drift with ret, not with the market-cap
ratio; "capital" sizes the legs at K). For a
signal traded once a year the gross returns differ as well: MATLAB re-weights
the carried portfolios every month.
When a sort trades¶
There is no argument for the trading schedule. A sort trades in every month in which the signal has a value for any stock, and in no other month. What you pass as the signal therefore decides the strategy:
| Signal has values | The sort |
|---|---|
| every month (momentum, a signal from quarterly Compustat columns, a filled annual signal) | sorts and trades every month; gross returns are those of monthly rebalanced portfolios |
each June only (a signal from annual Compustat columns as aa.load returns them) |
sorts and trades each June and holds for the year |
Annual Compustat columns (at, be, gp, …, and columns added with
aa add-compustat-vars --annual) are stored in ccm_panel on one row a year:
the June in which the record becomes available. aa.load returns them that
way, so a signal computed from them has values in June only:
import assayinganomalies as aa
d = aa.load(["ret", "me", "gp", "at", "tcost"])
signal = d["gp"] / d["at"] # values in June only
# Traded each June, held for the year:
res = aa.run_univariate_sort(d["ret"], signal, d["me"], tcosts=d["tcost"])
# Traded every month on the same annual information:
monthly = aa.fill_months(signal) # June value carried through May
res_m = aa.run_univariate_sort(d["ret"], monthly, d["me"], tcosts=d["tcost"])
aa.fill_months(x, months=11) carries each stock's last value forward for at
most months calendar months, on the rows the stock has. Loading with
aa.load(..., fill_annual=True) applies it to each annual column before you
compute the signal; Ch 12 says what that does and does not
fill. With a June-only signal, res.tcosts_ts is positive in each June after
the first and zero in every other month, and the first June's purchase is
res.entry_cost; with the filled signal tcosts_ts has a cost every month.
The two strategies hold the same stocks in July. They differ afterwards. The June-only strategy lets its positions drift for twelve months. The filled strategy sorts again every month on the same values, which brings each portfolio back to its target weights (value weights at that month's market cap, or equal weights), drops stocks that have left the panel and uses that month's breakpoints, and it pays for those trades.
Three things to check in your own signals:
- Stray values make a trade month. If a signal that is meant to be annual has values for a few stocks in some other month, that month is a trade month, and the portfolios are re-formed from those few stocks only. Make sure the months in which the strategy should not trade are entirely missing.
- Quarterly Compustat columns are stored filled month by month, so a signal built from them trades every month.
- The Chen–Zimmerman signals trade as their file gives them: a signal the authors fill monthly trades monthly.
run_bivariate_sort is different: it carries a June assignment through the
following months and re-weights the portfolios every month (calc_ptf_rets).
Public surface: analytics/__init__.py¶
The package re-exports these sort symbols from analytics.sorts and
analytics.held:
| Export | Role |
|---|---|
run_univariate_sort |
Main univariate entry |
run_bivariate_sort |
Main bivariate entry |
SortResult, BivariateSortResult |
Result dataclasses |
calc_held_ptfs |
Held-leg returns and costs for a given portfolio assignment (the calculation behind run_univariate_sort) |
held_legs, held_long_short, held_portfolio_costs, held_composite_long_short |
The held-leg core on numpy grids (analytics/held.py); held_portfolio_costs prices every portfolio held on its own; the last one prices a side made of several portfolios, as the factor costs need (Ch 9b) |
fill_months |
Carry a value forward a bounded number of calendar months |
calc_ptf_rets |
Monthly re-weighted portfolio returns (bivariate sorts, holding_period > 1, nmv_anomalies industry VW) |
est_factor_regs |
Standalone factor regressions on a pret matrix |
load_factors |
Load ts_data factors for models 1/3/4/5/6 |
Other analytics/__init__.py exports (FMB, protocol, results builders) belong to
later chapters.
analytics/sorts.py — result types¶
SortResult¶
Signature — dataclass fields:
| Field | Meaning |
|---|---|
leg_returns |
Raw monthly portfolio returns, columns 1..K |
long_short |
Top bin minus bottom bin (when add_long_short=True) |
long_short_net |
Net L/S after costs (tcost path) |
metadata |
Dict of sort settings (weighting, holding period, …) |
xret, txret |
Mean excess return (%/mo) and t-stat |
alpha, talpha |
Factor alpha (%/mo) and t-stat |
sharpe, info |
Annualized Sharpe and information ratio |
resid |
Factor regression residuals |
alphas, tstats |
Legacy: alpha in decimal return units |
factor_loadings, factor_loading_tstats |
Per-factor betas and t-stats |
r2, r2_adj |
OLS R² and adjusted R² |
ptf_num_stocks |
Count of stocks per leg per month |
ptf_market_cap |
Sum of lagged mcap in leg |
tcosts_ts, netpret, to_ts, netxret, tnetxret, turnover, tcosts, ptf_costs, ptf_to, entry_cost, ptf_entry_costs, tcosts_ts_short |
Per-stock tcost panel only; see Held legs for what each holds |
Note the units: xret and alpha are in percent per month, while the
legacy alphas field is in decimal units.
Properties
pret—leg_returnspluslong_shortcolumn.dates— index ofleg_returns.
Methods
table()— DataFrame of the standard sort-results layout; requiresfactor_modelat sort time.print_results()— header +table(), or legacy raw-return table if no factors.plot_results()— four panels (cumulative log return, 60-month rolling Sharpe, L/S stock count, annual return bars).
By default factor_model=None, print_results=False and plot_results=False,
so a sort runs quietly and skips the factor regressions unless asked.
BivariateSortResult¶
Signature:
| Member | Content |
|---|---|
flat |
SortResult for the n1×n2 grid on flattened portfolio ids (no L/S column) |
cell_returns |
same data, columns (bin1, bin2) MultiIndex |
cond_var1_given_var2 |
high−low var1 within each var2 bin |
cond_var2_given_var1 |
high−low var2 within each var1 bin |
metadata |
sort dimensions, sort_type, weighting, etc. |
Methods
print_grid(label, name1, name2)— average-return grid plus conditional var2|var1 strategy table; returns the grid DataFrame.
GRS test results appear in the printed output from
_print_bivariate_results_matlab_like; they are not stored as attributes on
flat.
Binning stack¶
_matlab_prctile(x, pcts)¶
Signature — x: 1d finite values; pcts: percentile levels 0–100.
Returns — breakpoint values, same length as pcts.
What it does — Sorts finite x, uses plot positions ((i - 0.5)/n), linear
interpolation. This differs from the numpy.percentile / pandas quantile
rule ((i-1)/(n-1)) and follows the original MATLAB toolkit, whose prctile
uses plot positions. This is the 1-D finite-only
copy; the three implementations (tcosts keeps ±Inf; this and NMV drop non-finite)
are compared in
Ch 9.
_get_breakpoints(sig, n_bins, breaks, nyse_flag, mcap)¶
Signature
sig— cross-section Series indexed by permno (one date).n_bins— int (e.g. 5) or explicit cut list[30, 70]→ 3 bins.breaks—"name"|"nyse"|"cap".nyse_flag,mcap— same-date slices for filter / cap breaks.
Returns — Series of breakpoint values indexed by percentile fraction.
What it does — See four-semantics section. Cap branch sorts by signal,
cumulative mcap mass, finds value cuts. An empty NYSE filter gives empty
breakpoints (no all-stock fallback).
_assign_bins(sig, breakpoints, n_bins)¶
Signature — sig cross-section; breakpoints sorted cut values; n_bins count.
Returns — nullable Int64 Series, bins 1..n_bins or NA.
What it does — Bin 1: sig < bp[0]; middle: [bp[j-1], bp[j]); top:
sig >= bp[-1]. Tie rule: >= pushes a stock equal to a breakpoint into the
higher bin.
_bin_by_cross_section(signal, n_bins, breaks, nyse_flag, mcap)¶
What it does — groupby date level; per month call _get_breakpoints +
_assign_bins; restore MultiIndex. Used by all univariate and unconditional
bivariate sorts.
_conditional_bin_by_cross_section(signal2, bins1, ...)¶
What it does — For each date and each bins1 value, restrict signal2 to
members of that bin, compute breakpoints on the subset, assign bins 1..n2.
Lag machinery and portfolio returns¶
_calendar_lag_positions(date_codes, permnos, lag=1)¶
Signature — integer date codes and permno array (panel sorted by date, permno).
Returns — int array: source row index for value lag calendar months earlier,
or -1 if that (date, permno) cell is absent.
What it does — Encodes (date, permno) as date * stride + permno_code,
subtracts lag * stride, binary-searches.
Why it matters — groupby("permno").shift(1) follows each stock's previous
observed row, which can be 13 months back if the stock skipped months. A
calendar lag looks exactly one calendar month back and finds nothing, which
is treated as NaN/0. Getting this wrong resurrects stale portfolio
assignments across gaps.
_take_lagged(values, lag_src, fill)¶
What it does — out[i] = values[lag_src[i]] when lag_src[i] >= 0, else
fill. Vector gather used with _calendar_lag_positions.
calc_ptf_rets(returns, ind, mcap, *, holding_period=1, weighting="v")¶
Signature
returns,ind,mcap—(date, permno)Series;indis portfolio id 1..K or 0.holding_period— months of overlapping membership (union of lags 0..K-1).weighting—"v"or"e".
Returns — (ptf_ret, ptf_n, ptf_m) DataFrames indexed by date, columns 1..K.
What it does — Execution order:
- Calendar-lag
indandmcapone month. - Carry-forward lagged
indthrough empty rebalance months, bounded by detected rebalance frequency (mode of gaps between rebalance months, the smallest on ties) — this is what lets annual Compustat signals be held for a full year. - If
holding_period > 1, union membership with further calendar lags oflind. - Filter to finite
retand finite laggedmcap. - VW or EW aggregate per date per portfolio (long panel +
bincount).
Industry VW returns in Ch 11 also use this function.
Every month each portfolio earns the return of fresh target weights (the
lagged market caps, or equal weights), also in the months through which an
assignment is carried. run_univariate_sort calls it only for
holding_period > 1; with the default it uses calc_held_ptfs.
calc_held_ptfs(returns, ind, mcap, tcosts=None, *, weighting="v", n_ptfs=None, short=1, long=None, convention="dollar", label=None)¶
Signature
returns,ind,mcap,tcosts—(date, permno)Series;ind,mcapandtcostsare read on the index ofreturns.tcostsholds decimal half-spreads.n_ptfs— number of portfolio columns (a portfolio that never has a stock still gets its column).short,long— the pair that is costed;longdefaults to the last portfolio.convention—"dollar"(default) or"capital"(check_conventionraisesValueErroron anything else).label— names the strategy in the warning logged atK ≤ 0.
Returns — a HeldSort: leg_returns, num_stocks, market_cap
(date × portfolio frames on the observed dates), costs (a frame with cost,
turnover, each leg's part, the capital K at each trade and
cost_exchanged, the cost of the pair with its legs exchanged; None without
tcosts), restarts, entry_cost (the first purchase of the pair, which is
not in costs), and each portfolio's own cost, turnover and entry cost
(ptf_costs, ptf_turnover, entry_costs).
What it does — builds the dense grid (a complete monthly calendar, so a
month absent from the panel is an empty row, by the stocks that are ever
assigned), calls held_legs and, with costs, held_portfolio_costs and
held_long_short (Held legs). Rows and columns are found from
the labels, never by position; duplicate (date, permno) keys raise.
fill_months(x, months=11)¶
Signature — x is a numeric Series or DataFrame on a (date, permno)
index with month-end dates; a DataFrame is filled column by column.
Returns — same index and columns, as float.
What it does — a missing cell takes the stock's most recent value if that
value is at most months calendar months older. Months in which the stock has
no row still count toward the limit. Values that are present are not changed,
and no row is added. The default 11 is the annual case: a June value reaches
the following May and stops. The Python counterpart of MATLAB FillMonths;
_calendar_ffill (used by the Fama–MacBeth code and fill_var) is the same
routine for one Series. See When a sort trades.
Entry points¶
run_univariate_sort(returns, signal, mcap, *, ...)¶
Keyword arguments
| Python kwarg | Notes |
|---|---|
returns |
Month-t returns; not pre-lagged |
signal |
Contemporaneous: portfolios are formed on the month-t signal and returns accrue from month t+1. The months in which it has values are the months the sort trades |
mcap |
VW target weights at a trade (month-t market cap) |
n_bins=5 |
int or [30,70] cut list |
breaks="name" |
"name" → all stocks; "nyse" → NYSE breakpoints; "cap" → cap-mass breakpoints |
nyse_flag |
Required when breaks="nyse" |
portfolio_mass |
Defaults to mcap for cap breaks |
weighting="v" |
"v"/"V" value, "e"/"E" equal; anything else raises |
holding_period=1 |
Above 1: overlap union via calc_ptf_rets (not held legs), gross returns only |
convention="dollar" |
Size of the two legs after a trade: "dollar" ($1 each) or "capital" (both at the strategy's capital) |
time_period |
YYYYMM; subsets before lag → first month empty |
add_long_short=True |
Top − bottom bin |
factor_model |
1/3/4/5/6 or a DataFrame of factors; None (default) skips regressions |
tcosts |
Scalar/Series → subtract from L/S; MultiIndex panel of decimal half-spreads → priced on the held legs' trades; the first purchase is reported as entry_cost and is not in the cost series. Raises with holding_period > 1 |
robust_se=False |
White SE if True; classical OLS default |
print_results=False |
Print the results table |
plot_results=False |
Draw the four-panel strategy figure |
Pipeline: concat → optional
_time_mask → _bin_by_cross_section → ind with 0 for unassigned →
calc_held_ptfs (calc_ptf_rets when holding_period > 1) → optional L/S →
factor stats → optional tcost block → SortResult.
Indicator construction and the sort itself happen in this one call.
run_bivariate_sort(returns, signal1, signal2, mcap, *, ...)¶
Keyword arguments — all univariate kwargs except add_long_short, plus:
| Python kwarg | Notes |
|---|---|
signal1 |
Row / first sort dimension |
signal2 |
Column / second sort dimension |
n_bins1, n_bins2 |
Bins along each dimension |
sort_type="unconditional" |
"conditional" for nested sort |
No add_long_short on the flat grid; conditional strategies are always built.
What it does — bin both
dimensions → combined ind → calc_ptf_rets → reshape to grid → build cond1/
cond2 L/S legs → factor regressions (input_is_excess=True on conditional
legs, since a long–short return is already an excess return).
Factor models and regressions¶
load_factors(db_path=None)¶
Returns — month-end DataFrame: mkt, smb, hml, rf, mom, smb2, rmw, cma,
read from ts_data. Renames mktrf→mkt, umd→mom. FF5/FF6 need smb2
from ts_data (Ch 5 ingest).
FACTOR_MODEL_COLS (module constant)¶
Maps model id → required columns. Models 5 and 6 use smb2
(five-factor SMB), renamed to smb in _resolve_factor_model.
_resolve_factor_model(index, factor_model, db_path=None)¶
What it does — Accepts int code or user DataFrame; aligns to pret.index;
attaches rf when present.
est_factor_regs(pret, *, factor_model, add_long_short=False, robust_se=False, input_is_excess=False)¶
Signature — pret: DataFrame of raw portfolio returns (columns 1..K).
Returns — (alphas, tstats, loadings, loading_tstats, r2) in decimal units
(legacy path); use _matlab_style_sort_outputs for %/mo display fields.
What it does — Optionally appends L/S column; resolves factors; delegates to
_run_factor_regs. Used inside sort entry points and available standalone.
_run_factor_regs(leg_ts, long_short, factors, robust, input_is_excess)¶
What it does — Per column: excess return (subtract rf unless L/S or
input_is_excess); stack [const, factors]; _ols; collect alphas, loadings,
R².
_ols(y, X, robust=False)¶
Returns — beta, tstats, r2. Classical standard errors by default,
White standard errors with robust=True. Ch 14 covers the public nanols.
_matlab_style_sort_outputs(pret, *, factors, robust_se, input_is_excess)¶
Returns — dict with xret, txret, alpha, talpha, sharpe, info,
resid, r2_adj in display units (%/mo). Drives SortResult.table().
_matlab_mean_tstat(x)¶
Mean and t-stat of a return series, i.e. a regression on a constant.
_factor_details(pret, factors, *, input_is_excess, robust_se)¶
Returns — dict with raw-unit xret, alpha, betas, resid, etc. for
the bivariate print path and the GRS test.
_grs_test_like_matlab(details, factors)¶
Returns — (pvals, Fstats, dfs) length-2 arrays: full model and reduced model.
What it does — Full GRS: (\alpha'\Sigma_e^{-1}\alpha) adjusted for factor
means. Reduced: test on
mean excess returns vs estimated return covariance. Uses SciPy f.sf when
available. Sample covariances use pandas/numpy defaults.
Output formatters¶
_print_prt_sort_results_like_matlab(...)¶
Prints the standard univariate sort-results table.
_print_bivariate_results_matlab_like(out, n1, n2, factor_model, robust_se)¶
Prints the GRS lines, the conditional strategy tables, and the average return / firm count / size matrices for a bivariate sort.
_plot_bivariate_results_matlab_like(out, n1, n2, factor_model)¶
What it does — Heatmap of the bivariate grid plus conditional L/S time series. Optional.
SortResult.plot_results()¶
Four-panel strategy figure; see SortResult.
Small helpers¶
| Name | Role |
|---|---|
_to_month_end |
YYYYMM int → month-end Timestamp; validates month range |
_time_mask |
Boolean mask for time_period on MultiIndex or date index |
_ensure_multiindex |
Raises if Series is not (date, permno) |
_n_bins_count |
int → itself; cut list → len+1 |
_take_lagged |
Vector gather for calendar lag |
_matlab_mean_tstat |
Mean and t-stat of a return series (ddof=1) |