Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Very simple programming question

Can someone tell me why the context.tgtamt returns '0' in the second 'percent to hold' step below code? I am a newbie Python programmer and I am confused about this. The num holdings returns 2. 1/2 seems like it should return .5? The variable is defined as type float? So what am I missing? Thanks.

def initialize(context):  
    context.sb = symbols('SPY', 'IEF')  
    schedule_function(rebal,  
                      date_rule=date_rules.week_start(),                      time_rule=time_rules.market_close(minutes=1))  
    context.tgtamt = float(.5)  
def handle_data(context, data):  
    pass  
def rebal (context, data):  
   for s in data:  
    print ('value of cntxt.tgtamt step1 : %s' %context.tgtamt)  
    numholdings = (len(context.sb))  
    log.info("number of holding %s" % (numholdings))  
    context.tgtamt = 1/numholdings  
    log.info("percent to hold - tgtamtstep2 : %s" % (context.tgtamt))  
    order_target_percent(s,context.tgtamt)  
    log.info("buying %s" % (s.symbol))  
    record(leverage = context.account.leverage)  
3 responses

This is a particularly bone-headed mis-feature of python version 2 - integer division leads to an integer. To do what you want, change it to 1.0/numholdings

Also, for future reference, you can't set the 'type' of any reference in python, as you believe you did in initialize; they are just names, and they can refer to anything, and they can change what they refer to.

x = True  
x = 'hello'  
x = 5  

That is totally valid. Python is stupid.

Simon,
THANKS on this. I was banging my head against a wall trying to find that error.
Best,
Tom