Skip to content

Instantly share code, notes, and snippets.

@jdlin
Created September 22, 2017 03:49
# This strategy was taken from http://www.investopedia.com/articles/trading/08/atr.asp
# The idea is to use ATR to identify breakouts, if the price goes higher than
# the previous close + ATR, a price breakout has occurred. The position is closed when
# the price goes 1 ATR below the previous close.
# This algorithm uses ATR as a momentum strategy, but the same signal can be used for
# a reversion strategy, since ATR doesn't indicate the price direction.
# Because this algorithm uses the history function, it will only run in minute mode.
# entry and exit points for trading the SPY.
import talib
import numpy as np
import pandas as pd
# Setup our variables
def initialize(context):
context.stock = symbol('SPY')
# Create a variable to track the date change
context.date = None
# Algorithm will only take long positions.
# It will stop if encounters a short position.
set_long_only()
def handle_data(context, data):
# We will constrain the trading to once per day at market open in this example.
todays_date = get_datetime().date()
# Do nothing unless the date has changed and it's a new day.
if todays_date == context.date:
return
# Set the new date
context.date = todays_date
# Track our position
current_position = context.portfolio.positions[context.stock].amount
record(position_size=current_position)
# Load historical data for the stocks
high = history(30, '1d', 'high')
low = history(30, '1d', 'low')
close = history(30, '1d', 'close_price')
# Calculate the ATR for the stock
atr = talib.ATR(high[context.stock],
low[context.stock],
close[context.stock],
timeperiod=14)[-1]
price=data[context.stock].price
# Use the close price from 2 days ago because we trade at market open
prev_close = close.iloc[-3][context.stock]
# An upside breakout occurs when the price goes 1 ATR above the previous close
upside_signal = price - (prev_close + atr)
# A downside breakout occurs when the previous close is 1 ATR above the price
downside_signal = prev_close - (price + atr)
# Enter position when an upside breakout occurs. Invest our entire portfolio to go long.
if upside_signal > 0 and current_position <= 0:
order_target_percent(context.stock, 1.0)
# Exit position if a downside breakout occurs
elif downside_signal > 0 and current_position >= 0:
order_target_percent(context.stock, 0.0)
record(upside_signal=upside_signal,
downside_signal=downside_signal,
ATR=atr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment