from pandas_datareader import data, wb
import pandas as pd
import numpy as np
import datetime
%matplotlib inline
from ipywidgets import interactive
from IPython.display import Audio, display
# Widget related imports
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
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)
start = datetime.datetime(2006, 1, 1)
end = datetime.datetime(2016, 12, 1)
start
#Bank of America
BAC = data.DataReader("BAC", 'google', start, end)
# CitiGroup
C = data.DataReader("c", 'google', start, end)
#Goldman sachs
GS = data.DataReader("GS", 'google', start, end)
#JPMorgan Chase
JPM = data.DataReader("JPM", 'google', start, end)
# Morgan Stanley
MS = data.DataReader("MS", 'google', start, end)
# Wells Fargo
WFC = data.DataReader("WFC", 'google', start, end)
# Could also do this for a Panel Object
df = data.DataReader(['BAC', 'C', 'GS', 'JPM', 'MS', 'WFC'],'google', start, end)
tickers = ['BAC', 'C', 'GS', 'JPM', 'MS', 'WFC']
tickers
bank_stocks = pd.concat([BAC, C, GS, JPM, MS, WFC],axis=1)
bank_stocks
bank_stocks = pd.concat([BAC, C, GS, JPM, MS, WFC], axis=1,keys=tickers)
bank_stocks
bank_stocks.columns.names = ['Bank Ticker','Stock Info']
bank_stocks.head()
bank_stocks.xs(key='Close',axis=1,level='Stock Info').max()
bank_stocks['BAC'].max()
returns = pd.DataFrame()
for tick in tickers:
returns[tick+' Return'] = bank_stocks[tick]['Close'].pct_change()
returns.head()
#returns[1:]
import seaborn as sns
sns.pairplot(returns[1:])
returns.min()
# Worst Drop (4 of them on Inauguration day)
returns.idxmin()
# Best Single Day Gain
# citigroup stock split in May 2011, but also JPM day after inauguration.
returns.idxmax()
returns.std() # Citigroup riskiest
returns.head()
returns.loc['2015-01-01':'2015-12-31'].std() # Very similar risk profiles, but Morgan Stanley or BofA
sns.distplot(returns.loc['2015-01-01':'2015-12-31']['MS Return'],color='green',bins=100)
sns.distplot(returns.loc['2008-01-01':'2008-12-31']['C Return'],color='red',bins=100)
import matplotlib.pyplot as plt
import plotly.graph_objs as go
import plotly.plotly as py
import plotly.offline as offline
import seaborn as sns
sns.set_style('whitegrid')
%matplotlib inline
# Optional Plotly Method Imports
import plotly
import cufflinks as cf
cf.go_offline()
offline.init_notebook_mode()
import matplotlib.pyplot as plt
import plotly.graph_objs as go
import plotly.plotly as py
import plotly.offline as offline
import seaborn as sns
sns.set_style('whitegrid')
%matplotlib inline
# Optional Plotly Method Imports
import plotly
import cufflinks as cf
cf.go_offline()
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
from plotly import __version__
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
init_notebook_mode(connected=True)
import matplotlib.pyplot as plt
import plotly.graph_objs as go
import plotly.plotly as py
import seaborn as sns
sns.set_style('whitegrid')
%matplotlib inline
import cufflinks as cf
init_notebook_mode(connected=True)
init_notebook_mode(connected=True)
py.sign_in("dattatele","93reCjIosFgiul4JuaIb")
for tick in tickers:
bank_stocks[tick]['Close'].plot(figsize=(12,4),label=tick)
plt.legend()
bank_stocks.xs(key='Close',axis=1,level='Stock Info').plot()
bank_stocks.xs(key='Close',axis=1,level='Stock Info').iplot()
banK_stock_df = bank_stocks.xs(key='Close',axis=1,level='Stock Info')
# plotly
banK_stock_df.iplot()
plt.figure(figsize=(12,6))
BAC['Close'].loc['2008-01-01':'2009-01-01'].rolling(window=30).mean().plot(label='30 Day Avg')
BAC['Close'].loc['2008-01-01':'2009-01-01'].plot(label='BAC CLOSE')
plt.legend()
sns.heatmap(bank_stocks.xs(key='Close',axis=1,level='Stock Info').corr(),annot=True)
sns.clustermap(bank_stocks.xs(key='Close',axis=1,level='Stock Info').corr(),annot=True)
close_corr = bank_stocks.xs(key='Close',axis=1,level='Stock Info').corr()
close_corr.iplot(kind='heatmap',colorscale='rdylbu')
BAC[['Open', 'High', 'Low', 'Close']].loc['2015-01-01':'2016-01-01'].iplot(kind='candle')
MS['Close'].loc['2015-01-01':'2016-01-01'].ta_plot(study='sma',periods=[13,21,55],title='Simple Moving Averages')
BAC['Close'].loc['2015-01-01':'2016-01-01'].ta_plot(study='boll')
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)