Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
How to liquidate all positions?

Hi everyone,

As I wish to close all my positions as signal shows, I use

    for stock in sell_pos:  
        if context.portfolio.positions[stock].amount != 0:  
            order_target(stock, 0 )  

However, the position does not all down to zero. It only sells one shares: (please see the screenshot via the link)
screenshot

Could you guys please advise where is wrong with my code? Thanks in advance!

6 responses

SH,

It may be the slippage model kicking in. Are there subsequent fills that eventually bring the position to zero?

Also, you might have a look at the order object. You should be able to do something like this:

order_ids = {}  
for stock in sell_pos:  
    if context.portfolio.positions[stock].amount != 0:  
        order_ids[stock] = order_target(stock, 0 )  

Then, you can have a look at the order objects, by using get_order().

Grant

Hi Grant,

Thanks so much for your advice. However, I met another problem: if I use above code, it will close out all the positions EVERYDAY and then long/short the same position the day after.

If I use

    for stock in sell_pos:  
        if context.portfolio.positions[stock].amount > 0:  
            order_target(stock, 0)  

it will hold the positions from the very first day till the end of the backtest (no other transactions at all). Would you please give me some advice again? Thank you very much!

SH,

It's tricky to be helpful without the relevant portions of the rest of your code. Do you have any other ordering anywhere in your algo? I just don't see how order_target(stock, 0) should be doing anything but closing out positions.

Grant

Hi Grant,

Thanks so much for your kind help. I just found out the reason - a stupid mistake: forget to reset the list before creating the sell_pos.

In any case, thank you so much for your patient and trick!

Hi,

Is it possible to liquidate portion of open shares or orders? For instance I wish to liquidate half of my portfolio value, not all.

Thank you!

Try:

for stock in context.stocks:  
    if data.can_trade(stock):  
        order_target_percent(stock,leverage*weight[stock])  

If the weights are normalized to 1.0 and the leverage is less than 1.0, then you should shift your portfolio partly to cash.