A Practical Guide to Moving Average Methods — Part One: Foundations of Moving Averages

Ali kamali
5 min readJan 28, 2024

--

Image created by the author

This tutorial is the first in a three part series to demystify the fundamental concepts of moving averages, a cornerstone in time series analysis.

In this series, we delve into the main concepts and core types of moving averages: the Simple Moving Average (SMA), which lays the groundwork for understanding this concept; and the Weighted Moving Average (WMA), which allows for customized weighting of data points. This foundational knowledge sets the stage for more sophisticated techniques like ARIMA and EWMA, further enhancing your toolkit for effective and accurate data forecasting.

Our journey begins with the basics, unpacking the essence of moving averages and their pivotal role in data analysis. This tutorial is tailored to provide not just theoretical insights but practical applications, along with Python code examples.

In the realm of time series analysis and forecasting, moving averages play a critical role. By smoothing out data fluctuations, they help in revealing underlying trends and patterns. This method is particularly valuable in sectors where understanding and predicting future trends is essential for making informed decisions.

At its core, a moving average is a statistical method pivotal in time series analysis. It’s employed to analyze a set of data points by creating a series of averages of different subsets of the full data set. It involves calculating the average of data points over a specified period, known as the ‘window.’ As new data becomes available, this window moves forward, encompassing the most recent data while dropping the oldest, thereby updating the average continuously.

The primary advantage of using a moving average lies in its ability to filter out ‘noise’ — the random short-term fluctuations that can often obscure the true direction of the underlying trend. By averaging the data, these transient changes are smoothed out, allowing clearer visibility of longer-term patterns or trends. This smoothing effect is particularly beneficial in volatile markets or sectors where data can fluctuate wildly due to a variety of unpredictable factors.

Moreover, moving averages can be tailored to suit various analytical needs. For instance, a shorter moving average window will stay closer to the original data and react more quickly to recent changes, while a longer window will provide a smoother, more generalized view of the trend over time. This flexibility allows analysts to choose the appropriate balance between sensitivity to recent data changes and the smoothing of volatility, depending on their specific analysis requirements.

There are various types of moving averages, each with its unique way of calculating and emphasizing different data points. The most commonly used types include the Simple Moving Average (SMA) and Weighted Moving Average (WMA).

Simple Moving Average

Let’s start with Simple Moving Average. To illustrate the concept of SMA in a more tangible way, let’s consider a practical example using Python. Here, we compute an SMA which is the arithmetic average of a set of values over a specified period. We use a hypothetical dataset representing weekly closing prices of a stock to illustrate this:

import pandas as pd

# Sample dataset: weekly closing prices of a stock
data = {'Price': [10, 12, 14, 16, 18, 20, 22]}
df = pd.DataFrame(data)

# Calculate a 3-week SMA
df['SMA_3'] = df.iloc[:,0].rolling(window=3).mean()

In this code, we first create a DataFrame with a series of stock prices and then calculate 3-week SMA.

The rolling method allows us to specify a ‘window’ of time (3 weeks in this case) for the moving average calculation. This ‘window’ slides across our data, calculating the average for each subset of values.

The mean() function computes the average of the values within each window. So, for each set of three prices in our dataset, mean() calculates their average, providing us with the SMA at each point.

   Price  SMA_3
0 10 NaN
1 12 NaN
2 14 12.0
3 16 14.0
4 18 16.0
5 20 18.0
6 22 20.0

The first two entries for SMA_3 are NaN because there aren't enough data points to calculate a 3-week average until the third week. From the third entry onwards, we see the SMA calculated for each 3-week window.

Weighted Moving Average

Now, let’s delve into the Weighted Moving Average (WMA), a variation of the moving average that allows for customized weighting of data points. For one instance, you can assigns more weight to recent data points, reflecting their greater relevance to the analysis.

To demonstrate WMA, we’ll use a similar dataset of weekly closing prices of a stock:

import pandas as pd
import numpy as np

# Sample dataset
data = {'Price': [10, 12, 14, 16, 18, 20, 22]}
df = pd.DataFrame(data)

# Calculate 3-week WMA
weights = np.array([1, 2, 3])
sum_weights = np.sum(weights)
df['WMA_3'] = df['Price'].rolling(window=3).apply(lambda x: np.dot(x, weights) / sum_weights, raw=True)

Here, we first define our dataset similar to the SMA example. To calculate the WMA:

  1. Define Weights: We explicitly define the weights for each week within our 3-week ‘window’. In this case, the most recent week is given the highest weight, reflecting its importance.
  2. Calculate WMA: Using the rolling method, we specify our 3-week window. Within this window, we apply a custom function that calculates the weighted average by using np.dot to multiply each set of prices by the corresponding set of weights and then divide by the sum of the weights. This custom function is applied to each window of data to compute the WMA.

The result is a new column, WMA_3, showing the weighted moving average for each period.

   Price      WMA_3
0 10 NaN
1 12 NaN
2 14 12.67
3 16 14.67
4 18 16.67
5 20 18.67
6 22 20.67

The first two entries in WMA_3 are NaN for the same reason as in the SMA example: there aren't enough data points to calculate a 3-week average. From the third entry onwards, the WMA is calculated for each 3-week window, taking into account the assigned weights.

The Weighted Moving Average (WMA) allows for customization of the weights assigned to each data point within the moving average window. This flexibility means that while it’s common to give more emphasis to recent data points in many financial and analytical applications, the weighting is entirely customizable based on the specific needs or goals of the analysis. Weights can be adjusted to emphasize not just the most recent data but any period or specific points that are of particular interest. For instance, in seasonal analysis, certain times of the year could be given more weight.

Diving into the basics of Moving Averages, we’ve just scratched the surface of this powerful analytical tool. While SMA and WMA offer great starting points, there’s more to discover.

Next in this series, we’re going to explore Exponential Moving Averages (EMA), which bring its own unique twists to the table. EMA focuses more on recent data, offering a fresh look at trends.

--

--

Ali kamali

Ph.D. candidate in Industrial Engineering with a focus on predictive data science and machine learning.