SMA Percent Band

Demonstrate integration of pinkfish with the quantopian empyrical library
https://github.com/quantopian/empyrical

1. The SPY closes above its upper band, buy
2. If the SPY closes below its lower band, sell your long position.

In [1]:
import pandas as pd
import matplotlib.pyplot as plt
import datetime
from talib.abstract import *
import empyrical as em

import pinkfish as pf
import strategy

# 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 = '^GSPC'
#symbol = 'SPY'
#symbol = 'DJA'
#symbol = 'DIA'
#symbol = 'QQQ'
#symbol = 'IWM'
#symbol = 'TLT'
#symbol = 'GLD'
#symbol = 'AAPL'
#symbol = 'BBRY'
#symbol = 'GDX'
capital = 10000
#start = datetime.datetime(1900, 1, 1)
start = datetime.datetime.strptime(pf.SP500_BEGIN, '%Y-%m-%d')
end = datetime.datetime.now()

Include dividends? (If yes, set to True)


In [4]:
use_adj = True

Define high low trade periods


In [5]:
sma_period = 200
percent_band = 3.5

Run Strategy


In [6]:
s = strategy.Strategy(symbol, capital, start, end, use_adj, sma_period, percent_band)
s.run()

Retrieve log DataFrames


In [7]:
rlog, tlog, dbal = s.get_logs()
stats = s.get_stats()

In [8]:
tlog.tail(10)


Out[8]:
entry_date entry_price exit_date exit_price pl_points pl_cash qty cumul_total direction symbol
19 1998-11-04 1118.67 1999-10-15 1247.41 128.74 20340.92 158 187440.41 LONG ^GSPC
20 1999-10-29 1362.93 2000-10-10 1387.02 24.09 3468.96 144 190909.37 LONG ^GSPC
21 2003-04-22 911.37 2004-08-06 1063.97 152.60 33571.99 220 224481.36 LONG ^GSPC
22 2004-11-04 1161.67 2007-11-21 1416.77 255.10 51275.10 201 275756.46 LONG ^GSPC
23 2009-06-12 946.21 2010-06-04 1064.88 118.67 35838.33 302 311594.79 LONG ^GSPC
24 2010-10-05 1160.75 2011-08-04 1200.07 39.32 10891.63 277 322486.42 LONG ^GSPC
25 2012-01-18 1308.04 2015-08-21 1970.89 662.85 168363.89 254 490850.31 LONG ^GSPC
26 2016-04-18 2094.34 2018-10-24 2656.10 561.76 134260.64 239 625110.95 LONG ^GSPC
27 2019-03-21 2854.88 2020-03-09 2746.56 -108.32 -24047.00 222 601063.95 LONG ^GSPC
28 2020-06-03 3122.87 2020-07-17 3224.73 101.86 19862.67 195 620926.63 LONG ^GSPC

In [9]:
dbal.tail()


Out[9]:
high low close shares cash leverage state
date
2020-07-13 632991.69 616243.12 617372.17 195 2104.28 1.00 -
2020-07-14 626289.52 611997.96 625620.68 195 2104.28 1.00 -
2020-07-15 633568.89 626252.48 631283.49 195 2104.28 1.00 -
2020-07-16 630080.31 625829.35 629140.44 195 2104.28 1.00 -
2020-07-17 630926.63 630926.63 630926.63 0 630926.63 1.00 X

Run Benchmark, Retrieve benchmark logs


In [10]:
benchmark = pf.Benchmark(symbol, capital, s._start, s._end, s._use_adj)
benchmark.run()
benchmark.tlog, benchmark.dbal = benchmark.get_logs()


1957-03-04 00:00:00 BUY  226 ^GSPC @ 44.06
2020-07-17 00:00:00 SELL 226 ^GSPC @ 3224.73

Empyrical API


In [11]:
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)

returns = dbal['close'].pct_change()
benchmark_rets = benchmark.dbal['close'].pct_change()

returns.index = returns.index.tz_localize('UTC')
benchmark_rets.index = benchmark_rets.index.tz_localize('UTC')

