How to do the Capital Asset Pricing Model (CAPM) in Python

1 min

The Capital Asset Pricing Model (CAPM) is a financial model used to determine the expected return of an asset based on its risk and the expected return of the market as a whole.

It assumes that the expected return of an asset is equal to the risk-free rate plus a risk premium, which is proportional to the asset's beta (a measure of the asset's volatility relative to the market).

To implement the CAPM in Python, you can use a few libraries such as NumPy, Pandas, and SciPy to perform necessary calculations. Here is an example of how to do this:

import numpy as np
import pandas as pd
from scipy.stats import linregress

# Load your asset and market data
asset_returns = [0.05, 0.06, 0.07, 0.08, 0.09]
market_returns = [0.04, 0.05, 0.06, 0.07, 0.08]

# Calculate the beta of the asset
beta, alpha, r_value, p_value, std_err = linregress(market_returns, asset_returns)

# Estimate the expected return of the asset
risk_free_rate = 0.03
expected_return = risk_free_rate + beta * (np.mean(market_returns) - risk_free_rate)

print("Beta: ", beta)
print("Expected return: ", expected_return)

Here is how to do with selected companies :

import numpy as np
import pandas as pd
from scipy.stats import linregress
import yfinance as yf

# We select the assets we want to target
assets = ["AAPL", "MSFT", "GOOGL"]

# We get the prices we want
prices = yf.download(assets, start="2021-01-01", end="2021-12-31")["Adj Close"]

# Load your asset and market data
asset_returns = prices.pct_change().mean().to_list()
market_returns = [0.04, 0.05, 0.06]

# Calculate the beta of the asset
beta, alpha, r_value, p_value, std_err = linregress(market_returns, asset_returns)

# Estimate the expected return of the asset
risk_free_rate = 0.03
expected_return = risk_free_rate + beta * (np.mean(market_returns) - risk_free_rate)

print("Beta: ", beta)
print("Expected return: ", expected_return)

market_returns are usually computed as the total returns of a market index, such as the S&P 500 or the Dow Jones Industrial Average, over a specified period of time.

The total return of an index is the change in the value of the index, including both price appreciation and dividends, over a specified period of time.

This is just a basic example and the actual implementation may vary depending on the type and size of the data being used.