OPEN-SOURCE SCRIPT
Simple Moving Average (SMA)

## Overview and Purpose
The Simple Moving Average (SMA) is one of the most fundamental and widely used technical indicators in financial analysis. It calculates the arithmetic mean of a selected range of prices over a specified number of periods. Developed in the early days of technical analysis, the SMA provides traders with a straightforward method to identify trends by smoothing price data and filtering out short-term fluctuations. Due to its simplicity and effectiveness, it remains a cornerstone indicator that forms the basis for numerous other technical analysis tools.
## What’s Different in this Implementation
- **Constant streaming update:**
On each bar we:
1) subtract the value leaving the window,
2) add the new value,
3) divide by the number of valid samples (early) or by `period` (once full).
- **Deterministic lag, same as textbook SMA:**
Once full, lag is `(period - 1)/2` bars—identical to the classic SMA. You just **don’t lose the first `period-1` bars** to `na`.
- **Large windows without penalty:**
Complexity is constant per tick; memory is bounded by `period`. Very long SMAs stay cheap.
## Behavior on Early Bars
- **Bars < period:** returns the arithmetic mean of **available** samples.
Example (period = 10): bar #3 is the average of the first 3 inputs—not `na`.
- **Bars ≥ period:** behaves exactly like standard SMA over a fixed-length window.
> Implication: Crosses and signals can appear earlier than with `ta.sma()` because you’re not suppressing the first `period-1` bars.
## When to Prefer This
- Backtests needing early bars: You want signals and state from the very first bars.
- High-frequency or very long SMAs: O(1) updates avoid per-bar CPU spikes.
- Memory-tight scripts: Single circular buffer; no large temp arrays per tick.
## Caveats & Tips
Backtest comparability: If you previously relied on na gating from ta.sma(), add your own warm-up guard (e.g., only trade after bar_index >= period-1) for apples-to-apples.
Missing data: The function treats the current bar via nz(source); adjust if you need strict NA propagation.
Window semantics: After warm-up, results match the textbook SMA window; early bars are a partial-window mean by design.
## Math Notes
Running-sum update:
sum_t = sum_{t-1} - oldest + newest
SMA_t = sum_t / k where k = min(#valid_samples, period)
Lag (full window): (period - 1) / 2 bars.
## References
- Edwards & Magee, Technical Analysis of Stock Trends
- Murphy, Technical Analysis of the Financial Markets
The Simple Moving Average (SMA) is one of the most fundamental and widely used technical indicators in financial analysis. It calculates the arithmetic mean of a selected range of prices over a specified number of periods. Developed in the early days of technical analysis, the SMA provides traders with a straightforward method to identify trends by smoothing price data and filtering out short-term fluctuations. Due to its simplicity and effectiveness, it remains a cornerstone indicator that forms the basis for numerous other technical analysis tools.
## What’s Different in this Implementation
- **Constant streaming update:**
On each bar we:
1) subtract the value leaving the window,
2) add the new value,
3) divide by the number of valid samples (early) or by `period` (once full).
- **Deterministic lag, same as textbook SMA:**
Once full, lag is `(period - 1)/2` bars—identical to the classic SMA. You just **don’t lose the first `period-1` bars** to `na`.
- **Large windows without penalty:**
Complexity is constant per tick; memory is bounded by `period`. Very long SMAs stay cheap.
## Behavior on Early Bars
- **Bars < period:** returns the arithmetic mean of **available** samples.
Example (period = 10): bar #3 is the average of the first 3 inputs—not `na`.
- **Bars ≥ period:** behaves exactly like standard SMA over a fixed-length window.
> Implication: Crosses and signals can appear earlier than with `ta.sma()` because you’re not suppressing the first `period-1` bars.
## When to Prefer This
- Backtests needing early bars: You want signals and state from the very first bars.
- High-frequency or very long SMAs: O(1) updates avoid per-bar CPU spikes.
- Memory-tight scripts: Single circular buffer; no large temp arrays per tick.
## Caveats & Tips
Backtest comparability: If you previously relied on na gating from ta.sma(), add your own warm-up guard (e.g., only trade after bar_index >= period-1) for apples-to-apples.
Missing data: The function treats the current bar via nz(source); adjust if you need strict NA propagation.
Window semantics: After warm-up, results match the textbook SMA window; early bars are a partial-window mean by design.
## Math Notes
Running-sum update:
sum_t = sum_{t-1} - oldest + newest
SMA_t = sum_t / k where k = min(#valid_samples, period)
Lag (full window): (period - 1) / 2 bars.
## References
- Edwards & Magee, Technical Analysis of Stock Trends
- Murphy, Technical Analysis of the Financial Markets
Open-source script
In true TradingView spirit, the creator of this script has made it open-source, so that traders can review and verify its functionality. Kudos to the author! While you can use it for free, remember that republishing the code is subject to our House Rules.
github.com/mihakralj/pinescript
A collection of mathematically rigorous technical indicators for Pine Script 6, featuring defensible math, optimized implementations, proper state initialization, and O(1) constant time efficiency where possible.
A collection of mathematically rigorous technical indicators for Pine Script 6, featuring defensible math, optimized implementations, proper state initialization, and O(1) constant time efficiency where possible.
Disclaimer
The information and publications are not meant to be, and do not constitute, financial, investment, trading, or other types of advice or recommendations supplied or endorsed by TradingView. Read more in the Terms of Use.
Open-source script
In true TradingView spirit, the creator of this script has made it open-source, so that traders can review and verify its functionality. Kudos to the author! While you can use it for free, remember that republishing the code is subject to our House Rules.
github.com/mihakralj/pinescript
A collection of mathematically rigorous technical indicators for Pine Script 6, featuring defensible math, optimized implementations, proper state initialization, and O(1) constant time efficiency where possible.
A collection of mathematically rigorous technical indicators for Pine Script 6, featuring defensible math, optimized implementations, proper state initialization, and O(1) constant time efficiency where possible.
Disclaimer
The information and publications are not meant to be, and do not constitute, financial, investment, trading, or other types of advice or recommendations supplied or endorsed by TradingView. Read more in the Terms of Use.