aggregate_returns = em.aggregate_returns(returns, 'yearly')
alpha = em.alpha(returns, benchmark_rets)
alpha_aligned = em.alpha_aligned(returns, benchmark_rets)
alpha_beta = em.alpha_beta(returns, benchmark_rets)
alpha_beta_aligned = em.alpha_beta_aligned(returns, benchmark_rets)
annual_return = em.annual_return(returns)
annual_volatility = em.annual_volatility(returns)
beta = em.beta(returns, benchmark_rets)
beta_aligned = em.beta_aligned(returns, benchmark_rets)
cagr = em.cagr(returns)
calmar_ratio = em.calmar_ratio(returns)
capture = em.capture(returns, benchmark_rets)
conditional_value_at_risk = em.conditional_value_at_risk(returns)
cum_returns = em.cum_returns(returns)
cum_returns_final = em.cum_returns_final(returns)
down_alpha_beta = em.down_alpha_beta(returns, benchmark_rets)
down_capture = em.down_capture(returns, benchmark_rets)
downside_risk = em.downside_risk(returns)
excess_sharpe = em.excess_sharpe(returns, benchmark_rets)
max_drawdown = em.max_drawdown(returns)
omega_ratio = em.omega_ratio(returns)
sharpe_ratio = em.sharpe_ratio(returns)
simple_returns = em.simple_returns(dbal['close'])
sortino_ratio = em.sortino_ratio(returns)
stability_of_timeseries = em.stability_of_timeseries(returns)
tail_ratio = em.tail_ratio(returns)
up_alpha_beta = em.up_alpha_beta(returns, benchmark_rets)
up_capture = em.up_capture(returns, benchmark_rets)
up_down_capture = em.up_down_capture(returns, benchmark_rets)
value_at_risk = em.value_at_risk(returns)

In [12]:
s = pd.Series(dtype=object)
s['aggregate_returns'] = aggregate_returns
s['alpha'] = alpha
s['alpha_aligned'] = alpha_aligned
s['alpha_beta'] = alpha_beta
s['alpha_beta_aligned'] = alpha_beta_aligned
s['annual_return'] = annual_return
s['annual_volatility'] = annual_volatility
s['beta'] = beta
s['beta_aligned'] = beta_aligned
s['cagr'] = cagr
s['calmar_ratio'] = calmar_ratio
s['capture'] = capture
s['conditional_value_at_risk'] = conditional_value_at_risk
s['cum_returns'] = cum_returns
s['cum_returns_final'] = cum_returns_final
s['down_alpha_beta'] = down_alpha_beta
s['down_capture'] = down_capture
s['downside_risk'] = downside_risk
s['excess_sharpe'] = excess_sharpe
s['max_drawdown'] = max_drawdown
s['omega_ratio'] = omega_ratio
s['sharpe_ratio'] = sharpe_ratio
s['simple_returns'] = simple_returns
s['sortino_ratio'] = sortino_ratio
s['stability_of_timeseries'] = stability_of_timeseries
s['tail_ratio'] = tail_ratio
s['up_alpha_beta'] = up_alpha_beta
s['up_capture'] = up_capture
s['up_down_capture'] = up_down_capture
s['value_at_risk'] = value_at_risk

In [13]:
df = pd.DataFrame(s, columns=['value'])
df


Out[13]:
value
aggregate_returns 1957 -0.07 1958 0.25 1959 0.08 1960 ...
alpha 0.04
alpha_aligned 0.04
alpha_beta [0.03682204498023256, 0.43232791200860965]
alpha_beta_aligned [0.03682204498023256, 0.43232791200860965]
annual_return 0.07
annual_volatility 0.11
beta 0.43
beta_aligned 0.43
cagr 0.07
calmar_ratio 0.31
capture 0.97
conditional_value_at_risk -0.02
cum_returns date 1957-03-04 00:00:00+00:00 0.00 1957-03...
cum_returns_final 62.09
down_alpha_beta [-0.35570706746344505, 0.32218799754729727]
down_capture 0.77
downside_risk 0.07
excess_sharpe -0.01
max_drawdown -0.22
omega_ratio 1.15
sharpe_ratio 0.67
simple_returns date 1957-03-05 0.00 1957-03-06 0.00 195...
sortino_ratio 0.95
stability_of_timeseries 0.98
tail_ratio 1.05
up_alpha_beta [0.6882994780303586, 0.29050730496945115]
up_capture 0.41
up_down_capture 0.53
value_at_risk NaN