mirror of
https://github.com/wassname/catalyst.git
synced 2026-07-10 12:55:58 +08:00
75 lines
2.4 KiB
Python
Executable File
75 lines
2.4 KiB
Python
Executable File
#!/usr/bin/python
|
|
#
|
|
# Copyright 2012 Quantopian, Inc.
|
|
#
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
# you may not use this file except in compliance with the License.
|
|
# You may obtain a copy of the License at
|
|
#
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
#
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
# See the License for the specific language governing permissions and
|
|
# limitations under the License.
|
|
|
|
import matplotlib.pyplot as plt
|
|
|
|
from zipline.algorithm import TradingAlgorithm
|
|
from zipline.transforms import MovingAverage
|
|
from zipline.utils.factory import load_from_yahoo
|
|
|
|
|
|
class DualMovingAverage(TradingAlgorithm):
|
|
"""Dual Moving Average Crossover algorithm.
|
|
|
|
This algorithm buys apple once its short moving average crosses
|
|
its long moving average (indicating upwards momentum) and sells
|
|
its shares once the averages cross again (indicating downwards
|
|
momentum).
|
|
|
|
"""
|
|
def initialize(self, short_window=200, long_window=400):
|
|
# Add 2 mavg transforms, one with a long window, one
|
|
# with a short window.
|
|
self.add_transform(MovingAverage, 'short_mavg', ['price'],
|
|
days=short_window)
|
|
|
|
self.add_transform(MovingAverage, 'long_mavg', ['price'],
|
|
days=long_window)
|
|
|
|
# To keep track of whether we invested in the stock or not
|
|
self.invested = False
|
|
|
|
self.short_mavgs = []
|
|
self.long_mavgs = []
|
|
|
|
def handle_data(self, data):
|
|
short_mavg = data['AAPL'].short_mavg['price']
|
|
long_mavg = data['AAPL'].long_mavg['price']
|
|
if short_mavg > long_mavg and not self.invested:
|
|
self.order('AAPL', 100)
|
|
self.invested = True
|
|
elif short_mavg < long_mavg and self.invested:
|
|
self.order('AAPL', -100)
|
|
self.invested = False
|
|
|
|
# Save mavgs for later analysis.
|
|
self.short_mavgs.append(short_mavg)
|
|
self.long_mavgs.append(long_mavg)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
data = load_from_yahoo(stocks=['AAPL'], indexes={})
|
|
dma = DualMovingAverage()
|
|
results = dma.run(data)
|
|
|
|
results.portfolio_value.plot()
|
|
|
|
data['short'] = dma.short_mavgs
|
|
data['long'] = dma.long_mavgs
|
|
data[['AAPL', 'short', 'long']].plot()
|
|
plt.legend(loc=0)
|
|
plt.show()
|