Skip to content

Instantly share code, notes, and snippets.

@eldritchideen
Forked from Slater-Victoroff/gist:9896046
Last active August 29, 2015 14:18
Show Gist options
  • Save eldritchideen/d69360008847b72941e3 to your computer and use it in GitHub Desktop.
Save eldritchideen/d69360008847b72941e3 to your computer and use it in GitHub Desktop.
from zipline.algorithm import TradingAlgorithm
from zipline.transforms import MovingAverage
from zipline.utils.factory import load_from_yahoo
from zipline.finance.slippage import FixedSlippage
from zipline.finance.commission import PerShare
from datetime import datetime
import matplotlib.pyplot as plt
class DualMovingAverage(TradingAlgorithm):
def initialize(self, short_window=50, long_window=200):
self.min_window = max(short_window,long_window)
self.add_transform(MovingAverage, 'short_mavg', ['price'], window_length=short_window)
self.add_transform(MovingAverage, 'long_mavg', ['price'], window_length=long_window)
self.invested, self.days = (False, 0)
self.set_slippage(FixedSlippage(spread=0.00))
self.set_commission(PerShare(cost=0.00))
def handle_data(self, data):
self.short_mavg = data['SPY'].short_mavg['price']
self.long_mavg = data['SPY'].long_mavg['price']
self.buy, self.sell = (False, False)
if self.short_mavg > self.long_mavg and self.days > self.min_window and not self.invested:
self.order_percent('SPY',1)
self.invested, self.buy = (True, True)
elif self.short_mavg < self.long_mavg and self.days > self.min_window and self.invested:
self.order_percent('SPY',-1)
self.invested, self.sell = (False, True)
self.days = self.days + 1
self.record(
short_mavg=self.short_mavg, long_mavg=self.long_mavg,
buy=self.buy, sell=self.sell, days=self.days)
data = load_from_yahoo(
stocks=['SPY'], indexes={}, start=datetime(2000, 1, 1),
end=datetime(2014, 3, 25), adjusted=bool(1))
results = DualMovingAverage().run(data)
results.portfolio_value.plot(title="Equity Curve")
plt.show()
results.to_csv('/Users/jeickmeier/Desktop/python_results.csv',',')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment