Skip to main content
LearnMLAcademy
Intermediate10 min read

Moving Average

Smooth noisy temporal signals using Simple and Exponential Moving Averages, with Python code, architecture diagrams, worked examples, and interview quiz.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

Moving Average in Time Series: SMA, EMA, WMA and MA(q)

Time-series data often moves up and down from one period to the next. A moving average helps us smooth some of those short-term fluctuations so that the broader pattern is easier to see.

Understand First

Take recent values
→ Move a window
→ Calculate an average
→ Smooth the series

For example, suppose daily website visits are 10, 20, 30, 40, 50. A 3-day moving average first uses 10, 20 and 30, then moves one step and uses 20, 30 and 40, then 30, 40 and 50.

WindowCalculation3-Day Average
Days 1–3(10 + 20 + 30) / 320
Days 2–4(20 + 30 + 40) / 330
Days 3–5(30 + 40 + 50) / 340

Two meanings of “Moving Average”

This lesson covers both moving averages used for smoothing (such as SMA and EMA) and the statistical MA(q) model used inside ARMA/ARIMA. They sound similar, but they are not the same idea.


What Is a Simple Moving Average?

A Simple Moving Average (SMA) calculates the arithmetic mean of observations inside a fixed-size rolling window. With a 3-period trailing SMA, every value in the most recent three observations receives equal weight.

SMA Formula

SMAt = (Xt + Xt-1 + ... + Xt-n+1) / n

For values 10, 20 and 30:

SMA = (10 + 20 + 30) / 3 = 20

Why does a moving average smooth data?

A single unusual observation affects only part of the window instead of becoming the entire displayed value. Averaging therefore reduces some short-term variation, although it can also make the smoothed series react more slowly to genuine changes.

Original values vs 3-period SMA

1
10
2
20
3
30
4
40
5
50
6
60
7
70
SMA
—
SMA
—
SMA
20
SMA
30
SMA
40
SMA
50
SMA
60

The first two SMA values are unavailable because a full 3-observation window does not yet exist.


Choosing the Moving-Average Window

The window size controls how much smoothing you get. There is no universally best window.

WindowTypical behaviorTrade-off
Smaller windowResponds faster to recent movementRetains more short-term noise
Larger windowProduces stronger smoothingCan lag behind genuine changes

Domain structure can also matter. For daily data, a 7-day window may be useful when weekly behavior is relevant; for monthly data, 12 periods may be meaningful when yearly seasonality is important. These are examples, not automatic rules.


SMA, WMA, EMA and Cumulative Average

1. Simple Moving Average (SMA)

Every observation inside the fixed window receives equal weight. SMA is easy to understand and is useful for descriptive smoothing, but larger windows can respond slowly to new changes.

2. Weighted Moving Average (WMA)

A WMA assigns chosen weights to observations. The weights do not have to decrease linearly; the weighting scheme depends on how you define it.

Example weights: 1, 2, 3 for values 10, 20, 30

WMA = (1×10 + 2×20 + 3×30) / (1+2+3) = 140 / 6 ≈ 23.33

3. Exponential Moving Average (EMA)

EMA gives more weight to recent observations while older observations retain progressively smaller influence. A common recursive form is:

EMAt = αXt + (1 − α)EMAt−1

When EMA is parameterized by a pandas-style span, α = 2 / (span + 1).

For span = 3:

α = 2 / (3 + 1) = 0.5

Start with EMA₁ = 10. For the next value 20:

EMA₂ = 0.5×20 + 0.5×10 = 15

Python detail that matters

In pandas, ewm(...).mean() uses adjust=True by default. The simple recursive formula above corresponds directly to adjust=False, which is why the Python example below specifies it explicitly.

4. Cumulative / Expanding Average

A cumulative average uses all observations seen so far, so its window keeps expanding rather than staying fixed. It is useful for quantities such as a running lifetime average, but it behaves differently from a fixed-window SMA.

