Im sorry I know this is very bad code but I just cant figure out why this very simple mean reversion algo on Apple will not work. Here is my code below.
"""
This is a template algorithm on Quantopian for you to adapt and fill in.
"""
import quantopian.algorithm as algo
from quantopian.pipeline import Pipeline
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.filters import QTradableStocksUS
def initialize(context):
"""
Called once at the start of the algorithm.
"""
# Rebalance every day, 1 hour after market open.
algo.schedule_function(
rebalance,
algo.date_rules.every_day(),
algo.time_rules.market_open(hours=1),
)
def make_pipeline():
"""
A function to create our dynamic stock selector (pipeline). Documentation
on pipeline can be found here:
https://www.quantopian.com/help#pipeline-title
"""
universe = QTradableStocksUS()
# Create a Returns factor with a 5-day lookback window for all securities
# in our QTradableStocksUS Filter.
recent_returns = Returns(
window_length= 5,
mask=universe
)
# Factor of yesterday's close price.
yesterday_close = USEquityPricing.close.latest
# Turn our recent_returns factor into a z-score factor to normalize the results.
recent_returns_zscore = recent_returns.zscore()
# Define high and low returns filters to be the bottom 10% and top 10% of
# securities in the QTradableStocksUS.
low_returns = recent_returns_zscore.percentile_between(0,5)
high_returns = recent_returns_zscore.percentile_between(95,100)
# Add a filter to the pipeline such that only high-return and low-return
# securities are kept.
securities_to_trade = (low_returns | high_returns)
pipe = Pipeline(
columns={
'recent_returns_zscore': recent_returns_zscore
},
screen=securities_to_trade
)
return pipe
def rebalance(context, data):
"""
Execute orders according to our schedule_function() timing.
"""
pass
def record_vars(context, data):
"""
Plot variables at the end of each day.
"""
pass
def handle_data(context, data):
"""
Called every minute.
"""
universe = QTradableStocksUS()
# Create a Returns factor with a 5-day lookback window for all securities
# in our QTradableStocksUS Filter.
recent_returns = data.history(sid(24), 'price', 50, '1d')
# Turn our recent_returns factor into a z-score factor to normalize the results.
recent_returns_zscore = recent_returns.zscore()
# Define high and low returns filters to be the bottom 10% and top 10% of
# securities in the QTradableStocksUS.
low_returns = recent_returns_zscore.percentile_between(0,5)
high_returns = recent_returns_zscore.percentile_between(95,100)
# Add a filter to the pipeline such that only high-return and low-return
# securities are kept.
securities_to_trade = (low_returns | high_returns)
if sid(24) in securities_to_trade:
if sid(24) in low_returns:
order_target_percent(symbol('AAPL'), .05)
elif sid(24) in high_returns:
order_target_percent(sid(24), -.05)
pass