Simple Moving Average (SMA)
Define the Window Before the Mean
Install and import
npm install fintech-algorithmsimport { 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
| Name | Type | Notes |
|---|---|---|
values | (number | null)[] | Observation series in chronological order, oldest first. nulls: propagate |
window | number | Number 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
executed Captured by running this function on the input its own test provides. Real output of real code — but not asserted against a published figure.
Input
[10, 13, 12, 15, 14, 18]3Call
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
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.
References
- Single Moving Average — NIST/SEMATECH
- Averaging Methods — NIST/SEMATECH
- Centered Moving Average — NIST/SEMATECH
- Common Approaches to Univariate Time Series — NIST/SEMATECH
- `DataFrame.rolling` — pandas project
- `Rolling.mean` — pandas project
- Secured Overnight Financing Rate Data — Federal Reserve Bank of New York
- Markets Data APIs — Federal Reserve Bank of New York
- Additional Information about Reference Rates — Federal Reserve Bank of New York
- Source-to-claim map
- Reproducibility boundary