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 the periods
In [4]:
periods = range(50, 525, 25)
periods = [str(period) for period in periods]
Run Strategy
In [5]:
strategies = pd.Series(dtype=object)
for period in periods:
print("{0}".format(period), end=" ")
strategies[period] = strategy.Strategy(symbol, capital, start, end, sma_period=int(period))
strategies[period].run()
_, strategies[period].tlog, strategies[period].dbal = strategies[period].get_logs()
strategies[period].stats = strategies[period].get_stats()
Summarize results
In [6]:
metrics = ('start',
'ending_balance',
'annual_return_rate',
'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',
'trades_per_year',
'pct_profitable_trades',
'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[periods[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['200'].dbal, benchmark=benchmark.dbal)
In [ ]: