在C#中计算队列中的指数移动平均线

时间:2011-12-09 18:28:02

标签: c# average

我有一个简单的类来计算我添加到它的值的移动平均值。我这样用它:

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
        {
            ???
        }
    }
}

我想扩展此类以返回ExponentialMovingAverage。您将如何写入报价中的排队项目的指数平均值?

我意识到你需要在课堂上添加一个Alpha属性,但我不知道如何完成计算的数学运算。

4 个答案:

答案 0 :(得分:14)

LINQ怎么样:

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

我想指出,对于实时财务数据,这高度效率低下。一种更好的方法是缓存先前的EMA值并使用上述(恒定时间)递归公式在新报价上更新它。

答案 1 :(得分:4)

不需要指数移动平均线的队列,因为您只需要跟踪以前的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;
    }
}

答案 2 :(得分:3)

这是@ MattWolf的答案的最小版本,其API略有不同,并使用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;
}

答案 3 :(得分:0)

我认为@Ani的答案需要进行一些细微调整。 初始值将设置为“ alpha * nextQuote”,而不仅仅是“ nextQuote”。 最简单的解决方法是将初始种子值设置为与第一条记录匹配,然后第一轮迭代变为alpha * S1 +(1- alpha)* S1:

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