Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
help with how to ensure that algorithm is not investing more than 5% of total exposure in a single stock

Hi,

So i am trying to create an algorithm such that my portfolio is not investing more than 5% in a single stock. However, the stock can grow to more than 5% but every time i rebalance (be it daily, weekly or monthly) i want it to go back to at most 5% of my portfolio.

Was wondering how i can do this with "order_optimal_portfolio" as well as with "order_target_percent".
Take note that i want to buy from a specific set of stocks.
Long/Short is based on stocks with 20day Exponential Moving Average crossing 50day Exponential Moving Average. Liquidating position is based on price crossing 50day Exponential Moving Average.

Currently, I am ordering and rebalancing based on the code below.

Would love to hear your opinions on this method as well!

Thanks!

def my_rebalance_L(context, data):  
    long_secs = context.output.loc[  
        context.output['EMA_20'] > context.output['EMA_50']  
        ].index.tolist()  
    for security in long_secs:  
        if security not in context.portfolio.positions and data.can_trade(security):  
            order_target_percent(security, 0.05)  
def my_rebalance_CL(context, data):  
    liquidate_long = context.output.loc[  
        context.output['close'] < context.output['EMA_50']  
        ].index.tolist()  
    for security in context.portfolio.positions:  
        if security in liquidate_long:  
            order_target_percent(security,0)  
def my_rebalance_S(context, data):  
    short_secs = context.output.loc[  
        context.output['EMA_20'] < context.output['EMA_50']  
        ].index.tolist()  
    for security in short_secs:  
        if security not in context.portfolio.positions and data.can_trade(security):  
            order_target_percent(security, -0.01)  
def my_rebalance_CS(context, data):  
    liquidate_short = context.output.loc[  
         context.output['close'] > context.output['EMA_50']  
        ].index.tolist()  
    for security in context.portfolio.positions:  
       if security in liquidate_short:  
            order_target_percent(security, 0)