In [1]:
%load_ext autoreload
%autoreload 2
In [2]:
api_key = "API_KEY"
rh_user = "user"
rh_pass = "pass"
demo_run = True
In [3]:
import pandas as pd
import numpy as np
In [4]:
from pyrh import Robinhood
if not demo_run:
client = Robinhood(username=rh_user, password=rh_pass)
client.login()
else:
client = None
In [5]:
from backend.robinhood_data import RobinhoodData
rh = RobinhoodData('data/', client)
if demo_run:
demo_orders = rh.demo_orders()
demo_dividends= rh.demo_dividends()
else:
demo_orders = None
demo_dividends= None
dividends, orders, open_positions, closed_positions = rh.download(demo_orders, demo_dividends)
In [6]:
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
from backend.market_data import download_save_market_data
market = download_save_market_data(
api_key=api_key,
symbols=orders.symbol.unique(),
start_date=orders.date.min(),
end_date=pd.Timestamp("today", tz='UTC'))
In [7]:
from backend.portfolio_models import PortfolioModels
import empyrical as emp
In [8]:
# main calculations section
ptf = PortfolioModels('data')
summary = ptf.portfolio_summary()
stocks = ptf.stocks_risk()
df_corr, df_cov = ptf.stocks_correlation()
ptf_stats = ptf.portfolio_stats()
markowitz = ptf.markowitz_portfolios()
investment, dividends = ptf.portfolio_returns()
In [9]:
summary
Out[9]:
In [10]:
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib.dates as mdates
sns.set_style("whitegrid")
MY_DPI = 450
f, ax1 = plt.subplots(figsize=(9, 4), dpi=MY_DPI)
ax2 = ax1.twinx()
ax1.plot(investment, linewidth=1, color='#67a9cf')
ax1.axhline(y=0, color='#ca0020', linestyle='-', linewidth=0.5)
ax1.set_ylabel("Portfolio returns")
ax2.plot(dividends, linewidth=0.5, color='#ef8a62')
ax2.set_ylabel("Dividends")
# format y-axis
ax1.get_yaxis().set_major_formatter(
ticker.FuncFormatter(lambda x, p: '${:.0f}'.format(x)))
ax2.get_yaxis().set_major_formatter(
ticker.FuncFormatter(lambda x, p: '${:.0f}'.format(x)))
# format dates and grids
date_fmt = mdates.DateFormatter('%b-%Y')
ax1.xaxis.set_major_formatter(date_fmt)
ax1.grid(False, axis='both', linestyle='-', linewidth=0.5, color="#deebf7")
ax1.grid(b=None, axis='y')
ax2.grid(False, axis='both', linestyle='-', linewidth=0.5, color="#deebf7")
ax2.grid(b=None, axis='y')
plt.show()
In [11]:
ptf_stats
Out[11]:
In [12]:
stocks
Out[12]:
In [13]:
import seaborn as sns
fig, ax = plt.subplots(figsize=(10,10))
sns.heatmap(ax=ax, data=df_corr, center=0, annot=True)
Out[13]:
In [14]:
for l in markowitz:
print(l['name'])
print(l['weights'])
print('\n')