Skip to content

Instantly share code, notes, and snippets.

@IanLeatherbury
Last active January 8, 2017 19:08
Show Gist options
  • Save IanLeatherbury/f2484a77ae0fec77435dbedcd858bba8 to your computer and use it in GitHub Desktop.
Save IanLeatherbury/f2484a77ae0fec77435dbedcd858bba8 to your computer and use it in GitHub Desktop.
SPY Stop Loss Strat
from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.factors import AverageDollarVolume
from quantopian.pipeline.filters.morningstar import Q500US
from quantopian.pipeline.factors import Returns
from quantopian.pipeline import CustomFactor
def initialize(context):
# Rebalance at the end of every month
schedule_function(my_rebalance, date_rules.month_end(), time_rules.market_open(hours=1))
# Record tracking variables at the end of each month.
schedule_function(my_record_vars, date_rules.month_end(), time_rules.market_close())
context.SPY = sid(8554)
context.SSO = sid(32270)
set_slippage(slippage.VolumeShareSlippage(volume_limit=0.025, price_impact=0.1))
set_commission(commission.PerShare(cost=0.0075, min_trade_cost=1))
def my_rebalance(context,data):
#moving average
moving_average = data.history(context.SPY, 'price', 100, '1d')[:-1].mean()
#12 month returns
prices = data.history(context.SPY, "price", bar_count=365, frequency="1d")
pct_change = (prices.ix[-1] - prices.ix[0]) / prices.ix[0]
#if (SPY > moving average) or 12 month average > 0, purchase
if data.current(context.SPY, 'price') > moving_average and pct_change > 0 and data.can_trade(context.SPY) and data.can_trade(context.SSO):
log.info("leverage = 1.75")
order_target_percent(context.SPY, .25)
order_target_percent(context.SSO, .75)
elif data.current(context.SPY, 'price') > moving_average or pct_change > 0 and data.can_trade(context.SPY) and data.can_trade(context.SSO):
log.info("leverage = 1.25")
order_target_percent(context.SPY, .75)
order_target_percent(context.SSO, .25)
else:
log.info("sold")
order_target_percent(context.SPY, 0)
order_target_percent(context.SSO, 0)
pass
def my_record_vars(context, data):
"""
Plot variables at the end of each day.
"""
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment