ExponentialMovingAverage.cs 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. namespace Mirror
  2. {
  3. // implementation of N-day EMA
  4. // it calculates an exponential moving average roughly equivalent to the last n observations
  5. // https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
  6. public class ExponentialMovingAverage
  7. {
  8. readonly float alpha;
  9. bool initialized;
  10. public double Value { get; private set; }
  11. public double Var { get; private set; }
  12. public ExponentialMovingAverage(int n)
  13. {
  14. // standard N-day EMA alpha calculation
  15. alpha = 2.0f / (n + 1);
  16. }
  17. public void Add(double newValue)
  18. {
  19. // simple algorithm for EMA described here:
  20. // https://en.wikipedia.org/wiki/Moving_average#Exponentially_weighted_moving_variance_and_standard_deviation
  21. if (initialized)
  22. {
  23. double delta = newValue - Value;
  24. Value += alpha * delta;
  25. Var = (1 - alpha) * (Var + alpha * delta * delta);
  26. }
  27. else
  28. {
  29. Value = newValue;
  30. initialized = true;
  31. }
  32. }
  33. }
  34. }