Files
QuanTAlib/Source/Indicators/EMA_Series.cs
T

64 lines
2.3 KiB
C#
Raw Normal View History

2022-04-19 14:35:10 -07:00
namespace QuanTAlib;
2022-04-19 22:34:42 -07:00
using System;
2022-04-19 14:35:10 -07:00
2022-04-19 22:34:42 -07:00
/* <summary>
2022-04-19 14:35:10 -07:00
EMA: Exponential Moving Average
2022-04-19 22:34:42 -07:00
EMA needs very short history buffer and calculates the EMA value using just the
previous EMA value. The weight of the new datapoint (k) is k = 2 / (period-1)
2022-04-19 14:35:10 -07:00
Sources:
https://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:moving_averages
https://www.investopedia.com/ask/answers/122314/what-exponential-moving-average-ema-formula-and-how-ema-calculated.asp
https://blog.fugue88.ws/archives/2017-01/The-correct-way-to-start-an-Exponential-Moving-Average-EMA
2022-04-19 22:34:42 -07:00
2022-04-19 14:35:10 -07:00
Issues:
There is no consensus what the first EMA value should be - a zero, a first
2022-04-19 22:34:42 -07:00
datapoint, or an average of the initial Period bars. All three starting methods
converge within 20+ bars to the same moving average. Most implementations (including this one)
use SMA() for the first Period bars as a seeding value for EMA.
</summary> */
2022-04-19 14:35:10 -07:00
public class EMA_Series : Single_TSeries_Indicator
{
2022-04-19 22:34:42 -07:00
private readonly System.Collections.Generic.List<double> _buffer = new();
2022-04-19 14:35:10 -07:00
private readonly double _k, _k1m;
private double _lastema, _lastlastema;
public EMA_Series(TSeries source, int period, bool useNaN = false) : base(source, period, useNaN)
{
this._k = 2.0 / (this._p + 1);
this._k1m = 1.0 - this._k;
this._lastema = this._lastlastema = double.NaN;
if (this._data.Count > 0) { base.Add(this._data); }
}
2022-04-19 23:29:04 -07:00
public override void Add((DateTime t, double v) TValue, bool update)
2022-04-19 14:35:10 -07:00
{
double _ema = 0;
if (update) { this._lastema = this._lastlastema; }
if (this.Count < this._p)
{
2022-04-19 23:29:04 -07:00
if (update) { this._buffer[this._buffer.Count - 1] = TValue.v; }
2022-04-19 14:35:10 -07:00
else
{
2022-04-19 23:29:04 -07:00
this._buffer.Add(TValue.v);
2022-04-19 14:35:10 -07:00
}
if (this._buffer.Count > this._p) { this._buffer.RemoveAt(0); }
for (int i = 0; i < this._buffer.Count; i++) { _ema += this._buffer[i]; }
_ema /= this._buffer.Count;
}
else
{
2022-04-19 23:29:04 -07:00
_ema = TValue.v * this._k + this._lastema * this._k1m;
2022-04-19 14:35:10 -07:00
}
this._lastlastema = this._lastema;
this._lastema = _ema;
2022-04-19 23:29:04 -07:00
var ret = (TValue.t, this.Count < this._p - 1 && this._NaN ? double.NaN : _ema);
2022-04-19 14:35:10 -07:00
base.Add(ret, update);
}
}