Multifactor models: estimation, testing and risk models
Study multifactor pricing and risk models, Fama-MacBeth regressions, Fama-French factors and factor-based covariance estimation.
After this lesson you can
- Estimate a factor model by time-series regression and test it with GRS.
- Implement Fama-MacBeth, explain errors in variables and adjust standard errors with Shanken and Newey-West.
- Construct Fama-French factors from sorted portfolios and explain the five-factor model.
- Estimate a statistical risk model using PCA and a fundamental model using cross-sectional characteristics.
- Decompose portfolio variance into factor and idiosyncratic contributions.
Before you start
- 28Capital Asset Pricing ModelJensen's alphaGibbons-Ross-Shanken testArbitrage pricing theoryStochastic discount factorLedoit-Wolf shrinkage
- 27Newey-West HAC standard errorsWeighted least squaresGeneralized least squaresMeasurement error and attenuation bias
- 12Principal component analysisFactor analysis
More than one source of risk
CAPM attributes differences in expected returns to one beta. If several common forces affect assets, a multifactor model lets us study more exposures. But there are two distinct questions: do factors explain expected returns, and do they predict the covariance a portfolio needs? A useful answer to the second does not establish the first.
The factor time-series regression for asset ‘s excess return is
With traded factors expressed as excess returns, loadings are sensitivities to factor portfolios; the intercept is alpha relative to the model. The previous lesson’s joint GRS test uses alphas and their residual covariance. Its exact F distribution requires normality, temporal independence, conditional homoskedasticity and sufficient rank: HAC errors for an individual alpha do not automatically make classical GRS robust.
If the beta-pricing model is correct and factors are traded excess-return portfolios with identity exposures to themselves, necessarily . Then . Tradability alone does not impose zero alphas: the pricing relationship is also required. A linear multifactor SDF can produce it if it satisfies pricing equations; as in CAPM, its positivity must be checked when used as a no-arbitrage certificate.
Two steps for the cross-section
In Fama-MacBeth, loadings are first estimated from a time series, followed by a cross-sectional regression each period of returns on those loadings and, optionally, an intercept. The time average of slopes estimates premiums. Observable characteristics such as size or industry exposure can also replace betas: then coefficients measure associations with those characteristics and are not automatically beta risk prices.
With slopes, the i.i.d. standard error of their mean is their sample standard deviation divided by . Uncertainty is not obtained by treating the pooled observations as independent: a common shock affects many assets in the same month. Time averaging retains that cross-sectional dependence in the slope series. If slopes are autocorrelated, the variance of their mean uses long-run covariance, estimable by Newey-West with specified lags and weights. With few months, neither the normal approximation nor an arbitrary bandwidth guarantees coverage.
If the cross-sectional design is fixed and full rank, each coefficient vector is . By linearity, its average equals the cross-sectional regression of average returns on . This estimator identity does not make it valid to calculate uncertainty as if all asset-month observations were independent. Nor does it apply unchanged when characteristics, composition or weights change across sections.
For HAC, center the series and calculate . Newey-West with lags estimates covariance of the mean as . With and divisor this gives an asymptotic version of the i.i.d. error; the divisor in the sample standard deviation above introduces a different finite correction.
First-stage betas are estimates, not exact data. Their error can distort the cross-sectional slope and its uncertainty. Shanken (1992) studies that error under specific assumptions. For a correct beta-pricing model, fixed betas estimated in the same sample, temporally independent traded factors, full-rank design and temporally independent residuals with zero conditional mean and constant covariance, write . If is sample covariance of cross-sectional coefficients and inserts factor covariance into the slope block, with zeros for the intercept, the adjusted asymptotic covariance of the full mean vector is
The adjustment addresses variation from estimating betas; Newey-West addresses temporal dependence. They are not substitutes or a universal formula for rolling betas, changing characteristics or arbitrary sampling schemes. Correcting uncertainty does not by itself eliminate errors-in-variables bias; longer windows, instrumental variables or joint models require further assumptions and validation.
Fama-French factors
Fama-French factors are returns on portfolios built with reproducible rules. FF3 combines excess market, SMB (small minus big) and HML (high minus low book-to-market value). FF5 adds RMW (robust minus weak operating profitability) and CMA (conservative minus aggressive investment). These are not arbitrary regression labels: they depend on universe, formation date, weights and available data.
The official FF5 methodology uses three groups of six value-weighted portfolios, sorted 2×3 by size and respectively value, profitability or investment. HML averages the two high-value portfolios and subtracts the two low-value portfolios; RMW and CMA use analogous extreme differences. Five-factor SMB averages the small-minus-big differences of the three sorts, so it should not automatically be replaced by published FF3 SMB. Accounting data from an earlier fiscal year form portfolios beginning the following July: respecting that lag avoids using future information. Library coverage, criteria and revisions matter.
Annual formation separates small and large firms using a size breakpoint and divides each characteristic into three groups, then crosses the groups. For example, HML is average high value among small and large firms minus the corresponding low-value average. Each internal portfolio return is value-weighted, while differences between portfolios are averaged with weights from the factor definition. These two weightings serve different purposes. Such a long-short factor is the excess return of a self-financing portfolio before costs, not a promise of net profit.
The additional factors are motivated by profitability and investment patterns FF3 may omit, not a guarantee that five factors explain every asset or period. Comparing models requires the same sample and test portfolios, checking alphas and GRS, and remembering that portfolios used to construct factors can appear among evaluated assets. Higher in-sample proves neither a pricing theory nor a future strategy.
A manageable risk matrix
In a factor covariance model, with residuals uncorrelated with factors implies
Here and . Taking diagonal is a modeling assumption, not an identity: residuals of related firms may remain correlated. For weights , aggregate exposure is and variance is . The terms may be negative even though total variance is nonnegative when the matrices are positive semidefinite.
For active risk against a benchmark, replace with : the square root of the resulting variance is ex-ante tracking error. An Euler risk contribution can allocate each factor covariance differently from the cross-term bar; document the convention and ensure contributions sum to the total.
A full covariance for assets contains free entries. With factors and diagonal , storing , and the diagonal requires values. Not all are identifiable parameters: factor rotations can represent the same covariance. The structure reduces dimensionality but does not guarantee good conditioning if idiosyncratic risks are estimated near zero or exposures are collinear.
The decomposition follows by expanding the covariance of : both cross terms vanish only if . For a portfolio, captures variance associated with factor , while the cross term with contains both orders and therefore has a factor of two. To allocate each cross term to individual factors, one option gives half to each, with contributions . This allocation can be negative while summing exactly to .
Statistical and fundamental factors
A statistical model extracts factors using PCA on centered returns. Principal eigenvectors represent directions of greatest variance, not unique economic names; signs and rotations within a subspace are arbitrary. Factor count can be chosen by out-of-sample prediction or penalized criteria. The Marchenko-Pastur reference describes independent noise under an ideal model; residual correlation, heterogeneity and finite samples alter its interpretation.
In the figure, ICp2 compares for , where is the sum of discarded eigenvalues divided by . Loss always improves as components are added, and the penalty offsets that improvement. The criterion comes from Bai and Ng (2002), whose results depend on assumptions and large-panel asymptotics. The 80% threshold answers a different question: how many components capture that fraction of variation, including noise variation. The generator’s true number is known only in this experiment; real data have no such answer label.
In a fundamental model, exposures are characteristics known or constructed before the period, such as industry, size or value. Each month a cross-sectional regression, often weighted, estimates factor returns; their temporal covariance and residual risk are then estimated. If you include an intercept and all mutually exclusive industries, the columns sum to one and the design is singular. Remove a reference industry or impose an explicit constraint; contributions depend on that convention. Weights and historical data availability are also part of the model.
Lab: Fama-MacBeth and correction
The following function accepts returns and fixed or varying characteristics. It includes an intercept and calculates Newey-West on the coefficient series with Bartlett weights. Synthetic data use known characteristics, so this first test has no beta-estimation error.
import numpy as np
def hac_media(z,L):
z=np.asarray(z,float); T=len(z)
if not 0<=L<T: raise ValueError('Rezagos inválidos')
x=z-z.mean(axis=0); S=x.T@x/T
for j in range(1,L+1):
G=x[j:].T@x[:-j]/T; S+=(1-j/(L+1))*(G+G.T)
return S/T
def fama_macbeth(returns,characteristics,L=0):
R=np.asarray(returns,float); C=np.asarray(characteristics,float)
if R.ndim!=2: raise ValueError('R debe ser T por N')
T,N=R.shape
if C.ndim==2: C=np.broadcast_to(C,(T,*C.shape))
if C.ndim!=3 or C.shape[:2]!=(T,N) or not np.isfinite(R).all() or not np.isfinite(C).all(): raise ValueError('Datos incompatibles')
coefs=[]
for t in range(T):
X=np.column_stack((np.ones(N),C[t]))
if N<=X.shape[1] or np.linalg.matrix_rank(X)<X.shape[1]: raise ValueError('Diseño singular')
coefs.append(np.linalg.lstsq(X,R[t],rcond=None)[0])
coefs=np.asarray(coefs); avg=coefs.mean(axis=0); cov=hac_media(coefs,L); se=np.sqrt(np.diag(cov))
return avg,se,avg/se,coefs
g=np.random.default_rng(280701); T=180; N=60
beta=np.linspace(.4,1.6,N)[:,None]; f=g.normal(.006,.04,T)
R=f[:,None]*beta[:,0]+g.normal(0,.05,(T,N))
avg,se,t,series=fama_macbeth(R,beta,L=3)
print('coeficientes:',np.round(avg,6),'| errores HAC:',np.round(se,6),'| t:',np.round(t,3))
print('prima verdadera:',.006,'| media del factor generado:',round(f.mean(),6))To see the classical correction, beta is now estimated using the entire same generated panel and the second stage rerun. Covariance of the coefficient series and factor uses divisor . This formula comparison is limited to the i.i.d. scenario and same window; it does not mechanically combine a Shanken correction with HAC for a different design.
X=np.column_stack((np.ones(T),f)); estimated=np.linalg.lstsq(X,R,rcond=None)[0][1,:,None]
avg2,se2,_,lam=fama_macbeth(R,estimated,L=0)
W=np.cov(lam,rowvar=False,bias=True); omega=np.var(f); star=np.zeros((2,2)); star[1,1]=omega
c=avg2[1]**2/omega; V=((1+c)*(W-star)+star)/T
print('primas:',np.round(avg2,6),'| errores sin ajuste:',np.round(se2,6),'| Shanken:',np.round(np.sqrt(np.diag(V)),6),'| c:',round(c,6))A coverage check uses another seed and known betas. It generates 100 i.i.d. panels of 80 months, with true premium 0.2 and one fixed characteristic. Count how many 95% normal intervals contain the value; the proportion has Monte Carlo error and does not establish coverage for dependent data or estimated betas.
g=np.random.default_rng(280703); C=np.linspace(-1,1,30)[:,None]; cover=0; reps=100
for _ in range(reps):
slopes=g.normal(.2,.4,80)
panel=slopes[:,None]*C[:,0]+g.normal(0,.2,(80,30))
estimate,error,_,_=fama_macbeth(panel,C,L=0)
cover+=abs(estimate[1]-.2)<=1.96*error[1]
rate=cover/reps
print('Cobertura:',cover,'de',reps,'| proporción:',round(rate,3),'| error Monte Carlo:',round(np.sqrt(rate*(1-rate)/reps),3))With that seed, 90 of the 100 intervals included the premium, with estimated Monte Carlo error 0.03. An experiment of only 100 replicates leaves appreciable uncertainty about coverage and should not be confused with a result for every design.
Lab: out-of-sample covariance
The synthetic panel has 60 assets, three industries and one style characteristic. One industry is used as a reference: intercept plus two dummies and style. The generator includes known heterogeneous idiosyncratic variances used to weight the fundamental fit. Training and evaluation periods are disjoint; the future set only evaluates, not selects the model.
g=np.random.default_rng(280702); N=60; train=180; test=180
industry=np.arange(N)%3; style=g.normal(size=N)
B=np.column_stack((np.ones(N),industry==1,industry==2,style)).astype(float)
Ftrue=np.array([[.0004,.00004,0,.00003],[.00004,.0002,.00002,0],[0,.00002,.00018,0],[.00003,0,0,.0003]])
specific=np.linspace(.0003,.0009,N)
factor=g.multivariate_normal([.005,.001,-.001,.002],Ftrue,train+test)
panel=factor@B.T+g.normal(size=(train+test,N))*np.sqrt(specific)
tr=panel[:train]; te=panel[train:]; weight=1/specific
W=np.sqrt(weight)[:,None]; A=np.linalg.lstsq(W*B,W*tr.T,rcond=None)[0].T
resid=tr-A@B.T; Fhat=np.cov(A,rowvar=False,ddof=1); D=np.var(resid,axis=0,ddof=1)
fund=B@Fhat@B.T+np.diag(D)
S=np.cov(tr,rowvar=False,ddof=1); vals,vec=np.linalg.eigh(S); order=np.argsort(vals)[::-1]; vals=vals[order]; vec=vec[:,order]
k=4; low=(vec[:,:k]*vals[:k])@vec[:,:k].T
pca=low+np.diag(np.maximum(np.diag(S-low),1e-8))
future=np.cov(te,rowvar=False,ddof=1)
def gmv(cov):
x=np.linalg.solve(cov,np.ones(len(cov))); return x/x.sum()
for name,cov in [('muestral',S),('fundamental',fund),('PCA',pca)]:
w=gmv(cov); err=np.linalg.norm(cov-future,'fro'); predicted=np.sqrt(w@cov@w); realized=np.std(te@w,ddof=1)
print(name,'error Frobenius',round(err,6),'vol predicha',round(predicted,6),'vol futura',round(realized,6))
print('factores verdaderos / recuperados, medias:',np.round(factor[:train].mean(axis=0),5),np.round(A.mean(axis=0),5))Future covariance is also a noisy estimate, and one split does not establish general superiority. The fundamental model benefits from knowing the characteristics and variances used as weights in this generator; a real application must estimate them without looking ahead. The portfolio is minimum-variance without short-sale constraints or costs and is evaluated with fixed weights, not as a traded strategy’s return.
In the run with seed 280702, future volatilities were approximately 0.029229 for sample covariance, 0.023924 for the fundamental model and 0.025810 for PCA. These are realized monthly standard deviations in this one synthetic split, not a universal ranking. Estimated factor means can be compared with means of factors generated in the same period; the discrepancy includes cross-sectional idiosyncratic noise.
Lab: public factors
The next lab uses local Python with network access and statsmodels. It downloads monthly series from the Kenneth French library, aligns July 1963 through December 2024 and compares CAPM, FF3 and FF5 on the same 25 size-value portfolios. Downloaded history can be revised. FF3 and FF5 are downloaded separately because their SMB factors are not identical; GRS retains its classical assumptions.
import io,zipfile,urllib.request
import numpy as np
import statsmodels.api as sm
from scipy.stats import f as f_dist
base='https://mba.tuck.dartmouth.edu/pages/Faculty/ken.french/ftp/'
def tabla(nombre,marca,n):
with urllib.request.urlopen(base+nombre,timeout=30) as response: raw=response.read()
with zipfile.ZipFile(io.BytesIO(raw)) as z: lines=z.read(z.namelist()[0]).decode('latin1').splitlines()
i=next(i for i,line in enumerate(lines) if marca in line)+(1 if marca.startswith(',') else 2)
rows=[]
for line in lines[i:]:
cells=[x.strip() for x in line.split(',')]
if len(cells)!=n+1 or len(cells[0])!=6 or not cells[0].isdigit(): break
rows.append([int(cells[0])]+[float(x) for x in cells[1:]])
return np.asarray(rows)
ff3=tabla('F-F_Research_Data_Factors_CSV.zip',',Mkt-RF,SMB,HML,RF',4)
ff5=tabla('F-F_Research_Data_5_Factors_2x3_CSV.zip',',Mkt-RF,SMB,HML,RMW,CMA,RF',6)
ports=tabla('25_Portfolios_5x5_CSV.zip','Average Value Weighted Returns -- Monthly',25)
dates=ff5[:,0]; dates=dates[(dates>=196307)&(dates<=202412)]
arrays=[a[np.isin(a[:,0],dates)] for a in (ff3,ff5,ports)]
serial=dates//100*12+dates%100
if len(dates)!=738 or dates[0]!=196307 or dates[-1]!=202412 or np.any(np.diff(serial)!=1) or any(not np.array_equal(a[:,0],dates) or np.any(a[:,1:]<=-99) for a in arrays): raise ValueError('Fechas o datos ausentes')
a3,a5,p=arrays
if not np.allclose(a3[:,4],a5[:,6]): raise ValueError('Tipos sin riesgo incompatibles')
Y=(p[:,1:]-a5[:,6,None])/100
print('meses alineados:',len(dates),'| intervalo:',int(dates[0]),int(dates[-1]))npm run lab and open the connection link.def ajuste_grs(Y,F):
T,N=Y.shape; K=F.shape[1]; X=np.column_stack((np.ones(T),F))
C=np.linalg.lstsq(X,Y,rcond=None)[0]; E=Y-X@C; S=E.T@E/T; Z=F-F.mean(axis=0); O=Z.T@Z/T
if T<=N+K or np.linalg.matrix_rank(X)<K+1 or np.linalg.matrix_rank(S)<N or np.linalg.matrix_rank(O)<K: raise ValueError('Rango insuficiente')
stat=(T-N-K)/N*(C[0]@np.linalg.solve(S,C[0]))/(1+F.mean(axis=0)@np.linalg.solve(O,F.mean(axis=0)))
return C,float(stat),float(f_dist.sf(stat,N,T-N-K))
for label,F in [('CAPM',a3[:,1:2]/100),('FF3',a3[:,1:4]/100),('FF5',a5[:,1:6]/100)]:
C,stat,pvalue=ajuste_grs(Y,F); model=sm.OLS(Y[:,0],sm.add_constant(F)).fit(cov_type='HAC',cov_kwds={'maxlags':3})
print(label,'GRS',round(stat,4),'p',f'{pvalue:.3g}','| alfa primero',round(C[0,0],6),'| HAC',round(model.bse[0],6),'| R²',round(model.rsquared,4),'| coincide',bool(np.allclose(C[:,0],model.params)))npm run lab and open the connection link.In the CRSP 202609 download run for this lesson, GRS statistics were 4.1331 for CAPM, 3.6369 for FF3 and 3.0008 for FF5; their p-values were 1.35e-10, 9.04e-09 and 1.65e-06. The first rose from 0.6258 to 0.9056 and 0.9233. These are descriptive results for these 25 portfolios and this sample, with the stated GRS limitations; a library revision may change them.
Exercises
Step 1 of 3. What loadings do the factor portfolios have?
def fama_macbeth(R,C,L=0):
raise NotImplementedError()Ideas to remember
A pricing factor and a risk factor answer different questions. Fama-MacBeth averages cross-sectional regressions and requires inference adapted to dependence and estimated exposure; FF3 and FF5 are defined portfolios. Covariance models simplify risk when their assumptions and out-of-sample evaluation are reasonable, and require attention to identification, residuals and data available at each date.