In the world of investment analysis, few models have been as influential or widely used as the Capital Asset Pricing Model (CAPM). Despite being developed in the 1960s, this elegant framework remains a cornerstone of modern portfolio theory and is still widely used by financial analysts, fund managers, and individual investors alike.
Today, I want to walk you through building your own CAPM calculator in Python—a tool that can help you estimate expected returns for any stock or portfolio based on its risk characteristics. So you can get results like shown below about your stock portfolio:
What is CAPM?
Before diving into the code, let's briefly review what CAPM actually does. At its core, CAPM provides a framework for estimating the expected return of an asset based on its systematic risk (beta) relative to the market.
The fundamental equation is elegantly simple:
E(Ri) = Rf + βi × [E(Rm) - Rf]
Where:
E(Ri) is the expected return of asset i
Rf is the risk-free rate
βi is the beta of asset i (a measure of its systematic risk)
E(Rm) is the expected return of the market
[E(Rm) - Rf] is the market risk premium
Building the Calculator
Our CAPM calculator will be built in Python using pandas for data manipulation, yfinance for retrieving stock prices, pandas_datareader for accessing risk-free rates, and statsmodels for running the regressions.
I'll structure this as a modular set of functions that you can easily reuse and adapt for your own investment analysis:
1. Downloading the Data
First, we need historical price data for our stocks, a market index, and the risk-free rate:
def download_data(tickers, market_ticker='SPY', rf_ticker='TB3MS', start_date="2000-01-01", end_date=None):
"""
Download stock prices, market prices, and risk-free rate data.
"""
# Download stock prices
stock_prices = yf.download(tickers, start=start_date, end=end_date)["Close"]
# Download market prices
mkt_prices = yf.download(market_ticker, start=start_date, end=end_date)["Close"]
# Download risk-free rate
rf = pdr.DataReader(rf_ticker, 'fred', start=start_date, end=end_date)
return stock_prices, mkt_prices, rf
We're using:
yfinance
to download stock and market index pricespandas_datareader
to access the 3-Month Treasury Bill rate from FRED (Federal Reserve Economic Data)
Keep reading with a 7-day free trial
Subscribe to Quantitative Financial Insights to keep reading this post and get 7 days of free access to the full post archives.