namespace QuanTAlib; /// /// Calculates the median value over a specified period. /// Provides a measure of central tendency that is robust to outliers. /// public class Median : AbstractBase { private readonly int Period; private readonly CircularBuffer _buffer; /// /// Initializes a new instance of the Median class. /// /// The number of data points to consider. Must be at least 1. /// /// Thrown when the period is less than 1. /// public Median(int period) : base() { if (period < 1) { throw new ArgumentOutOfRangeException(nameof(period), "Period must be greater than or equal to 1."); } Period = period; WarmupPeriod = period; _buffer = new CircularBuffer(period); Name = $"Median(period={period})"; Init(); } /// /// Initializes a new instance of the Median class with a data source. /// /// The source object that publishes data. /// The number of data points to consider. public Median(object source, int period) : this(period) { var pubEvent = source.GetType().GetEvent("Pub"); pubEvent?.AddEventHandler(source, new ValueSignal(Sub)); } /// /// Manages the state of the indicator. /// /// Indicates if the current data point is new. protected override void ManageState(bool isNew) { if (isNew) { _lastValidValue = Input.Value; _index++; } } /// /// Performs the median calculation. /// /// /// The current median value of the dataset. /// /// /// Uses a sorting approach to find the median. If there's not enough data, /// it uses the average as a temporary measure. /// protected override double Calculation() { ManageState(Input.IsNew); _buffer.Add(Input.Value, Input.IsNew); double median; if (_index >= Period) { var sortedValues = _buffer.GetSpan().ToArray(); Array.Sort(sortedValues); int middleIndex = sortedValues.Length / 2; if (sortedValues.Length % 2 == 0) { // Even number of values: average of two middle values median = (sortedValues[middleIndex - 1] + sortedValues[middleIndex]) / 2.0; } else { // Odd number of values: middle value median = sortedValues[middleIndex]; } } else { // Not enough data, use average as temporary measure median = _buffer.Average(); } IsHot = _index >= WarmupPeriod; return median; } }