Created
May 7, 2021 10:23
-
-
Save cocowalla/bd6fd0e9c613c0aa9a28c0716a8efb73 to your computer and use it in GitHub Desktop.
Exponential Weighted Moving Average
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ExponentialWeightedMovingAverage | |
{ | |
private bool isInitialized; | |
// Smoothing/damping coefficient | |
private double alpha; | |
public double Average { get; private set; } | |
public ExponentialWeightedMovingAverage(int samplesPerWindow) | |
{ | |
// Both `2 / (n + 1)` is a fairly standard ways of choosing an alpha value, even if somewhat arbitrary | |
this.alpha = 2d / (samplesPerWindow + 1); | |
} | |
public double Update(double val) | |
{ | |
// First tick will initialize the average, subsequent ticks trigger the recursive weighting function | |
if (this.isInitialized) | |
{ | |
// EMA[current] = EMA[previous] + alpha * (current_value - EMA[previous]) | |
this.Average += this.alpha * (val - this.Average); | |
} | |
else | |
{ | |
// For the first update, just use the value as-is | |
this.Average = val; | |
this.isInitialized = true; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment