Calculate Exponential Moving Average on a Queue in C#
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.
Do do not need a queue for an Exponential Moving Average because you only need to keep track of the previous EMA.
public class ExponentialMovingAverageIndicator
{
private bool _isInitialized;
private readonly int _lookback;
private readonly double _weightingMultiplier;
private double _previousAverage;
public double Average { get; private set; }
public double Slope { get; private set; }
public ExponentialMovingAverageIndicator(int lookback)
{
_lookback = lookback;
_weightingMultiplier = 2.0/(lookback + 1);
}
public void AddDataPoint(double dataPoint)
{
if (!_isInitialized)
{
Average = dataPoint;
Slope = 0;
_previousAverage = Average;
_isInitialized = true;
return;
}
Average = ((dataPoint - _previousAverage)*_weightingMultiplier) + _previousAverage;
Slope = Average - _previousAverage;
//update previous average
_previousAverage = Average;
}
}
Here's a minimal version of @MattWolf's answer with a slightly different API, and using C# 7.
public sealed class FloatExponentialMovingAverageCalculator
{
private readonly float _alpha;
private float _lastAverage = float.NaN;
public FloatExponentialMovingAverageCalculator(int lookBack) => _alpha = 2f / (lookBack + 1);
public float NextValue(float value) => _lastAverage = float.IsNaN(_lastAverage)
? value
: (value - _lastAverage)*_alpha + _lastAverage;
}