Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Is this the right way to execute loop and execute orders ?

"weights" is an array containing the weights of each stock in "context.reqd_data "(both arrays are of equal length) , "context.prev_weights" is yet another array which stores the weights of previous day . I am firstly executing the orders for the stocks which have reduced weight today so that it frees up cash to avoid leveraging. Is this the right approach to do it ? Also can I use the following loops to execute orders (maybe I can't since I am getting some errors)?

        for x in range(0,len(weights)):  
            if abs(weights[x]) < abs(context.prev_weights[x]):  
                order_target_percent(context.reqd_data[x],weights[x])  
        for x in range(0,len(weights)):  
            if abs(weights[x]) > abs(context.prev_weights[x]):  
                order_target_percent(context.reqd_data[x],weights[x])  
        for x in range(0,len(weights)):  
            if weights[x] != weights[x]:  
                order_target_percent(context.reqd_data[x],0)  

Runtime exception: IndexError: list index out of range

I get this error at the start of each loop.

2 responses

I am not sure but perhaps you should try len(weights)-1 instead of len(weights) in the for loop.

This is not an "off by 1" error. If the length len(a) of an array a is n, the loop for i in range(0, n): ... will refer to elements a[0] through a[n-1] as it should. (It is customary to use names like i, j, ..., for integer loop indexes; x suggests a floating-point number.)

Notice you are referring to three arrays here: weights, context.prev_weights, and context.reqd_data. Are you sure they're always the same length? In fact, the error will not be thrown if the other two arrays are longer than weights.

Further, the first two order_target_percent calls are the same. You can combine the first two loops into

        for x in range(len(weights)):  
            if abs(weights[x]) != abs(context.prev_weights[x]):  
                order_target_percent(context.reqd_data[x], weights[x])  

range(0, n) is the same as range(n).

And the last loop can be eliminated, because the if condition is never true.