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)
In [3]:
pf.DEBUG = True
Some global data
In [4]:
symbol = '^GSPC'
#symbol = 'SPY'
capital = 10000
start = datetime.datetime(1900, 1, 1)
end = datetime.datetime.now()
Define Strategy Class
In [5]:
class Strategy:
def __init__(self, symbol, capital, start, end):
self._symbol = symbol
self._capital = capital
self._start = start
self._end = end
def _algo(self):
pf.TradeLog.cash = self._capital
for i, row in enumerate(self._ts.itertuples()):
date = row.Index.to_pydatetime()
high = row.high; low = row.low; close = row.close
end_flag = pf.is_last_row(self._ts, i)
shares = 0
# buy
if self._tlog.shares == 0:
shares = self._tlog.buy(date, close)
# sell
elif end_flag:
shares = self._tlog.sell(date, close)
if shares > 0:
pf.DBG("{0} BUY {1} {2} @ {3:.2f}".format(
date, shares, self._symbol, close))
elif shares < 0:
pf.DBG("{0} SELL {1} {2} @ {3:.2f}".format(
date, -shares, self._symbol, close))
# record daily balance
self._dbal.append(date, high, low, close)
def run(self):
self._ts = pf.fetch_timeseries(self._symbol)
self._ts = pf.select_tradeperiod(self._ts, self._start, self._end,
use_adj=True)
self._ts, self._start = pf.finalize_timeseries(self._ts, self._start)
self._tlog = pf.TradeLog(self._symbol)
self._dbal = pf.DailyBal()
self._algo()
def get_logs(self):
""" return DataFrames """
self.tlog = self._tlog.get_log()
self.dbal = self._dbal.get_log(self.tlog)
return self.tlog, self.dbal
def get_stats(self):
stats = pf.stats(self._ts, self.tlog, self.dbal, self._capital)
return stats
Run Strategy
In [6]:
s = Strategy(symbol, capital, start, end)
s.run()
Retrieve log DataFrames
In [7]:
tlog, dbal = s.get_logs()
stats = s.get_stats()
In [8]:
tlog.tail()
Out[8]:
In [9]:
dbal.tail()
Out[9]:
In [10]:
pf.print_full(stats)
Summary
In [11]:
pf.summary(stats)
Out[11]:
In [12]:
returns = dbal['close']
pf.monthly_returns_map(returns['1990':])
In [13]:
returns = dbal['close']
pf.holding_period_map(returns['1990':])