Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Liquidating

A start toward liquidating on portfolio drop to reduce drawdown. The heart of this one is the append and next two lines.
Could combine with a slope calculation for example and/or other.

def handle_data(context, data):  
    if liquidate(context, data):  
        # Do something differently like sitting out for awhile, then ...  
        return

    [normal ordering etc]

def liquidate(context, data):  
    lookback = 30              # Number of days portfolio values to keep.  
    ratio    = .91             # How low before liquidation.  
    if 'pf' not in context:    # Portability. Init in initialize() for better efficiency.  
        context.pf = []        # A list for portfolio values.  
        context.date_prv = ''  # To be able to keep only one value per day.  
    if context.date_prv != get_datetime().date():   # If new day.  
        context.date_prv = get_datetime().date()    # New previous date.  
        context.pf.append(context.portfolio.portfolio_value) # Portfolio value added once per day  
        context.pf = context.pf[-lookback:]                  # Trim list  
    if context.pf[-1] < ratio * max(context.pf):    # If last value below highest by ratio amount.  
        log.info('Liquidating {} < {} * {}'.format(  
                context.pf[-1], ratio, ratio * max(context.pf)))  
        # Liquidate, scorched earth policy, make this less dumberer.  
        for s in data:  # Consider instead only selling those going down etc.  
            order_target(s, 0)      # Sell all. Or shorting etc  
        return 1  
    return 0