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]:
symbol = 'SPY'
capital = 10000
start = datetime.datetime(1900, 1, 1)
end = datetime.datetime.now()
Timeseries
In [4]:
# fetch timeseries, select, finalize
ts = pf.fetch_timeseries(symbol)
ts = pf.select_tradeperiod(ts, start, end, use_adj=True)
ts, start = pf.finalize_timeseries(ts, start)
# create tradelog and daily balance objects
tlog = pf.TradeLog(symbol)
dbal = pf.DailyBal()
In [5]:
ts
Out[5]:
Algorithm
In [6]:
pf.TradeLog.cash = capital
# loop through timeseries
for i, row in enumerate(ts.itertuples()):
date = row.Index.to_pydatetime()
end_flag = pf.is_last_row(ts, i)
# buy
if tlog.shares == 0:
tlog.buy(date, row.close)
# sell
elif end_flag:
tlog.sell(date, row.close)
# record daily balance
dbal.append(date, row.high, row.low, row.close)
Retrieve logs and get stats
In [7]:
tlog = tlog.get_log()
dbal = dbal.get_log(tlog)
stats = pf.stats(ts, tlog, dbal, capital)
Benchmark: Run, retrieve logs, generate stats
In [8]:
benchmark = pf.Benchmark(symbol, capital, start, end, use_adj=False)
benchmark.run()
benchmark.tlog, benchmark.dbal = benchmark.get_logs()
benchmark.stats = benchmark.get_stats()
Plot Equity Curves: Strategy vs Benchmark
In [9]:
pf.plot_equity_curve(dbal, benchmark=benchmark.dbal)
Dividends (strategy) vs No-Dividends (benchmark)
In [10]:
df = pf.summary(stats, benchmark.stats, metrics=pf.currency_metrics)
df
Out[10]:
In [11]:
extras = ('avg_month',)
df = pf.plot_bar_graph(stats, benchmark.stats, extras=extras)
df
Out[11]: