Python

# Calculate the CAPM with Python in 3 Easy Steps

## What will we cover?

In this lesson we will learn about the CAPM and how to calculate it.

The objectives of this tutorial is:

• Understand the CAPM (Capital Asset Pricing Model).
• Beta and CAPM calculations.
• Expected return of an investment.

## Step 1: What is the CAPM?

The CAPM calculates the relationship between systematic risk and expected return. There are several assumptions behind the CAPM formula that have been shown not to hold in reality. But still, the CAPM formula is still widely used.

The formula is as follows.

## Step 2: Get some data to make calculations on

Let’s get some data and calculate it.

```import numpy as np
import datetime as dt
import pandas as pd

tickers = ['AAPL', 'MSFT', 'TWTR', 'IBM', '^GSPC']
start = dt.datetime(2015, 12, 1)
end = dt.datetime(2021, 1, 1)

data = pdr.get_data_yahoo(tickers, start, end, interval="m")

log_returns = np.log(data/data.shift())
```

Feel free to change the tickers to your choice and remember to update the dates to fit your purpose.

## Step 3: How to calculate CAPM with Python (NumPy and pandas)

The calculations are done quite easily.

Again, when we look at the formula, the risk free return is often set to 0. Otherwise, the 10 years treasury note is used. Here, we use 1.38%. You can update it for more up to date value with the link.

```cov = log_returns.cov()
var = log_returns['^GSPC'].var()

beta = cov.loc['AAPL', '^GSPC']/var

risk_free_return = 0.0138
market_return = .105
expected_return = risk_free_return + beta*(market_return - risk_free_return)
```

Notice, you can calculate it all simultaneously.

## Want more?

This is part of a 2.5 hour full video course in 8 parts about Risk and Return.

Rune

Share
Rune

## Learn Python FREE Online

Why learn Python? There are many reasons to learn Python, and that is the power…

3 days ago

## How to Check if a Number is Even or Odd with Python

What will you learn? How to use the modulo operator to check if a number…

1 week ago

## The Truth About Being a Python Software Contractor

There are a lot of Myths out there There are lot of Myths about being…

2 months ago

## Do This and 10X Your Salary as a Software Engineer

To be honest, I am not really a great programmer - that is not what…

2 months ago

## Ultimate Guide to the Data Science Career Path

What does it take to become a Data Scientist? Data Science is in a cross…

2 months ago

## How to Setup a MySQL Server in Docker for Your Python Project

What will you learn? Need to setup a SQL server? You don’t need to install…

4 months ago