Back to Community

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 ...  

    [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.  = []        # 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.  # Portfolio value added once per day  =[-lookback:]                  # Trim list  
    if[-1] < ratio * max(    # If last value below highest by ratio amount. 'Liquidating {} < {} * {}'.format(  
      [-1], ratio, ratio * max(  
        # 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