Back to Community
Order Target Percent

Hi,

I want to run a code that has even position sizing up to a maximum of 1.5%.

The code I tried running was

def my_weights(context):

    num_secs = (len(short_secs) + len(long_secs))  

    if 1/num_secs < 0.015:  
        weight = (1/num_secs)  
    else:  
        weight = 0.015  

    long_weight = 0.015  
    short_weight = -0.015

and then calling it using:

order_target_percent(security, context.long_weight)  

But I keep getting an error. How do I get this to work?

Thanks,
Chris

6 responses

Hi Chris,

Are you wanting to maintain a gross leverage of 1.0?

Also, I would use 1.0/num_secs to ensure that you are doing floating point division.

What error are you getting? Your code does not change context.long_weight so maybe the error is that context.long_weight doesn't exist?

Hi Grant,

Yes I would live leverage of 1.0. And it seemed to work by changing it to 1.0. Does context.long_weight not draw on the long_weight function embedded my_weights(context)?

edit - should have read;

long_weight = weight
short_weight = -weight

You have to do this:

context.long_weight = weight  
context.short_weight = -weight  

Or simply use:

context.weight = weight  

Then, when you order the shorts, you can use:

order_target_percent(security, -context.weight)  

To keep the gross leverage at 1.0, you need to consider that for less than 67 securities in your universe, you'll have a problem, since 1/66 = 0.0152 (and 1/67 = 0.0149) which is greater than your limit of 0.015, so you'd need to drop the gross leverage to less than 1.0 for less than 67 securities. For a universe of 67 or larger, if you want equal weights, then you'll always be within the limit of 0.015, and maintain a gross leverage of 1.0.

So, I'm confused what you are trying to do. If you want "even position sizing" and 0.015 max weight and gross leverage of 1.0, then it seems you are just talking about a constraint on the number of securities in your universe, right? Or am I missing something?

Ok thanks for the weights.

Say the filter has 100 securities that it wants to buy, I want it to allocate 1% of my portfolio to each position.

However, if I only 20 securities pass through the filter, I want it to allocate only 1.5% of my portfolio instead of 5%, so I'll only be using 30% of my capital at that stage.

Does that make sense?

so I'll only be using 30% of my capital at that stage

You gross leverage will be < 1.0, but from your comments above, I thought you wanted ~ 1.0. Either way, if you are still stuck, just let me know.

I should've said <=1. Thanks Grant