Exponential Moving Average

Pieter P

Difference equation

The Difference equation of an exponential moving average filter is very simple: In this equation, is the current output, is the previous output, and is the current input; is a number between 0 and 1. If , the output is just equal to the input, and no filtering takes place

The filter is called 'exponential', because the weighting factor of previous inputs decreases exponentially. This can be easily demonstrated by substituting the previous outputs:

Impulse and step response

From the previous equation, we can now easily calculate the impulse and step response.

The impulse response is the output of the filter when a Kronecker delta function is applied to the input. For example, if , the impulse response is as follows:

The step response is the output of the filter when a Heaviside step function is applied to the input. For example, if , the step response is as follows:

Transfer function

You can express the output of discrete-time linear time-invariant systems, of which the EMA is an example, as the convolution of the input with the impulse response.
You can easily see that all terms where are zero, because the Kronecker delta is zero in that case. Only the term for is non-zero, in which case the Kronecker delta is one, so the result is just .
If is the transformation performed by the DTLTI system, and by using the fact that is a linear transformation and that it is time-invariant: Analysis of such systems is usually easier in the Z-domain, in which the convolution is reduced to a simple product.
The (unilateral) Z-transform is defined as: If , and are the Z-transforms of the input, output and impulse response respectively, then: is called the transfer function of the system.

Let's calculate the transfer function of the EMA.
We can use one of two approaches: use the difference equation and use some of the properties of the Z-transform to calculate , or apply the definition of the Z-transform to the impulse response directly.

Using the difference equation

All you have to do is apply the time shifting property of the Z transform: Then just rearrange the terms.

Using the impulse response

The last step is only valid if the sum converges, this is the case for . (See Infinite Geometric Series)

In these expressions, is a complex variable, and is a complex function.
There are a couple of interesting values for : values that result in the numerator becoming zero, called zeros, and values that result in the denominator becoming zero, called poles. By rewriting the transfer function, we can easily see that is a zero, and is a pole.

The poles and zeros determine the overall effect of the transfer function, so pole-zero plots are a very useful tool when describing filters.
This is the pole-zero plot of the same example EMA as before, with . The zero in the origin is indicated by an O, and the pole at by an X.

Frequency response

An important property of discrete-time linear time-invariant systems is that it preserves the pulsatance (frequency) of sinusoidal signals, only the phase shift and the amplitude are altered.
This makes it relatively easy to express the frequency response (sometimes called magnitude response) of a filter.

We're interested in the spectrum of frequencies that a signal contains, so it makes sense to decompose it as a sum of sines and cosines. That's exactly what the discrete-time Fourier transform does: Note that this is just a special case of the Z-transform, where .

The frequency response of the filter describes how the spectrum of a signal is altered when it passes through the filter. It relates the spectrum of the output signal to the spectrum of the input signal . We already had an expression for the spectrum of the output divided by the spectrum of the input, we called it the transfer function . To get the frequency response of the filter, we can just evaluate the transfer function for . Also note that this is the DTFT of the impulse response . We can now calculate the amplitude of each frequency component in the output by taking the modulus of . For reasons that will become apparent in a minute, we'll calculate the modulus squared. We use Euler's formula for writing the exponential as a sines and cosines. is the normalized pulsatance in radians per sample. You can substitute it with where is the frequency in Hertz, and is the sample frequency of the system in Hertz.

We can now plot the filter's gain in function of the frequency. These plots often use a logarithmic scale, to show the gain in decibels. In order to calculate the power gain, the amplitude is squared. Note that when a frequency is not present in the output signal, the gain will be . If a frequency has an amplitude of one in the output signal, the gain will be . You can clearly see the low-pass behavior of the EMA: low frequencies have a near-unit gain, and high frequencies are attenuated.

To get a better understanding of where this curve comes from, we can plot the entire surface in the Z-domain. As mentioned above, the DTFT is just a special case of the Z-transform, where , i.e. the unit circle in the complex plane. Remember that the point is a point with a distance of to the origin, and with an angle of between its position vector and the positive x axis. The image of the unit circle is shown in blue. Notice that this is the same curve as the blue curve in the magnitude response graph above: close to 0 when (the right half of the circle) and negative when (the left half of the circle).
You can clearly see the effect of the pole at . The zero in the origin has no effect on the frequency response, because it doesn't alter the image of the unit circle, since or .

Cutoff frequency

The cutoff frequency is defined as the frequency of the half-power point, where the power gain is a half. It's often called the -point, because .
To find it, just solve the following equation:

For example, if , then .
To convert it to a frequency in Hertz, you can multiply by , with the sample frequency.
For example, if the sample frequency is , then .

Plotting the frequency response in Python

We can use the SciPy and Matplotlib modules to plot the frequency response in Python.

from scipy.signal import freqz 
import matplotlib.pyplot as plt
from math import pi, acos
import numpy as np

alpha = 0.25

b = np.array(alpha)
a = np.array((1, alpha - 1))

print("b =", b)                        # Print the coefficients
print("a =", a)

x = (alpha**2 + 2*alpha - 2) / (2*alpha - 2)
w_c = acos(x)                          # Calculate the cut-off frequency

w, h = freqz(b, a)                     # Calculate the frequency response

plt.subplot(2, 1, 1)                   # Plot the amplitude response
plt.suptitle('Bode Plot')            
plt.plot(w, 20 * np.log10(abs(h)))     # Convert to dB
plt.ylabel('Magnitude [dB]')
plt.xlim(0, pi)
plt.ylim(-18, 1)
plt.axvline(w_c, color='red')
plt.axhline(-3, linewidth=0.8, color='black', linestyle=':')

plt.subplot(2, 1, 2)                   # Plot the phase response
plt.plot(w, 180 * np.angle(h) / pi)    # Convert argument to degrees
plt.xlabel('Frequency [rad/sample]')
plt.ylabel('Phase [°]')
plt.xlim(0, pi)
plt.ylim(-90, 90)
plt.yticks([-90, -45, 0, 45, 90])
plt.axvline(w_c, color='red')
plt.show()