Demonstrate integration of pinkfish with the quantopian pyfolio library
https://github.com/quantopian/pyfolio
1. The SPY closes above its upper band, buy
2. If the SPY closes below its lower band, sell your long position.
Note: The function create_returns_tear_sheet() in the last cell takes several minutes to complete.
In [1]:
import warnings
warnings.simplefilter(action='ignore', category=UserWarning)
import pandas as pd
import matplotlib.pyplot as plt
import datetime
from talib.abstract import *
import pyfolio
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]:
In [9]:
dbal.tail()
Out[9]:
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()
Pyfolio Returns Tear Sheet
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')
live_start_date=None
live_start_date='2010-01-01'
pyfolio.create_returns_tear_sheet(returns, benchmark_rets=benchmark_rets, live_start_date=live_start_date)
#pyfolio.create_simple_tear_sheet(returns, benchmark_rets=benchmark_rets)
#pyfolio.create_interesting_times_tear_sheet(returns, benchmark_rets=benchmark_rets)