Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Stoploss as a percentage?

Hi all, I'm super new to Quantopian and I'm hoping to create a stop loss for a percentage loss.

The format I'm using is to setup the stop loss when I initially open the position... It looks like this:
order_target_percent(security, -.1, style=StopOrder( CODE ))
I just want to close out the position when it has lost 15% in value. I've tried various things for the last 30 minutes or so, to no avail.


6 responses

You could do something like this. Notice that to close a position enter 0 (not -.1). Get what you paid for the security with the '.cost_basis' method. You may want to verify you hold the position first?

price = context.portfolio.positions[security].cost_basis * (1 -.STOP_LOSS_PERCENT)  
order_target_percent(security, 0, style=StopOrder( price ))  

Thanks for your time and help.

I eventually figured out a way to do it based on what you said. For some reason "stoporder" isnt working for me. Something I'm doing wrong, I'm sure. In any case, here's the code that I ended up using:

    curr = context.portfolio.positions[security].last_sale_price  
    cost = context.portfolio.positions[security].cost_basis  
    if curr < (cost * .85):  
        order_target_percent(security, 0)  

Hello Mark and Dan,
I am also interested in trailing stop loss. In my strategy, I buy 10 stocks which have the highest momentum at the end of each month. After one month, I will sell all and repeat the buying step. It means that I don't know the names of stocks in the portfolio. Can you tell me how I should modify the code above to have trailing stop loss in my strategy? I want to sell any stock that lost 10% of its value.


I would created

schedule_function(stop_loss, date_rules.every_day(), time_rules.market_open(minutes = 60))  

and run exactly what Dan and Mark proposed

def stop_loss(context,data):  
    stop_pct = 0.10

    for sec in context.portfolio.positions:  
        curr = context.portfolio.positions[sec].last_sale_price  
        cost = context.portfolio.positions[sec].cost_basis  
        if curr < cost*(1.0 - stop_pct):  
            order_target_percent(sec, 0)  

But stop_pct = 0.10 for sure will substantially decrease return.

Hi Vladimir,
Thank you very much for your response. It worked wonderfully. Can you tell me how I should modify the code to set "trailing stop loss" instead of "stop loss"? The trailing stop loss is calculated based on the highest price of the stock since I bought it.

Thank you very much, Vladimir.