Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Amount of Positions

Hi everyone,
I was wondering how to set a limit(7) on the amount of positions my portfolio contains. If the portfolio has reached the max number of positions, no new positions will be taken until some of the existing positions are closed out. Your help is greatly appreciated!

1 response

I guess you have to wrap the order_target around a function that checks how many positions you currently have.Something like...

def initialize(context):  
      context.max_position = 100

def my_order_target(context, security, amount):  
    current_position = 0  
    for sec in context.portfolio.positions:  
        sec_amount = context.portfolio.positions[sec].amount  
        current_position += sec_amount  if sec_amount >= 0 else  -sec_amount  
    if current_position+amount >= context.max_position:  
        amout = context.max_position - current_position  
    if amout >= 0:  
        order_target(security, amount)

You might also want to avoid calling the function if there are open orders pending.