A library for calculating simple moving averages

Related tags

Video moving_average
Overview

simple_moving_average

Test coverage

This crate provides several algorithms for calculating the simple moving average (SMA) of a series of data samples. SMAs are commonly used to implement low-pass filters, the second-most useful filter type, bested only by coffee filters.

All algorithms implement the [SMA] trait, which provides an implementation-agnostic interface. The interface is generic over sample type, meaning that any type that supports addition and division by a scalar can be averaged. This includes most primitive numeric types (f32, u32, ...), Duration and many third party math library (nalgebra, euclid, cgmath, ...) vector and matrix types.

Examples

Scalars

let mut ma = SumTreeSMA::<_, f32, 2>::new(); // Sample window size = 2
ma.add_sample(1.0);
ma.add_sample(2.0);
ma.add_sample(3.0);
assert_eq!(ma.get_average(), 2.5); // = (2 + 3) / 2

Vectors

let mut ma = NoSumSMA::<_, f64, 2>::new();
ma.add_sample(Vector3::new(1.0, 2.0, 3.0));
ma.add_sample(Vector3::new(-4.0, -2.0, -1.0));
assert_eq!(ma.get_average(), Vector3::new(-1.5, 0.0, 1.0));

Durations

let mut ma = SingleSumSMA::<_, _, 10>::from_zero(Duration::ZERO);
loop {
	let instant = Instant::now();
	// [ application code ]
	ma.add_sample(instant.elapsed());
	dbg!("Average iteration duration: {}", ma.get_average());
	# break;
}

Algorithm implementations

One way to achieve good performance when calculating simple moving averages is to cache previous calculations, specifically the sum of the samples currently in the sample window. Caching this sum has both pros and cons, which is what motivates the three different implementations presented below.

Implementation Add sample Get average Caveat
[NoSumSMA] O(1) O(N) -
[SingleSumSMA] O(1) O(1) Accumulates floating point rounding errors.
[SumTreeSMA] O(log(N)) O(1) -

N refers to the size of the sample window.

All implementations have O(N) space complexity. [NoSumSMA] and [SingleSumSMA] are completely // backed by arrays, so they are by default stack allocated. [SumTreeSMA] stores some data in an array, but its sum tree is stored in a Vec.

NoSumSMA

The most straightforward way of implementing a moving average is to not cache any sum at all, hence the name if this implementation. The sum of all samples is calculated from scratch, at O(N) time complexity (N being the sample window size), every time the average is requested.

When to use

  • When the sample window size is so small that the samples summation cost is negligible.
  • When new samples are written significantly more often than the average value is read.

SingleSumSMA

This implementation caches the sum of all samples in the sample window as a single value, leading to O(1) time complexity for both writing new samples and reading their average. A problem with this approach is that most floating point numbers can't be stored exactly, so every time a such a number is added to the cached sum, there is a risk of accumulating a rounding error.

The magnitude of the accumulated error depends on many factors, including sample window size and sample distribution. Below is a visualization of how the absolute difference in average value between [SingleSumSMA] and [NoSumSMA] (which does not suffer from accumulated rounding errors) grows with the number of samples, for a typical window size and set of samples.

Sample type: f32, Sample window size: 10, Sample distribution: Uniform[-100, 100]

Difference between SingleSumSMA and NoSumSMA

Note: Both axes of the graph are logarithmic. The Y axis values represent the maximum differences found over 100 test runs.

One way to reduce the error is to use wider type, e.g. f64 instead of f32. The absolute error is also less prominent when the samples lie near the interval [-1, 1], as that is where floating point precision is at its highest.

When to use

  • When sample values can be represented exactly in memory, in which case there is no downside to this approach. This is true for all primitive integer types and Duration.
  • When performance is more important than numerical accuracy.

SumTreeSMA

There is a way of avoiding the accumulated floating point rounding errors, without having to re-calculate the whole samples sum every time the average value is requested. The downside though, is that it involves both math and binary trees:

A sum is the result of applying the binary and associative addition operation to a set of operands, which means that it can be represented as a binary tree of sums.

For example

(1) + (2) + (3) + (4) + (5) + (6) =

(1 + 2) + (3 + 4) + (5 + 6) =

(3) + (7) + (11) =

(3 + 7) + (11) =

(10) + (11) =

(10 + 11) =

(21)

can be represented as the following tree.

