This code can successfully run multiple sids but cannot run with only one. If I do this I get a runtime error on line 22.The error says:
There was a runtime error.
TypeError: 'zipline.assets._assets.Equity' object is not iterable
User Algorithm: 22, in handleData
for stock in context.stocks:
Here is the code:
# Put any initialization logic here. The context object will be passed to
# the other methods in your algorithm.
def initialize(context):
context.stocks = sid(24)
# context.stocks = sid(24), sid(46631), sid(5061), sid(6683), sid(45815), sid(3149), sid(49209), sid(42950), sid(41579), sid(4589), sid(45971), sid(28016), sid(20133), sid(8554), sid(698)
# PNRA
schedule_function(
func=handleData,
date_rule=date_rules.every_day(),
time_rule=time_rules.market_open(hours=0, minutes=1),
half_days=True
)
# Will be called on every trade event for the securities you specify.
def handle_data(context,data):
pass
def handleData(context, data):
print(context.stocks)
for stock in context.stocks:
if stock in data:
print(data)
MA1 = data[stock].mavg(50)
MA2 = data[stock].mavg(100)
current_price = data[stock].price
current_positions = context.portfolio.positions[stock].amount
cash = context.portfolio.cash
if (MA1 > MA2) and current_positions == 0:
number_of_shares = int(cash/current_price)
order(stock, number_of_shares)
log.info("buying shares")
elif (MA1 < MA2) and current_positions != 0:
order_target(stock, 0)
log.info("selling shares")
record(MA1 = MA1, MA2 = MA2, Price = current_price)
return
Please note that handleData is not the same as handle_data. Does anyone know where I have gone wrong?
Thanks,
Nick