Use Fama-French factors and statsmodels to decompose portfolio risk in Python
By PyQuant News
Published: 2026-03-28
URL: https://pyquantnews.substack.com/p/know-whats-actually-driving-returns
Each week, I send out one Python tutorial to help you get started with algorithmic trading, market data analysis, and quant finance. Upgrade to a paid plan to access the code notebooks.

In todayâs post, youâll use Python and a well-known academic model to measure how much of your portfolioâs risk comes from two specific market forces (company size and investment style), and how much is left unexplained.
What factor models actually do
A factor model breaks your portfolioâs returns into pieces, each tied to a specific market force, so you can see whatâs really driving your gains and losses.
The idea comes from Eugene Fama and Kenneth French, two finance professors who published their three-factor model in 1992.
Before their work, most people assumed the overall market was the only force that mattered. Fama and French showed that two additional forces, company size (whether a stock is from a large or small company) and investment style (whether a stock looks cheap or expensive relative to its fundamentals), explained a significant chunk of stock returns that the market alone couldnât account for.
How professionals use this
Today, portfolio managers at large firms run this kind of analysis routinely to understand where their risk is coming from.
They measure how sensitive their portfolio is to each force using a statistical technique called regression, which finds the mathematical relationship between their returns and each factor.
If the analysis shows too much exposure to one force, they adjust by buying or selling stocks that represent that force.
The goal isnât to eliminate risk entirely but to make sure the risks theyâre taking are intentional and well-understood.
Why this matters for you
Even if youâre just getting started, this kind of analysis helps you answer a question that most beginners never think to ask: how much of my portfolioâs movement is explained by forces I can identify, and how much is a mystery?
Once you can measure your exposure to specific forces, you can make informed decisions about whether to increase or decrease that exposure.
Instead of guessing why your portfolio went up or down last month, youâll have concrete numbers showing which forces contributed and by how much.
Thatâs a meaningful upgrade from just watching your account balance and hoping for the best.
Letâs see how it works with Python.
This Substack is reader-supported. To get the code notebooks and support my work, consider becoming a free or paid subscriber.
Library installation
Install the required libraries for fetching market data, accessing academic factor datasets, and running regression analysis.

Imports and setup
numpy handles array math and covariance calculations. pandas provides DataFrames for organizing return series. pandas\_datareader pulls Fama-French factor data directly from Kenneth Frenchâs data library.
yfinance downloads historical stock prices from Yahoo Finance. statsmodels supplies OLS regression and rolling regression tools for measuring factor sensitivities over time.

Load factor data and stock prices
Fetch the Fama-French three-factor dataset starting from 2000, which contains monthly returns for the market, size (SMB), and value (HML) factors published by Kenneth Frenchâs data library.

SMB (Small Minus Big) measures the return difference between small-cap and large-cap stocks each month. HML (High Minus Low) measures the return difference between value stocks and growth stocks. These two series are the market forces we want to test our portfolio against.
Download monthly closing prices for SPY (our benchmark) and three tech stocks, then compute percentage returns and convert to monthly periods so they align with the Fama-French data.

Aligning time periods between your portfolio returns and the factor data is essential. If the frequencies donât match, the regression will either fail or produce misleading results. Using monthly periods here ensures a clean join later.
Compute active returns and run regression
Separate SPY as the benchmark, average the remaining stock returns into an equal-weight portfolio, and subtract the benchmark to get active returns, which represent the portion of performance not explained by simply holding the market.

Active returns isolate what your specific stock picks contributed beyond broad market movement. This is the signal we actually want to decompose. If you skip this step and regress raw returns, youâd be measuring total market exposure rather than the unique bets your portfolio is making.
Combine active returns with the SMB and HML factor series into a single DataFrame, dropping any months where data is missing, then run OLS regression to estimate how sensitive our active returns are to each factor.

The coefficients b1 and b2 are your portfolioâs factor sensitivities, often called factor loadings or betas. A positive SMB loading means your portfolio tilts toward smaller companies relative to SPY.
A negative HML loading means it tilts toward growth stocks rather than value stocks. These numbers turn a vague sense of âI own tech stocksâ into a precise measurement of what forces are actually moving your returns.
Run a 12-month rolling regression to see how your portfolioâs sensitivity to each factor changes over time, then plot the rolling coefficients.

The result is a plot that looks like this.

A single regression gives you one average sensitivity across the entire period, but markets shift. Rolling regression reveals whether your exposure to size or value has been growing, shrinking, or flipping direction. Professionals use this to catch drift in their portfolios before it becomes a problem.
Decompose portfolio risk by factor
Use the factor covariance matrix and the regression coefficients to calculate each factorâs marginal contribution to the total variance of active returns, expressed as a fraction of total active risk.

This is the payoff of the entire analysis. Instead of just knowing your factor sensitivities, you now know what percentage of your portfolioâs active risk each factor actually accounts for. The unexplained portion represents risk from stock-specific events, sector dynamics, or other forces not captured by the two-factor model.
If the unexplained share is large, it means your portfolioâs behavior is driven by something beyond size and value, which could be a good thing if intentional or a warning sign if not. This decomposition is exactly how professional risk managers decide whether a portfolioâs risk profile matches the bets they intended to make.
Your next steps
You now have a way to measure exactly which market forces are driving your portfolioâs returns and how much of your risk is still unexplained. That means you can stop guessing and start making position adjustments based on what the numbers actually show.