jmquintana79
5/8/2017 - 6:28 AM

moving average

Moving Average: Simple and Modified

## calculate Simple Moving Average
def simple_moving_avg(w,nprev):
    import numpy as np
    import copy
    # assign
    wp = copy.deepcopy(w)
    # calculate simple moving average
    n = len(wp)
    for i in range(nprev,n):
        signal = wp[i-nprev:i+1]
        if len(signal[~np.isnan(signal)])>0: w[i] = np.mean(signal[~np.isnan(signal)])
        else: w[i] = np.nan
    # return
    return w



## calculate Modified Moving Average
def modified_moving_avg(w,nprev):
    import numpy as np
    # calculate simple moving average
    n = len(w)
    for i in range(nprev,n):
        signal = w[i-nprev:i+1]
        if len(signal[~np.isnan(signal)])>0: w[i] = np.mean(signal[~np.isnan(signal)])
    # return
    return w