Chapter 15 — Portfolio costs, generalized alpha, and anomaly decay¶
Part III of the assayinganomalies tutorial. Prerequisite chapters: 1–14, especially 9/9b (stock-level
tcostand FF factor costs) and 13 (run_univariate_sort,SortResult). Python modules covered:analytics/costs.py,analytics/gen_alpha.py,analytics/anomaly_decay.py.
What this chapter answers¶
- Which calculation prices a strategy's trades today (held legs,
Chapter 13) and what
calc_tcosts, the port of MATLABcalcTcosts.m, still is: a function you can call, which no sort, protocol stage or build stage calls any more. - How
calc_tcoststurns a stock-level half-spread panel into portfolio-level costs: what “turnover at rebalance” means, how rebalancing frequency is inferred, and why the returned turnover is two-sided. - Why
analytics.costs.make_ff_tcostsis a one-line re-export of the Chapter 9b implementation. - The Novy-Marx / Velikov (2016) generalized-α construction: net MVE of
(factors, anomaly) scaled by the anomaly weight, then OLS on the net MVE of
the factors alone — and which SMB is used (plain
smb, notsmb2). - How
run_anomaly_decaymeasures anomaly decay across the Chen–Zimmerman catalog, including the synthetic{1, 2}-leg trick. - That
run_univariate_sortcomputes no trading costs at holding periods longer than one month (see Known limitations).
Where this sits in the pipeline¶
Chapter 9 builds the stock-level half-spread tcost. Chapter 13 bins stocks
and, when a per-stock tcost panel is passed, prices the trades of the held
legs (calc_held_ptfs, analytics/held.py) to fill SortResult.tcosts_ts /
netpret. Chapter 9b prices the 2×3 FF portfolios with the same held-leg core
into mkt_tc…umd_tc. This chapter covers calc_tcosts (the MATLAB
calculation, kept as a function), the gen-α stack that consumes the sort's and
the factors' costs, and the CZ publication-decay loop.
calc_tcosts and the held-leg calculation answer different questions.
calc_tcosts prices the trades of a portfolio that is set back to target
weights on a constant $1 base, with positions between rebalances drifting with
the market-cap ratio; it pairs with calc_ptf_rets, which earns the return of
fresh target weights every month. The held-leg calculation prices the trades
of the portfolio whose return it reports: positions drift with ret, and at a
trade the legs are sized by convention. The first purchase is reported as
one number (entry_cost) and is not in the cost series.
The two do not give the same costs for any signal.
flowchart TD
TC["ccm_panel.tcost (Ch 9)"]
IND["portfolio ind (Ch 13)"]
CALC["calc_tcosts (standalone)"]
HELD["held legs (Ch 13)"]
FF["make_ff_tcosts (impl in Ch 9b)"]
TS["ts_data mkt_tc..umd_tc, smb_tc_capital..umd_tc_capital, smb_tc_capital_short..umd_tc_capital_short"]
SORT["SortResult.tcosts_ts"]
GA["calc_gen_alpha"]
BASIC["make_basic_sorts_results gen_alpha (Ch 17)"]
CZ["cz_anomalies + cz_signal_info"]
DEC["run_anomaly_decay"]
PLT["plot_anomaly_decay"]
TC --> CALC
IND --> CALC
TC --> HELD
IND --> HELD
HELD --> SORT
HELD --> FF --> TS
SORT --> GA
TS --> GA
GA --> BASIC
CZ --> DEC --> PLT
calc_tcosts accepts long (date, permno) frames, MultiIndexed
Series/frames or already-wide date × permno frames. _to_wide turns each
into a labelled wide frame, and _shared_axis puts all of them on one grid
of sorted permnos and complete month-end dates before any arithmetic.
calc_tcosts: turnover at rebalance¶
This section describes calc_tcosts as a function. It is not what
run_univariate_sort or the factor costs use; for those see
Chapter 13, Held legs and
Chapter 9b.
The algorithm is the Detzel–Novy-Marx–Velikov (2023) constant-$1 book. At each date t and each portfolio i:
- Target (“out”) weights (w^{\text{out}}{t}) are the weighting matrix
restricted to stocks with
ind == i, row-normalized to sum to 1. Optionalptf_retsmultiplies those weights by (1+r) (growing base). Default is a constant $1 book. - Incoming (“in”) weights are last rebalance’s out-weights, lagged by the inferred rebalancing frequency (f), times the ex-dividend gross return approximated as (\mathrm{ME}t / \mathrm{ME}).
- (\Delta w = w^{\text{out}} - w^{\text{in}}). Two-sided turnover is (\sum_j |\Delta w_j|). Portfolio cost is (\sum_j |\Delta w_j|\,\mathrm{tcost}_j).
A June-only assignment grid has (f = 12): January–May contribute (typically)
NaN/zero turnover because no stock is assigned; June is the rebalance. Monthly
momentum has (f = 1) and trades every month. calc_tcosts returns the
two-sided series. (SortResult.turnover in Chapter 13 is a different number:
the held legs' traded dollars over leg value, both legs, divided by 4, averaged
over the months with a return.)
The tcosts input is a panel of decimal effective half-spreads: the
stock-level tcost column from Chapter 9, not a full spread. Multiplying
two-sided (|\Delta w|) by the half-spread charges one half-spread on each
side of every trade, so a full replacement of a leg pays one half-spread to
sell and one to buy. Passing full spreads would double every cost.
calc_tcosts(tcosts, ind, me, weighting="v", ptf_rets=None, compute_dw=True, holding_period=1)¶
Signature
| Parameter | Default | Shape / dtype | Notes |
|---|---|---|---|
tcosts |
required | long (date, permno) or wide date × permno |
Decimal effective half-spreads from Ch 9. |
ind |
required | same dates and permnos | 1 = first/short leg, n_ptfs = last/long leg, 0 = not held. |
me |
required | same dates and permnos | Market equity; also the VW weight source. |
weighting |
"v" |
'v' / 'e' / DataFrame |
Custom matrix with the same dates and permnos. |
ptf_rets |
None |
date × portfolio ids 1..n_ptfs |
Growing-base option, read by label. None gives the constant $1 book. |
compute_dw |
True |
bool | False skips the dense net-dW buffer. |
holding_period |
1 |
int | Prices the union of the last holding_period formations, the membership calc_ptf_rets earns returns on. |
Returns — three date-indexed DataFrames:
ptf_tc— date ×{1..n_ptfs}portfolio costs (decimal per month).ptf_to— same shape, two-sided turnover.dw— date × permno net weight change (long minus short). Zeros ifcompute_dw=Falseor fewer than two rebalance months.
What it does
_to_wide on tcosts, ind, me (and a custom weighting DataFrame), then
_shared_axis and a label-based reindex of each onto the shared grid (see
_to_wide and the shared axis). VW
copies me; EW is 1.0 wherever me is not NaN (including zeros, which is
immaterial on CRSP ME). n_ptfs = nanmax(ind).
Portfolio i's membership in row t is ind == i in rows
t − holding_period + 1 … t (_held_membership; just ind == i by default).
With holding_period > 1 the function raises for a custom weighting
matrix, and for assignments that skip calendar months (annual or gapped
rebalancing).
Weights that are NaN (an assigned stock with missing me) are set to zero
before row-normalization, so such a stock gets a zero target weight. Its trade
is not charged, though: with me missing in month t the drift ratio
me(t) / me(t − f) is NaN, so the incoming weight and the weight change are
NaN, and the nansum over stocks leaves them out. The weight the stock carried
from the last rebalance leaves the portfolio without a cost.
Rebalance months are rows with any ind > 0. Frequency is the mode of
gaps between those rows (np.diff then pd.Series.mode().iloc[0]).
With fewer than two rebalance months the function logs a warning and returns
NaN costs / zero dw.
reb_mask = np.nansum(ind_mat > 0, axis=1) > 0
reb_months = np.where(reb_mask)[0]
# ...
reb_gaps = np.diff(reb_months)
reb_freq = int(pd.Series(reb_gaps).mode().iloc[0])
# Gross return ex-dividends: me(t) / me(t - reb_freq)
me_lag = np.full_like(me_mat, np.nan)
if reb_freq < n_months:
me_lag[reb_freq:] = me_mat[:-reb_freq]
gretxd = me_mat / me_lag
for i in range(n_ptfs):
# ... w_out row-normalized; lag_w_out filled with 0 (MATLAB lag(..., 0))
w_in = lag_w_out * gretxd
dw_i = w_out - w_in
ptf_to[:, i] = np.nansum(np.abs(dw_i), axis=1)
ptf_tc[:, i] = np.nansum(np.abs(dw_i) * tc_mat, axis=1)
Net dW is the last portfolio's weight change minus the first's. Only those
two slices are kept when compute_dw=True, rather than a full
n_months × n_stocks × n_ptfs cube. compute_dw=False skips them.
Callers. None in the package. run_univariate_sort (Ch 13),
make_anom_strat_results (Ch 17) and the factor costs (Ch 9b) price held
legs. Call calc_tcosts yourself, together with calc_ptf_rets, for the
MATLAB calculation.
_to_wide(obj, name) and the shared axis¶
Signature — _to_wide(obj, name) takes one input and the argument name
used in error messages, and returns a labelled wide DataFrame
(date index, permno columns). _shared_axis(frames) takes the dict of
converted inputs and returns (obs_dates, grid_dates, permnos).
What _to_wide does — three shapes:
(date, permno)MultiIndex (Series or one-column frame):unstack("permno").- Columns include
dateandpermno:set_indexthenunstack. - Otherwise already wide: returned as is.
Duplicate (date, permno) keys, duplicate wide dates or permno columns, and
more than one value column raise ValueError naming the input.
What _shared_axis does — every input must cover the same set of dates
and the same set of permnos, in any order. A mismatch raises ValueError
naming the input and giving examples. Such mismatches include a missing
stock, 200001 against 2000-01-31, and '10001' against 10001. Dates
must be month-end timestamps. The grid is the sorted permnos by the complete
month-end calendar from the first to the last date. calc_tcosts reads each
input onto it with reindex, computes, and returns only the observed dates.
Why labels matter. If the inputs were combined by position, the row and
column order of each input would change the answer. With costs
[.01, .02, .08], reversing only the assignment columns would move per-leg
costs from [.03, .015] to [.10, .05]. Aligning every input on one labelled
grid makes the result independent of how each input is ordered. Because the
grid is calendar-complete, a month absent from the inputs is an empty row. The
rebalancing frequency and the me lag then count calendar months, and the
month after the gap has no prior weights, the same as the first formation
month.
make_ff_tcosts(panel, tcost_series, annual=None, *, convention="dollar") — the split¶
The implementation lives at transforms/tcosts.py::make_ff_tcosts
(Chapter 9b). This module's function forwards every
argument to it:
def make_ff_tcosts(panel, tcost_series, annual=None, *, convention="dollar"):
from assayinganomalies.transforms.tcosts import make_ff_tcosts as _impl
return _impl(panel, tcost_series, annual, convention=convention)
aa.make_ff_tcosts in __init__.py is this wrapper. panel must carry
ret, me, nyse_flag and R12_2; annual holds the June-only accounting
inputs (be, at, revt, cogs, xsga, xint) and is read from panel,
masked to June, when omitted. If an input is missing, _ff_tcosts_or_zeros
returns zero non-market costs and logs a warning. convention is the size of a
factor's two sides after a trade, as in run_univariate_sort; the result has
mkt_tc, smb_tc … umd_tc under that convention and the sums ff3_tc …
ff6_tc, and under "capital" also smb_tc_short … umd_tc_short, the cost
of each factor held short. Stage compute-ff-tcosts calls
transforms.tcosts.make_ff_tcosts_table instead, which returns both
conventions and the short costs for storage.
The analytics wrapper exists so from assayinganomalies.analytics import make_ff_tcosts
matches the public analytics surface. It is not a second implementation. See
Chapter 9b for the 2×3 sorts, the held 2×3 portfolios and the monthly
re-split of each side.
Generalized alpha — math preamble¶
Novy-Marx and Velikov (RFS 2016; “A Taxonomy of Anomalies and Their Trading Costs”) define generalized α as the intercept from regressing a cost-adjusted, anomaly-scaled tangency portfolio on the cost-adjusted tangency of the factors alone.
Let (R) be gross returns and (\tau) trading costs, both (T \times K)
(factors) or (T \times (K+1)) (factors plus the anomaly L/S). A long position
nets (R - \tau); a short position nets (-R - \tau). calc_net_mve
searches long / short / not-held combinations of the non-market columns
(column 0, the market, is assumed costless and is always held long in the
search) and returns signed weights (w) of the combination with the highest
Sharpe among those whose held non-market weights are all strictly positive.
The formulas below charge a short position the cost (\tau) of a long one,
which is exact for costs computed under convention="dollar". Under
"capital" a short position has its own cost (\tau^{s}); see
The cost of a short position.
Two net-MVE problems:
[ w_{x,y} = \mathrm{netMVE}\bigl( [R_x,\, y] - [\tau_x,\, \tau_y],\; -[R_x,\, y] - [\tau_x,\, \tau_y] \bigr) ] [ w_x = \mathrm{netMVE}(R_x - \tau_x,\; -R_x - \tau_x) ]
If the anomaly weight (w_{x,y}^{\text{anom}} \neq 0),
[ Y_t = \frac{[R_x,\, y]t\, w - [\tau_x,\, \tau_y]t\, |w {|w_{x,y}^{\text{anom}}|}, \qquad X_t = R_{x,t}\, w_x - \tau_{x,t}\, |w_x|. ]}|
Then nanols(100 Y, [1, X]). The intercept is gen-α in percent per month,
scaled so a unit weight on the anomaly is comparable across models. If the
anomaly is not held, the intercept is NaN, not zero (the returned OlsRes
is built by hand).
Unconstrained tangency weights (used inside the search, and as a fast path when every non-market weight is already positive) are
[ w = \frac{\Sigma^{-1}\mu}{1'\Sigma^{-1}\mu}. ]
Signed weights sum to 1; (|w|) need not. One-asset case: (w = \mathrm{sign}(\mu)), Sharpe (w\mu / \sqrt{\Sigma}).
GEN_ALPHA_FACTOR_COLS / GEN_ALPHA_TCOST_COLS¶
Signature — module-level dict[int, list[str]]. Not a function.
What they do — map factor-model codes {1, 3, 4, 5, 6} to column lists.
Factors: mkt, smb, hml, mom, rmw, cma. Costs: mkt_tc, smb_tc,
hml_tc, umd_tc, rmw_tc, cma_tc.
# Factor-model codes used by makeBasicSortsResults gen-α block.
# MATLAB loads plain `smb` (not smb2) even for models 5/6.
GEN_ALPHA_FACTOR_COLS: dict[int, list[str]] = {
1: ["mkt"],
3: ["mkt", "smb", "hml"],
4: ["mkt", "smb", "hml", "mom"],
5: ["mkt", "smb", "hml", "rmw", "cma"],
6: ["mkt", "smb", "hml", "rmw", "cma", "mom"],
}
Two naming traps:
- Gen-α uses plain
smb(FF3, includes financials) even for models 5 and 6, whereas Chapter 13’sest_factor_regs/load_factorspath usessmb2for FF5/FF6. This follows the original MATLAB toolkit, whose gen-α block loads plainsmbfor every model. - Factor returns rename
umd → mom; factor costs stayumd_tc. The dictionaries therefore do not share suffixes.
calc_mve(rets)¶
Signature — rets: (T \times K) ndarray or DataFrame of asset returns.
Returns — weights shape (K,), SR float (ex-post Sharpe of (w'R)).
What it does — drop rows that are not all-finite
(np.isfinite(r).all(axis=1), which catches NaN and Inf). Empty (K)
raises. Fewer than two rows: zeros and Sharpe 0. Then (\mu), and (\Sigma)
as the sample covariance (np.cov(..., ddof=1), divisor (N-1)).
mu = r.mean(axis=0) # (K,)
sigma = np.cov(r, rowvar=False, ddof=1)
if n_assets == 1:
sigma = np.atleast_2d(float(sigma))
mu_col = float(mu[0])
weights = np.array([1.0 * np.sign(mu_col)], dtype=float)
denom = float(np.sqrt(sigma[0, 0]))
sr = float(weights[0] * mu_col / denom) if denom > 0 else 0.0
return weights, sr
# weights = (Σ^{-1} μ) / (1' Σ^{-1} μ)
try:
sigma_inv = np.linalg.inv(sigma)
except np.linalg.LinAlgError:
sigma_inv = np.linalg.pinv(sigma)
A singular (\Sigma) falls back to the pseudo-inverse. Zero or non-finite (1'\Sigma^{-1}\mu), or non-positive portfolio variance, returns zeros / 0 Sharpe rather than Inf/NaN. With one asset the weight is (\mathrm{sign}(\mu)) (so (\mu = 0) gives weight 0), not the mean-variance formula.
calc_net_mve(rets, rets_s)¶
Signature — rets, rets_s: (T \times K) long-side and short-side
already cost-adjusted net returns. Returns — signed weights (K,)
and the best Sharpe.
What it does
- (K=0): zeros. (K=1): compare (\bar r / s) long vs short; take the
strictly better positive Sharpe; ties or non-finite leave zeros.
Standard deviations use
ddof=1, and NaN in the series propagates into the mean (no NaN-skipping). - (K>1): unconstrained
calc_mve(r_long). If every non-market weight is> 0and Sharpe beats 0, return immediately. - Else enumerate (3^{K-1}) combinations. Column 0 is fixed long. Remaining columns get base-3 digits ({0,1,2}) = not held / long / short, generated by counting down from (3^{K-1}-1) to 0 and reading off base-3 digits.
n_combs = 3 ** (n_factors - 1)
pos_index = np.zeros((n_combs, n_factors), dtype=int)
pos_index[:, 0] = 1
xt = np.arange(n_combs - 1, -1, -1, dtype=int) # nCombs-1 … 0
for i in range(1, n_factors):
ttemp = xt % 3
xt = (xt - ttemp) // 3
pos_index[:, i] = ttemp
for i in range(n_combs):
# swap in short-side returns; drop not-held columns; calc_mve
# accept if n_left == 1 or all non-market held weights > 0
A combination wins only if Sharpe is strictly higher than the incumbent and
every held non-market weight is strictly positive. Short legs are stored with
a minus sign. n_left == 1 (market only) is accepted explicitly. Because the
comparisons are strict, equal long/short Sharpes leave (w=0), and the
enumeration order decides which of two equally good combinations is kept.
calc_gen_alpha(anom_ret, anom_tcosts, factor_rets, factor_tcosts, print_res=False, *, anom_tcosts_short=None, factor_tcosts_short=None)¶
Signature
| Parameter | Shape | Notes |
|---|---|---|
anom_ret |
(T,) |
Gross anomaly L/S, decimal. |
anom_tcosts |
(T,) |
Portfolio-level L+S costs (SortResult.tcosts_ts). |
factor_rets |
(T \times K) | Gross factors, same order as costs. |
factor_tcosts |
(T \times K) | mkt_tc is 0 by construction. |
print_res |
bool | prt(alpha_res) if true. |
anom_tcosts_short |
(T,), optional |
Costs of the anomaly held short (SortResult.tcosts_ts_short). Omitted: a short position is charged anom_tcosts. |
factor_tcosts_short |
(T \times K), optional | Costs of the factors held short, columns as factor_tcosts. Omitted: a short position is charged factor_tcosts. |
Returns — (OlsRes, w_x_y, w_x). OlsRes.beta[0] is gen-α in %/month
when nvar==2.
What it does — length check (raises if the inputs have different
lengths). Stack anomaly as the last column. Two calc_net_mve calls as in
the preamble, both on the common months (below). If the last weight is nonzero, nanols(100*y, [ones, x]) with
labels const, mve_x; otherwise the intercept is NaN. Chapter 14’s
nanols / OlsRes / prt apply.
Sample rule. Both MVE portfolios are estimated on the same months: those
in which the anomaly return, its cost and every factor return and cost are
finite (_common_rows); the regression runs on the same months. The MATLAB
original estimates the factor-only MVE on every month with factor data. For a
strategy whose data start after the window opens, the joint MVE then
re-optimizes the factor weights on the shorter sample, and the in-sample gain
from that alone, divided by the strategy's small weight, shows up as a large
generalized alpha. With the common sample a strategy that covers the whole
window gets exactly the MATLAB number. Fewer than two common months give zero
weights and an "unavailable" outcome.
Sign. The intercept is per unit of |w_y| (Novy-Marx and Velikov 2016),
so it is positive whichever side the net MVE portfolio holds; it is zero only
when the strategy gets zero weight. estimate_gen_alpha returns the weight as
GenAlphaOutcome.w_anom (negative = held short), and the outcome summaries
carry it per cell, because a tiny weight can make a modest intercept look large.
rows = _common_rows(y_anom, tc_anom, f_rets, f_tc)
g_c, tc_c = gross_anom_factors[rows], tcosts_anom_factors[rows]
f_c, ftc_c = f_rets[rows], f_tc[rows]
tcs_c, ftcs_c = tcosts_short_anom_factors[rows], f_tc_s[rows]
w_x_y, _ = calc_net_mve(g_c - tc_c, -g_c - tcs_c)
w_x, _ = calc_net_mve(f_c - ftc_c, -f_c - ftcs_c)
if w_x_y[-1] != 0:
y = _net(
gross_anom_factors, tcosts_anom_factors, tcosts_short_anom_factors, w_x_y
) / abs(float(w_x_y[-1]))
x = _net(f_rets, f_tc, f_tc_s, w_x)
X = np.column_stack([np.ones(t), x])
alpha_res = nanols(100.0 * y, X, labels=["const", "mve_x"])
Without the two optional arguments the short-cost arrays are the long-cost
arrays and _net(gross, long_tc, short_tc, w) is gross @ w - long_tc @ |w|,
the formulas of the preamble.
Protocol wiring (Chapter 17, not owned here): make_basic_sorts_results
takes SortResult.long_short and tcosts_ts (and tcosts_ts_short under
"capital"), slices time_period, and calls
factor_matrix_for_gen_alpha + estimate_gen_alpha. make_res_to_print
(Chapter 19) calls the same pair for Fig_AlphaPrctl net alphas.
The cost of a short position¶
The net MVE portfolio may hold a factor or the anomaly short. A strategy held short is the same two portfolios with the legs exchanged (Ch 13, Held legs).
- Under
convention="dollar"each leg goes back to $1 at a trade whichever leg is long, so the strategy held short costs what the strategy costs. One cost series serves both positions and the two optional arguments are not needed. - Under
convention="capital"the strategy held short has its own capital,K' = 1 + short P&L − long P&L, and its own cost. For a sort that isSortResult.tcosts_ts_short; for the factors it is the columnssmb_tc_short…umd_tc_shortofmake_ff_tcosts(..., convention="capital")(stored ints_dataassmb_tc_capital_short…).
calc_gen_alpha and estimate_gen_alpha take these as anom_tcosts_short and
factor_tcosts_short. With them a short position nets -gross - short cost
in the search for both MVE portfolios, and the returns of the portfolios found
charge each asset its long cost where its weight is positive and its short
cost where it is negative. A month counts toward the common sample only if the
short costs are finite as well. Without them, or with short costs equal to the
long ones, the calculation is unchanged. If anom_tcosts_short is given
without factor_tcosts_short, a factor held short is charged its ordinary
cost and a warning says so.
A protocol run passes both by itself under "capital": the factor-cost frame
it reads from the database carries smb_tc_short … umd_tc_short, and each
sort carries tcosts_ts_short. Under "dollar" it passes nothing.
factor_short_tcosts_for_gen_alpha(factor_model, dates, factor_tcosts) picks
the model's short-cost columns from such a frame, aligned with the second
output of factor_matrix_for_gen_alpha; it returns None when the frame has
none.
With d a loaded panel, signal a signal and panel the input of
make_ff_tcosts:
from assayinganomalies.analytics.gen_alpha import (
estimate_gen_alpha, factor_matrix_for_gen_alpha, factor_short_tcosts_for_gen_alpha,
)
res = aa.run_univariate_sort(d["ret"], signal, d["me"], tcosts=d["tcost"], convention="capital")
ff_tc = aa.make_ff_tcosts(panel, d["tcost"], convention="capital") # smb_tc … and smb_tc_short …
dates = res.long_short.dropna().index
f, f_tc = factor_matrix_for_gen_alpha(4, dates, factor_tcosts=ff_tc)
f_tc_short = factor_short_tcosts_for_gen_alpha(4, dates, ff_tc)
outcome, alpha_res, w_x_y, w_x = estimate_gen_alpha(
res.long_short[dates], res.tcosts_ts[dates], f, f_tc,
anom_tcosts_short=res.tcosts_ts_short[dates], factor_tcosts_short=f_tc_short,
)
factor_matrix_for_gen_alpha(factor_model, dates, factors=None, factor_tcosts=None, *, db_path=None)¶
Signature — factor_model in {1,3,4,5,6}; dates is the index to
reindex onto. factors / factor_tcosts optional; missing factors load via
load_factors(db_path) (Ch 13). Missing tcost columns become 0.0 (including
the whole frame when factor_tcosts is None).
Returns — (f_df, tc_df) with columns from the two dicts, same dates
index.
What it does — rename mktrf→mkt, umd→mom, smb2→smb on the factor
frame; mom_tc→umd_tc on costs if needed; select and reindex. Because of
the smb2→smb rename, passing five-factor SMB under the name smb2 makes
gen-α use it as plain smb.
fac = factors.copy()
rename = {"mktrf": "mkt", "umd": "mom", "smb2": "smb"}
fac = fac.rename(columns={k: v for k, v in rename.items() if k in fac.columns})
f_df = fac[fcols].reindex(dates)
if factor_tcosts is None:
tc_df = pd.DataFrame(0.0, index=dates, columns=tcols)
else:
tc = factor_tcosts.copy()
if "umd_tc" not in tc.columns and "mom_tc" in tc.columns:
tc = tc.rename(columns={"mom_tc": "umd_tc"})
for c in tcols:
if c not in tc.columns:
tc[c] = 0.0
tc_df = tc[tcols].reindex(dates)
Not in analytics.__all__ or the package __all__. Callers import from
gen_alpha (results.py, res_to_print.py).
Anomaly decay¶
run_anomaly_decay loads the CZ catalog, loops over signals with
documentation-driven rebalancing / screens / sample windows, and runs
run_univariate_sort on a two-leg indicator for each. plot_anomaly_decay
then lines the L/S returns up on publication December and plots the
cross-sectional average with a 60-month moving mean.
_two_leg_sort(returns, leg, mcap, *, weighting, time_period)¶
Signature — leg is a (date, permno) Series with 1 = short, 2 = long,
NaN = out. Returns — SortResult (Ch 13).
What it does — run_univariate_sort with n_bins=2, breaks="nyse",
nyse_flag=(leg == 2), factor_model=4.
return run_univariate_sort(
returns=returns,
signal=leg,
mcap=mcap,
n_bins=2,
breaks="nyse",
nyse_flag=(leg == 2),
weighting=weighting,
time_period=time_period,
factor_model=4,
)
Integer n_bins=2 asks for a 50th-percentile cut. Pinning the NYSE flag to
the long leg makes that cut the percentile of a column of 2s, i.e. exactly
2.0. _assign_bins (Ch 13) then puts leg==1 in bin 1 (x < 2) and
leg==2 in bin 2 (x >= 2), so the sort reproduces the indicator's
holdings exactly.
The decay plot uses only pret["long_short"], so the four-factor
regressions that factor_model=4 computes are unused for the figure.
run_anomaly_decay(anoms_panel, summary, *, returns, mcap, prc=None, exchcd=None, nyse_flag=None, verbose=True)¶
Signature
| Parameter | Notes |
|---|---|
anoms_panel |
(date, permno) index; columns = signals. |
summary |
aa.get_cz_signal_info(); match on lowercase acronym. |
returns, mcap |
MultiIndex series. |
prc, exchcd, nyse_flag |
Screens whose input is None are skipped. |
verbose |
Per-signal exceptions are caught and, when True, printed. |
Returns — dict[str, SortResult], one entry per signal that ran. A
signal that raises is skipped rather than aborting the loop.
What it does — in execution order:
- Rebalance mask.
PortfolioPeriod12 or 36 → keep June only; 6 → June and December; 3 → quarter-ends. Other values: monthly (no mask). The mask decides when the strategy trades:run_univariate_sortbuys the legs in the months that keep a signal and holds them, without re-weighting, until the next such month (Ch 13). - Screens on a whitespace-stripped
Filterstring:abs(prc)>1,abs(prc)>5,exchcd%in%c(1,2),exchcd==1,me>me_nyse20. The last is a NYSE-break size quintile (_bin_by_cross_section(mcap, 5, breaks="nyse", ...)) computed once and cached; drop bin 1. Theprcandexchcdscreens keep only names that pass the test (var.where(prc.abs() > 1),fillna(False)forexchcd), so names with a missing price or exchange code are dropped. - Sample. Skip if
SampleStartYearis NaN. Start =100*year + (6 if StartMonth is NaN else StartMonth). End = last date with any finite signal plusPortfolioPeriodmonths (0 if period is NaN), clipped to the panel. - Legs.
changeinrecommendation: per-date 20th/80th percentiles, short/long tails, viagroupby(level="date").transform(quantile). This uses pandas' linearquantile, a different rule from the percentile routines used elsewhere in the library (Ch 9, 11, 13).numearnincrease,rdcap: 0 vs>0.Cat_Form == "discrete": min vs max of the finite values of the series.- Else quantile:
nptfs = 5orround(1/LSQuantile). Pass explicit percentile cuts[100/n, (n-1)100/n](or[50]if (n=2)) intorun_univariate_sort. Only the extreme bins matter: the middle bin is inert inlong_short = last - first. - NYSE quantile filter:
breaks="nyse"is used only whennyse_flagis present; otherwise name breaks.
- Weighting:
"v"iffStockWeight == "VW", else"e", read from the summary row matched to the signal.
period = r["PortfolioPeriod"]
if period in (12, 36):
var = var.where(june)
elif period == 6:
var = var.where(june_dec)
elif period == 3:
var = var.where(quarter_end)
# screens ... sample window ...
weighting = "v" if r["StockWeight"] == "VW" else "e"
# ChangeInRecommendation / NumEarnIncrease+RDcap / discrete / quantile
results[label] = _two_leg_sort(...) # or run_univariate_sort(..., n_bins=pct)
Acronyms in cz_signal_info are lowercased at ingest (Ch 5); matching
label.lower() is the intended join.
plot_anomaly_decay(results, summary, all_dates)¶
Signature — results from run_anomaly_decay; summary same CZ table;
all_dates unique month-end index of the panel (length n_months).
Returns — relative, shape (2*n_months+1, n_results), NaN-padded
pre/post publication L/S returns. There is one column per entry in
results (signals that ran), not per signal in the catalog.
What it does — publication date = month-end of December of Year
(_to_month_end(100*Year+12)). Skip if Year is NaN or pub is outside
that strategy’s return index. e = searchsorted(pub, "right") so the
publication month is in the pre-period slice.
relative = np.full((2 * n_months + 1, len(results)), np.nan)
for k, (label, res) in enumerate(results.items()):
# ...
pub = _to_month_end(int(100 * rows.iloc[0]["Year"] + 12))
ls = res.pret["long_short"]
e = int(ls.index.searchsorted(pub, side="right"))
relative[n_months - e:n_months, k] = ls.to_numpy()[:e]
relative[n_months:n_months + len(ls) - e, k] = ls.to_numpy()[e:]
avg = np.nanmean(relative, axis=1)
x = np.arange(-n_months, n_months + 1) / 12
fig, ax = plt.subplots()
ax.plot(x, 100 * avg, color=(0.8, 0.8, 0.8), lw=1.0, label="Average")
ax.plot(x, 100 * moving(avg, 60), lw=1.8, label="5-year moving average")
ax.set_ylim(-0.5, 1.0)
ax.set_xlim(-30, 20)
# ... xlabel / title / legend / plt.show()
return relative
Axes: years on (x), percent per month on (y), ylim [-0.5, 1],
xlim [-30, 20]. moving (a 60-month centered moving average here) lives in
analytics/plots.py (Chapter 19). res.pret is the Chapter 13 property that
appends long_short to leg_returns. The figure is drawn with matplotlib and
shown with plt.show().