The CAPM: equilibrium, beta and its tests
Derive CAPM, estimate alpha and beta, interpret the GRS test, and examine market proxies and empirical security market lines.
After this lesson you can
- Derive CAPM from the tangency portfolio first-order condition and market equilibrium.
- Estimate betas and alphas by time-series regression and quantify their uncertainty.
- Implement the GRS joint-zero-alpha test and interpret it as Sharpe distance from the frontier.
- Explain Roll's critique and the limitations of testing CAPM with a market-index proxy.
- Reproduce the historical security market line with beta-sorted portfolios and relate it to the low-beta anomaly.
Before you start
- 28Tangency portfolioCapital market lineTwo-fund separationSharpe ratioEfficient frontier
- 05Sampling distribution of OLS coefficientsGaussian linear modelWald testNormal sampling theory: chi-squared, Student t and F distributionsF-test for nested linear models
- 27Heteroskedasticity-consistent standard errors (HC0 to HC3)
Which risk should be rewarded?
A stock can fluctuate greatly because of its own news and still add little risk to a broad portfolio. CAPM asks what expected premium rewards the risk remaining when an investor can diversify. Its theoretical answer is covariance with the market portfolio, not the asset’s isolated volatility.
For equally weighted assets with variance and common correlation , the variance of the average is . The sum contains diagonal terms and covariances. The limit is : if all risk in this model vanishes; a shared factor remains. Diversification does not guarantee eliminating every risk in a real market.
From the investor to equilibrium
The capital asset pricing model (CAPM) combines fund separation with equilibrium. In a one-period version, all investors have the same asset set, the same return distribution and mean-variance preferences with positive risk aversion; they can lend or borrow at the same risk-free rate, and no costs or constraints prevent them from holding the portfolios. The market is also assumed to clear, the aggregate risky portfolio to have positive supply and variance, and the market premium to be positive.
Under these assumptions, each investor holds a combination of the risk-free asset and the same tangency portfolio, though total exposures differ. Adding positions makes the aggregate supply of risky assets proportional to that portfolio. The market portfolio , weighted by the value of all risky assets, therefore coincides with it. This conclusion depends on equilibrium and common assumptions; it does not follow from optimizing one isolated investor’s portfolio.
Write , let be market weights and . Tangency gives for some . Multiplying by gives . Component is
Beta is the asset’s covariance with the market divided by market variance. It is dimensionless, can be negative and can also be written . The model rewards beta: a highly volatile asset with negative covariance can have a negative premium, under the model’s assumptions and expectations.
The security market line (SML) plots expected mean against beta: intercept , slope . In excess returns it passes through the origin. It differs from the capital market line, which relates mean to volatility for efficient combinations. Do not confuse the horizontal axes or treat a historical scatter as known expectations.
The points were calculated using the market factor and risk-free rate from the Kenneth French Data Library, over the fixed window July 1963 to December 2024. The cross-sectional fit uses betas and means from the same period, so it is descriptive and can suffer estimation error on both axes. Beta deciles are formed each June using historical information; their plotted betas are re-estimated over the selected period. The library may revise historical data.
In this particular download, the ten beta deciles in 1963-2024 give an annualized cross-sectional slope of 0.03230, versus an annualized market premium of 0.07041. The 25 size-value portfolios give slope −0.04323 with the same factor and period. These are two summaries of the same US history, with different errors and compositions; they do not prove the future slope must be flat. The lab recalculates them from original files.
Regression, alpha and beta
For excess returns and , estimate
Jensen’s alpha is the intercept of this regression relative to the chosen factor. In population CAPM with the correct market portfolio and appropriate conditions, . The estimate is an ordinary least squares slope; . measures variance explained in sample, not whether the model prices the asset correctly.
Uncertainty matters: a positive estimated alpha may be noise, and examining many alphas increases the chance of finding a large one by chance. Classical standard errors require the regression assumptions; heteroskedasticity or temporal dependence require suitable estimators, such as a robust matrix with appropriate lags. The exact GRS inference below does not automatically survive those modifications.
With one factor treated as fixed, positive variation and independent zero-mean errors with constant variance , and . Replace unknown variance with residual sum of squares divided by for classical standard errors. The normality assumption permits exact t intervals; with dependent errors, an HAC estimator and its lag count require additional choices.
Two practical adjustments address different problems. Vasicek combines a noisy beta with a prior mean using an uncertainty-dependent weight under an explicit beta-distribution model. Dimson includes lags and leads of market return in the regression and sums their coefficients to capture quotes that react with delay; lag choice and calendar matter. Neither alone removes selection bias or structural change.
For example, if and, conditionally on it, with known parameters, the posterior mean is . A less precise beta receives more prior weight. Estimating , and introduces additional uncertainty; the adjustment does not replace a confidence interval.
Joint testing and geometry
Let be a matrix of asset excess returns and a factor matrix. The regression includes an intercept and factor columns. Let be the intercept vector, residual covariance with divisor , the factor mean and its centered covariance, also with divisor .
The Gibbons-Ross-Shanken test (GRS) for uses the following form, consistent with the original derivation:
With , full-rank design and errors independent over time, zero-mean and multivariate normal conditional on factors, with constant positive-definite residual covariance, under it follows . These divisor conventions are essential: if you use the residual estimator with divisor , adjust the scaling factor. The distribution is exact under those assumptions; it is not guaranteed for residuals with heteroskedasticity, autocorrelation or arbitrary tails.
The scale can be reconstructed without memorization. Let , and , corresponding to the intercept. By the Schur complement, . Conditional on the design, under the null is normal with covariance and independent of , which has Wishart degrees of freedom. Hotelling’s transformation gives . Substituting gives exactly the formula above.
In the block decomposition of factor and asset covariance, the difference between maximum squared Sharpe of the expanded set and that of factors alone is with the divisors above. The denominator is one plus squared Sharpe of the factors. Thus GRS measures relative improvement in the frontier, weights alphas by residual covariance and has a null distribution under the stated assumptions. A small sample or highly correlated assets can reduce power; failure to reject does not prove all alphas are exactly zero.
What an index tests
Roll’s critique notes that CAPM refers to the portfolio of all risky assets, which is not fully observed. With an index as a substitute, a joint test evaluates that index’s mean-variance efficiency within the chosen set, together with statistical assumptions. Rejecting that proxy does not by itself show the true market portfolio is inefficient. It also does not make a test useless: it precisely defines the portfolio and set tested.
Without unlimited borrowing at the risk-free rate, Black’s zero-beta CAPM uses a reference portfolio uncorrelated with the market instead of a common financing rate. Intertemporal CAPM adds hedging demands against changes in investment opportunities; one market beta may not summarize all relevant risks. These are models with additional assumptions and factors, not automatic repairs for an observed alpha.
Frazzini and Pedersen study a betting against beta portfolio combining long exposure to low beta and short exposure to high beta, scaled to neutralize beta in the model. Their financing-constraint mechanism is a modeled explanation, not a deduction from this figure. Evidence of a flat historical SML is sensitive to period, portfolio construction, beta measurement, costs and proxy choice.
Lab: matrix OLS and test size
The first cell implements regression for all assets simultaneously and the statistic with divisors . It solves linear systems instead of forming inverses. A rank error or singular residual covariance prevents applying this version of the test.
import numpy as np
from scipy.stats import f as f_dist
def grs_test(excess_returns, factor_returns):
Y=np.asarray(excess_returns,dtype=float)
F=np.asarray(factor_returns,dtype=float)
if F.ndim==1: F=F[:,None]
if Y.ndim!=2 or F.ndim!=2 or len(Y)!=len(F):
raise ValueError('Se requieren matrices con el mismo número de filas')
T,N=Y.shape
K=F.shape[1]
if N<1 or K<1 or T<=N+K or not np.isfinite(Y).all() or not np.isfinite(F).all():
raise ValueError('Dimensiones insuficientes o datos no finitos')
X=np.column_stack((np.ones(T),F))
coef,_,rank,_=np.linalg.lstsq(X,Y,rcond=None)
if rank<K+1: raise ValueError('Factores de rango insuficiente')
residuos=Y-X@coef
S=residuos.T@residuos/T
centred=F-F.mean(axis=0)
Omega=centred.T@centred/T
alpha=coef[0]
if np.linalg.matrix_rank(S)<N or np.linalg.matrix_rank(Omega)<K:
raise ValueError('Covarianza singular')
try:
[email protected](S,alpha)
den=1+F.mean(axis=0)@np.linalg.solve(Omega,F.mean(axis=0))
except np.linalg.LinAlgError as exc:
raise ValueError('Covarianza singular') from exc
stat=(T-N-K)/N*num/den
return float(stat),float(f_dist.sf(stat,N,T-N-K))
def ajustar_capm(Y,factor):
Y=np.asarray(Y,dtype=float)
X=np.column_stack((np.ones(len(factor)),np.asarray(factor)))
coef=np.linalg.lstsq(X,Y,rcond=None)[0]
residual=Y-X@coef
return coef,residualTo check size and power, we use normal factors, normal residuals with a common and an idiosyncratic component, and independence between factors and residuals. The alternative plants alternating-sign alphas; the observed outcome depends on the seed and alternative size. The experiment is divided into blocks to keep each browser cell brief.
def bloque(seed,reps=100):
g=np.random.default_rng(seed)
T,N=120,25
alpha_alt=.006*np.where(np.arange(N)%2==0,1.,-1.)
rechazos=np.zeros(2,dtype=int)
for _ in range(reps):
factor=g.normal(.006,.04,size=T)
errors=.05*(.4*g.normal(size=(T,1))+np.sqrt(1-.4**2)*g.normal(size=(T,N)))
base=factor[:,None]*np.linspace(.6,1.4,N)+errors
for j,alpha in enumerate((np.zeros(N),alpha_alt)):
_,p=grs_test(base+alpha,factor)
rechazos[j]+=p<.05
return rechazos
cuentas=bloque(280501)
print('Bloque 1:',cuentas)cuentas+=bloque(280502)
print('Acumulado:',cuentas)cuentas+=bloque(280503)
print('Acumulado:',cuentas)cuentas+=bloque(280504)
print('Acumulado:',cuentas)cuentas+=bloque(280505)
prob=cuentas/500
error=np.sqrt(prob*(1-prob)/500)
print('Rechazos nula y alternativa:',cuentas,'de 500')
print('Proporciones:',np.round(prob,4),'| error estándar Monte Carlo:',np.round(error,4))Size is the rejection probability when the null is true; power is the rejection probability under this particular alternative. The simulation does not demonstrate robustness to real non-Gaussian residuals or measure power for every alpha vector.
With these five seeds, the run produced 25 rejections in 500 replicates under the null and 492 under the alternative: proportions 0.050 and 0.984, with approximate Monte Carlo standard errors 0.0097 and 0.0056. These figures describe the cell’s generator; another alternative or residual covariance can have different power.
Lab: Kenneth French portfolios
We repeat the analysis on the 25 size-value portfolios and beta-sorted deciles. The library publishes monthly simple returns in percent; subtract the same month’s risk-free rate and use Mkt-RF as a proxy for market excess return. The previous figure retains a summary of a download with CRSP vintage 202609. The cell queries current files, whose history may be revised, so figures may change. It needs local Python and network access; the interactive’s copy does not depend on downloading while reading.
The cross-sectional slope fits means to betas estimated in the same period. Means are multiplied by 12 as an arithmetic scale, not compounded annual returns. The example HAC standard errors relax some individual-error assumptions, but do not turn classical GRS into a robust test.
import io,zipfile,urllib.request
import numpy as np
import pandas as pd
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_mensual(nombre,marca,n_columnas):
with urllib.request.urlopen(base+nombre,timeout=30) as response:
contenido=response.read()
with zipfile.ZipFile(io.BytesIO(contenido)) as z:
texto=z.read(z.namelist()[0]).decode('latin1')
lineas=texto.splitlines()
i=next(j for j,linea in enumerate(lineas) if marca in linea)
i += 1 if marca.startswith(',') else 2
datos=[]
for linea in lineas[i:]:
campos=[v.strip() for v in linea.split(',')]
if len(campos)!=n_columnas+1 or len(campos[0])!=6 or not campos[0].isdigit(): break
datos.append([int(campos[0])]+[float(v) for v in campos[1:]])
return np.asarray(datos)
factores=tabla_mensual('F-F_Research_Data_Factors_CSV.zip',',Mkt-RF,SMB,HML,RF',4)
valor=tabla_mensual('25_Portfolios_5x5_CSV.zip','Average Value Weighted Returns -- Monthly',25)
beta=tabla_mensual('Portfolios_Formed_on_BETA_CSV.zip','Value Weighted Returns -- Monthly',15)
beta=np.column_stack((beta[:,0],beta[:,6:])) # los últimos diez son los deciles
def alinear(portafolios,desde,hasta):
fechas=np.intersect1d(factores[:,0],portafolios[:,0])
fechas=fechas[(fechas>=desde)&(fechas<=hasta)]
f=factores[np.isin(factores[:,0],fechas)]
p=portafolios[np.isin(portafolios[:,0],fechas)]
meses=(fechas//100)*12+fechas%100
if (len(f)==0 or fechas[0]!=desde or fechas[-1]!=hasta or np.any(np.diff(meses)!=1)
or not np.array_equal(f[:,0],p[:,0]) or np.any(p[:,1:]<=-99)
or np.any(f[:,1:]<=-99)):
raise ValueError('Fechas incompatibles o datos ausentes')
return (p[:,1:]-f[:,4,None])/100,f[:,1]/100
print('Se descargaron factores, 25 carteras y deciles de beta.')npm run lab and open the connection link.Both results tables are recalculated, not copied from the widget. Three preset periods are calculated and the first regression is checked with statsmodels. A difference between cross-sectional slope and market premium summarizes a sample; it does not control for beta error or by itself prove an exploitable anomaly.
def estimar(Y,f):
X=np.column_stack((np.ones(len(f)),f))
coef=np.linalg.lstsq(X,Y,rcond=None)[0]
E=Y-X@coef
T,N=Y.shape
S=E.T@E/T
omega=np.mean((f-f.mean())**2)
if T<=N+1 or omega<=0 or np.linalg.matrix_rank(S)<N:
raise ValueError('Muestra o covarianza insuficientes')
F=(T-N-1)/N*(coef[0]@np.linalg.solve(S,coef[0]))/(1+f.mean()**2/omega)
return coef,float(F),float(f_dist.sf(F,N,T-N-1))
for etiqueta,datos in [('tamaño-valor',valor),('deciles beta',beta)]:
for periodo,desde,hasta in [('1963-1990',196307,199012),('1991-2024',199101,202412),('1963-2024',196307,202412)]:
Y,f=alinear(datos,desde,hasta)
coef,F,p=estimar(Y,f)
pendiente,intercepto=np.polyfit(coef[1],12*Y.mean(axis=0),1)
print(etiqueta,periodo,'n',len(f),'prima anualizada',round(float(12*f.mean()),5),
'pendiente',round(float(pendiente),5),'GRS',round(F,4),'p',f'{p:.3g}')
Y,f=alinear(datos,196307,202412)
coef,_,_=estimar(Y,f)
ajuste=sm.OLS(Y[:,0],sm.add_constant(f)).fit(cov_type='HAC',cov_kwds={'maxlags':3})
print('Statsmodels coincide en alfa y beta:',bool(np.allclose(ajuste.params,coef[:,0])),
'| alfa y beta:',np.round(ajuste.params,5),
'| errores HAC alfa y beta:',np.round(ajuste.bse,6),
'| R²:',round(float(ajuste.rsquared),4))npm run lab and open the connection link.The test family is large: a joint rejection does not by itself identify which portfolio causes the deviation, and a notable individual alpha after many searches is not independent evidence. Compare periods, intervals and definitions before attributing an economic cause.
In the download used for the figure, the first size-value portfolio in 1963-2024 gave monthly and ; statsmodels obtained and HAC alpha standard error 0.001909 with three lags. These figures check the regression on that sample, not skill or proof that the proxy is the complete market. Updated data or a different lag choice can change them.
Exercises
Step 1 of 3. What relationship does tangency imply?
Step 1 of 3. How does the asset mean decompose?
def grs_test(Y,F):
raise NotImplementedError()Ideas to remember
CAPM identifies rewarded risk with covariance relative to the market portfolio under demanding equilibrium assumptions. Estimating beta and testing alphas are different problems: GRS combines alphas and their covariance, but its exact distribution depends on its assumptions, and empirical results also depend on the proxy and sample.