Joshua Joshua - 1 year ago 426
C# Question

Calculate Exponential Moving Average on a Queue in C#

I have a simple class for calculating the moving average of values I add to it. I use it like this:

MovingAverage ma = new MovingAverage();

//the class
public class MovingAverage
public int Period = 5;
private Queue<double> Quotes = new Queue<double>();

public void Push(double quote)
if (Quotes.Count == Period)

public void Clear()
public double Average { get { if (Quotes.Count == 0) return 0; return Quotes.Average(); } }
public double ExponentialMovingAverage

I would like to extend this class to also return the ExponentialMovingAverage. How would you write return the Exponential Average of the Queued items in Quotes?

I realize you will need to add an Alpha property to the class but I'm not sure how to complete the math for the calculation.

Ani Ani
Answer Source

How about with LINQ:

return Quotes.DefaultIfEmpty()
             .Aggregate((ema, nextQuote) => alpha * nextQuote + (1 - alpha) * ema);

I would point out that for real-time financial data, this is highly inefficient. A much better way would be to cache the previous EMA value and update it on a new quote with the above (constant-time) recurrence-formula.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download