A stock that's going up tends to keep going up...until it doesn't. Momentum is the theory that stocks that have recently gone up will keep going up disproportionate to their underlying value because folks are overenthusiastic about them.
1. The SPY is higher than X days ago, buy
2. If the SPY is lower than X days ago, sell your long position.
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'
#symbol = 'OIH'
capital = 10000
start = datetime.datetime(1900, 1, 1)
#start = datetime.datetime.strptime(pf.SP500_BEGIN, '%Y-%m-%d')
end = datetime.datetime.now()
Define lookback period in months
In [4]:
period = None
Run Strategy
In [5]:
s = strategy.Strategy(symbol, capital, start, end, period, margin=2)
s.run()
Retrieve log DataFrames
In [6]:
tlog, dbal = s.get_logs()
stats = s.get_stats()
In [7]:
tlog.tail(10)
Out[7]:
In [8]:
dbal.tail()
Out[8]:
Generate strategy stats - display all available stats
In [9]:
pf.print_full(stats)
Equity curve
Run Benchmark, Retrieve benchmark logs, and Generate benchmark stats
In [10]:
benchmark = pf.Benchmark(symbol, capital, s._start, s._end)
benchmark.run()
benchmark.tlog, benchmark.dbal = benchmark.get_logs()
benchmark.stats = benchmark.get_stats()
Plot Equity Curves: Strategy vs Benchmark
In [11]:
pf.plot_equity_curve(dbal, benchmark=benchmark.dbal)
Plot Trades
In [12]:
pf.plot_trades(dbal, benchmark=benchmark.dbal)
Bar Graph: Strategy vs Benchmark
In [13]:
df = pf.plot_bar_graph(stats, benchmark.stats)
df
Out[13]:
In [14]:
returns = dbal['close']
returns.tail()
Out[14]:
In [15]:
benchmark_returns = benchmark.dbal['close']
benchmark_returns.tail()
Out[15]:
In [16]:
pf.prettier_graphs(returns, benchmark_returns, label1='Strategy', label2='Benchmark', points_to_plot=5000)