Hello - first time posting.
I have this running - but can't seem to work out how to have multiple stocks (within the S&P 500) included. Everything I have done freezes or crashes the algo. I have used the FAQ for Universe and Multiple but I can't seem to join the dots. Any ideas? Thank you for your assistance!
Samantha
import math
import talib
from scipy import stats
from pytz import timezone
def initialize(context):
context.security = sid(38936)
context.time = "15:58:00" # Time for processing
context.days = 0 # days in trade
context.intrade = False
def handle_data(context, data):
# convert datetime to US/Eastern timezone
date = get_datetime().astimezone(timezone('US/Eastern'))
# Get current time
ctime = "%02d:%02d:%02d" % (date.hour, date.minute, date.second)
if ctime != context.time:
# processing happens only once per day
# exit if it's not time to process
return
# Skip further processing if there are open orders
if get_open_orders(context.security):
return
# assign security and price to local variables for later usage
security = context.security
price = data[security].price
if context.intrade:
# increment days in trade
context.days += 1
# check exit conditions
if context.intrade:
if can_exit(context):
# Sell security
amount = context.portfolio.positions[security].amount
log.info('Selling %s of %s' % (amount, security.symbol))
order(security, -amount)
context.days = 0
context.intrade = False
return
# check enter conditions
elif can_enter(context, price):
# Buy security
amount = math.floor((context.portfolio.cash) / price)
log.info('Buying %s of %s (%s of %s)' % (amount, security.symbol,
amount * price, context.portfolio.cash))
order(context.security, amount)
context.intrade = True
def can_enter(context, price):
# calculate zscore
close16 = history(16, '1d', 'close_price')[context.security]
zscore = stats.zscore(close16, axis=0, ddof=1)[-1]
if zscore >= -2:
log.debug("Can't enter. Zscore(%f) >= -2" % zscore)
return False
# calculate SMA 200
hist200 = history(200, '1d', 'close_price')[context.security]
sma200 = talib.SMA(hist200, timeperiod=200)[-1]
if price <= sma200:
log.debug("Can't enter. price(%f) <= SMA200(%f)" % (price, sma200))
return False
# calculate WLR 16
high16 = history(16, '1d', 'high')[context.security]
low16 = history(16, '1d', 'low')[context.security]
wlr16 = talib.WILLR(high16, low16, close16)[-1]
if wlr16 >= -90:
log.debug("Can't enter. WLR 16(%f) >= -90" % wlr16)
return False
# calculate BBL 16 upper limit
bbl16 = talib.BBANDS(close16, 16)[0][-1]
if price >= bbl16:
log.debug("Can't enter. BBANDS 16(%f) >= price(%f)" % (bbl16, price))
return False
return True
def can_exit(context):
# calculate zscore
close16 = history(16, '1d', 'close_price')[context.security]
zscore = stats.zscore(close16, axis=0, ddof=1)[-1]
return zscore > -1 or context.days > 15