In [1]:
%matplotlib inline
In [2]:
# Make the plots larger
from IPython.core.pylabtools import figsize
figsize(15, 5)
In [3]:
import pandas as pd
import pandas.io.data as web
from matplotlib import pyplot as plt
Get stock prices for Google, Apple, Marcosoft and Facebook during 2013-01-01 - 2013-12-31
In [4]:
prices = web.get_data_yahoo(['GOOGL', 'AAPL', 'MSFT', 'FB'], start='2013-01-01', end='2013-12-31')['Adj Close']
prices.head()
Out[4]:
In [5]:
prices.plot()
Out[5]:
Get qoutes of S&P 500 during 2013-01-01 - 2013-12-31
In [6]:
gspc = web.get_data_yahoo('^GSPC', start='2013-01-01', end='2013-12-31')['Adj Close']
gspc.name = '^GSPC'
gspc.head()
Out[6]:
Get risk free rate
In [7]:
risk_free_rate = web.get_quote_yahoo('^TNX')['last'][0] / 100
risk_free_rate
Out[7]:
In [8]:
daily_risk_free_rate = (1 + risk_free_rate) ** (1 / len(gspc)) - 1
daily_risk_free_rate
Out[8]:
In [9]:
def capm_analysis(stock, index, risk_free_rate, window=None):
stock_ret = stock.pct_change().dropna()
index_ret = index.pct_change().dropna()
stock_premium = stock_ret - risk_free_rate
index_premium = index_ret - risk_free_rate
window = window or len(index_ret)
betas = pd.ols(y=stock_premium, x=index_premium, window=window).beta
return betas.rename(columns={'x': 'beta', 'intercept': 'alpha'})
In [10]:
capm_analysis(prices['GOOGL'], gspc, daily_risk_free_rate).iloc[0]
Out[10]:
In [11]:
pd.DataFrame({stock: capm_analysis(prices[stock], gspc, daily_risk_free_rate).iloc[0]
for stock in prices})
Out[11]:
In [12]:
capm_analysis(prices['GOOGL'], gspc, daily_risk_free_rate, 30)['beta'].plot()
Out[12]:
In [13]:
pd.DataFrame({stock: capm_analysis(prices[stock], gspc, daily_risk_free_rate, 30)['beta']
for stock in prices}).plot()
Out[13]:
In [14]:
returns = prices.pct_change().dropna()
corr = returns.corr()
corr
Out[14]:
In [15]:
from statsmodels.graphics.correlation import plot_corr
plot_corr(corr, cmap='hot')
None
In [16]:
pd.scatter_matrix(returns, diagonal='kde', figsize=(10, 10))
Out[16]:
In [17]:
plt.scatter(returns.mean(), returns.std())
plt.xlabel('Expected returns')
plt.ylabel('Risk')
for label, x, y in zip(returns.columns, returns.mean(), returns.std()):
plt.annotate(
label,
xy = (x, y), xytext = (20, -20),
textcoords = 'offset points', ha = 'right', va = 'bottom',
bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.5),
arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))