Simple Moving Average (SMA)

Haiyue
9min

I. What is SMA

The Simple Moving Average (SMA) is one of the most fundamental and classic indicators in technical analysis. It smooths price data by calculating the arithmetic mean of closing prices over a given period, filtering out short-term noise to reveal the underlying trend direction.

Historical Background

The concept of SMA dates back to early 20th-century statistics. In financial markets, the use of moving averages was first popularized by Richard Donchian in the 1930s. Known as the “father of trend following,” Donchian was the first to systematically apply moving averages to commodity futures trading. Since then, SMA has become a standard introductory indicator in virtually every technical analysis textbook and serves as the computational foundation for many composite indicators (such as MACD and Bollinger Bands).

Indicator Classification

  • Type: Overlay indicator, plotted directly on the price chart
  • Category: Moving Averages
  • Default Parameters: Period n=20n = 20, data source is closing price (Close)
Common Period Choices
  • Short-term: 5, 10, 20 days — suitable for short-term trading
  • Medium-term: 50 days — commonly used to assess intermediate trends
  • Long-term: 100, 200 days — key reference lines watched by institutional investors

II. Mathematical Principles and Calculation

Core Formula

The SMA formula is straightforward — a simple arithmetic mean of nn prices within the window:

SMAt=1ni=0n1Pti=Pt+Pt1+Pt2++Ptn+1nSMA_t = \frac{1}{n} \sum_{i=0}^{n-1} P_{t-i} = \frac{P_t + P_{t-1} + P_{t-2} + \cdots + P_{t-n+1}}{n}

Where:

  • PtP_t is the price at period tt (typically the closing price)
  • nn is the window length (period) of the moving average

Step-by-Step Calculation

  1. Choose the window size: Select the calculation period nn (e.g., 20).
  2. Collect the most recent nn prices: Look back nn closing prices from the current time point.
  3. Sum and divide by nn: All prices are equally weighted, then averaged.
  4. Slide the window: As time advances one period, drop the oldest price, add the newest price, and recalculate.

Weight Characteristics

SMA assigns identical weights wi=1nw_i = \frac{1}{n} to every price within the window, which means:

  • A price from 20 days ago contributes exactly the same as yesterday’s price
  • When an extreme value enters or exits the window, the SMA value may shift abruptly
About Lag

The average lag of SMA is n12\frac{n-1}{2} periods. For a 20-day SMA, the average lag is approximately 9.5 days. This is the most significant inherent drawback of SMA, and it is the core problem that improved moving averages like EMA and HMA aim to solve.


III. Python Implementation

import numpy as np
import pandas as pd

def sma(close: pd.Series, period: int = 20) -> pd.Series:
    """
    Calculate the Simple Moving Average (SMA)

    Parameters
    ----------
    close : pd.Series
        Closing price series
    period : int
        Calculation period, default is 20

    Returns
    -------
    pd.Series
        SMA value series
    """
    return close.rolling(window=period, min_periods=period).mean()


def sma_numpy(close: np.ndarray, period: int = 20) -> np.ndarray:
    """
    Manual SMA implementation using numpy (for understanding the principle)
    """
    n = len(close)
    result = np.full(n, np.nan)
    for i in range(period - 1, n):
        result[i] = np.mean(close[i - period + 1 : i + 1])
    return result


