Files
QuanTAlib/Source/Indicators/RMA_Series.cs
T

63 lines
2.1 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
RMA: wildeR Moving Average
2022-04-19 22:34:42 -07:00
J. Welles Wilder introduced RMA as an alternative to EMA. RMA's weight (k) is
set as 1/period, giving less weight to the new data compared to EMA.
2022-04-19 14:35:10 -07:00
2022-04-19 22:34:42 -07:00
Sources:
2022-04-19 14:35:10 -07:00
https://archive.org/details/newconceptsintec00wild/page/23/mode/2up
https://tlc.thinkorswim.com/center/reference/Tech-Indicators/studies-library/V-Z/WildersSmoothing
https://www.incrediblecharts.com/indicators/wilder_moving_average.php
Issues:
Pandas-TA library calculates RMA using straight Exponential Weighted Mean:
pandas.ewm().mean() and returns incorrect first (period) of bars compared to
published formula. This implementation passess the validation test in Wilder's book.
2022-04-19 22:34:42 -07:00
</summary> */
2022-04-19 14:35:10 -07:00
public class RMA_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 RMA_Series(TSeries source, int period, bool useNaN = false) : base(source, period, useNaN)
{
this._k = 1.0 / (double)(this._p);
this._k1m = 1.0 - this._k;
this._lastema = this._lastlastema = double.NaN;
if (_data.Count > 0) { base.Add(_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) { _buffer[_buffer.Count - 1] = TValue.v; }
2022-04-19 14:35:10 -07:00
else
{
2022-04-19 23:29:04 -07:00
_buffer.Add(TValue.v);
2022-04-19 14:35:10 -07:00
}
if (_buffer.Count > this._p) { _buffer.RemoveAt(0); }
for (int i = 0; i < _buffer.Count; i++) { _ema += _buffer[i]; }
_ema /= this._buffer.Count;
}
else
{
2022-04-19 23:29:04 -07:00
_ema = TValue.v * _k + _lastema * _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);
}
}