Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Basic Loop Question

Hi,

I am trying to create a loop that quantifies the market value of each position at the start of the trading day. For some reason, my loop is not working and I can't figure out why. I would appreciate any help understanding why the loop is not working correctly. See below

def before_trading_start(context, data):  
    LV = SV = 0  
    for security  in context.portfolio.positions:  
        current_price = data.current(security , 'price')  
        shares = security.amount  
        if shares > 0:  
            LV += shares*current_price  
        if shares < 0:  
            SV += shares*current_price  
    print LV  
3 responses

The problem is that 'security' is an equity object.

    shares = security.amount  

When you do the above, you are probably thinking security is a 'position' object. 'security' does not have an attribute '.amount'. What you should do is loop over both the key and the values of the positions dictionary. This can be done using the following notation.

def before_trading_start(context, data):  
    LV = SV = 0  
    for security, position in context.portfolio.positions.items():  
        current_price = data.current(security , 'price')  
        shares = position.amount  
        if shares > 0:  
            LV += shares*current_price  
        if shares < 0:  
            SV += shares*current_price  
    print LV 

I didn't actually try the above code but it should work. Maybe look at this post for similar issues
https://www.quantopian.com/posts/error-getting-portfolio-positions#587a3a31a3844c4c708adb4a

Good luck.

What I ended up doing was modifying the code to look like this. I believe this does the same thing as your solution above. Do you agree?

def compute_weights(context):  

    # compute short beta exposure  

    Long = 0.5  
    Short = -0.5  
    context.BOD_LV = context.BOD_SV = 0  

    for security  in context.portfolio.positions:  
        price = context.portfolio.positions[security].last_sale_price  
        shares = context.portfolio.positions[security].amount  
        if shares > 0:  
            context.BOD_LV += shares*price  
        if shares < 0:  
            context.BOD_SV += shares*price  

    context.BOD_leverage = (context.BOD_LV + abs(context.BOD_SV))/context.portfolio.portfolio_value  

Yes, that works too!