In finance, the capital asset pricing model (CAPM) is a model used to determine a theoretically appropriate required rate of return of an asset, to make decisions about adding assets to a well-diversified portfolio.
Along with such parameters as the expected return of the market and the expected return of a theoretical risk-free asset, the model takes into account the asset's sensitivity to non-diversifiable risk, often represented by the quantity beta (β).
The beta coefficient is a measure of the volatility, or systematic risk, of an individual stock in comparison to the volatility of the entire market.
Let's calculate the beta coefficient for the CAMP model.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import datetime
First, we shall go to Yahoo Finance and download The Royal Bank of Scotland Group plc (RBS) historical prices and the historical data on S&P 500 Index.
We are interested in monthly values in particular:
df_rbs = pd.read_csv(r'C:\Users\user-dns\Desktop\Disc R\Python Basics\RBS.csv', parse_dates = True, index_col = 'Date')
df_gspc = pd.read_csv(r'C:\Users\user-dns\Desktop\Disc R\Python Basics\^GSPC.csv', parse_dates = True, index_col = 'Date')
df_rbs.head()
df = pd.concat([df_rbs['Close'], df_gspc['Close']], axis = 1)
df.columns = ['RBS','^GSPC']
df.head()
df_returns = df.pct_change(1).dropna()
df_returns.head()
By this point, we have selected the Close values of RBS and S&P 500, merged the two tables and calculated montly percentage change.
Let's plot now the monthly percentage change values to see how RBS prices and the S&P500 index related to each other historically:
plt.figure(figsize=(20,10))
df_returns['RBS'].plot()
df_returns['^GSPC'].plot()
plt.ylabel('Daily Return of The Royal Bank of Scotland Group plc (RBS) VS S&P500')
plt.show
import seaborn as sns
X = df_returns['^GSPC']
y = df_returns['RBS']
sns.regplot(X, y, data = df_returns)
Finally, we use OLS linear regression to find the beta coefficient:
from sklearn.linear_model import LinearRegression
lm = LinearRegression()
X = np.asanyarray(df_returns[['^GSPC']])
y = np.asanyarray(df_returns[['RBS']])
lm.fit (X, y)
print ('Beta coefficient: ', lm.coef_)
An alternative way is to use Statsmodels library.
Along with the coefficient of relative volatility Beta, it has a detailed summary of the regression results:
import statsmodels.api as sm
X = sm.add_constant(X)
model = sm.OLS(y, X)
results = model.fit()
print(results.summary())
Let's see if the coefficient we got is close enough to the official one.
Yep, it's pretty close indeed:
from IPython.display import Image
Image('RBS.jpg', width=700, height=700)