Functional Weave
Code in TypeScript

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

  • movingAverage(1, 2, 3, 4, 5, 3, simple, 2) → 2, 3, 4 simple average of three over 1..5
  • movingAverage(1, 2, 3, 4, 5, 3, exponential, 2) → 2, 3, 4 exponential over 1..5 with window 3 (alpha 0.5)
  • movingAverage(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.

export function movingAverage(values: readonly number[], window: number, kind: MovingAverageKind, decimals: number): readonly number[]
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

export type MovingAverageKind = "simple" | "exponential";

Your code names it in one line, in the file that uses it

import { movingAverage } from "#fune/stats.moving-average@^1";
impl/typescript.ts · 70 lines · open · raw
import { type MovingAverageKind } from "./stats_moving_average_types.ts";

const POW10 = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12];

// Half away from zero on the binary64 value, then -0 becomes 0. Only floor,
// * and / are used, so every language rounds the same double the same way.
function roundTo(x: number, decimals: number): number {
  const scale = POW10[decimals];
  const y = Math.abs(x) * scale;
  let r = Math.floor(y);
  if (y - r >= 0.5) r += 1;
  const out = r / scale;
  return (x < 0 ? -out : out) + 0;
}

// Summed afresh, left to right, so the result never depends on the history
// a running sum would carry.
function windowMean(values: readonly number[], end: number, window: number): number {
  let sum = 0;
  for (let i = end - window + 1; i <= end; i++) sum += values[i];
  return sum / window;
}

/**
 * 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.
 */
export function movingAverage(
  values: readonly number[],
  window: number,
  kind: MovingAverageKind,
  decimals: number,
): readonly number[] {
  if (!Array.isArray(values)) throw new TypeError("values must be a list of numbers");
  for (const v of values) {
    if (typeof v !== "number" || !Number.isFinite(v)) {
      throw new TypeError(`values must be finite numbers, received ${v}`);
    }
  }
  if (!Number.isInteger(window) || window < 1) {
    throw new RangeError(`window must be a whole number of 1 or greater, received ${window}`);
  }
  if (kind !== "simple" && kind !== "exponential") {
    throw new RangeError(`unknown moving average kind "${kind}"`);
  }
  if (!Number.isInteger(decimals) || decimals < 0 || decimals > 12) {
    throw new RangeError(`decimals must be a whole number from 0 to 12, received ${decimals}`);
  }

  const out: number[] = [];
  if (values.length < window) return out;

  if (kind === "simple") {
    for (let end = window - 1; end < values.length; end++) {
      out.push(roundTo(windowMean(values, end, window), decimals));
    }
    return out;
  }

  const alpha = 2 / (window + 1);
  let ema = windowMean(values, window - 1, window);
  out.push(roundTo(ema, decimals));
  for (let i = window; i < values.length; i++) {
    ema = ema + alpha * (values[i] - ema);
    out.push(roundTo(ema, decimals));
  }
  return out;
}

Install

fune build

With that line in your source, in a TypeScript project (language typescript in fune.project), fune build resolves it and nothing else, pins them in fune.lock, downloads only the TypeScript 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 TypeScript stats.moving-average-1.0.0-typescript.fune · 8,908 bytes sha256 fe0178bf7bebe1feb46720c7bf34fac096dc2b7b349c2c3896103a015586f5cb

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

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