In [1]:
import pandas as pd
import matplotlib.pyplot as plt
import datetime
from talib.abstract import *
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 = '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()
Define percent bands (from 0 to 10% increment by 0.5)
In [4]:
bands = range(0, 100, 5)
bands = [str(band) for band in bands]
Run Strategy
In [5]:
strategies = pd.Series(dtype=object)
for band in bands:
print("{0}".format(band), end=" ")
strategies[band] = strategy.Strategy(symbol, capital, start, end, sma_period=200, percent_band=int(band)/10)
strategies[band].run()
_, strategies[band].tlog, strategies[band].dbal = strategies[band].get_logs()
strategies[band].stats = strategies[band].get_stats()
Summarize results
In [6]:
metrics = ('annual_return_rate',
'ending_balance',
'max_closed_out_drawdown',
'drawdown_annualized_return',
'drawdown_recovery',
'best_month',
'worst_month',
'sharpe_ratio',
'sortino_ratio',
'monthly_std',
'pct_time_in_market',
'total_num_trades',
'pct_profitable_trades',
'trades_per_year',
'avg_points')
df = strategy.summary(strategies, metrics)
df
Out[6]:
Bar graphs
In [7]:
strategy.plot_bar_graph(df, 'annual_return_rate')
strategy.plot_bar_graph(df, 'ending_balance')
strategy.plot_bar_graph(df, 'sharpe_ratio')
strategy.plot_bar_graph(df, 'max_closed_out_drawdown')
Run Benchmark
In [8]:
s = strategies[bands[0]]
benchmark = pf.Benchmark(symbol, capital, s._start, s._end)
benchmark.run()
benchmark.tlog, benchmark.dbal = benchmark.get_logs()
benchmark.stats = benchmark.get_stats()
Equity curve
In [9]:
pf.plot_equity_curve(strategies['35'].dbal, benchmark=benchmark.dbal)