watex.utils.moving_average#
- watex.utils.moving_average(y, *, window_size=3, method='sma', mode='same', alpha=0.5)[source]#
A moving average is used with time series data to smooth out short-term fluctuations and highlight longer-term trends or cycles.
Funtion analyzes data points by creating a series of averages of different subsets of the full data set.
- Parameters:
y (array_like, shape (N,)) – the values of the time history of the signal.
window_size (int) – the length of the window. Must be greater than 1 and preferably an odd integer number.Default is
3method (str) – variant of moving-average. Can be
sma,cma,wmaandemafor simple, cummulative, weight and exponential moving average. Default issma.mode (str) – returns the convolution at each point of overlap, with an output shape of (N+M-1,). At the end-points of the convolution, the signals do not overlap completely, and boundary effects may be seen. Can be
full,sameandvalid. See ~np.convole for more details. Default issame.alpha (float,) – smoothing factor. Only uses in exponential moving-average. Default is
.5.
- Returns:
ya – Averaged time history of the signal
- Return type:
array like, shape (N,)
Notes
The first element of the moving average is obtained by taking the average of the initial fixed subset of the number series. Then the subset is modified by “shifting forward”; that is, excluding the first number of the series and including the next value in the subset.
Examples
>>> import numpy as np ; import matplotlib.pyplot as plt >>> from watex.utils.exmath import moving_average >>> data = np.random.randn (37) >>> # add gaussion noise to the data >>> data = 2 * np.sin( data) + np.random.normal (0, 1 , len(data)) >>> window = 5 # fixed size to 5 >>> sma = moving_average(data, window) >>> cma = moving_average(data, window, method ='cma' ) >>> wma = moving_average(data, window, method ='wma' ) >>> ema = moving_average(data, window, method ='ema' , alpha =0.6) >>> x = np.arange(len(data)) >>> plt.plot (x, data, 'o', x, sma , 'ok--', x, cma, 'g-.', x, wma, 'b:') >>> plt.legend (['data', 'sma', 'cma', 'wma'])
References