MethodWhich observations matter?Weights
SMAFixed recent windowEqual
WMAUsually a chosen windowUser-defined
EMACurrent + decaying influence from the pastExponentially decaying
Cumulative averageAll observations so farEqual across included history

Smoothing Is Not Automatically Forecasting

A trailing 3-period SMA calculated at time t usually includes the observation at time t. That makes it a useful smoother, but it is not automatically a prediction that existed before time t was observed.

Smoothing at Day 7

Uses Days 5, 6 and 7:

(50 + 60 + 70) / 3 = 60

One-step forecast for Day 7

Must use information available before Day 7, e.g. Days 4, 5 and 6:

(40 + 50 + 60) / 3 = 50

Avoid future-data leakage

A centered moving average can use observations from both sides of a timestamp. That can be useful for retrospective visualization, but it would leak future information if used as a feature for a real-time forecasting model. For prediction, construct features only from information that would have been available at prediction time.


Moving-Average Model MA(q): A Different Concept

In ARMA and ARIMA, the MA(q) part does not mean averaging the latest observations. Instead, the current process value is represented using the current random shock and a finite number of past shocks/errors.

MA(q) form

Xt = c + εt + θ1εt−1 + ... + θqεt−q

  • c: constant/baseline term, depending on model parameterization
  • ε: innovation or random shock
  • θ: coefficients on lagged shocks
  • q: highest moving-average lag included

Worked MA(2) forecasting example

Suppose the fitted model has c = 50, θ₁ = 0.8, θ₂ = 0.3, with previous estimated innovations 4 and −2. For a one-step forecast, the future innovation has expectation zero, so:

Forecast = 50 + 0.8(4) + 0.3(−2)

= 50 + 3.2 − 0.6

= 52.6

The key point is that this MA(2) calculation uses past innovations/errors. It is structurally different from taking a 2-period or 3-period arithmetic moving average of observed values.

ConceptUsesMain purpose
SMA / EMAObserved valuesSmoothing / descriptive tracking; can also be used in simple forecasting rules
MA(q)Current and lagged innovationsStatistical time-series modeling

Going Deeper: MA(q), Stationarity, White Noise and ACF

Stationarity

Classical MA(q) is a stationary time-series model. In practical weak-stationarity terms, we look for stable mean and variance and an autocovariance structure that depends on lag rather than calendar time. This is different from saying that the series must stay inside fixed numerical bounds.

White noise / innovations

White noise is commonly modeled with mean zero, constant finite variance and no serial correlation. After fitting a time-series model, residual diagnostics check whether meaningful autocorrelation remains; residuals behaving approximately like white noise are a good sign that the model has captured much of the predictable linear structure.

ACF and the order q

For an ideal pure MA(q) process, the autocorrelation function has a characteristic cutoff after lag q. In real datasets, an ACF plot can therefore provide clues about candidate MA orders, but it should not be treated as an automatic rule that always reveals the “optimal q.” Mixed ARMA/ARIMA structure, finite samples and noise make identification less clean.


Python: SMA, EMA and a Time-Safe One-Step Moving Average

Self-contained pandas example

import pandas as pd

# Sequential time-series observations
df = pd.DataFrame({
    "Value": [10, 20, 30, 40, 50, 60, 70]
})

# 3-period trailing Simple Moving Average (smoother)
df["SMA_3"] = df["Value"].rolling(window=3).mean()

# Recursive EMA matching: EMA_t = alpha*x_t + (1-alpha)*EMA_(t-1)
df["EMA_3"] = df["Value"].ewm(span=3, adjust=False).mean()

# One-step-ahead 3-period moving-average forecast.
# shift(1) ensures the value at time t is not used to predict time t.
df["MA_3_Forecast"] = (
    df["Value"]
    .shift(1)
    .rolling(window=3)
    .mean()
)

print(df.round(2).to_string(index=False))

next_forecast = df["Value"].tail(3).mean()
print("Next-period 3-value forecast:", round(next_forecast, 2))

