Both ok. I pictured a route like this, guard against margin though, at a minimum, record cash.
def rebalance(context, data):
#long_weight, short_weight = compute_weights(context, data)
context.long_secs = context.output[context.output['longs']].index
context.short_secs = context.output[context.output['shorts']].index
longs = {}
shrts = {}
# zscore screen, both at same time
for stock in context.long_secs.union(context.short_secs):
zscore = calculate_zscore(stock ,data)
if zscore < -1.65:
# The value of zscore here so far is unused, just a way of storing these in dict instead of list
longs[stock] = zscore
log.info(' long {}: {}'.format(stock.symbol, '%.4f' % zscore)) # to 4 decimal places
elif zscore > 1.65:
shrts[stock] = zscore
log.info('short {}: {}'.format(stock.symbol, '%.4f' % zscore)) # to 4 decimal places
# Place orders for longs
for stock in longs:
order_target_percent(stock, .6 / len(longs))
log.info(' long ' + stock.symbol)
# Place orders for shorts
for stock in shrts:
order_target_percent(stock, -.4 / len(shrts))
log.info('short ' + stock.symbol)