Files
QuanTAlib/lib/averages/Kama.cs
T

117 lines
3.8 KiB
C#
Raw Normal View History

2024-10-27 09:38:53 -07:00
using System;
2024-09-23 08:34:47 -07:00
namespace QuanTAlib;
2024-10-27 09:38:53 -07:00
/// <summary>
/// KAMA: Kaufman's Adaptive Moving Average
/// An adaptive moving average that adjusts its smoothing based on market efficiency.
/// KAMA responds quickly during trending periods and becomes more stable during
/// sideways or choppy markets.
/// </summary>
/// <remarks>
/// The KAMA calculation process:
/// 1. Calculates the Efficiency Ratio (ER) to measure market noise
/// 2. Uses ER to determine the optimal smoothing between fast and slow constants
/// 3. Applies the adaptive smoothing to create the moving average
///
/// Key characteristics:
/// - Self-adaptive to market conditions
/// - Fast response during trends
/// - Stable during sideways markets
/// - Uses market efficiency for smoothing adjustment
/// - Reduces whipsaws in choppy markets
///
/// Sources:
/// Perry Kaufman - "Smarter Trading"
/// https://www.investopedia.com/terms/k/kaufmansadaptivemovingaverage.asp
/// </remarks>
2024-09-23 08:34:47 -07:00
public class Kama : AbstractBase
{
private readonly int _period;
private readonly double _scFast, _scSlow;
2024-09-24 16:41:26 -07:00
private CircularBuffer? _buffer;
2024-09-23 08:34:47 -07:00
private double _lastKama, _p_lastKama;
2024-10-27 09:38:53 -07:00
/// <param name="period">The number of periods used to calculate the Efficiency Ratio.</param>
/// <param name="fast">The number of periods for the fastest EMA response (default 2).</param>
/// <param name="slow">The number of periods for the slowest EMA response (default 30).</param>
/// <exception cref="ArgumentException">Thrown when period is less than 1.</exception>
2024-10-06 14:44:43 -07:00
public Kama(int period, int fast = 2, int slow = 30)
2024-09-23 08:34:47 -07:00
{
if (period < 1)
{
throw new ArgumentException("Period must be greater than or equal to 1.", nameof(period));
}
_period = period;
_scFast = 2.0 / (((period < fast) ? period : fast) + 1);
_scSlow = 2.0 / (slow + 1);
WarmupPeriod = period;
Name = $"Kama({_period}, {fast}, {slow})";
Init();
}
2024-10-27 09:38:53 -07:00
/// <param name="source">The data source object that publishes updates.</param>
/// <param name="period">The number of periods used to calculate the Efficiency Ratio.</param>
/// <param name="fast">The number of periods for the fastest EMA response (default 2).</param>
/// <param name="slow">The number of periods for the slowest EMA response (default 30).</param>
2024-09-23 08:34:47 -07:00
public Kama(object source, int period, int fast = 2, int slow = 30) : this(period, fast, slow)
{
var pubEvent = source.GetType().GetEvent("Pub");
pubEvent?.AddEventHandler(source, new ValueSignal(Sub));
}
public override void Init()
{
base.Init();
2024-09-24 16:41:26 -07:00
_buffer = new CircularBuffer(_period + 1);
2024-09-23 08:34:47 -07:00
_lastKama = 0;
}
protected override void ManageState(bool isNew)
{
if (isNew)
{
_lastValidValue = Input.Value;
_index++;
_p_lastKama = _lastKama;
}
else
{
_lastKama = _p_lastKama;
}
}
protected override double Calculation()
{
ManageState(Input.IsNew);
_buffer!.Add(Input.Value, Input.IsNew);
double kama;
if (_index <= _period)
{
kama = Input.Value;
}
else
{
double change = Math.Abs(_buffer[^1] - _buffer[0]);
double volatility = 0;
for (int i = 1; i < _buffer.Count; i++)
{
volatility += Math.Abs(_buffer[i] - _buffer[i - 1]);
}
double er = volatility != 0 ? change / volatility : 0;
double sc = (er * (_scFast - _scSlow)) + _scSlow;
sc *= sc; // Square the smoothing constant
kama = _lastKama + (sc * (Input.Value - _lastKama));
}
_lastKama = kama;
IsHot = _index >= WarmupPeriod;
return kama;
}
2024-10-27 09:38:53 -07:00
}