Last active
July 19, 2024 05:08
-
-
Save nathanvy/06fe459f636753fc56e7607ce8385d3d to your computer and use it in GitHub Desktop.
Quick script to compute CAPM-derived cost of equity
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import yfinance as yf | |
import numpy as np | |
def get_data(ticker, start_date, end_date): | |
stock_data = yf.download(ticker, start=start_date, end=end_date) | |
return stock_data['Adj Close'] | |
def compute_beta(stock_prices, index_prices): | |
stock_returns = stock_prices.pct_change().dropna() | |
index_returns = index_prices.pct_change().dropna() | |
covariance_matrix = np.cov(stock_returns, index_returns) | |
covariance = covariance_matrix[0, 1] | |
variance = covariance_matrix[1, 1] | |
beta = covariance / variance | |
return beta | |
def capm(r_free, r_market, beta): | |
return r_free + (beta * (r_market - r_free)) | |
stock_ticker = 'PLTR' | |
index_ticker = '^GSPC' # Yahoo calls the S&P 500 GSPC instead of SPX like everyone else normal | |
start_date = '2020-09-30' | |
end_date = '2023-01-01' | |
spx_return_10y = 0.1086 # 10 year 10.86% annual return per https://www.spglobal.com/spdji/en/indices/equity/sp-500/#overview | |
us10y = 0.042 # US10Y yield per FRED/St Louis Fed | |
stock_prices = get_data(stock_ticker, start_date, end_date) | |
index_prices = get_data(index_ticker, start_date, end_date) | |
beta = compute_beta(stock_prices, index_prices) | |
coe = capm(us10y, spx_return_10y, beta) | |
print(f"The beta of {stock_ticker} relative to {index_ticker} is: {beta} for a cost of equity of: {coe}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment