Execute the following steps to implement the CAPM in Python.
- Import the libraries:
import pandas as pd
import yfinance as yf
import statsmodels.api as sm
- Specify the risky asset and the time horizon:
RISKY_ASSET = 'AMZN'
MARKET_BENCHMARK = '^GSPC'
START_DATE = '2014-01-01'
END_DATE = '2018-12-31'
- Download the necessary data from Yahoo Finance:
df = yf.download([RISKY_ASSET, MARKET_BENCHMARK],
start=START_DATE,
end=END_DATE,
adjusted=True,
progress=False)
- Resample to monthly data and calculate the simple returns:
X = df['Adj Close'].rename(columns={RISKY_ASSET: 'asset',
MARKET_BENCHMARK: 'market'})
.resample('M')
.last()
.pct_change()
.dropna()
- Calculate beta using the covariance approach:
covariance = X.cov().iloc[0,1]
benchmark_variance = X.market.var()
beta = covariance / benchmark_variance
The result of the code is beta = 1.6709.
- Prepare the input and estimate the CAPM as a linear regression:
y = X.pop('asset')
X = sm.add_constant(X)
capm_model = sm.OLS(y, X).fit()
print(capm_model.summary())
The following image shows the results of estimating the CAPM model:
These results indicate that the beta (denoted as market here) is equal to 1.67, which means that Amazon's returns are 67% more volatile than the market (proxied by S&P 500). The value of the intercept is relatively small and statistically insignificant at the 5% significance level.