The Capital Asset Pricing Model ( CAPM ) is a fundamental concept in finance that gives us the expected return on investment, considering its risk and the overall market’s behavior. It is an important part of modern portfolio theory and has many applications in investment management, risk assessment, financial decision-making, etc. In this article, we will learn the basics of CAPM and how to use it in Python.

The Capital Asset Pricing Model (CAPM) is a fundamental concept in finance that provides a linear relationship between the expected return of an asset and its systemic risk, measured by its beta coefficient. Python libraries like Pandas, Numpy, and Matplotlib can be utilized to calculate and visualize CAPM, making it a powerful tool for financial analysis, risk assessment, and investment decision-making.

** Disclaimer:** This article does not provide you with any investment advice and all the information used in this article concerns Indian financial markets.

Recommended: Large integer handling in Python (optimization)

## Understanding the Basics of CAPM

CAPM was introduced in this world by William Sharpe in the 1960s. This model provides us with a linear relationship between the expected return of an asset and its systemic risk, commonly measured by its beta(β) coefficient. Let us look at its formula.

Let us look at the graph of CAPM as well to understand it further.

## Implementing Python in CAPM

Python programming language is an excellent tool for financial analysis. We can use libraries like Numpy, Pandas, and Matplotlib to calculate and visualize data. We will learn how to implement CAPM in Python with user-generated data.

Let us look at the code for the same.

```
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import linregress
# Generate random data for asset returns and market returns
np.random.seed(0)
n = 1000 # Number of data points
asset_returns = np.random.normal(loc=0.08, scale=0.15, size=n) # Mean = 0.08, Standard Deviation = 0.15
market_returns = np.random.normal(loc=0.1, scale=0.2, size=n) # Mean = 0.1, Standard Deviation = 0.2
# Calculate beta coefficient using linear regression
beta, alpha, _, _, _ = linregress(market_returns, asset_returns)
# Define risk-free rate and expected market return
risk_free_rate = 0.03
expected_market_return = 0.08
# Calculate expected return using CAPM
expected_return = risk_free_rate + beta * (expected_market_return - risk_free_rate)
# Plot Security Market Line
plt.figure(figsize=(10, 6))
plt.plot([0, 1], [risk_free_rate, expected_market_return], label='Market Portfolio', linestyle='-', color='blue')
plt.plot(beta, expected_return, marker='o', markersize=8, color='red', label='Asset')
plt.title('Security Market Line (SML)')
plt.xlabel('Beta (β)')
plt.ylabel('Expected Return')
plt.legend()
plt.grid(True)
plt.show()
```

The above code generates random data for asset returns and market returns. Ultimately, we will plot a graph.

The above code is a very simple way to understand CAPM.

## Detailed Analysis of CAPM using Python

Let us look at a detailed way to understand CAPM.

### 1. **Importing libraries**

```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import linregress
```

We have imported pandas, numpy, matplotlib, and linregress to perform calculations and plot the graph of the figure formed.

**2. Loading Data from CSV file**

```
data = pd.read_csv('your_data.csv') # Replace 'your_data.csv' with the path to your CSV file
```

The CSV file can be downloaded from the Yahoo finance website, as shown below. pd.read_csv() function reads data from a CSV file and uploads it into panda DataFrame. Replace ‘your_data.csv’ with the downloaded data file from the Yahoo finance website. You can download CSV files for any listed companies from their website.

**3. Extracting Asset Returns and Market Returns**

```
asset_returns = data['Asset Returns']
market_returns = data['Market Returns']
```

This gives us the respective columns from the DataFrame and assigns them variables.

**4. Calculating Beta (β)**

```
beta, alpha, _, _, _ = linregress(market_returns, asset_returns)
```

linregress() calculates linear least-squares regression for market returns and asset returns. It also provides us with the slope and intercept of the regression line.

**5. Defining Risk-Free Rate and Expected Market Return**

```
risk_free_rate = 0.03
expected_market_return = 0.08
```

Generally, the risk-free rate is taken from the government website and the expected market return is taken from the NSE website. Here we have assumed both the variables.

**6. Calculating Expected Return using CAPM**

```
expected_return = risk_free_rate + beta * (expected_market_return - risk_free_rate)
```

This is the CAPM formula to get the asset’s expected return in the current financial year.

**7. Printing Results and Plotting Security Market Line (SML)**

```
print("Beta (β):", beta)
print("Expected Return:", expected_return)
plt.figure(figsize=(10, 6))
plt.plot([0, 1], [risk_free_rate, expected_market_return], label='Market Portfolio', linestyle='-', color='blue')
plt.plot(beta, expected_return, marker='o', markersize=8, color='red', label='Asset')
plt.title('Security Market Line (SML)')
plt.xlabel('Beta (β)')
plt.ylabel('Expected Return')
plt.legend()
plt.grid(True)
plt.show()
```

## Conclusion

Here you go! In this article, we have learned what the Capital Asset Pricing Model ( CAPM ) is and how we have to implement different Python libraries like Pandas, Numpy, Matplotlib, etc. to perform financial analysis.

Hope you enjoyed reading it!!

Recommended: How to Scrape Yahoo Finance Data in Python using Scrapy