Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
HELP with Backtesting and Selling orders

Hello,
I've been trying to get an answer regarding this issue, but still cannot figure it out. For my algo, I am trying to build a stop-loss logic as the following: (after a purchase is made)

  1. If stock percent change goes down by a certain percent (say X%), Sell all 100% using
    #sell all  
    elif context.trans_mode =="Sell_Mode" and purch_curr_pctChange < X_PercSell:  
        order_target_percent(context.stock1,0.0)  
  1. If stock percent change goes up by a certain percent (say Y%), Sell half (50%) of current position using
#sell half  
    elif context.trans_mode =="Sell_Mode" and purch_curr_pctChange > Y_PercSell:  
        for stock in context.portfolio.positions:  
            order_target_percent(stock, -0.5)  

The first stop-loss logic is working and selling exactly the purchased amount of shares. However, in the second stop-loss logic, it's not putting an order to exactly sell half the number of shares.

I tried another approach; to define the number of shares bought, then use half of the number to sell using the following:

#get the number of shares bought  
num_of_shares = context.portfolio.positions[context.stock1].amount  
half_num_of_shares = num_of_shares/2  
#sell half  
elif context.trans_mode =="Sell_Mode" and purch_curr_pctChange > Y_PercSell:  
        order_target_value(context.stock1, -half_num_of_shares)  

but it's still not working. For example, it purchases 120 shares at first, then when I am trying to sell half, it defines half_num_of_shares = 60.
but then when it commits to the sell half, it sells 180 shares instead of 60. In other words, it is adding the number of shares I want to sell to the number of shares bought 120+60. I don't understand why this is happening.

Hope my description of the problem makes sense.

2 responses

Use your second approach but replace 'order_target_value' with the plain 'order' method https://www.quantopian.com/help#api-order .

    order(context.stock1, -half_num_of_shares)  

It makes sense that 'order_target_value' will end up selling 3 times the desired shares. It's placing orders to get to a specified target value . In the example above, that target value is -60. If the current holdings are 120, it places orders to sell 180 shares to get to the target of -60 shares.

Using the plain 'order' method will simply place an order for the desired shares as you are looking to do.

Good luck.

It's working now!
Much thanks, Dan.