fintech-algorithms
Using a coding agent? Give it the skill: npx skills add IslamBaraka90/Fintech-Algorithms-Library What it does →

Simple Moving Average (SMA)

Define the Window Before the Mean

Install and import#

bash
npm install fintech-algorithms
ts
import { calculateSma } from "fintech-algorithms/technical-indicators/trend-smoothing/sma";

Signature#

calculateSma(values, window)

Arithmetic mean of the last window observations, emitted at every position where a complete window is available.

Parameters#

NameTypeNotes
values(number | null)[]Observation series in chronological order, oldest first.
nulls: propagate
windownumberNumber of observations in the mean.
min: 1 · integer: true

Returns#

(number | null)[] · length same-as-input

Index i holds the mean of observations i - window + 1 through i.

Warm-up#

The first window - 1 positions are null. Warm-up positions are null rather than a partial result, so a consumer never mistakes an incomplete window for a real value.

Errors#

  • When window < 1 or is not an integer — throws RangeError

Complexity: time O(n), space O(1).

Worked example#

verified This is the worked example published in the article, replayed by the test suite on every run. The output cannot drift.

Input#

values
[10, 13, 12, 15, 14, 18]
window
3

Call#

calculateSma(values, window)

Returns#

array of 6 nulls

[
  null,
  null,
  11.666666666666666,
  13.333333333333334,
  13.666666666666666,
  15.666666666666666
]

Other exports#

This module also exports calculateSmaSeries. Every module additionally exports run as an alias of its primary function, and a meta object carrying its catalog id, domain, family, shape and article URL.

Diagrams#

Simple Moving Average (SMA) — sma path
Simple Moving Average (SMA) — sma window update

Calculation flow#

SMA calculation flow
flowchart TD
    A["Receive ordered observation x_t"] --> B{"Window is a positive integer and x_t is finite?"}
    B -- "No" --> X["Reject input"]
    B -- "Yes" --> C["Add x_t to rolling sum"]
    C --> D{"More than n observations?"}
    D -- "Yes" --> E["Subtract outgoing x_(t-n)"]
    D -- "No" --> F{"At least n observations?"}
    E --> F
    F -- "No" --> G["Emit null · warming"]
    F -- "Yes" --> H["Emit rolling_sum / n · ready"]

How it works#

This page states the contract — how to call it correctly. The article explains the concept: why it works, and where it breaks.

Read the article →

References#

The rest of the Trend Smoothing family#