‌           21
‌          /  \
‌         /    \
‌       10      11
‌      /  \      \
‌     /    \      \
‌    3      7      11
‌   / \    / \    /  \
‌  1   2  3   4  5    6

If one of the leaf nodes (i.e. samples) were to change, only the nodes comprising the direct path between that leaf and the root need to be re-calculated, leading to log(N) calculations, N being the window size. This is exactly what happens when a sample is added; the oldest sample gets replaced with the new sample and sum tree leaf node corresponding to the oldest sample is updated with the new sample value.

One existing leaf node (i.e. sample value) is always re-read when updating that leaf node's neighbor, meaning that after N samples have been added, all the leaf nodes have been re-read. This is what keeps the floating point rounding error from accumulating.

Author's note: If anyone has the brains and will to prove this formally, they are most welcome to submit a PR. In the mean time, there is a unit test that empirically proves that the rounding error does not accumulate. Part of that test's output data is visualized in the graph below, showing no accumulated rounding errors when compared with [NoSumSMA].

Difference between SumTreeSMA and NoSumSMA

When to use

  • In most cases where floating point data is involved, unless writes are much more common than reads.

License

MIT

You might also like...
💰 Midas is a free and open source Moving Average Trading backtest simulator.
💰 Midas is a free and open source Moving Average Trading backtest simulator.

Midas is a free and open source Moving Average Trading backtest simulator Bilibili Video: https://www.bilibili.com/video/BV11o4y1B7fL ⚠️ Warning Inves

Split text into semantic chunks, up to a desired chunk size. Supports calculating length by characters and tokens

Large language models (LLMs) can be used for many tasks, but often have a limited context size that can be smaller than documents you might want to use. To use documents of larger length, you often have to split your text into chunks to fit within this context size.

Moving to the new Arbiter framework to test Portfolio.

Stable Pool Simulation The simulation in this repository is intended to demonstrate a basic simulation created with the Arbiter framework. To do so, w

a simple program that you can scrap, is shit and really simple but is cool.

if you want to run it you need to have installed curl by default scrap youtube, but you can change it, also change the number of threads and run: carg

This is a simple Telegram bot with interface to Firefly III to process and store simple transactions.
This is a simple Telegram bot with interface to Firefly III to process and store simple transactions.

Firefly Telegram Bot Fireflies are free, so beautiful. (Les lucioles sont libres, donc belles.) ― Charles de Leusse, Les Contes de la nuit This is a s

simple-eq is a crate that implements a simple audio equalizer in Rust.

simple-eq A Simple Audio Equalizer simple-eq is a crate that implements a simple audio equalizer in Rust. It supports a maximum of 32 filter bands. Us

A simple key value database for storing simple structures.

Perdia-DB A simple key value database for storing simple structures. No nesting of structures is supported, but may be implemented in the future. Toke

A dead simple ANSI terminal color painting library for Rust.