# ========== Usage Example ==========
if __name__ == "__main__":
    # Generate simulated OHLCV data
    np.random.seed(42)
    dates = pd.date_range("2024-01-01", periods=100, freq="D")
    price = 100 + np.cumsum(np.random.randn(100) * 0.5)

    df = pd.DataFrame({
        "date": dates,
        "open":  price + np.random.randn(100) * 0.2,
        "high":  price + np.abs(np.random.randn(100) * 0.5),
        "low":   price - np.abs(np.random.randn(100) * 0.5),
        "close": price,
        "volume": np.random.randint(1000, 10000, size=100),
    })
    df.set_index("date", inplace=True)

    # Calculate SMA with different periods
    df["SMA_10"] = sma(df["close"], period=10)
    df["SMA_20"] = sma(df["close"], period=20)
    df["SMA_50"] = sma(df["close"], period=50)

    # Print last 10 rows
    print(df[["close", "SMA_10", "SMA_20", "SMA_50"]].tail(10))

    # Golden Cross / Death Cross signal example
    df["signal"] = np.where(
        df["SMA_10"] > df["SMA_20"], 1,    # Golden Cross: short-term crosses above long-term
        np.where(df["SMA_10"] < df["SMA_20"], -1, 0)  # Death Cross
    )
    cross = df["signal"].diff().abs() > 0
    print("\nCrossover signal points:")
    print(df.loc[cross, ["close", "SMA_10", "SMA_20", "signal"]])

IV. Problems the Indicator Solves

1. Trend Identification

The most fundamental role of SMA is to filter noise and reveal trends. When price fluctuates around the SMA:

  • Price consistently above SMA -> Uptrend
  • Price consistently below SMA -> Downtrend
  • Price frequently crossing SMA -> Consolidation / No trend

2. Support and Resistance

Long-period SMAs (e.g., 50-day, 200-day) are commonly used by market participants as dynamic support and resistance levels. When price pulls back toward the 200-day moving average, buying interest often emerges.

3. Crossover Signals (Golden Cross / Death Cross)

Signal TypeConditionMeaning
Golden CrossShort-term SMA crosses above long-term SMABullish signal
Death CrossShort-term SMA crosses below long-term SMABearish signal

The classic combination of 50-day / 200-day crossover is known as the “Golden Cross” and “Death Cross,” forming the signal foundation for many institutional strategies.

4. Multiple Moving Average Systems

Using 3 or more SMAs of different periods to form a moving average system can assess trend strength:

  • Bullish alignment (short > medium > long) -> Strong uptrend
  • Bearish alignment (short < medium < long) -> Strong downtrend
  • Intertwined moving averages -> Direction unclear
Note

SMA crossover signals exhibit significant lag and are not suitable for use as standalone signals in high-frequency or fast-reversing markets. It is advisable to confirm signals with momentum indicators such as RSI or MACD.


V. Advantages, Disadvantages, and Use Cases

Advantages

AdvantageDescription
Simple calculationRequires only addition and division; easy to understand and implement
Good stabilityEqual weighting prevents overreaction to a single outlier
High versatilityBuilt into virtually every trading platform; universal across markets
Building blockServes as the computational basis for Bollinger Bands, MACD, and other composite indicators

Disadvantages

DisadvantageDescription
High lagAverage lag of (n1)/2(n-1)/2 periods; slow to react to trend changes
Equal-weight flawOld prices carry the same weight as new prices, contradicting the intuition that recent data matters more
Window jumpSMA value may shift abruptly when an extreme price exits the window
Fails in ranging marketsGenerates many false signals in trendless, choppy markets

Use Cases

  • Strong trending markets: SMA performs best when trends are well established
  • Daily timeframe and above: On short timeframes (e.g., 1-minute), noise is high and SMA signals are unreliable
  • As a filter: Used in combination with other indicators, e.g., “only go long when price is above the 200-day SMA”

Comparison with Other Moving Averages

MetricSMAEMAWMAHMA
LagHighestLowerLowerLowest
SmoothnessHighMediumMediumHigh
Computational complexityLowestLowLowMedium
Sensitivity to outliersLowMediumMediumHigh
Practical Advice
  1. Beginners should start with SMA to understand the core logic of moving average systems.
  2. In trend-following strategies, SMA is often used to determine the overall direction (e.g., the 200-day line), while EMA or HMA is used for entry signals.
  3. When backtesting, note that SMA crossover strategies tend to perform well in trending markets but can suffer significant drawdowns due to frequent false signals in ranging markets.