import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.graph_objs as go
import plotly.plotly as py
sns.set_style('whitegrid')
import cufflinks as cf
import datetime
import quandl
from pandas_datareader import data, wb
from scipy import stats
%matplotlib inline
py.sign_in("dattatele","93reCjIosFgiul4JuaIb")
# Widget related imports
from ipywidgets import interactive
from IPython.display import Audio, display
import ipywidgets as widgets
from IPython.display import display, clear_output, Javascript
from traitlets import Unicode
# nbconvert related imports
from nbconvert import get_export_names, export_by_name
from nbconvert.writers import FilesWriter
from nbformat import read, NO_CONVERT
from nbconvert.utils.exceptions import ConversionException
import pandas_datareader as web
notebook_name = widgets.Text()
js = """IPython.notebook.kernel.widget_manager.get_model('%s').then(function(model) {
model.set('value', IPython.notebook.notebook_name);
model.save();
});
""" % notebook_name.model_id
display(Javascript(data=js))
filename = notebook_name.value
filename
exporter_names = widgets.Dropdown(options=get_export_names(), value='html')
export_button = widgets.Button(description="Export")
download_link = widgets.HTML(visible=False)
quandl.ApiConfig.api_key = 'ygw7cuU2fx8t7pgxAtcm'
cof = quandl.get_table('WIKI/PRICES', ticker = 'COF', date = { 'gte': '2007-08-07', 'lte': '2017-08-07' })
cof['date'] = pd.to_datetime(cof['date'])
cof.set_index('date',inplace=True)
cof.head()
jpm = quandl.get_table('WIKI/PRICES', ticker = ['JPM'], date = { 'gte': '2007-08-07', 'lte': '2017-08-07' })
jpm['date'] = pd.to_datetime(jpm['date'])
jpm.set_index('date',inplace=True)
jpm.head()
tickers = ['JPM', 'COF']
bank_stocks = pd.concat([cof, jpm],axis=1,keys=tickers)
bank_stocks.head()
bank_stocks.columns.names = ['Bank Ticker','Stock Info']
bank_stocks.head()
bank_stocks.xs(key='close',axis=1,level='Stock Info').max()
bank_stocks['JPM'].max()
returns = pd.DataFrame()
for tick in tickers:
returns[tick+' Return'] = bank_stocks[tick]['close'].pct_change()
returns.head()
sns.pairplot(returns[1:],size=3.5)
returns.min()
returns.idxmin()
returns.idxmax()
returns.std()
for tick in tickers:
bank_stocks[tick]['close'].plot(figsize=(16,6),label=tick)
plt.legend(loc=2)
bank_stocks.xs(key='close',axis=1,level='Stock Info').iplot()
plt.figure(figsize=(16,6))
cof['close'].loc['2008-01-01':'2010-01-01'].rolling(window=30).mean().plot(label='30 Day Avg')
cof['close'].loc['2008-01-01':'2010-01-01'].plot(label='COF CLOSE')
plt.legend()
plt.figure(figsize=(16,6))
jpm['close'].loc['2008-01-01':'2010-01-01'].rolling(window=30).mean().plot(label='30 Day Avg')
jpm['close'].loc['2008-01-01':'2010-01-01'].plot(label='JPM CLOSE')
plt.legend()
plt.figure(figsize=(16,6))
cof['close'].loc['2016-01-01':'2017-07-07'].rolling(window=30).mean().plot(label='30 Day Avg')
cof['close'].loc['2016-01-01':'2017-07-07'].plot(label='COF CLOSE')
plt.legend()
plt.figure(figsize=(16,6))
jpm['close'].loc['2016-01-01':'2017-07-07'].rolling(window=30).mean().plot(label='30 Day Avg')
jpm['close'].loc['2016-01-01':'2017-07-07'].plot(label='JPM CLOSE')
plt.legend()
cof[['open', 'high', 'low', 'close']].loc['2016-01-01':'2017-07-07'].iplot(kind='candle')
cof['close'].loc['2016-01-01':'2017-07-017'].ta_plot(study='sma',title='Simple Moving Averages')
cof['close'].loc['2016-01-01':'2017-07-07'].ta_plot(study='boll')
jpm['close'].loc['2016-01-01':'2017-07-07'].ta_plot(study='boll')
jpm['close'].resample('M').mean().plot(kind='bar', figsize=(16,6))
cof['close'].resample('M').mean().plot(kind='bar', figsize=(16,6))
bank_stocks[['JPM', 'COF']].expanding().mean().plot(figsize=(16,6))
bank_stocks[['JPM', 'COF']].expanding().mean().iplot()
jpm['First Difference'] = jpm['open'] - jpm['open'].shift(1)
jpm['First Difference'].plot(figsize=(16,6))
cof['First Difference'] = cof['open'] - cof['open'].shift(1)
cof['First Difference'].plot(figsize=(16,6))
# Normalized return - like Cumulative daily return
for stock_df in (cof,jpm):
stock_df['Normed Return'] = stock_df['adj_close'] / stock_df.iloc[0]['adj_close']
cof.head()
cof.tail()
jpm.head()
jpm.tail()
A portfolio is a set of weighted securities. Returns of portfolio
Weights for each company? Market Cap(number of shares*price)
CAPM equation, Like simple linear regeression, y=mx+b
CAPM equation describes the return of some individual stock 'i'.
CAPM states that aplha should be expected to be zero.
It basically implies that you can not beat the general marke, alpha is random and cannot be predicted.
Return of Portfolio,
Beta Term - there will be relationship between our portfolio return and the overall market return.
CAPM says that the alpha term can not be predicted, we will fundamentally disagree with that model of thinking
Create Strategies that allow us to have significant alpha terms, [i.e. beating the barket]
import pandas_datareader as web
start = pd.to_datetime('2007-08-07')
end = pd.to_datetime('2017-08-07')
spy_etf = web.DataReader('SPY', 'google',start,end)
spy_etf.head()
jpm['close'].plot(label='JPM', figsize=(10,8))
cof['close'].plot(label='COF')
spy_etf['Close'].plot(label='SPY Index')
plt.legend()
jpm['cumulative'] = jpm['close']/jpm['close'].iloc[0]
cof['cumulative'] = cof['close']/cof['close'].iloc[0]
spy_etf['cumulative'] = spy_etf['Close']/spy_etf['Close'].iloc[0]
jpm['cumulative'].plot(label='JPM',figsize = (16,6))
cof['cumulative'].plot(label='COF')
spy_etf['cumulative'].plot(label='SPY')
plt.legend()
jpm['Daily Return'] = jpm['close'].pct_change(1)
cof['Daily Return'] = cof['close'].pct_change(1)
spy_etf['Daily Return'] = spy_etf['Close'].pct_change(1)
plt.scatter(jpm['Daily Return'],cof['Daily Return'],alpha=0.25)
beta,alpha,r_value,p_value,std_err = stats.linregress(jpm['Daily Return'].iloc[1:],
cof['Daily Return'].iloc[1:])
beta
alpha
r_value
This is very useful tool to share and convert the file into different file format. source
file_writer = FilesWriter()
def export(name, nb):
# Get a unique key for the notebook and set it in the resources object.
notebook_name = name[:name.rfind('.')]
resources = {}
resources['unique_key'] = notebook_name
resources['output_files_dir'] = '%s_files' % notebook_name
# Try to export
try:
output, resources = export_by_name(exporter_names.value, nb)
except ConversionException as e:
download_link.value = "<br>Could not export notebook!"
else:
write_results = file_writer.write(output, resources, notebook_name=notebook_name)
download_link.value = "<br>Results: <a href='files/{filename}'><i>\"{filename}\"</i></a>".format(filename=write_results)
download_link.visible = True
def handle_export(widget):
with open(filename, 'r') as f:
export(filename, read(f, NO_CONVERT))
export_button.on_click(handle_export)
display(exporter_names, export_button, download_link)