Get Started

Calculating beta with CAPM

There are many ways to model stock returns, but the Capital Asset Pricing Model, or CAPM, is one the most well known:

$$ E(R_{P}) - RF = \beta_{{P}}(E(R_{M})-RF)\ $$

  • \(E(R_{P}) - RF\): The excess expected return of a stock or portfolio P
  • \(E(R_{M}) - RF\): The excess expected return of the broad market portfolio B
  • \(RF\): The regional risk free-rate
  • \(\beta_{{P}}\): Portfolio beta, or exposure, to the broad market portfolio B

You can call the .fit() method from statsmodels.formula.api on an .ols(formula, data) model object to perform the analysis, and the .summary() method on the analysis object to anaylze the results.

The FamaFrenchData DataFrame is available in your workspace and contains the proper data for this exercise.

This is a part of the course

“Introduction to Portfolio Risk Management in Python”

View Course

Exercise instructions

  • First, you will need to import statsmodels.formula.api as smf.
  • Define a regression model that explains Portfolio_Excess as a function of Market_Excess.
  • Extract and print the adjusted r-squared of the fitted regression model.
  • Extract the market beta of your portfolio.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Import statsmodels.formula.api
import ____ as ____ 

# Define the regression formula
CAPM_model = smf.ols(formula=____, data=FamaFrenchData)

# Print adjusted r-squared of the fitted regression
CAPM_fit = CAPM_model.fit()
print(CAPM_fit____)

# Extract the beta
regression_beta = CAPM_fit____
print(regression_beta)
Edit and Run Code