Factor investing, risk premia and the factor zoo
Construct characteristic-sorted factors and examine their risks, multiple testing, replication, publication effects and trading costs.
After this lesson you can
- Build long-short factors from characteristic-sorted portfolios using data available at each date.
- Explain risk and behavioral accounts of major premiums and their risk profiles, including momentum crashes.
- Apply multiple-testing corrections to the factor zoo and explain thresholds such as t > 3.
- Measure an anomaly's post-publication decay and sensitivity to transaction costs.
- Critically evaluate an anomalies paper's universe, weighting, microcaps, data and implicit number of tests.
Before you start
From an anomaly to a portfolio
A characteristic predicting historical returns can become a portfolio long high-characteristic assets and short low-characteristic assets. Between a published association and an investable premium lie decisions about data, formation, liquidity and costs. A characteristic may look powerful because it was tested among many or includes information not yet available.
Characteristic sorting starts with a formation date, eligible universe and signal known then. It divides assets into groups using breakpoints, calculates weighted returns within each group and subtracts the short leg from the long. An independent 2×3 sort divides size into two and signal into three using separate cuts; six intersections are formed and the two extreme spreads averaged. This is not the same rule as sorting the signal within each size group.
If an accounting signal is published months after the close, using its value at the close introduces look-ahead. A six-month rule is useful in some annual designs, not a guarantee for every firm: use each datum’s availability date and historical version. Equal weighting gives an illiquid microcap the same weight as a large company. Value weighting and cuts defined using larger firms can reduce microcap influence but also change the estimand. Both decisions should be reported.
For example, at the end of June fix the universe and breakpoints using data then available; in July measure returns on the resulting portfolios. If the previous fiscal year’s balance sheet has only an accounting date and no disclosure date, document the conservative lag and its limits. Include delistings, mergers and exit returns where available so the sample is not retrospectively restricted to survivors. Decide how to handle ties and empty cells before inspecting returns: in the lab, values equal to each threshold go into the adjacent lower group and an empty cell raises an explicit error.
Premiums and their risks
Factor premiums group strategies with similar exposures: value buys cheap versus expensive; momentum buys recent winners and sells losers; size compares small and large; low beta or volatility compares less and more sensitive assets; quality may combine profitability, stability or low leverage; investment compares firms expanding assets at different rates. Each name admits many definitions. An observed premium may reflect risk compensation, financing constraints, expectation errors or other frictions; those explanations do not follow simply from a positive mean.
The risk hypothesis interprets a premium as compensation for especially poor outcomes in states relevant to investors. Behavioral explanations may appeal to underreaction or overreaction to news; constraint explanations to some investors being unable to borrow or short freely. These mechanisms require additional predictions, for example about when risk concentrates or how the premium varies with constraints. A label such as “quality” does not by itself identify which is correct. Correlated signals may duplicate exposure without adding a new independent source of risk.
Momentum crashes illustrate premium risk. After a prolonged decline, losers in the short leg can be highly sensitive to the market; a rapid rebound lifts them more than winners and hurts the spread. Conditional beta changes with regime, and a historical average beta can hide that exposure.
In a linear approximation, if winners have beta 0.5 and losers beta 2, a portfolio with one dollar long and one short has beta . A 10% market rebound would contribute approximately −15% to the spread before idiosyncratic components and costs. This is a local sensitivity, not a return prediction or guarantee that beta remains fixed during the rebound.
In data studied by Daniel and Moskowitz (2016), the loser decile rose 163% from March to May 2009, versus 8% for the winner decile. This describes their portfolios and that episode, not a simulator figure. Hedging estimated beta or reducing exposure can change risk, but requires real-time estimation and does not necessarily eliminate costs or other risks.
The zoo and multiple testing
The factor zoo contains many related signals, construction variants and tests of the same economic hypothesis. Dependence means 300 names do not necessarily equal 300 independent tests; unpublished attempts also exist that the observed database does not reveal. Correcting only tests appearing in a table may still underestimate the total search.
For multiple comparisons, Bonferroni uses per test and controls the probability of at least one false rejection by the union bound, without requiring independence, provided each p-value is valid. Holm orders p-values and applies sequential thresholds; it also controls FWER under arbitrary dependence. Benjamini-Hochberg (BH) orders , finds the largest with and rejects up to it. Its FDR is the expected proportion of false rejections among rejections, conventionally zero if there are none; standard control requires independence or certain positive dependence, not arbitrary dependence.
To see why the family matters, if 300 independent null tests have size 5%, the expected number of false rejections is 15 and the probability of at least one is , nearly one. Independence simplifies that calculation, but the expectation of 15 needs only a 0.05 false-rejection probability for each test. If the best of many factors is sought and only that result reported, the selected individual t no longer has the interpretation of a test fixed before looking at the data.
With 300 two-sided normal tests and , Bonferroni requires . If standard deviation is estimated and the sample finite, the Student threshold depends on degrees of freedom. Harvey, Liu and Zhu (2016) argue that a new factor should clear a higher bar than conventional, proposing t above 3 in their analysis. This is not a universal threshold equivalent to Bonferroni for every number of tests, dependence or error criterion.
Replication, selection and publication
Hou, Xue and Zhang (2020) replicate anomalies using rules that reduce microcap weight, including NYSE breakpoints and value weighting, and find a high failure rate under their replication definition. Jensen, Kelly and Pedersen (2023) use another population, global factors and a Bayesian model sharing information across related signals; they reach a more favorable interpretation. These are not directly interchangeable estimates of one rate: samples, tests, definitions and assumptions differ. Hierarchical shrinkage can stabilize noisy estimates but depends on a prior distribution and selection model.
A useful reading of a paper starts with formation date and available data, continues through firm coverage and microcap treatment, and compares weighting, exposure to existing factors, costs and truly subsequent samples. A t below a threshold does not prove the effect is exactly zero; one above does not guarantee investability. A replication using another portfolio definition may answer a different economic question.
Post-publication decay compares results before and after a signal becomes known. McLean and Pontiff (2016) estimate returns 26% lower outside the original sample and 58% lower after publication, both relative to the original sample; their analysis attributes the 32-percentage-point difference in relative reduction to publication-informed trading. Their figures combine evidence of statistical selection and possible price response; they do not establish that every anomaly loses exactly those fractions or that every later change is causal.
To evaluate a strategy, calculate turnover by leg, purchase and sale costs, securities lending, financing, capacity and constraints. If is the gross spread and estimated total cost that month is , the simplified net series is . For example, a monthly spread of 0.6% with total cost of 0.4 percentage points leaves 0.2% before other costs: actual costs have not been measured here. Turnover does not automatically equal cost; it needs execution prices and notional conventions.
Lab: factor factory
We generate 120 assets over 181 months. Return depends on a lagged state with coefficient 0.004 and an independent shock. The contemporaneous signal artificially includes that shock and would only be available after the return: using it in the same month is deliberate leakage. The function calculates independent 2×3 cuts, weights by size within the six cells and averages spreads across both size groups. It does not simulate fees or real firms.
import numpy as np
def double_sort_factor(panel,signal,size,lag=1):
panel=np.asarray(panel,float); signal=np.asarray(signal,float); size=np.asarray(size,float)
if panel.ndim!=2 or signal.shape!=panel.shape or size.shape!=(panel.shape[1],) or lag not in (0,1): raise ValueError('Datos incompatibles')
if not np.isfinite(panel).all() or not np.isfinite(signal).all() or not np.isfinite(size).all() or np.any(size<=0): raise ValueError('Datos inválidos')
T,N=panel.shape; out=[]
for t in range(1,T):
x=signal[t-lag]; r=panel[t]
small=size<=np.median(size); lo,hi=np.quantile(x,[1/3,2/3]); legs=[]
for group in (small,~small):
for mask in (x<=lo,(x>lo)&(x<=hi),x>hi):
idx=group&mask
if not idx.any(): raise ValueError('Cartera vacía')
legs.append(np.average(r[idx],weights=size[idx]))
out.append((legs[2]+legs[5]-legs[0]-legs[3])/2)
return np.asarray(out)
g=np.random.default_rng(280801); T,N=181,120; size=np.exp(g.normal(0,1,N))
state=g.normal(size=N); signals=[]; returns=[]; true_state=[]
for t in range(T):
prev=state; state=.8*prev+.6*g.normal(size=N); shock=g.normal(size=N)
signals.append(state+.8*shock); returns.append(.004*prev+.04*shock); true_state.append(prev)
signal=np.asarray(signals); panel=np.asarray(returns); true_state=np.asarray(true_state)
for lag in (1,0):
factor=double_sort_factor(panel,signal,size,lag)
exposure=double_sort_factor(true_state,signal,size,lag)
print('desfase',lag,'media mensual',round(factor.mean(),5),'componente plantada',round(.004*exposure.mean(),5),'t i.i.d.',round(factor.mean()/(factor.std(ddof=1)/np.sqrt(len(factor))),2))The run with seed 280801 gave 0.00790 monthly for the valid lag versus 0.00670 planted component in those portfolios; the difference is sample noise. With leakage, the spread was 0.05976, much larger than its 0.00530 state component because sorting sees the contemporaneous shock. The t-statistics are descriptive and do not replace inference robust to temporal dependence.
For sensitivity analysis, apply a hypothetical fixed total cost to the valid spread. The values are not derived from quotes or measured turnover: they show how much gross margin each assumption consumes.
valid=double_sort_factor(panel,signal,size,lag=1)
for cost in (0.,.001,.005,.01):
print('coste total mensual',cost,'| media neta mensual',round(float((valid-cost).mean()),5))In this run, an assumed cost of 0.005 leaves a net mean of 0.00290; at cost 0.01, the mean is −0.00210. This conclusion applies only to that fixed cost and simulated sample.
Lab: the zoo with public data
The Open Source Asset Pricing database publishes long-short returns and signal metadata. We use its revision-pinned 2026.10 version, not a manual factor selection. The wide file contains monthly percentage returns oriented according to the original paper’s sign. The metadata table provides publication year. Local Python with network access, pandas, pyarrow, scipy and statsmodels is required; code downloads primary files into memory.
The first analysis calculates an i.i.d. two-sided t-statistic for each series mean with at least 60 months and applies three adjustments to those p-values. It demonstrates methods, not a valid FDR estimate if p-values ignore autocorrelation or the set excludes unpublished tests. It then compares five years before publication year with five after, excluding publication year; it requires at least 48 observed months in each window. The median of differences is not the difference of medians or a causal estimate of publication.
import io, urllib.request
import numpy as np, pandas as pd
from scipy import stats
from statsmodels.stats.multitest import multipletests
revision='ad1dfba5a6d80c4ce53ce6b8127f5a949dda1e40'
base=f'https://huggingface.co/datasets/OpenSourceAP/CrossSection/resolve/{revision}/'
def fetch(path):
with urllib.request.urlopen(base+path,timeout=90) as response: return response.read()
r=pd.read_parquet(io.BytesIO(fetch('Portfolios/Full%20Sets%20OP/PredictorLSretWide.parquet')))
doc=pd.read_csv(io.BytesIO(fetch('SignalDoc.csv')))
doc['Year']=pd.to_numeric(doc['Year'],errors='coerce')
doc=doc.dropna(subset=['Acronym','Year']).drop_duplicates('Acronym')
years=dict(zip(doc.Acronym,doc.Year.astype(int))); r['date']=pd.to_datetime(r.date)
print('tabla:',r.shape,'| desde',r.date.min().date(),'hasta',r.date.max().date())npm run lab and open the connection link.rows=[]
for name in r.columns.drop('date'):
if name not in years: continue
y=years[name]; series=r[['date',name]].dropna(); values=series[name].to_numpy(float)
if len(values)<60 or values.std(ddof=1)==0: continue
statistic=values.mean()/(values.std(ddof=1)/np.sqrt(len(values)))
p=2*stats.t.sf(abs(statistic),len(values)-1)
pre=series[(series.date.dt.year>=y-5)&(series.date.dt.year<y)][name]
post=series[(series.date.dt.year>y)&(series.date.dt.year<=y+5)][name]
before,after=(pre.mean(),post.mean()) if len(pre)>=48 and len(post)>=48 else (np.nan,np.nan)
rows.append((name,y,len(values),statistic,p,before,after))
result=pd.DataFrame(rows,columns=['factor','year','n','t','p','pre','post'])
for method in ('bonferroni','holm','fdr_bh'):
result[method]=multipletests(result.p,alpha=.05,method=method)[0]
paired=result.dropna(subset=['pre','post'])
print('factores:',len(result),'| pares pre/post:',len(paired))
print('p<.05:',sum(result.p<.05),'| Bonferroni:',sum(result.bonferroni),'| Holm:',sum(result.holm),'| BH:',sum(result.fdr_bh))
print('medianas pre, post y diferencia emparejada (puntos porcentuales mensuales):',np.round([paired.pre.median(),paired.post.median(),(paired.post-paired.pre).median()],4))
print(paired[['factor','year','pre','post']].head(5).to_string(index=False))npm run lab and open the connection link.In this specific revision, 212 factors and 208 window pairs were analyzed; 174 had individual p below 0.05 and 96, 102 and 167 passed Bonferroni, Holm and BH respectively. Pre- and post-publication medians were 0.4457 and 0.2739 monthly percentage points, and median paired difference was −0.1345. The series are selected from the literature and intervals may overlap original samples; these figures are descriptive and do not measure publication’s causal effect.
Exercises
def double_sort_factor(panel,signal,size,lag=1):
raise NotImplementedError()Step 1 of 3. What does the union bound give for threshold u?
Ideas to remember
The factor depends on its universe, available signal, cuts, weighting and execution. A positive premium in a simulation or paper does not show it survives costs or multiple tests. Replication results and post-publication evolution must be interpreted with their specific populations, windows and assumptions.