Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Creating custom Simple Moving Averages?

Hello,

I want to create a moving average of n1=(highest high and lowest low for 9 days)/2 ( past 9 days not including the current day data) and similarly moving average of n2=(highest high and lowest low for 30 days)/2 ( past 30 days not including the current day data).

Long:
n1>n2

Sell:
previous day high < n1

Thanks in advance.

1 response

@Suryadeep N,

You can start with the code in this strategy. The method you'd be interested is "CalcHighLowRange". You'll need to enact your own entry/exit logic. This one uses the existing highlowsaw mechanism (something I was toying with).

Your spec was rather vague so I assumed some things. Here's the code for that method. If anyone with some even mediocre experience with pandas could convert those two loops to a rolling_mean or an applies with lambda... I'm sure we would all benefit.

def CalcHighLowRange(context, data):  
    '''  
    rangeA = SMA((HH(9) + LL(9)) / 2, 9)  
    rangeB = SMA((HH(30) + LL(30)) / 2, 30)  
    '''  
    highDeckA = history(HighLowRngPeriodsA * 2, "1d", "high").dropna(axis=1)[0:-1]  
    highDeckB = history(HighLowRngPeriodsB * 2, "1d", "high").dropna(axis=1)[0:-1]  
    lowDeckA  = history(HighLowRngPeriodsA * 2, "1d", "low").dropna(axis=1)[0:-1]  
    lowDeckB  = history(HighLowRngPeriodsB * 2, "1d", "low").dropna(axis=1)[0:-1]

    for stock in data:  
        try:  
            # A  
            window   = len(highDeckA[stock]) - HighLowRngPeriodsA  
            rangeSum = 0  
            for i in xrange(HighLowRngPeriodsA):  
                rangeSum += (highDeckA[stock][i:i + window].max() + lowDeckA[stock][i:i + window].min()) / 2.0  
            data[stock].HighLowRangeA = rangeSum / HighLowRngPeriodsA

            # B  
            window   = len(highDeckB[stock]) - HighLowRngPeriodsB  
            rangeSum = 0  
            for i in xrange(HighLowRngPeriodsB):  
                rangeSum += (highDeckB[stock][i:i + window].max() + lowDeckB[stock][i:i + window].min()) / 2.0  
            data[stock].HighLowRangeB = rangeSum / HighLowRngPeriodsB  
        except:  
            continue