Fama-MacBeth Regression in Python: 2026 Guide with Newey-West SEs

You have a stock characteristic, such as a value ratio or a momentum signal, and you want to know whether the market pays a premium for it and whether that premium is statistically real. Fama-MacBeth regression is the classic two-step answer, and the standard-error step is where implementations most often differ. If you have not read Fama-French factor regression in Python, start there for time-series factor loadings; this post adds the cross-sectional view.
How this guide was built. This guide is grounded in the original Fama and MacBeth (1973) and Newey and West (1987) papers (also indexed as NBER working paper t0055), the official statsmodels and linearmodels documentation, and a transparent simulated demonstration. This guide is based on the original papers, official documentation and a simulated demonstration; we did not run the method on live market data. All output numbers come from a simulation with a fixed random seed of 7.
What Is Fama-MacBeth Regression and Why Quants Use It
Fama and MacBeth (1973) estimate cross-sectional return premia with a two-step procedure: one regression per period, then a time-series average of the slopes. The Wikipedia overview summarizes the method as a way to estimate parameters for asset pricing models.
The usual alternative is a pooled regression: stack every stock-month into one panel and run a single OLS. That mixes two kinds of variation. Cross-sectional variation asks which stocks earn more in a given month, while time-series variation asks which months earn more overall. When many stocks share the same monthly shock, a pooled regression treats their residuals as independent, so its standard errors can look far more precise than the evidence supports. Fama-MacBeth sidesteps this by making each month one data point for inference.
The Two-Step Procedure, Step by Step
Step one runs a separate cross-sectional OLS of returns on characteristics in each period t, producing a slope vector g_t. Step two averages the g_t over time, and the premium’s standard error is std(g_t)/sqrt(T), as set out in Fama and MacBeth (1973).
Write N for the number of stocks and T for the number of cross-sectional regressions. Each period regresses returns on the characteristic with an intercept:
Step 1, for each period t = 1..T: R[t] = a_t + g_t * X[t] + e[t]
Step 2, across periods: premium = mean(g_t)
SE = std(g_t, ddof=1) / sqrt(T)
Two design choices matter. First, the demo uses the characteristic at month t to explain returns at month t+1, so the predictor is known before the returns it explains. This gives 240 months and 239 cross-sections. Second, the slope series is the sampling object. Each month contributes one number, so shocks shared across stocks within a month are absorbed into that month’s regression rather than counted as hundreds of independent observations.
Why the Time-Series SE of the Slopes Is the Right Inference
The Fama-MacBeth standard error is the time-series standard deviation of the monthly slopes divided by the square root of T, because each cross-sectional regression counts as one draw. Inference therefore rests on variation across the slope series rather than across individual stocks, as Fama and MacBeth (1973) set out.
The logic is one observation per period. The sample variance of the slopes measures how much the premium moves from period to period, and dividing by the square root of T converts that into uncertainty about the average. The Wikipedia overview notes that these standard errors are corrected for cross-sectional correlation but not for time-series autocorrelation, which is the gap Newey-West addresses.
When and Why the Newey-West Correction Matters
Newey and West (1987) propose a heteroskedasticity- and autocorrelation-consistent (HAC) covariance that tapers autocovariances with Bartlett weights, w_l = 1 - l/(L+1), which keeps the estimated matrix positive semi-definite. The NBER record and the Wikipedia entry on the estimator describe the construction.
The naive standard error assumes the monthly slopes are uncorrelated over time. If they are autocorrelated, perhaps because a characteristic is slow-moving or a premium is persistent, the naive error can misstate the uncertainty of the average. The Newey-West estimator adds weighted autocovariances of the slope series, with weights that decline linearly to zero as the lag grows.
Newey-West does not always widen standard errors. In the simulated demonstration below, it reduced the standard error by 12%, while the lag-1 autocorrelation of the slopes was −0.008. The correction matters when slope autocorrelation is substantial, so check autocorrelation at several lags before deciding whether the adjustment changes your conclusion.
Choosing the Lag Length L
The Bartlett kernel truncates the autocovariance sum at lag L, so L decides how many autocovariances of the slope series enter the HAC correction, as Newey and West (1987) define it. The demonstration sets L to 6 for its monthly series, a judgment call rather than a derived optimum.
Lag selection is a trade-off. A longer lag captures more persistence, but it adds more estimated autocovariances, each noisier when the sample is limited, as it is with 239 cross-sections in the demo. A short lag can miss persistence that is really there. A practical check is to recompute the standard error for a few nearby values of L and see whether your conclusion changes. Some practitioners use automatic lag selectors that choose L from the data. Those are worth knowing, but they rest on their own assumptions, so treat them as a starting point.
The Python Implementation
A NumPy-only implementation needs three small functions: one estimates per-period cross-sectional slopes, one averages them and computes the naive standard error, and one computes the Newey-West HAC standard error with Bartlett weights. Cross-checks against statsmodels cov_hac and the linearmodels documentation need matched conventions: the naive SE here uses ddof=1, while the Newey-West sum divides by T, so digits will not match a library exactly unless its conventions are aligned.
The estimator is written from scratch so every step is visible and no library defaults apply. The driver, simulate_demo, generates data, runs both steps, and prints the results table. Save the code as fm_demo.py and run it with python fm_demo.py.
"""Fama-MacBeth two-step regression with Newey-West standard errors.
NumPy only. Simulated demonstration: no market data is used.
"""
import numpy as np
def cross_sectional_slopes(R, X):
"""Step 1 of Fama & MacBeth (1973): one cross-sectional OLS per period.
R : (T, N) returns realized in each period.
X : (T, N) characteristic observed before those returns.
Returns g : (T, K) per-period slopes (K = 1 here).
"""
R = np.asarray(R, dtype=float)
X = np.asarray(X, dtype=float)
slopes = []
for t in range(R.shape[0]):
Z = np.column_stack([np.ones(R.shape[1]), X[t]]) # intercept + characteristic
beta, *_ = np.linalg.lstsq(Z, R[t], rcond=None)
slopes.append(beta[1:])
return np.vstack(slopes)
def fm_premium(g):
"""Step 2 of Fama & MacBeth (1973): time-series mean and naive SE."""
g = np.asarray(g, dtype=float)
T = g.shape[0]
lambda_hat = g.mean(axis=0)
naive_se = g.std(axis=0, ddof=1) / np.sqrt(T)
t_stats = lambda_hat / naive_se
return lambda_hat, naive_se, t_stats
def newey_west_se(g, L):
"""Newey & West (1987) HAC standard error for the mean of g.
Bartlett weights w_l = 1 - l/(L+1) taper the autocovariances and keep
the estimated long-run covariance positive semi-definite.
"""
g = np.asarray(g, dtype=float)
T = g.shape[0]
u = g - g.mean(axis=0) # demeaned slope series
omega = u.T @ u / T # lag-0 autocovariance
for lag in range(1, L + 1):
w = 1.0 - lag / (L + 1.0) # Bartlett weight
gamma = u[lag:].T @ u[:-lag] / T # lag-`lag` autocovariance
omega += w * (gamma + gamma.T)
return np.sqrt(np.diag(omega / T))
def simulate_demo(seed=7, N=500, T=240, rho=0.9, premium=0.0030,
noise_sd=0.05, L=6):
"""Simulated demo: 30 bp/month premium per 1-sd characteristic."""
rng = np.random.default_rng(seed)
# AR(1) characteristic, standardized cross-sectionally each month
eps = rng.standard_normal((T, N))
X = np.empty((T, N))
X[0] = eps[0]
for t in range(1, T):
X[t] = rho * X[t - 1] + np.sqrt(1 - rho**2) * eps[t]
X = (X - X.mean(axis=1, keepdims=True)) / X.std(axis=1, keepdims=True)
# Characteristic at month t predicts returns at t+1: T=240 gives 239 cross-sections
X_lag = X[:-1]
R = premium * X_lag + noise_sd * rng.standard_normal((T - 1, N))
# Fama & MacBeth (1973) two-step procedure, then Newey & West (1987) HAC SE
g = cross_sectional_slopes(R, X_lag) # step 1: per-period slopes
lam, naive, t_naive = fm_premium(g) # step 2: time-series average
nw = newey_west_se(g, L) # HAC standard error
ac1 = np.corrcoef(g[:-1, 0], g[1:, 0])[0, 1]
print(f"True premium (simulated): {premium * 1e4:.0f} bp/month")
print(f"FM lambda-hat: {lam[0] * 1e4:.1f} bp/month")
print(f"Lag-1 autocorr of slopes: {ac1:.3f}")
print(f"Naive SE: {naive[0] * 1e4:.2f} bp (t = {t_naive[0]:.2f})")
print(f"Newey-West SE (L={L}): {nw[0] * 1e4:.2f} bp (t = {lam[0] / nw[0]:.2f})")
print(f"NW/naive SE ratio: {nw[0] / naive[0]:.2f}")
return g
if __name__ == "__main__":
simulate_demo(seed=7)
Simulated Results: What the Seeded Run Shows
In the simulated demonstration with seed 7 (N=500 stocks, 239 cross-sections), the Fama-MacBeth estimate was 30.2 bp per month against a true premium of 30 bp per month, and Newey-West reduced the standard error by 12%. These figures come from running the code above and are not market evidence.
The table reports simulated output for seed 7 with the demo configuration: N=500 stocks, T=240 months giving 239 cross-sections, an AR(1) characteristic with rho=0.9, a true premium of 30 bp per month per one-sd characteristic, and return noise with sd 5%.
| Quantity | Value |
|---|---|
| True premium (simulated) | 30 bp/month |
| FM λ̂ estimate | 30.2 bp/month |
| Lag-1 autocorrelation of monthly slopes | −0.008 |
| Naive SE | 1.42 bp (t = 21.28) |
| Newey-West SE (L=6) | 1.25 bp (t = 24.14) |
| NW/naive SE ratio | 0.88 |
Expect close agreement, not identical digits, if you rerun the script on a different NumPy or RNG version.
Three points stand out. First, 30.2 bp sits close to the built-in 30 bp premium, so the two-step procedure recovered the parameter the simulation contains. That is a property of the simulation, not evidence that the method identifies premia in real markets, where characteristics are noisy, correlated and subject to regime change. Second, the lag-1 autocorrelation of −0.008 is well inside the sampling noise of a 239-observation series; by the usual approximation, a white-noise autocorrelation has a standard error near 1/√239, about 0.065. The 12% reduction is most plausibly driven by the weighted higher-lag terms, which are noisy at this sample size, rather than by persistent slope autocorrelation. Third, both t-statistics are large because the simulation builds the premium in and controls the noise.
A clean simulated recovery like this is exactly why simulated demos must never be read as backtest evidence. A backtest on real data can look just as tidy after many trials, which is the problem covered in how to detect backtest overfitting in Python.
Library Alternatives: statsmodels and linearmodels
statsmodels provides HAC covariance through cov_hac and OLS through its OLS class. Its cov_hac documentation states the HAC implementation is “verified only for nlags=0”, so treat lagged results with care. linearmodels, developed on GitHub, provides a FamaMacBeth estimator for panel data and fills the panel and asset-pricing gaps that statsmodels leaves.
| Approach | Transparency | HAC support | Panel and asset-pricing models | Best use |
|---|---|---|---|---|
| NumPy from scratch | Every step visible | Only what you implement and test | You build them | Learning, auditing, custom work |
| statsmodels | Library-defined | cov_hac, documented as verified only for nlags=0 |
Limited | General regression and cross-checks |
| linearmodels | Library-defined | HAC options not covered in the page we checked | Panel and asset-pricing focus, including FamaMacBeth |
Production panel and asset-pricing work |
The caveat deserves emphasis. If you use cov_hac with nlags above zero, the official documentation says that path is verified only for nlags=0. Validate any lagged result against an independent calculation, such as the NumPy function above, before relying on it.
Where Real Factor Data Comes From (If You Extend This)
Kenneth French’s Data Library, hosted by Dartmouth’s Tuck School, is the canonical source for Fama/French factor data, and its factor description documents what each series contains. The Fama-French three-factor model overview on Wikipedia explains the framework behind those series.
This demonstration uses simulated data by design, so every number in this post is simulated. If you extend the work, note that the library mainly supplies factor and portfolio returns; stock-level characteristics beyond what it offers, such as the historical book-equity file, come from your own panel. A real Fama-MacBeth study needs a stock-level panel of returns and characteristics from your own data source. Keep the one-month lag between characteristic and return, and check the source’s terms before redistributing anything.
FAQ
The three questions below cover the points that matter most when applying this method. Each answer draws on the cited papers, the official documentation, or the simulated demonstration in this post. None relies on live-market results.
Why not just run one pooled regression over all stocks and months?
A pooled regression stacks all stock-months and runs one OLS, which treats the observations as more independent than they are, so its standard errors can be understated and look more precise than they are. Fama and MacBeth (1973) avoid this by treating each period’s cross-sectional regression as a single draw. That keeps inference tied to variation across periods.
Does Newey-West always make standard errors larger?
No. In the simulated demonstration, the Newey-West standard error was 0.88 times the naive one, a 12% reduction, with a lag-1 autocorrelation of −0.008. Newey and West (1987) present the correction as a general HAC estimator, and whether it widens or narrows your standard error depends on the autocorrelation structure of your slopes.
Can I use statsmodels instead of writing it myself?
Yes, for many regressions, but read the caveats first. The statsmodels cov_hac documentation says the HAC implementation is verified only for nlags=0, so cross-check lagged results independently. The linearmodels documentation covers the panel and asset-pricing models that statsmodels does not.
The Bottom Line
Fama-MacBeth is a sound default for estimating cross-sectional premia, because its two-step logic is simple and its inference runs over time. The care goes into the standard error, where naive and Newey-West choices can differ, as both Fama and MacBeth (1973) and Newey and West (1987) make clear.
Run one cross-sectional regression per period, average the slopes, and use the time-series standard error. Then check whether the slopes are autocorrelated before deciding whether Newey-West changes the answer. In the simulated run, the two-step procedure recovered the 30 bp premium as 30.2 bp, and Newey-West cut the standard error by 12%; that is a teaching result, not a market finding.
This guide is based on the original papers, official documentation and a simulated demonstration; we did not run the method on live market data.
For the natural next step, see Fama-French factor regression in Python, which extends the factor-based view of return modeling.
← Back to all posts

