In [1]:
import pandas as pd
import matplotlib.pyplot as plt
import datetime
from talib.abstract import *
import pinkfish as pf
# format price data
pd.options.display.float_format = '{:0.2f}'.format
%matplotlib inline
In [2]:
# set size of inline plots
'''note: rcParams can't be in same cell as import matplotlib
or %matplotlib inline
%matplotlib notebook: will lead to interactive plots embedded within
the notebook, you can zoom and resize the figure
%matplotlib inline: only draw static images in the notebook
'''
plt.rcParams["figure.figsize"] = (10, 7)
Some global data
Note: By using an underscore, we can use a symbol multiple times in a portfolio under a different name. This is useful when you want to have a short and long position at the same time.
In [3]:
weights = {'^GSPC': 0.50, 'TLT': 0.30, 'GLD': 0.10, 'TLT_SHRT': 0.10}
symbols = list(weights.keys())
directions = {'^GSPC': pf.Direction.LONG, 'TLT': pf.Direction.LONG,
'GLD': pf.Direction.LONG, 'TLT_SHRT' : pf.Direction.SHORT}
capital = 10000
start = datetime.datetime(1900, 1, 1)
#start = datetime.datetime.strptime(pf.SP500_BEGIN, '%Y-%m-%d')
end = datetime.datetime.now()
use_cache = False
In [4]:
portfolio = pf.Portfolio()
ts = portfolio.fetch_timeseries(symbols, start, end, use_cache=use_cache)
ts
Out[4]:
In [5]:
# add calendar columns
ts = portfolio.calendar(ts)
In [6]:
ts, start = portfolio.finalize_timeseries(ts, start)
In [7]:
portfolio.init_trade_logs(ts, capital, margin=2)
pf.TradeLog.instance
Out[7]:
In [8]:
for i, row in enumerate(ts.itertuples()):
date = row.Index.to_pydatetime()
end_flag = pf.is_last_row(ts, i)
# rebalance on the first trading day of each month
if row.first_dotm or end_flag:
#portfolio.print_holdings(date, row)
for symbol in portfolio.symbols:
price = portfolio.get_row_column_price(row, symbol)
weight = 0 if end_flag else weights[symbol]
direction = directions[symbol]
portfolio.adjust_percent(date, price, weight, symbol, row, direction)
# record daily balance
portfolio.record_daily_balance(date, row)
In [9]:
rlog, tlog, dbal = portfolio.get_logs()
In [10]:
rlog.head()
Out[10]:
In [11]:
tlog.tail(100)
Out[11]:
In [12]:
dbal.tail()
Out[12]:
In [13]:
stats = pf.stats(ts, tlog, dbal, capital)
pf.print_full(stats)
In [14]:
benchmark = pf.Benchmark('SPY', capital, start, end, use_adj=True)
benchmark.run()
In [15]:
benchmark.tlog, benchmark.dbal = benchmark.get_logs()
In [16]:
benchmark.stats = benchmark.get_stats()
In [17]:
pf.plot_equity_curve(dbal, benchmark=benchmark.dbal)
In [18]:
pf.plot_trades(dbal, benchmark=benchmark.dbal)
In [19]:
df = pf.summary(stats, benchmark.stats, metrics=pf.currency_metrics)
df
Out[19]:
In [20]:
df = pf.plot_bar_graph(stats, benchmark.stats)
df
Out[20]:
In [ ]: