0

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'])
Programming_Learner_DK
  • 1,509
  • 4
  • 23
  • 49

1 Answers1

0

just use

def np_moving_range(array, fill_val = None):
   return np.r_[fill_val, np.diff(array)]
   
Onyambu
  • 67,392
  • 3
  • 24
  • 53
  • np.diff() worked, here's the final form I used to match my function: np.abs(np.diff(a=my_array, n=1, prepend=np.nan)) – Programming_Learner_DK Mar 03 '23 at 09:24
  • @Python_Learner_DK i dont know why you would take absolutes since in your original code you did not. Also, instead of prepending NaN, you could define the fill value as NaN and just concatenate it if its NaN or if its a value, rather than prepending and then changing it to the fill value – Onyambu Mar 03 '23 at 13:05
  • Please look in my code, fourth line up from the bottom, you'll see the abs() function. For my end use I am always expecting the first value to be empty/nan. When I tested np.diff() it didn't return the first value (nan) so I used the prepend feature. – Programming_Learner_DK Mar 03 '23 at 17:54
  • @Python_Learner_DK Yes I see the `abs` function. Its okay – Onyambu Mar 03 '23 at 19:01