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
סקריפט קוד פתוח
ברוח TradingView אמיתית, היוצר של הסקריפט הזה הפך אותו לקוד פתוח, כך שסוחרים יכולים לבדוק ולאמת את הפונקציונליות שלו. כל הכבוד למחבר! למרות שאתה יכול להשתמש בו בחינם, זכור שפרסום מחדש של הקוד כפוף לכללי הבית שלנו.
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.
כתב ויתור
המידע והפרסומים אינם אמורים להיות, ואינם מהווים, עצות פיננסיות, השקעות, מסחר או סוגים אחרים של עצות או המלצות שסופקו או מאושרים על ידי TradingView. קרא עוד בתנאים וההגבלות.
סקריפט קוד פתוח
ברוח TradingView אמיתית, היוצר של הסקריפט הזה הפך אותו לקוד פתוח, כך שסוחרים יכולים לבדוק ולאמת את הפונקציונליות שלו. כל הכבוד למחבר! למרות שאתה יכול להשתמש בו בחינם, זכור שפרסום מחדש של הקוד כפוף לכללי הבית שלנו.
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.
כתב ויתור
המידע והפרסומים אינם אמורים להיות, ואינם מהווים, עצות פיננסיות, השקעות, מסחר או סוגים אחרים של עצות או המלצות שסופקו או מאושרים על ידי TradingView. קרא עוד בתנאים וההגבלות.