Files
QuanTAlib/lib/averages/Sma.cs
T

76 lines
2.5 KiB
C#
Raw Normal View History

2024-10-27 16:11:08 -07:00
using System.Runtime.CompilerServices;
2024-09-23 08:34:47 -07:00
namespace QuanTAlib;
2024-10-27 09:38:53 -07:00
/// <summary>
/// SMA: Simple Moving Average
/// The most basic form of moving average, calculating the arithmetic mean over a
/// specified period. Each data point in the period has equal weight in the
/// calculation.
/// </summary>
/// <remarks>
/// The SMA calculation process:
/// 1. Maintains a buffer of the last 'period' values
/// 2. Calculates arithmetic mean of all values in the buffer
/// 3. Updates buffer with new values in FIFO manner
///
/// Key characteristics:
/// - Equal weight for all values in the period
/// - Simple and straightforward calculation
/// - Significant lag due to equal weighting
/// - Smooth output with good noise reduction
/// - Most basic form of trend following
///
/// Sources:
/// https://www.investopedia.com/terms/s/sma.asp
/// https://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:moving_averages
/// </remarks>
2024-09-23 08:34:47 -07:00
public class Sma : AbstractBase
{
2024-09-23 22:08:40 -07:00
private readonly CircularBuffer _buffer;
2024-09-23 08:34:47 -07:00
2024-10-27 09:38:53 -07:00
/// <param name="period">The number of data points used in the SMA calculation.</param>
/// <exception cref="ArgumentOutOfRangeException">Thrown when period is less than 1.</exception>
2024-10-06 14:44:43 -07:00
public Sma(int period)
2024-09-23 08:34:47 -07:00
{
if (period < 1)
{
2024-10-27 16:11:08 -07:00
throw new System.ArgumentOutOfRangeException(nameof(period), "Period must be greater than or equal to 1.");
2024-09-23 08:34:47 -07:00
}
_buffer = new CircularBuffer(period);
Name = "Sma";
WarmupPeriod = 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 SMA calculation.</param>
2024-10-27 16:11:08 -07:00
public Sma(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-27 16:11:08 -07:00
[MethodImpl(MethodImplOptions.AggressiveInlining)]
2024-09-23 08:34:47 -07:00
protected override void ManageState(bool isNew)
{
if (isNew)
{
_lastValidValue = Input.Value;
_index++;
}
}
/// <summary>
2024-10-27 09:38:53 -07:00
/// Performs the core SMA calculation using the circular buffer's average.
2024-09-23 08:34:47 -07:00
/// </summary>
2024-10-27 09:38:53 -07:00
/// <returns>The calculated SMA value.</returns>
2024-09-23 08:34:47 -07:00
protected override double Calculation()
{
ManageState(IsNew);
_buffer.Add(Input.Value, Input.IsNew);
IsHot = _index >= WarmupPeriod;
2024-10-27 16:11:08 -07:00
return _buffer.Average();
2024-09-23 08:34:47 -07:00
}
2024-10-27 09:38:53 -07:00
}