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

Hi,
I feel this should be addressed in the API (and it maybe is, I just haven't found it), but is there an easy way to find out what stocks you own and if you own any stocks, sell all of them? I looked at context.portfolio.positions, but I don't know how to extract the information. I also don't want to hardcode security symbols into my algorithm.

Thanks for the help!

1 response

I happen to be working with that right now in case any of this makes any sense for ya.

c = context  
pflo = c.portfolio

if some condition calling for liquidation and not c.liquidating:  
    c.liquidating = 1    # Initialize liquidation  
    for sec in pflo.positions:    # Try to liquidate  
        if pflo.positions[sec].amount <= 0: continue  
        if get_open_orders(sec): continue    # Avoid shorting  
        order_target(sec, 0) # Sell all  
    return  

and then on succeeding bars, have to make sure. This is mostly a repeat of above with a logging line added:

if c.liquidating:    # Clean/finish up missed liquidations, partial sells etc.  
    for sec in pflo.positions:    # Try to complete liquidation  
        if pflo.positions[sec].amount <= 0: continue  
        if get_open_orders(sec): continue    # Avoid shorting  
        log.info('liquidating yet {} shrs {} of {} remaining'.format(  
                sec.symbol, pflo.positions[sec].amount, sec.symbol))  
        order_target(sec, 0) # Sell all  
    return  

Once done, clear the trigger:

if not pflo.positions_value:  
    c.liquidating = 0  
    return