Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Cannot use only one sid in context.stocks

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

1 response

So the runtime error is telling you exactly what is wrong, the Equity object is not iterable, when you loop in handleData you are expecting some sort of collection of securities, and it is getting only an Equity object. Luckily there is a really simple solution! Just warp your single stock in brackets...

context.stocks = [sid(24)]  

Putting it in brackets makes it a collection and thus an iterable.

Happy Coding

Disclaimer

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.