yansi A dead simple ANSI terminal color painting library for Rust. use yansi::Paint; print!("{} light, {} light!", Paint::green("Green"), Paint::red(

Simple and portable (but not inflexible) GUI library in C that uses the native GUI technologies of each platform it supports.
Simple and portable (but not inflexible) GUI library in C that uses the native GUI technologies of each platform it supports.

libui: a portable GUI library for C This README is being written. Status It has come to my attention that I have not been particularly clear about how

A simple steganography library written in rust

steganography A stable steganography library written in rust Crates.io Usage Add the following to the Cargo.toml in your project: [dependencies] stega

Simple neural network library for classification written in Rust.

Cogent A note I continue working on GPU stuff, I've made some interesting things there, but ultimately it made me realise this is far too monumental a

A simple message based networking library for the bevy framework

Spicy Networking for Bevy bevy_spicy_networking is a solution to the "How do I connect multiple clients to a single server" problem in your bevy games

Simple library to host lv2 plugins. Is not meant to support any kind of GUI.

lv2-host-minimal Simple library to host lv2 plugins. Is not meant to support any kind of GUI. Host fx plugins (audio in, audio out) Set parameters Hos

A Simple-to-use, cross-platform Rust Webcam Capture Library

Cross Platform Rust Library for powerful Webcam Capture and Virtual Webcams

Simple but powerful graph library for Rust

Graphlib Graphlib is a simple and powerful Rust graph library. This library attempts to provide a generic api for building, mutating and iterating ove

Simple assertion library for unit testing in python with a fluent API

Simple assertions library for unit testing in Python with a nice fluent API. Supports both Python 2 and 3.

A simple library for use one Rust code in multi platforms such as WebAssembly, Android and iOS
A simple library for use one Rust code in multi platforms such as WebAssembly, Android and iOS

chameleon chameleon is a simple library for use one Rust code in multi platforms such as WebAssembly, Android and iOS. Key Features TBA Quick Start TB

A simple rust library to help create octrees and quadtrees for chunked level of detail

LodTree LodTree, a simple tree data structure for doing chunk-based level of detail. Goals The aim of this crate is to provide a generic, easy to use

A simple authoritative server networking library for Bevy.

Bevy Networking Plugin This is a simple networking plugin for the Bevy game engine. This plugin provides the building blocks which game developers can

Owner
Oskar Gustafsson
Oskar Gustafsson
A simple CLI for UPnP media file streaming

Slingr A simple CLI for streaming media files over a local network to UPnP media renderers. Designed to work with cheap HDMI/DLNA/UPnP/Miracast Dongle

Yuval Adam 33 Aug 20, 2022
Simple playground project to explore the YUV4MPEG2 format.

2mpeg4yuv Simple playground project to explore the YUV4MPEG2 format. Quick Start Install the Rust Compiler Preview $ ./build.sh $ ./2mpeg4yuv preview

Tsoding 19 Dec 28, 2022
Xiu - A simple and secure live media server in pure Rust (RTMP/HTTP-FLV/HLS/Relay).🦀

Xiu is a simple and secure live media server written by pure Rust, it now supports popular live protocols like RTMP/HLS/HTTP-FLV (and maybe other protocols in the future), you can deploy it as a stand-alone server or a cluster using the relay feature.

HarlanC 602 Jan 2, 2023
High-level RTSP multimedia streaming library, in Rust

High-level RTSP multimedia streaming library, in Rust. Good support for ONVIF RTSP/1.0 IP surveillance cameras, as needed by Moonfire NVR. Works around brokenness in cheap closed-source cameras.

Scott Lamb 108 Jan 8, 2023
An audio playback library for Node.js

symphonia.js A "way too simple" cross-platform zero dependency audio playback library for Node.js Supported Platforms Windows (x64) macOS (x64) macOS

tropicbliss 11 Dec 28, 2022
Easy c̵̰͠r̵̛̠ö̴̪s̶̩̒s̵̭̀-t̶̲͝h̶̯̚r̵̺͐e̷̖̽ḁ̴̍d̶̖̔ ȓ̵͙ė̶͎ḟ̴͙e̸̖͛r̶̖͗ë̶̱́ṉ̵̒ĉ̷̥e̷͚̍ s̷̹͌h̷̲̉a̵̭͋r̷̫̊ḭ̵̊n̷̬͂g̵̦̃ f̶̻̊ơ̵̜ṟ̸̈́ R̵̞̋ù̵̺s̷̖̅ţ̸͗!̸̼͋

Rust S̵̓i̸̓n̵̉ I̴n̴f̶e̸r̵n̷a̴l mutability! Howdy, friendly Rust developer! Ever had a value get m̵̯̅ð̶͊v̴̮̾ê̴̼͘d away right under your nose just when

null 294 Dec 23, 2022
A Rust library for calculating sun positions

sun A rust port of the JS library suncalc. Install Add the following to your Cargo.toml [dependencies] sun = "0.2" Usage pub fn main() { let unixti

Markus Kohlhase 36 Dec 28, 2022
A Rust library for calculating perceptual hash values of images

img_hash Now builds on stable Rust! (But needs nightly to bench.) A library for getting perceptual hash values of images. Thanks to Dr. Neal Krawetz f

Austin Bonander 264 Dec 9, 2022
⚡ Garry's Mod module that boosts performance by moving -condebug file I/O to a separate thread

This is a Garry's Mod server module that moves -condebug file I/O out of the main thread, which should significantly improve performance for noisy servers.

William 32 Dec 28, 2022
Neovim plugin for moving lines up and down, written in Rust

Moveline.nvim Moveline is a simple plugin for moving lines up and down. It's written in Rust using my library nvim-utils. Installation Moveline can be

Will Hopkins 34 Mar 18, 2023