stats.moving-average
Simple or exponential moving average over a series, one value per full window, rounded to stated decimals.
2.0.0 · published 2026-10-03 by charlie · Anterra
Pinned by 24 tests, run in TypeScript, Python and Rust.
What it does
Smooths a series. Both kinds return one value for every position that has a full window behind it, so the output has `len(values) - window + 1` entries and the i-th output lines up with input `i + window - 1`. A series shorter than the window returns an empty list rather than an error: a chart with too few points yet should draw nothing, not fail.
- `simple`: the plain mean of the last `window` values. - `exponential`: alpha = 2 / (window + 1), the usual span convention. It is seeded with the simple average of the first window (so its first output equals the simple one), then each step is ema + alpha x (value - ema). Seeding with the first value instead, as some libraries do, gives different numbers for the whole series; the vectors pin this choice down.
For example
moving_average(1, 2, 3, 4, 5, 3, simple, 2)→ 2, 3, 4 simple average of three over 1..5moving_average(1, 2, 3, 4, 5, 3, exponential, 2)→ 2, 3, 4 exponential over 1..5 with window 3 (alpha 0.5)moving_average(2, 4, 6, 8, 3, exponential, 4)→ 4, 6 exponential is seeded with the first window's mean, not the first value
The function
The same function in TypeScript, Python and Rust, pinned by the same tests. Pick your language; the choice follows you around the registry.
def moving_average(values: Sequence[float], window: int, kind: MovingAverageKind, decimals: int) -> List[float]
| values | float[] | the series in time order |
| window | int | points per average, 1 or greater; exponential uses alpha = 2 / (window + 1) |
| kind | MovingAverageKind | simple or exponential |
| decimals | int | 0 to 12; each output is rounded half away from zero, on the exact value of the double, to this many places |
| returns | float[] | one value per position from window - 1 to the end; empty when the series is shorter than the window |
The type it declares, generated into your project
MovingAverageKind = Literal["simple", "exponential"]
Your code names it in one line, in the file that uses it
from fune.stats.moving_average import moving_average # stats.moving-average@^2
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
import math
from typing import List, Sequence
from .math_round_float import round_float ← from math.round-float ^1.0.0 · built alongside by fune
from .stats_moving_average_types import MovingAverageKind
def _window_mean(values: List[float], end: int, window: int) -> float:
# Summed afresh, left to right; math.fsum or sum() with a start value
# would round differently from the other languages.
total = 0.0
for i in range(end - window + 1, end + 1):
total = total + values[i]
return total / window
def moving_average(values: Sequence[float], window: int, kind: MovingAverageKind, decimals: int) -> List[float]:
"""Simple or exponential moving average, one value per full window.
The exponential average is seeded with the simple average of the first
window and carried unrounded; only the returned values are rounded, by
math.round-float on the exact value of each double (2.675 gives 2.67).
"""
if isinstance(values, (str, bytes)) or not isinstance(values, (list, tuple)):
raise TypeError("values must be a list of numbers")
for v in values:
if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v):
raise TypeError("values must be finite numbers, received %r" % (v,))
if isinstance(window, bool) or not isinstance(window, int) or window < 1:
raise ValueError("window must be a whole number of 1 or greater, received %r" % (window,))
if kind not in ("simple", "exponential"):
raise ValueError('unknown moving average kind "%s"' % (kind,))
# Checked here as well as in round_float (same wording), so a series too
# short to produce any output still refuses bad decimals.
if isinstance(decimals, bool) or not isinstance(decimals, int) or decimals < 0 or decimals > 12:
raise ValueError("decimals must be a whole number from 0 to 12, received %r" % (decimals,))
series = [float(v) for v in values]
out: List[float] = []
if len(series) < window:
return out
if kind == "simple":
for end in range(window - 1, len(series)):
out.append(round_float(_window_mean(series, end, window), decimals))
return out
alpha = 2.0 / (window + 1)
ema = _window_mean(series, window - 1, window)
out.append(round_float(ema, decimals))
for i in range(window, len(series)):
ema = ema + alpha * (series[i] - ema)
out.append(round_float(ema, decimals))
return outInstall
fune build
With that line in your source, in a Python project (language python in fune.project), fune build resolves it and its 1 dependency, pins them in fune.lock, downloads only the Python package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. Or pin a range in fune.project and build in one step:
fune add stats.moving-average
The manifest, vectors and README with only the Python implementation. Install it without the registry with fune add ./stats.moving-average-2.0.0-python.fune, or fetch it from a terminal with fune pull stats.moving-average@2.0.0:python.
The whole function, every language, is one file too: stats.moving-average-2.0.0.fune, 16,223 bytes, sha256 a3ae5d80d93991fcecfb0b38c0fdfef47b6272f0925172d288273ab4a28150a5. It installs into a project of any language.
Customise it in your app
The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.
before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.
# fune: before stats.moving-average
after — your function gets the result and the arguments, and returns the final result.
# fune: after stats.moving-average
replace — inside this capability’s code only, calls to a dependency go to your function, with the same signature. Other capabilities that use it are unaffected; write in * to replace it everywhere.
# fune: replace math.round-float in stats.moving-average
step — your function runs at a numbered point inside the function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show stats.moving-average --steps.
# fune: step stats.moving-average after <n|label>
Tests
A version published now needs at least 8 tests for every function, and one that expects the error for each function that throws; the registry refuses it otherwise. fune verify --all runs each case in TypeScript, Python and Rust, and a project runs them again with fune verify. This page lists the cases; it does not run them. The exact JSON is vectors.json.
| Case | Arguments | Expected | |
|---|---|---|---|
| simple average of three over 1..5 | 1, 2, 3, 4, 5, 3, simple, 2 | → | 2, 3, 4 |
| exponential over 1..5 with window 3 (alpha 0.5) | 1, 2, 3, 4, 5, 3, exponential, 2 | → | 2, 3, 4 |
| exponential is seeded with the first window's mean, not the first value | 2, 4, 6, 8, 3, exponential, 4 | → | 4, 6 |
| exponential with window 4 (alpha 0.4) reacts to a jump | 1, 2, 3, 4, 10, 4, exponential, 2 | → | 2.5, 5.5 |
| exponential with window 2 (alpha 2/3) | 10, 20, 30, 40, 2, exponential, 4 | → | 15, 25, 35 |
| exponential with window 1 is the series itself | 1, 5, 3, 1, exponential, 2 | → | 1, 5, 3 |
| simple with window 1 rounds each value | 1.26, -0.5, 1, simple, 1 | → | 1.3, -0.5 |
| a window as long as the series gives one value | 3, 5, 2, simple, 0 | → | 4 |
| a series shorter than the window gives nothing | 3, 5, 3, simple, 2 | → | |
| an empty series gives nothing | , 2, exponential, 2 | → |
Show the other 14 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| a half rounds away from zero | 0, 1, 2, simple, 0 | → | 1 |
| a negative half rounds away from zero | -1, 0, 2, simple, 0 | → | -1 |
| float drift is rounded away: (0.1 + 0.2) / 2 is 0.15 | 0.1, 0.2, 2, simple, 6 | → | 0.15 |
| 5/3 to two places | 1, 2, 2, 3, simple, 2 | → | 1.67 |
| 1.005 is stored just below 1.005, so it rounds to 1.00 | 1.005, 1, simple, 2 | → | 1 |
| 2.67 and 2.68 average to 2.675, stored as 2.67499999..., so it rounds to 2.67 (1.x gave 2.68) | 2.67, 2.68, 2, simple, 2 | → | 2.67 |
| the same below-the-tie average of negatives rounds to -2.67 (1.x gave -2.68) | -2.67, -2.68, 2, simple, 2 | → | -2.67 |
| exponential outputs are rounded on the exact double too: 2.675 gives 2.67 (1.x gave 2.68) | 0, 2.675, 1, exponential, 2 | → | 0, 2.67 |
| 1.45 is stored just below the tie, so it rounds to 1.4 at one place (1.x gave 1.5) | 1.45, 1, simple, 1 | → | 1.4 |
| 8.345 is stored just above the tie, so it still rounds up to 8.35 | 8.345, 1, simple, 2 | → | 8.35 |
| a window of 0 is an error | 1, 2, 0, simple, 2 | → | error: window must be a whole number of 1 or greater |
| an unknown kind is an error | 1, 2, 2, weighted, 2 | → | error: unknown moving average kind "weighted" |
| decimals above 12 is an error | 1, 2, 2, simple, 13 | → | error: decimals must be a whole number from 0 to 12 |
| a non-number value is an error | 1, —, 1, simple, 2 | → | error: values must be finite numbers |
More from the author
**Precision.** Every output is rounded to `decimals` places (0 to 12) by `math.round-float`: half away from zero, decided on the exact value of the double, -0 returned as 0. The running exponential average is carried unrounded; only what is returned is rounded, so the rounding does not compound. "The exact value of the double" is literal: 1.005 is stored as 1.00499999999999989..., so it rounds to 1.00 at two places, and the mean of 2.67 and 2.68 is the double 2.67499999999999982..., so it rounds to 2.67. Callers who need decimal-exact averages of money should average integer minor units with `stats.weighted-average` instead.
**Why the three languages agree to the bit.** Each window is summed afresh, left to right (not by a running add-and-subtract, which accumulates error differently depending on history), and only IEEE-754 +, -, x, / and floor are used, in the same order in every language. Each of those operations is correctly rounded by the standard, so TypeScript, Python and Rust hold the same double before rounding; `math.round-float` then rounds that double the same way in all three.
## Changes in 2.0.0
2.0.0 rounds on the exact value of the double, so an average of 2.67 and 2.68 (the double 2.67499999999999982...) now gives 2.67. 1.x rounded the scaled product instead (floor of |x| x 10^decimals, compared with a half), and 2.675 x 100 is exactly 267.5 in floating point, so 1.x said 2.68. The private rounding helper is gone: this version requires `math.round-float ^1.0.0` and rounds with it, so every float capability in the registry rounds alike.
Only outputs whose double lies just below (or just above) a tie that the scaled product lands exactly on change; everything else is the same double. None of the 1.x vectors changed answers (each was recomputed from the exact value of its double). New vectors pin the difference: the mean of 2.67 and 2.68 gives 2.67 (1.x 2.68), of -2.67 and -2.68 gives -2.67 (1.x -2.68), an exponential output of 2.675 gives 2.67 (1.x 2.68), and 1.45 at one place gives 1.4 (1.x 1.5); 8.345, stored just above its tie, still gives 8.35.
`decimals` is still 0 to 12, and still refused up front with the same message ("decimals must be a whole number from 0 to 12"), so a series too short for any output refuses it as before.
Files
| Path | Bytes |
|---|---|
| README.md | 3,090 |
| impl/python.py | 2,430 |
| impl/rust.rs | 2,724 |
| impl/typescript.ts | 2,245 |
| vectors.json | 3,112 |