Exponentially Weighted Moving Average (EWMA) in Python
Introduction
In time series analysis, the Exponentially Weighted Moving Average (EWMA) is a popular method used to smooth data and calculate the trend over a time period. It assigns exponentially decreasing weights to the observed data points, giving more importance to recent observations. This article will explain the concept of EWMA and provide a code example in Python.
Understanding EWMA
The EWMA is a weighted average where the weights decrease exponentially as we move further back in time. It is defined by the formula:
![EWMA Formula](
Where:
- Y<sub>t</sub> - the EWMA at time t
- α - the smoothing factor (0 < α < 1)
- X<sub>t</sub> - the observed value at time t
- Y<sub>t-1</sub> - the EWMA at time t-1
The smoothing factor α determines the rate at which the weights decrease. A smaller α gives more weight to recent observations, making the EWMA more sensitive to changes, while a larger α gives more weight to past observations, resulting in a smoother trend.
Code Example
import numpy as np
def ewma(data, alpha):
weights = np.exp(np.linspace(-1., 0., len(data)))
weights /= weights.sum()
avg = np.convolve(data, weights, mode='full')[:len(data)]
avg[:alpha] = avg[alpha]
return avg
# Example usage
data = [10, 12, 11, 13, 14, 15, 16]
alpha = 3
smoothed_data = ewma(data, alpha)
print(smoothed_data)
In this code example, we define a function ewma
that takes in a list of data and the smoothing factor alpha. It calculates the weights using the formula explained earlier. The np.convolve
function is then used to perform the weighted average calculation on the data. Finally, we adjust the first few elements of the result to avoid bias caused by insufficient data.
We apply the ewma
function on a sample dataset [10, 12, 11, 13, 14, 15, 16]
with a smoothing factor of 3. The resulting smoothed data is printed, which helps to identify the underlying trend in the dataset.
Conclusion
The Exponentially Weighted Moving Average (EWMA) is a useful method for smoothing time series data and identifying underlying trends. It assigns exponentially decreasing weights to observations, giving more importance to recent data points. In this article, we provided a code example in Python to demonstrate how to calculate EWMA. By tweaking the smoothing factor, you can adjust the sensitivity of the EWMA to changes in the data.