ExponentialMovingAverage.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // N-day EMA implementation from Mirror with a few changes (struct etc.)
  2. // it calculates an exponential moving average roughly equivalent to the last n observations
  3. // https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
  4. using System;
  5. namespace Mirror
  6. {
  7. public struct ExponentialMovingAverage
  8. {
  9. readonly double alpha;
  10. bool initialized;
  11. public double Value;
  12. public double Variance;
  13. public double StandardDeviation; // absolute value, see test
  14. public ExponentialMovingAverage(int n)
  15. {
  16. // standard N-day EMA alpha calculation
  17. alpha = 2.0 / (n + 1);
  18. initialized = false;
  19. Value = 0;
  20. Variance = 0;
  21. StandardDeviation = 0;
  22. }
  23. public void Add(double newValue)
  24. {
  25. // simple algorithm for EMA described here:
  26. // https://en.wikipedia.org/wiki/Moving_average#Exponentially_weighted_moving_variance_and_standard_deviation
  27. if (initialized)
  28. {
  29. double delta = newValue - Value;
  30. Value += alpha * delta;
  31. Variance = (1 - alpha) * (Variance + alpha * delta * delta);
  32. StandardDeviation = Math.Sqrt(Variance);
  33. }
  34. else
  35. {
  36. Value = newValue;
  37. initialized = true;
  38. }
  39. }
  40. public void Reset()
  41. {
  42. initialized = false;
  43. Value = 0;
  44. Variance = 0;
  45. StandardDeviation = 0;
  46. }
  47. }
  48. }