Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Backtest Issue: Short Sell/Buy Orders

When running my algorithm, I am seeing a short Sell order that is followed by a BUY order to balance out.
That said, the buy order is issued at a different price than the selling price. I am wondering if this process is affecting the Backtest Overall Return.
Please see an attached snap of the transaction detail.
https://www.dropbox.com/s/rs6ix6hq8bm5lw4/Short%20Sell%20Issue%20Back%20Test%20OPTT.PNG?dl=0

If so, how do I prevent that from happening?
Btw, I am using the following function to issue sell:

order_target_percent(context.stock1,0.0)  
2 responses

Can we get any more code to see what is triggering your buy?

So I think this is happening because of my second sell command. The first stop-less/sell logic sells all according to a certain condition. So order_target_percent(context.stock1,0.0) is working.
However, in the second stop-loss logic, I am trying to sell half of my current position when the price changes by a certain amount.

    #sell all  
    elif context.trans_mode =="Sell_Mode" and purch_curr_pctChange < X_PercSell:  
        order_target_percent(context.stock1,0.0)  
    #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)  
        log.info("Sell 50% with purchase price = "+str(costBasis) + " and current price = " + str(CurPriceClose))  

It's selling exactly what I can buy for 50% of my portfolio.

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

num_of_shares= context.portfolio.positions[context.stock1].amount  
elif context.trans_mode =="Sell_Mode" and purch_curr_pctChange > Y_PercSell:  
        half_num_of_shares = num_of_shares/2  
        log.info("Half of Number of Shares = "+str(half_num_of_shares))  
        order_target_value(context.stock1, -half_num_of_shares)  
        context.trans_mode = "Sell_Half_Mode"  

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 that makes sense.