Last active
February 28, 2017 10:50
-
-
Save ranaroussi/557b9615ff79d98ec3bb7f4032bbedf7 to your computer and use it in GitHub Desktop.
Example of a rapid prototyping of a strategy idea
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If using Jupyter notebook, use this: