Created
April 25, 2018 02:42
-
-
Save conanak99/edb403078eeb6be0cdd94d5c3bb7f894 to your computer and use it in GitHub Desktop.
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
# sample importing from your own library | |
#from samplelib.lib1 import print_something | |
from zipline.api import order_target, record, symbol, symbols, history | |
from zipline import run_algorithm | |
from time import time | |
import datetime | |
import pytz | |
import matplotlib.pyplot as plt | |
import pandas as pd | |
def initialize(context): | |
context.i = 0 | |
context.assets = symbols('AAPL','AMZN','MSFT','GOOG') | |
def handle_data(context, data): | |
# Skip first 200 days to get full windows | |
context.i += 1 | |
if context.i < 200: | |
return | |
start = time() | |
for asset in context.assets: | |
# Compute averages | |
# data.history() has to be called with the same params | |
# from above and returns a pandas dataframe. | |
short_mavg = data.history(asset, 'price', bar_count=50, frequency="1d").mean() | |
long_mavg = data.history(asset, 'price', bar_count=200, frequency="1d").mean() | |
# Trading logic | |
if short_mavg > long_mavg: | |
# order_target orders as many shares as needed to | |
# achieve the desired number of shares. | |
order_target(asset, 100) | |
elif short_mavg < long_mavg: | |
order_target(asset, 0) | |
# Save values for later inspection | |
record(**{ | |
asset.symbol:data.current(asset, 'price'), | |
asset.symbol + "short_mavg": short_mavg, | |
asset.symbol + "long_mavg" : long_mavg | |
}) | |
end = time() | |
print("handle data time", end-start) | |
def __main__(): | |
start = time() | |
perf = run_algorithm(start=datetime.datetime(2010, 1, 1,tzinfo=pytz.utc),end=datetime.datetime(2018,1,1,tzinfo=pytz.utc), | |
handle_data=handle_data, | |
initialize=initialize, | |
capital_base=10000000, | |
bundle='quandl') | |
end = time() | |
print("Core backtesting took: " , end-start) | |
__main__() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment