import numpy as np
import matplotlib
matplotlib.use('TKAgg')
%matplotlib inline
import pylab as py
py.ion()
import pandas as pd
import sys,os
import datetime
file_path = os.path.dirname(os.path.realpath('__file__'))
sys_path='%s/..'%file_path
sys.path.append(sys_path)
from investmenttools import PortfolioBuilder as PB
reload(PB)
## Get Data for S&P Index Portfolio
sp=PB.get_historical_closes(['SPY','IVV','VOO'],datetime.datetime(2001,1,1),datetime.datetime(2017,8,17))
sp.dropna(inplace=True)
sp.head(5)
## Get cumulative returns and plot
dp=sp.pct_change()
cp=(1+dp).cumprod()
cp.plot()
## Get Data for Govt index funds
bp=PB.get_historical_closes(['SHY','VGSH','SCHO','TUZ'],datetime.datetime(2001,1,1),datetime.datetime(2017,8,17))
bp.dropna(inplace=True)
bp.head(5)
bdp=bp.pct_change()
bcp=(1+bdp).cumprod()
bcp.plot()
### Rebalance Buffet-Portfolio and plot cumulative returns since 2004
portfolio=PB.Backtest_Annual_Rebalance(['SPY','SHY'],[.9,.1],datetime.datetime(2004,1,1),datetime.datetime(2017,8,17)\
,initial=10000)
portfolio.dropna(inplace=True)
portfolio.head(5)
## Plot the cumulative returns as well as the number of equity units for eash of the two funds in the portfolio
py.figure(figsize=(15,4))
py.subplot(131);portfolio[['Total','Cash']].sum(axis=1).plot();
py.xticks(fontsize=15,fontweight='bold');
py.yticks(fontsize=15,fontweight='bold');
py.legend(['Buffet Portfolio'])
py.subplot(132);portfolio['N_SPY'].plot();
py.xticks(fontsize=15,fontweight='bold');
py.yticks(fontsize=15,fontweight='bold');
py.legend(['SPY stocks'])
py.subplot(133);portfolio['N_SHY'].plot();
py.xticks(fontsize=15,fontweight='bold');
py.yticks(fontsize=15,fontweight='bold');
py.legend(['SHY stocks'])