Simple Moving Average (SMA)
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 , data source is closing price (Close)
- 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 prices within the window:
Where:
- is the price at period (typically the closing price)
- is the window length (period) of the moving average
Step-by-Step Calculation
- Choose the window size: Select the calculation period (e.g., 20).
- Collect the most recent prices: Look back closing prices from the current time point.
- Sum and divide by : All prices are equally weighted, then averaged.
- Slide the window: As time advances one period, drop the oldest price, add the newest price, and recalculate.
Weight Characteristics
SMA assigns identical weights 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
The average lag of SMA is 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 Type | Condition | Meaning |
|---|---|---|
| Golden Cross | Short-term SMA crosses above long-term SMA | Bullish signal |
| Death Cross | Short-term SMA crosses below long-term SMA | Bearish 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
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
| Advantage | Description |
|---|---|
| Simple calculation | Requires only addition and division; easy to understand and implement |
| Good stability | Equal weighting prevents overreaction to a single outlier |
| High versatility | Built into virtually every trading platform; universal across markets |
| Building block | Serves as the computational basis for Bollinger Bands, MACD, and other composite indicators |
Disadvantages
| Disadvantage | Description |
|---|---|
| High lag | Average lag of periods; slow to react to trend changes |
| Equal-weight flaw | Old prices carry the same weight as new prices, contradicting the intuition that recent data matters more |
| Window jump | SMA value may shift abruptly when an extreme price exits the window |
| Fails in ranging markets | Generates 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
| Metric | SMA | EMA | WMA | HMA |
|---|---|---|---|---|
| Lag | Highest | Lower | Lower | Lowest |
| Smoothness | High | Medium | Medium | High |
| Computational complexity | Lowest | Low | Low | Medium |
| Sensitivity to outliers | Low | Medium | Medium | High |
- Beginners should start with SMA to understand the core logic of moving average systems.
- 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.
- 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.