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
In [3]:
symbols = ['SPY', 'TLT', 'GLD']
weights = {'SPY': 0.50, 'TLT': 0.40, 'GLD': 0.10}
directions = {'SPY': pf.Direction.LONG, 'TLT': pf.Direction.LONG, 'GLD': pf.Direction.LONG}
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)
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)
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 = getattr(row, symbol + '_close')
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()
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 [21]:
returns = dbal['close']
returns.tail()
Out[21]:
In [22]:
benchmark_returns = benchmark.dbal['close']
benchmark_returns.tail()
Out[22]:
In [23]:
pf.prettier_graphs(returns, benchmark_returns,
label1='Strategy', label2='Benchmark',
points_to_plot=5000)