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..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.
pub fn moving_average(values: &[f64], window: i64, kind: &str, decimals: i64) -> Vec<f64>
| 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 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 is a string in Rust, one of: "simple", "exponential".
// Parameters take it as &str and results hold it as String.
Your code names it in one line, in the file that uses it
fune!(stats.moving-average@^1); // then call moving_average(…)
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
use super::funejson::Value; ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one
const POW10: [f64; 13] = [
1.0, 10.0, 100.0, 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.
fn round_to(x: f64, decimals: usize) -> f64 {
let scale = POW10[decimals];
let y = x.abs() * scale;
let mut r = y.floor();
if y - r >= 0.5 {
r += 1.0;
}
let out = r / scale;
(if x < 0.0 { -out } else { out }) + 0.0
}
// Summed afresh, left to right, so the result never depends on the history
// a running sum would carry.
fn window_mean(values: &[f64], end: usize, window: usize) -> f64 {
let mut sum = 0.0;
for v in &values[end + 1 - window..=end] {
sum += *v;
}
sum / window as f64
}
/// 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.
///
/// # Panics
/// Panics on a non-finite value, a window below 1, an unknown kind, or
/// decimals outside 0..=12.
pub fn moving_average(values: &[f64], window: i64, kind: &str, decimals: i64) -> Vec<f64> {
for v in values {
if !v.is_finite() {
panic!("values must be finite numbers, received {}", v);
}
}
if window < 1 {
panic!("window must be a whole number of 1 or greater, received {}", window);
}
if kind != "simple" && kind != "exponential" {
panic!("unknown moving average kind \"{}\"", kind);
}
if !(0..=12).contains(&decimals) {
panic!("decimals must be a whole number from 0 to 12, received {}", decimals);
}
let window = window as usize;
let places = decimals as usize;
let mut out = Vec::new();
if values.len() < window {
return out;
}
if kind == "simple" {
for end in window - 1..values.len() {
out.push(round_to(window_mean(values, end, window), places));
}
return out;
}
let alpha = 2.0 / (window as f64 + 1.0);
let mut ema = window_mean(values, window - 1, window);
out.push(round_to(ema, places));
for v in &values[window..] {
ema = ema + alpha * (*v - ema);
out.push(round_to(ema, places));
}
out
}
pub fn fune_vector(args: &[Value]) -> Value {
// Refuse what the typed signature cannot hold, with the wording TypeScript
// and Python use, rather than let the conversion below quietly change it.
for v in args[0].as_arr() {
if !matches!(v, Value::Int(_) | Value::Float(_)) {
panic!("values must be finite numbers, received {:?}", v);
}
}
let values: Vec<f64> = args[0].as_arr().iter().map(|v| v.as_f64()).collect();
let out = moving_average(&values, args[1].as_i64(), args[2].as_str(), args[3].as_i64());
Value::Arr(out.into_iter().map(Value::Float).collect())
}Install
fune build
With that line in your source, in a Rust project (language rust in fune.project), fune build resolves it and nothing else, pins them in fune.lock, downloads only the Rust 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. A crate’s build.rs runs it before every compile. 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 Rust implementation. Install it without the registry with fune add ./stats.moving-average-1.0.0-rust.fune, or fetch it from a terminal with fune pull stats.moving-average@1.0.0:rust.
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.
| 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 9 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 |
| 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
| Path | Bytes |
|---|---|
| README.md | 1,843 |
| impl/python.py | 2,629 |
| impl/rust.rs | 2,997 |
| impl/typescript.ts | 2,444 |
| vectors.json | 2,340 |