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)

This exercise is part of the course

Introduction to Portfolio Risk Management in Python

IntermediateSkill Level
4.5+
11 reviews

Evaluate portfolio risk and returns, construct market-cap weighted equity portfolios and learn how to forecast and hedge market risk via scenario generation.

Learn about the main factors that influence the returns of your portfolios and how to quantify your portfolio's exposure to these factors.

Exercise 1: The Capital Asset Pricing modelExercise 2: Excess returnsExercise 3: Calculating beta using co-varianceExercise 4: Calculating beta with CAPM
Exercise 5: Adjusted R-squaredExercise 6: Alpha and multi-factor modelsExercise 7: The Fama French 3-factor modelExercise 8: p-values and coefficientsExercise 9: Economic intuition in factor modelingExercise 10: The efficient market and alphaExercise 11: Expanding the 3-factor modelExercise 12: The 5-factor modelExercise 13: Alpha vs R-squared

What is DataCamp?

Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.

Start Learning for Free