Reference · Vectors

vec.rolling_mean

signature
vec.rolling_mean(list, int) -> list

What it does

The moving average: the mean of each run of window neighbouring items, as a list of floats. Only full windows count, so the result has len(xs) - window + 1 items and starts at the first position where a whole window fits. vec.rolling_mean(daily, 7) is a week's moving average.

Examples

print(vec.rolling_mean([1, 2, 3, 4, 5], 3))let daily = [10, 12, 9, 14, 11, 13, 8, 15]print(vec.rolling_mean(daily, 7))
output
[2.0, 3.0, 4.0][11.0, 11.714285714285714]

Edge cases

print(vec.rolling_mean([1, 2, 3], 1), vec.rolling_mean([1, 2, 3], 3))print(vec.rolling_mean([1, 2, 3], 4), vec.rolling_mean([], 2), vec.rolling_mean(null, 1))print(vec.rolling_mean([0.1, 0.2, 0.3], 3))print(vec.rolling_mean([1, 2], 2.0))
output
[1.0, 2.0, 3.0] [2.0][] [] [][0.19999999999999998][1.5]

Errors

A window below 1, a missing window, a window that is not an int, an item that is not an int or a float, or a first argument that is not a list are runtime errors, not error values.

this one fails
print(vec.rolling_mean([1, 2], 0))
output
line 1: `vec.rolling_mean`: the window must be at least 1, got 0
this one fails
print(vec.rolling_mean([1, 2]))
output
line 1: `vec.rolling_mean` expects an int as argument 2, got nothing

Chaining

let sales = [3, 5, 4, 6, 8]print(sales | vec.rolling_mean(2))print(sales | vec.rolling_mean(3) | vec.round(1) | last)
output
[4.0, 4.5, 5.0, 7.0]6.0

See also

vec.rolling_sum, stats.mean, vec.cumsum, vec.diff

Thread
7Useful? Like it, or add to its thread below.

Thread 0 posts

On vec.rolling_mean(): questions, tips, corrections, and code that uses it.

No posts yet. The first one opens the thread.

    Edit this page on GitHub · every example's output was made by running it (tools/refcheck.mjs) · questions on Discord or r/quillo