Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Look Back For Max High/Low Within A Certain # Of Days

Hi all, Im looking for an example for how to set up a trailing max High/Low but look within an N number of price bars. I tried min() max() but could not constrain it to a certain price bar period.

Example use: determine when price has closed above max high of the last N trading days - classic stuff

Thanks

4 responses

pandas has functions for rolling_max and rolling_min I believe.

Simon, thanks for getting back - I tred to integrate rollin_min/max but it has code error, not sure i added the function properly. Could not attach the backtest since it fails, so heres the code:

Thanks for your time

import pandas

def initialize(context):  
    set_benchmark(sid(8554))  
    context.stocks = [sid(8554), sid(21519), sid(19920)]  
    context.weight = 1.0 / (len(context.stocks))  
    schedule_function(  
        orderlogic,  
        date_rules.every_day(),  
        time_rules.market_open(hours=0, minutes=1)  
    )

def orderlogic(context, data):  
    high = history(60, "1d", "high")  
    low = history(60, "1d", "low")

    for stock in context.stocks:  
        price = data[stock].price  
        highp = high[stock][-2]  
        lowp = low[stock][-2]  
        # Trying to get the rolling N day max high/low for a stock  
        pmax = pandas.stats.moments.rolling_max(highp[stock], 10)  
        pmin = pandas.stats.moments.rolling_min(lowp[stock], 10)

        position = context.portfolio.positions[stock].amount  
        if price < pmin and position >= 0:  
            order_target_percent(stock, 0)  
            log.info("FLAT " + str(stock.symbol))  
        if price > pmax and position <= 0:  
            order_target_percent(stock, context.weight)  
            log.info("LONG " + str(stock.symbol))  


    record(  
        Price=price,  
        Weight=context.weight,  
        POS=position  
        )

def handle_data(context, data):  
    pass  

Maybe something like this?

Fantastic, Thanks Simon!