Files
QuanTAlib/lib/averages/Rma.cs
T

80 lines
1.7 KiB
C#
Raw Normal View History

2024-09-23 08:34:47 -07:00
using System;
using System.Runtime.CompilerServices;
2024-10-06 14:44:43 -07:00
namespace QuanTAlib;
2024-09-23 08:34:47 -07:00
2024-10-06 14:44:43 -07:00
public class Rma : AbstractBase
{
2024-09-23 08:34:47 -07:00
private readonly int _period;
2024-10-06 14:44:43 -07:00
private readonly double _alpha;
2024-09-23 08:34:47 -07:00
private double _lastRMA;
private double _savedLastRMA;
2024-10-06 14:44:43 -07:00
public Rma(int period)
{
if (period < 1)
{
2024-09-23 08:34:47 -07:00
throw new ArgumentException("Period must be greater than or equal to 1.", nameof(period));
}
_period = period;
WarmupPeriod = period * 2;
_alpha = 1.0 / _period; // Wilder's smoothing factor
Name = $"Rma({_period})";
Init();
2024-10-08 17:31:29 +00:00
}
2024-09-23 08:34:47 -07:00
2024-10-08 17:31:29 +00:00
public Rma(object source, int period) : this(period)
{
2024-09-23 08:34:47 -07:00
var pubEvent = source.GetType().GetEvent("Pub");
pubEvent?.AddEventHandler(source, new ValueSignal(Sub));
2024-10-08 17:31:29 +00:00
}
2024-09-23 08:34:47 -07:00
2024-10-08 17:31:29 +00:00
public override void Init()
{
2024-09-23 08:34:47 -07:00
base.Init();
_lastRMA = 0;
_savedLastRMA = 0;
2024-10-08 17:31:29 +00:00
}
2024-10-08 09:49:28 -07:00
2024-10-08 17:31:29 +00:00
protected override void ManageState(bool isNew)
{
2024-10-08 09:49:28 -07:00
if (!isNew)
2024-10-06 14:44:43 -07:00
{
2024-09-23 08:34:47 -07:00
_lastRMA = _savedLastRMA;
2024-10-08 09:49:28 -07:00
return;
2024-09-23 08:34:47 -07:00
}
2024-10-08 09:49:28 -07:00
_savedLastRMA = _lastRMA;
_lastValidValue = Input.Value;
_index++;
2024-10-08 17:31:29 +00:00
}
2024-10-08 09:49:28 -07:00
2024-10-08 17:31:29 +00:00
protected override double Calculation()
{
2024-09-23 08:34:47 -07:00
ManageState(Input.IsNew);
double rma;
2024-10-06 14:44:43 -07:00
if (_index == 1)
{
2024-10-08 09:49:28 -07:00
return Input.Value;
2024-10-06 14:44:43 -07:00
}
2024-10-08 09:49:28 -07:00
if (_index <= _period)
2024-10-06 14:44:43 -07:00
{
2024-09-23 08:34:47 -07:00
// Simple average during initial period
2024-10-08 09:49:28 -07:00
return (_lastRMA * (_index - 1) + Input.Value) / _index;
2024-10-06 14:44:43 -07:00
}
2024-10-08 09:49:28 -07:00
// Wilder's smoothing method
return _alpha * (Input.Value - _lastRMA) + _lastRMA;
2024-10-08 17:31:29 +00:00
}
2024-09-23 08:34:47 -07:00
2024-10-08 17:31:29 +00:00
_lastRMA = rma;
2024-09-23 08:34:47 -07:00
IsHot = _index >= WarmupPeriod;
return rma;
}
}