Published and maintained by Hanerest LLC.
In [6]:
# Initialization
%matplotlib inline
import datetime
import numpy as np
import pandas as pd
import pandas.io.data
import pandas.io.wb
from pandas import Series, DataFrame
import matplotlib.pyplot as plt, mpld3 # Require mpld3 library
import matplotlib as mpl
import Quandl
from yahoo_finance import Share
### SETTINGS ###
# Size for the charts
plt.rcParams['figure.figsize'] = 9, 6
# If your query exceeds the limits, you can get a free API key from Quandl.com
QUANDLKEY = ""
# Turn on the interactive charting for this notebook
mpld3.enable_notebook()
In [7]:
# S&P500 Index at Inflection Points
SP500 = pd.io.data.get_data_yahoo("^GSPC",
start=datetime.datetime(1900, 1, 1),
end=datetime.datetime(2015, 11, 1))['Adj Close']
SP500.plot()
Out[7]:
In [8]:
# S&P500 Index at Inflection Points in Log Scale
SP500.plot(logy=True)
Out[8]:
In [9]:
SP500PE = Quandl.get("MULTPL/SP500_PE_RATIO_MONTH", trim_start="1900-01-01", trim_end="2015-11-01", authtoken=QUANDLKEY, returns="pandas")
In [10]:
SP500PE["Average"]=SP500PE["Value"].mean()
SP500PE.plot()
Out[10]:
In [11]:
SP500PER = Quandl.get(["MULTPL/SP500_REAL_PRICE_MONTH","MULTPL/SP500_PE_RATIO_MONTH"], trim_start="1900-01-01", trim_end="2015-11-01", authtoken=QUANDLKEY, returns="pandas")
plt.scatter(SP500PER["MULTPL.SP500_REAL_PRICE_MONTH - Value"].pct_change(), SP500PER["MULTPL.SP500_PE_RATIO_MONTH - Value"])
plt.xlabel('Returns')
plt.ylabel('PE Ratio')
Out[11]:
In [12]:
# S&P500 Earning Per Share
SP500EPS = Quandl.get("MULTPL/SP500_EARNINGS_MONTH", trim_start="1900-01-01", trim_end="2015-11-01", authtoken=QUANDLKEY, returns="pandas")
SP500EPS.plot()
Out[12]:
In [13]:
# Dollar Index YoY Change
# Change to "FED/JRXWTFB_N_A" for annual data
DollarIndex = Quandl.get("FED/JRXWTFB_N_M", trim_start="2000-01-01", trim_end="2015-11-01", authtoken=QUANDLKEY, returns="pandas").pct_change()
DollarIndex.plot()
Out[13]:
In [14]:
# S&P 500 Sales Growth Rate by Year
SP500SALESG = Quandl.get("MULTPL/SP500_SALES_GROWTH_YEAR", trim_start="1900-01-01", trim_end="2015-11-01", authtoken=QUANDLKEY, returns="pandas")
SP500SALESG.plot()
Out[14]:
In [15]:
# Data from Vanguard ETFs Performance
# Value, Blend, Growth
# Large VTV, VV, VUG
# Mid VOE, VO, VOT
# Small VBR, VB, VBK
ticker_list = {'INTC': 'Intel',
'MSFT': 'Microsoft',
'IBM': 'IBM',
'BHP': 'BHP',
'RSH': 'RadioShack',
'TM': 'Toyota',
'AAPL': 'Apple',
'AMZN': 'Amazon',
'BA': 'Boeing',
'QCOM': 'Qualcomm',
'KO': 'Coca-Cola',
'GOOG': 'Google',
'SNE': 'Sony',
'PTR': 'PetroChina'}
In [16]:
styles = pd.io.data.get_data_yahoo(['VTV', 'VV', 'VUG', 'VOE', 'VO', 'VOT', 'VBR', 'VB', 'VBK'],
start=datetime.datetime(2006, 1, 1),
end=datetime.datetime(2015, 11, 1))['Adj Close']
In [17]:
# Calculating Cumulative Returns / Benchmark
styles = styles.resample("M")
style_returns = styles.pct_change()
style_index = (1 + style_returns).cumprod()
style_index["Benchmark"]=1
style_index.plot()
Out[17]:
In [18]:
# Returns for each styles
print "Value", "Blend", "Growth"
print "Large", style_index.VTV[-1], style_index.VV[-1], style_index.VUG[-1]
print "Mid", style_index.VOE[-1], style_index.VO[-1], style_index.VOT[-1]
print "Small", style_index.VBR[-1], style_index.VB[-1], style_index.VBK[-1]
In [19]:
# Data from SPDR ETFs Performance
# - Financial (XLF)
# - Health Care (XLV)
# - Technology (XLK)
# - Energy (XLE)
# - Consumer Discretionary (XLY)
# - Consumer Stable (XLP)
# - Industrials (XLI)
# - Utilities (XLU)
In [20]:
sectors = pd.io.data.get_data_yahoo(['XLF', 'XLV', 'XLK', 'XLE', 'XLY', 'XLP', 'XLI', 'XLU', 'SPY'],
start=datetime.datetime(2005, 1, 1),
end=datetime.datetime(2015, 11, 1))['Adj Close']
In [21]:
# Calculating Cumulative Returns / Benchmark
sectors = sectors.resample("M")
sectors_returns = sectors.pct_change()
sectors_index = (1 + sectors_returns).cumprod()
sectors_index["Benchmark"]=1
sectors_index.plot()
Out[21]:
In [22]:
# Calculating Beta
"""
# create a time-series of monthly data points
rts = df.resample('M',how='last') # Individual df
rbts = dfb.resample('M',how='last') # Market dfb
"""
dfsm = pd.DataFrame({'Stock' : sectors.XLP,
'Market' : sectors.SPY},
index=sectors.index)
dfsmc = dfsm.pct_change()
dfsmc = dfsmc.dropna()
covmat = np.cov(dfsmc["Stock"],dfsmc["Market"])
beta = covmat[0,1]/covmat[1,1]
alpha= np.mean(dfsm["Stock"])-beta*np.mean(dfsm["Market"])
print beta
In [23]:
# Sectors Correlation Table
sectors_corr = sectors.corr()
sectors_corr
Out[23]:
In [24]:
# Sectors Correlations Chart
plt.imshow(sectors_corr, cmap='hot', interpolation='none')
plt.colorbar()
plt.xticks(range(len(sectors_corr)), sectors_corr.columns)
plt.yticks(range(len(sectors_corr)), sectors_corr.columns);
In [25]:
# Risk/Return Table
plt.scatter(sectors_returns.mean(), sectors_returns.std())
plt.xlabel('Expected returns')
plt.ylabel('Risk')
for label, x, y in zip(sectors_returns.columns, sectors_returns.mean(), sectors_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'))
In [26]:
# Others Information
# Retrieved using Yahoo_Finance Library https://pypi.python.org/pypi/yahoo-finance/1.2.1
sector = Share("XLF")
print sector.get_dividend_yield(), sector.get_price_earnings_ratio(), sector.get_price_book()
In [27]:
# VIX Index
VIX = pd.io.data.get_data_yahoo("^VIX",
start=datetime.datetime(2008, 1, 1),
end=datetime.datetime(2015, 11, 1))['Adj Close']
In [28]:
# Vix Chart
VIX.plot()
Out[28]:
In [29]:
# Pullbacks
PULLBACKFILTER = 0.05
SP500_change = SP500.pct_change()
SP500_change[SP500_change>PULLBACKFILTER]
Out[29]:
In [30]:
# SP500 Annual Returns
SP500AR = SP500.resample("A").pct_change()
SP500AR.plot(kind="bar")
Out[30]:
In [31]:
# 10 Years Treasury Yields
T10 = pd.io.data.get_data_yahoo("^TNX",
start=datetime.datetime(1900, 1, 1),
end=datetime.datetime(2015, 11, 1))['Adj Close']
In [32]:
# 10 Years Treasury Yields Chart
T10.plot()
Out[32]:
In [33]:
# Relationship between Interest Rates and Equities
T10R = T10.resample("W")["19970101":]
SP500R = SP500.resample("W")["19970101":].pct_change()
plt.scatter(T10R, SP500R)
plt.xlabel("10 Year Treasury Bill")
plt.ylabel("S&P500 Returns")
Out[33]:
In [34]:
# Covariance Coefficient
# Rolling two year?
In [35]:
# GDP Growth Rate
USGDP = Quandl.get("FRED/GDP", trim_start="1900-01-01", trim_end="2015-11-01", authtoken=QUANDLKEY, returns="pandas")
In [36]:
# GDP at Log Scale
USGDP.plot(logy=True)
Out[36]:
In [37]:
# GDP YoY Change
USGDPYOY = USGDP.resample("A").pct_change()
USGDPYOY.plot()
print USGDPYOY.mean()
In [38]:
# Global GDP Growth Comparison
# List of country code: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3
GlobalGDP = pd.io.wb.download(indicator='NY.GDP.MKTP.KD.ZG', country=['USA', 'CHN', 'GBR', 'DEU', 'JPN'], start=2000, end=2015)
In [39]:
GlobalGDP.unstack().T
Out[39]:
In [40]:
GlobalGDP.unstack().T.plot()
Out[40]:
In [41]:
# Inflation
Inflation = Quandl.get("FRED/DDOE02USA086NWDB", trim_start="1950-01-01", trim_end="2015-11-01", authtoken=QUANDLKEY, returns="pandas")
In [42]:
Inflation.plot()
Out[42]:
In [43]:
# Household Debt to GDP
HouseholdDebt = Quandl.get(["FRED/HDTGPDUSQ163N", "FRED/HDTGPDDEA163N", "FRED/HDTGPDFRA163N"], trim_start="1900-01-01", trim_end="2015-11-01", authtoken=QUANDLKEY, returns="pandas")
In [44]:
HouseholdDebt.resample("A").plot()
Out[44]:
In [45]:
# 10 Year Treasury Yield
T10 = pd.io.data.get_data_yahoo("^TNX",
start=datetime.datetime(1900, 1, 1),
end=datetime.datetime(2015, 11, 1))['Adj Close']
T10.plot()
Out[45]:
In [46]:
# Federal Fund Rate
# Household Debt to GDP
FundRate = Quandl.get("FRED/FEDFUNDS", trim_start="1900-01-01", trim_end="2015-11-01", authtoken=QUANDLKEY, returns="pandas")
FundRate.plot()
Out[46]:
In [47]:
# Yield Curve
YieldCurve = Quandl.get("USTREASURY/YIELD", collapse="monthly", trim_start="1950-01-01", trim_end="2015-11-01", authtoken=QUANDLKEY, returns="pandas")
YieldCurve.plot()
Out[47]:
In [48]:
# Newest Yield Curve
YieldCurve[-1:].T.plot()
Out[48]:
General Asset Class:
In [49]:
assets = pd.io.data.get_data_yahoo(["ACWI", "LAG", "DJP", "FRI"],
start=datetime.datetime(2010, 1, 1),
end=datetime.datetime(2015, 11, 1))['Adj Close']
In [50]:
assets.plot()
Out[50]:
In [51]:
# Calculating Cumulative Returns / Benchmark
assets_returns = assets.pct_change()
assets_index = (1 + assets_returns).cumprod()
assets_index["Benchmark"]=1
assets_index.plot()
Out[51]:
In [52]:
# Sectors Correlation Table
assets_corr = assets.corr()
assets_corr
Out[52]:
In [53]:
# Sectors Correlations Chart
plt.imshow(assets_corr, cmap='hot', interpolation='none')
plt.colorbar()
plt.xticks(range(len(assets_corr)), assets_corr.columns)
plt.yticks(range(len(assets_corr)), assets_corr.columns);
In [55]:
# Risk/Return Table
plt.scatter(assets_returns.mean(), assets_returns.std())
plt.xlabel('Expected returns')
plt.ylabel('Risk')
for label, x, y in zip(assets_returns.columns, assets_returns.mean(), assets_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'))
In [ ]: