Joshua Joshua - 1 month ago 31
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();
ma.push(value1);
ma.push(value2);
...
Console.Writeline(average.Average);

//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)
Quotes.Dequeue();
Quotes.Enqueue(quote);

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


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

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.

Comments