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()
use_adj=True
Prepare timeseries
In [4]:
# fetch and select timeseries
ts = pf.fetch_timeseries(symbol)
ts = pf.select_tradeperiod(ts, start, end, use_adj=use_adj)
# Add technical indicator: day sma regime filter
ts['regime'] = \
pf.CROSSOVER(ts, timeperiod_fast=50, timeperiod_slow=200)
# Finalize the time series before implementing trading strategy
ts, start = pf.finalize_timeseries(ts, start)
# Create Trade Log (tlog); Create Daily Balance (dbal)
tlog = pf.TradeLog(symbol)
dbal = pf.DailyBal()
Algo: Buy when 50 day ma crosses above 200 day ma. Sell when 50 day ma crosses below 200 day ma.
In [5]:
pf.TradeLog.cash = capital
for i, row in enumerate(ts.itertuples()):
date = row.Index.to_pydatetime()
high = row.high; low = row.low; close = row.close;
end_flag = pf.is_last_row(ts, i)
# buy
if tlog.shares == 0 and row.regime > 0 and ts['regime'][i-1] < 0:
tlog.buy(date, close)
# sell
elif tlog.shares > 0 and (row.regime < 0 or end_flag):
tlog.sell(date, close)
# record daily balance
dbal.append(date, high, low, close)
Retrieve logs
In [6]:
tlog = tlog.get_log()
dbal = dbal.get_log(tlog)
Generate strategy stats - display all available stats
In [7]:
stats = pf.stats(ts, tlog, dbal, capital)
pf.print_full(stats)
Benchmark: Run, retrieve logs, generate stats
In [8]:
benchmark = pf.Benchmark(symbol, capital, start, end, use_adj=use_adj)
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)
Plot Trades
In [10]:
pf.plot_trades(dbal, benchmark=benchmark.dbal)
Strategy vs Benchmark
In [11]:
df = pf.summary(stats, benchmark.stats, metrics=pf.currency_metrics)
df
Out[11]:
In [12]:
extras = ('avg_month',)
df = pf.plot_bar_graph(stats, benchmark.stats, extras=extras)
df
Out[12]:
In [ ]: