Skip to content

Instantly share code, notes, and snippets.

@ranaroussi
Last active February 28, 2017 10:50
Show Gist options
  • Save ranaroussi/557b9615ff79d98ec3bb7f4032bbedf7 to your computer and use it in GitHub Desktop.
Save ranaroussi/557b9615ff79d98ec3bb7f4032bbedf7 to your computer and use it in GitHub Desktop.
Example of a rapid prototyping of a strategy idea
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
example of a rapid prototyping of a strategy idea using pandas
(c) Ran Aroussi <http://aroussi.com>
"""
import matplotlib.pyplot as plt
from pandas_datareader import data
# get SPY daily data since January 2000
df = data.get_data_yahoo("SPY", start="2000-01-01")
# create a new column with the day-today return (represents "the market")
df['market'] = df['Adj Close'].pct_change()
# slide the data and assign the market column's data to the strategy
# but only get the "market" column where the previous "market" was <= -0.005
df['strategy'] = df[ df['market'].shift(1) <= -0.005 ]['market']
# replace NAN values (days where we didn't "trade") with 0 (no return)
df['strategy'].fillna(0, inplace=True)
# plot the market and strategy data
plt.plot(df['market'].cumsum(), color="r", label='market')
plt.plot(df['strategy'].cumsum(), color="g", label='strategy')
plt.legend()
plt.tight_layout()
plt.show()
@ranaroussi
Copy link
Author

If using Jupyter notebook, use this:

%matplotlib inline
from pandas_datareader import data

df = data.get_data_yahoo("SPY", start="2000-01-01")

df['market'] = df['Adj Close'].pct_change()
df['strategy'] = df[ df['market'].shift(1) <= -0.005 ]['market']
df['strategy'].fillna(0, inplace=True)

df[['market', 'strategy']].cumsum().plot()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment