Functional Weave
Code in Python

stats.moving-average

Simple or exponential moving average over a series, one value per full window, rounded to stated decimals.

1.0.0 (not the latest) · published 2026-10-03 by charlie · Anterra

Pinned by 19 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..5
  • moving_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]
valuesfloat[]the series in time order
windowintpoints per average, 1 or greater; exponential uses alpha = 2 / (window + 1)
kindMovingAverageKindsimple or exponential
decimalsint0 to 12; each output is rounded half away from zero to this many places
returnsfloat[]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@^1
impl/python.py · 65 lines · open · raw
import math
from typing import List, Sequence

from .stats_moving_average_types import MovingAverageKind


POW10 = [1.0, 10.0, 100.0, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12]


def _round_to(x: float, decimals: int) -> float:
    # Half away from zero on the binary64 value, then -0 becomes 0. Python's
    # round() is half-even and would give round(0.5) == 0; this does not.
    scale = POW10[decimals]
    y = abs(x) * scale
    r = float(math.floor(y))
    if y - r >= 0.5:
        r += 1.0
    out = r / scale
    return (-out if x < 0 else out) + 0.0


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.
    """
    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,))
    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_to(_window_mean(series, end, window), decimals))
        return out

    alpha = 2.0 / (window + 1)
    ema = _window_mean(series, window - 1, window)
    out.append(_round_to(ema, decimals))
    for i in range(window, len(series)):
        ema = ema + alpha * (series[i] - ema)
        out.append(_round_to(ema, decimals))
    return out

Install

fune build

With that line in your source, in a Python project (language python in fune.project), fune build resolves it and nothing else, 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
Download for Python stats.moving-average-1.0.0-python.fune · 9,088 bytes sha256 125c3a138dbecafcd5776a0434de65ee9c0c9e8fd6429d0fb7c091b0eb6c90a8

The manifest, vectors and README with only the Python implementation. Install it without the registry with fune add ./stats.moving-average-1.0.0-python.fune, or fetch it from a terminal with fune pull stats.moving-average@1.0.0:python.

The whole function, every language, is one file too: stats.moving-average-1.0.0.fune, 14,752 bytes, sha256 b198f3f61aee2038d7c4fba2112ddb92138afe094729ec01694fce715c62ce93. 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 — it requires no other capability, so there is no dependency to replace.

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.

CaseArgumentsExpected
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 9 tests
CaseArgumentsExpected
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
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, half away from zero, applied to the binary64 value: y = |x| x 10^decimals, r = floor(y), plus one if y - r >= 0.5, divided back, sign restored, -0 returned as 0. The running exponential average is carried unrounded; only what is returned is rounded, so the rounding does not compound. Note that "applied to the binary64 value" is literal: 1.005 is stored as 1.00499999999999989..., so it rounds to 1.00 at two places. 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, and so return the same rounded value.

Files

PathBytes
README.md1,843
impl/python.py2,629
impl/rust.rs2,997
impl/typescript.ts2,444
vectors.json2,340