Search code examples
numpynumpy-ndarraynumpy-slicingnumpy-ufunc

Numpy function/method to calculate moving range?


Want to calculate moving range in numpy.

Wrote function using Pandas, want simple/fast way to return numpy array with equivalent values. Don't need the name of new array, just the values.

def get_moving_range(my_series, na_replace_value=None):
        """Returns calculated moving range series object.

        Args:
            my_series (pandas series): Series to derive moving range from.
            na_replace_value (numeric, optional): first value of moving range is nan by default, if different value is desired use this, otherwise leave as None. Defaults to None.
        """
        # rename series to keep it easy
        my_series.name = 'original'
        # convert to DataFrame
        df = my_series.to_frame()
        # create the offset so I can do the Xn - Xn-1 calculation easy
        df['shifted'] = df['original'].shift(1)
        # calculate the moving range values
        df['Moving Range'] = abs(df['original'] - df['shifted'])
        if na_replace_value != None:
                df.fillna(value=na_replace_value, inplace=True) 
        return(df['Moving Range'])

Solution

  • just use

    def np_moving_range(array, fill_val = None):
       return np.r_[fill_val, np.diff(array)]