I really should write more readable code...
OK, here's the same code, more clearly written with comments to help explain:
import pytz
def initialize(context):
context.stock = sid(8554)
context.date = None
def handle_data(context, data):
exchange_time = get_datetime().astimezone(pytz.timezone('US/Eastern'))
if exchange_time.date() != context.date: #is this a new day?
context.date = exchange_time.date()
# Get closing price for yesterday and closing of today's 1st minute (so 2 bars)
closes = history(bar_count=2, frequency='1d', field='price')
# Get opening price for today's 1st minute (i.e. today's open, only 1 bar requested)
opens = history(bar_count=1, frequency='1d', field='open_price')
s = context.stock
log.info('{dt}: Shares on record in {s}= {amt}'.format(dt=exchange_time,
s=s.symbol,
amt=context.portfolio.positions[s].amount))
yesterdays_close = closes[s][0]
todays_open = opens[s][0]
if todays_open > yesterdays_close:
order_target_percent(s, 1) # as in target 100% of your portfolio long in SPY (+1)
elif todays_open < yesterdays_close:
order_target_percent(s, -1) # as in target 100% of your portfolio short in SPY (-1)