Python Pandas

Pandas Exponential Moving Average

In Python, the “Pandas” library is used with various methods and with different data types, such as tabular, time series, and multidimensional. It can also be utilized to determine/calculate moving averages, which is simply the average value of a specific number of previous periods. The simple moving average gives equal weight to all observations in the window, while the exponential moving average (EMA) gives/provides more weight to recent/new observations and less weight to older ones.This write-up will present you with a detailed guide on finding the exponential moving average via the following content:

How to Calculate Pandas Exponential Moving Average in Python?

The “DataFrame.ewm()” is a function in pandas that is utilized to perform exponentially weighted moving average (EWMA) calculations on a DataFrame. The exponentially weighted calculations assign more weightage to recent/new observations than older/last ones.

Syntax

DataFrame.ewm(com=None, span=None, halflife=None, alpha=None, min_periods=0, adjust=True, ignore_na=False, axis=_NoDefault.no_default, times=None, method='single')

Parameters

In the above syntax:

  • The “com” parameter and the “span” parameter indicate the reduction in the center of mass and the span for the weighting function.
  • The “halflife” and “alpha” parameters specify the half-life and the smoothing factor for the weighting function.
  • The “min_periods” indicates the minimum number of observations needed to have a correct output/result.
  • The “adjust” parameter indicates whether to divide by the decaying adjustment factor in the beginning periods.
  • The “ignore_na” specifies whether to ignore missing values when calculating weights.

For other syntax functionality, you can check the official documentation.

Return Value

The return value of the “DataFrame.ewm()” function is a new DataFrame that contains the EWMA of the original DataFrame.

Example 1: Determine Exponential Weighted Moving Average

The following code is used to determine an exponentially weighted moving average for a specified number of previous/last periods. To determine the EWMA for three previous periods, the “span=3” is passed to the “ewm()” function. The span parameter specifies the number of periods to use for the EWMA. In this case, the adjust parameter is set to False, which means that the weights are not adjusted.

import pandas
data1 = pandas.DataFrame({'score1': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
                   'score2': [35, 30, 24, 26, 37, 30, 22, 25, 24, 29]})
data1['EWM'] = data1['score2'].ewm(span=3, adjust=False).mean()
print(data1)

The below output of the ewm() function is a new DataFrame that contains the EWMA of the original DataFrame:

Example 2: Visualize Exponential Weighted Moving Average

The “matplotlib” library can also be utilized to visualize the DataFrame column “score2” compared to the 3-day exponentially weighted moving average:

import pandas
import matplotlib.pyplot as plt
data1 = pandas.DataFrame({'score1': [10, 20, 3, 40, 5, 60, 7, 80, 9, 10],
                   'score2': [35, 30, 24, 26, 27, 30, 22, 25, 24, 29]})
data1['EWM'] = data1['score2'].ewm(span=3, adjust=False).mean()
print(data1)
plt.plot(data1['score2'], label='score2')
plt.plot(data1['EWM'], label='EWM')
plt.legend(loc=2)
plt.show()

The below output shows the DataFrame columns containing the exponential weighted average with a span of three days:

The below graph visualizes the column “score2” compared to the EWMA:

Bonus: How to Calculate a simple moving average in Python?

The “pandas.rolling()” function is used to determine the simple moving average in Python. Here is an example code that determines the simple moving average:

import pandas
import matplotlib.pyplot as plt
data1 = pandas.DataFrame({'score1': [10, 20, 3, 40, 5, 60, 7, 80, 9, 10],
                   'score2': [35, 30, 24, 26, 27, 30, 22, 25, 24, 29]})
data1 = data1.assign(Moving_Average = data1['score2'].rolling(3).mean())
print(data1)

The following output displays the simple moving average:

Conclusion

The “DataFrame.ewm()” function of the “pandas” library is used to execute exponentially weighted moving average computation on a DataFrame. In this exponentially weighted calculation, the “ewm()” function assigns more weight to recent/new observations than older ones. This write-up delivered a precise tutorial on retrieving the exponential moving average using several examples.

About the author

Haroon Javed

Hi, I'm Haroon. I am an electronics engineer and a technical content writer. I am a tech geek who loves to help people to the best of my knowledge.