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 Optimizations
In [4]:
# pick one
optimize_period = True
optimize_smas = False
optimize_pct = False
optimize_margin = False
# define high low trade periods ranges
if optimize_period:
Xs = range(2, 15, 1)
Xs = [str(X) for X in Xs]
# define SMAs ranges
elif optimize_smas:
Xs = range(20, 200, 10)
Xs = [str(X) for X in Xs]
# define stop loss percentage ranges
elif optimize_pct:
Xs = range(70, 96, 1)
Xs = [str(X) for X in Xs]
# define stop loss percentage ranges
elif optimize_margin:
Xs = range(10, 21, 1)
Xs = [str(X) for X in Xs]
Run Strategy
In [5]:
strategies = pd.Series(dtype=object)
for X in Xs:
print("{0}".format(X), end=" ")
if optimize_period:
strategies[X] = strategy.Strategy(symbol, capital, start, end, period=int(X))
elif optimize_smas:
strategies[X] = strategy.Strategy(symbol, capital, start, end, sma=int(X))
elif optimize_pct:
strategies[X] = strategy.Strategy(symbol, capital, start, end, stop_loss_pct=int(X))
elif optimize_margin:
strategies[X] = strategy.Strategy(symbol, capital, start, end, margin=int(X)/10)
strategies[X].run()
strategies[X].tlog, strategies[X].dbal = strategies[X].get_logs()
strategies[X].stats = strategies[X].get_stats()
Summarize results
In [6]:
metrics = ('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',
'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, 'sharpe_ratio')
strategy.plot_bar_graph(df, 'max_closed_out_drawdown')
Run Benchmark
In [8]:
s = strategies[Xs[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]:
if optimize_period: Y = '7'
elif optimize_smas: Y = '70'
elif optimize_pct: Y = '85'
elif optimize_margin: Y = '10'
pf.plot_equity_curve(strategies[Y].dbal, benchmark=benchmark.dbal)
In [ ]: