Files
QuanTAlib/lib/averages/Smma.cs
T

105 lines
2.9 KiB
C#
Raw Normal View History

2024-09-23 08:34:47 -07:00
using System;
namespace QuanTAlib;
2024-10-27 09:38:53 -07:00
/// <summary>
/// SMMA: Smoothed Moving Average
/// A modified moving average that gives more weight to recent prices while maintaining
/// a smooth output. It uses the previous SMMA value in its calculation, creating
/// a smoother line than traditional moving averages.
/// </summary>
/// <remarks>
/// The SMMA calculation process:
/// 1. Uses SMA for initial value (first period points)
/// 2. For subsequent points, calculates: (prevSMMA * (period-1) + price) / period
/// 3. This creates a smoothed effect with reduced volatility
///
/// Key characteristics:
/// - Smoother than traditional moving averages
/// - Reduced volatility in output
/// - Takes into account all previous prices
/// - Good for identifying overall trends
/// - Less lag than SMA but more than EMA
///
/// Implementation:
/// Based on smoothed moving average principles with
/// initial SMA seeding for stability
/// </remarks>
2024-09-23 08:34:47 -07:00
public class Smma : AbstractBase
{
private readonly int _period;
2024-09-24 16:41:26 -07:00
private CircularBuffer? _buffer;
2024-09-23 08:34:47 -07:00
private double _lastSmma, _p_lastSmma;
2024-10-27 09:38:53 -07:00
/// <param name="period">The number of data points used in the SMMA calculation.</param>
/// <exception cref="ArgumentException">Thrown when period is less than 1.</exception>
2024-10-06 14:44:43 -07:00
public Smma(int period)
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;
WarmupPeriod = period;
Name = $"Smma({_period})";
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 data points used in the SMMA calculation.</param>
2024-09-23 08:34:47 -07:00
public Smma(object source, int period) : this(period)
{
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);
2024-09-23 08:34:47 -07:00
_lastSmma = 0;
}
protected override void ManageState(bool isNew)
{
if (isNew)
{
_lastValidValue = Input.Value;
_p_lastSmma = _lastSmma;
_index++;
}
else
{
_lastSmma = _p_lastSmma;
}
}
protected override double Calculation()
{
ManageState(Input.IsNew);
_buffer!.Add(Input.Value, Input.IsNew);
double smma;
if (_index <= _period)
{
smma = _buffer.Average();
if (_index == _period)
{
_lastSmma = smma; // Initialize _lastSmma for the transition
}
}
else
{
smma = ((_lastSmma * (_period - 1)) + Input.Value) / _period;
}
_lastSmma = smma;
IsHot = _index >= WarmupPeriod;
return smma;
}
2024-10-27 09:38:53 -07:00
}