Expected output:

 Value  SMA_3  EMA_3  MA_3_Forecast
    10    NaN  10.00            NaN
    20    NaN  15.00            NaN
    30   20.0  22.50            NaN
    40   30.0  31.25           20.0
    50   40.0  40.62           30.0
    60   50.0  50.31           40.0
    70   60.0  60.16           50.0
Next-period 3-value forecast: 60.0
Value
10
Value
20
Value
30
Value
40
Value
50
Value
60
Value
70
EMA
10.00
EMA
15.00
EMA
22.50
EMA
31.25
EMA
40.63
EMA
50.31
EMA
60.16

Common Mistakes

Confusing SMA/EMA with MA(q)

SMA and EMA smooth observed values; MA(q) models innovations/errors.

Calling a smoother a forecast without checking timing

A rolling value that includes the current target is not a prediction made before that target was observed.

Using centered windows as predictive features

Centered windows may include future observations and cause leakage.

Assuming a larger window is always better

More smoothing also means slower response to genuine changes.

Saying EMA always beats SMA

The useful method depends on the data and goal; responsiveness is not automatically better accuracy.

Choosing q mechanically from the ACF

ACF patterns are useful identification clues, not universal guarantees.

Quick Recap

  • SMA: equal-weight average inside a fixed rolling window.
  • EMA: exponentially weighted smoother that gives greater influence to recent observations.
  • Window size: controls the responsiveness-versus-smoothing trade-off.
  • Forecasting: use only information available before the prediction time.
  • MA(q): a statistical model based on lagged innovations—not an arithmetic rolling average.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Moving Average"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Summary / Key Takeaways

  • A moving average smooths a rolling window of recent values.
  • A wider window smooths more but reacts more slowly.
  • Simple, weighted, and exponential averages weight history differently.
  • Forecast features must use only past data.
  • Smoothing can hide anomalies, turning points, and seasonality.
  • Evaluate chronologically against a naive baseline.

Knowledge Check

Progress: 0/4

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 4
What is the difference between SMA and EMA?
Question 2 of 4
SMA-7 is applied to daily sales data. What is the main limitation?
Question 3 of 4
What is a golden cross in the context of moving averages?
Question 4 of 4
Why should you NOT use future data points when computing a moving average for a real-time forecasting system?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1What is the difference between SMA and EMA?▼

Correct Answer: SMA assigns equal weight to all past n observations; EMA assigns exponentially decreasing weights — recent observations get more weight. EMA reacts faster to changes; SMA is smoother but lags more

For a trending or volatile series, EMA is often preferable — it reacts faster to real changes. For smoothing out noise without caring about recency, SMA is simpler.

2SMA-7 is applied to daily sales data. What is the main limitation?▼

Correct Answer: SMA-7 produces no forecast — it only smooths historical data. Additionally, it lags real changes by approximately 3 days (half the window)

Moving averages are smoothing tools, not forecasting models. The lag is inherent — averaging the last 7 points means the SMA always lags the true series by roughly window/2 days.

3What is a golden cross in the context of moving averages?▼

Correct Answer: When a short-period MA (e.g., 50-day) crosses above a long-period MA (e.g., 200-day) — used as a bullish signal in technical analysis suggesting upward momentum

The golden cross signals that short-term average has risen above long-term average, suggesting a recent upward trend strong enough to reverse the longer-term direction.

4Why should you NOT use future data points when computing a moving average for a real-time forecasting system?▼

Correct Answer: Using future values creates look-ahead bias — the system appears to know future values it would not have in production. This inflates metrics but the system fails immediately when deployed

A centered moving average uses future data that doesn't exist in real-time. Always use trailing-only (causal) moving averages for live forecasting systems.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Optional Learning Resources

These resources may complement the lesson. They are optional and are not required to use ML Academy.

As an Amazon Associate I earn from qualifying purchases. Other links are identified separately when they are not affiliate links.

Next