Files
QuanTAlib/lib/statistics/Median.cs
T

115 lines
3.3 KiB
C#
Raw Normal View History

2024-10-27 09:38:53 -07:00
using System;
using System.Linq;
2024-10-05 15:20:13 -07:00
namespace QuanTAlib;
2024-09-22 17:31:24 -07:00
2024-10-05 15:20:13 -07:00
/// <summary>
2024-10-27 09:38:53 -07:00
/// Median: Central Tendency Measure
/// A robust statistical measure that finds the middle value in a sorted dataset.
/// The median is less sensitive to outliers than the mean, making it particularly
/// useful for analyzing price data with extreme values.
2024-10-05 15:20:13 -07:00
/// </summary>
2024-10-11 18:02:09 -07:00
/// <remarks>
2024-10-27 09:38:53 -07:00
/// The Median calculation process:
/// 1. Collects values over specified period
/// 2. Sorts values in ascending order
/// 3. Finds middle value(s)
/// 4. Averages two middle values if even count
2024-10-11 18:02:09 -07:00
///
2024-10-27 09:38:53 -07:00
/// Key characteristics:
/// - Robust to outliers
/// - Always represents actual data point
/// - Splits dataset in half
/// - More stable than mean
/// - Maintains data scale
///
/// Formula:
/// For odd n: median = value at position (n+1)/2
/// For even n: median = (value at n/2 + value at (n/2)+1) / 2
///
/// Market Applications:
/// - Price distribution analysis
/// - Trend identification
/// - Outlier detection
/// - Support/resistance levels
/// - Filter extreme movements
///
/// Sources:
/// https://en.wikipedia.org/wiki/Median
/// "Statistics for Trading" - Technical Analysis of Financial Markets
///
/// Note: More robust than mean for non-normal distributions
2024-10-11 18:02:09 -07:00
/// </remarks>
2024-10-27 09:38:53 -07:00
2024-10-05 15:20:13 -07:00
public class Median : AbstractBase
2024-09-22 17:31:24 -07:00
{
2024-10-05 15:20:13 -07:00
private readonly int Period;
private readonly CircularBuffer _buffer;
2024-10-27 09:38:53 -07:00
/// <param name="period">The number of points to consider for median calculation.</param>
/// <exception cref="ArgumentOutOfRangeException">Thrown when period is less than 1.</exception>
2024-10-06 14:44:43 -07:00
public Median(int period)
2024-09-22 17:31:24 -07:00
{
2024-10-05 15:20:13 -07:00
if (period < 1)
2024-09-22 17:31:24 -07:00
{
2024-10-05 15:20:13 -07:00
throw new ArgumentOutOfRangeException(nameof(period),
"Period must be greater than or equal to 1.");
2024-09-22 17:31:24 -07:00
}
2024-10-05 15:20:13 -07:00
Period = period;
WarmupPeriod = period;
_buffer = new CircularBuffer(period);
Name = $"Median(period={period})";
Init();
}
2024-09-22 17:31:24 -07:00
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 points to consider for median calculation.</param>
2024-10-05 15:20:13 -07:00
public Median(object source, int period) : this(period)
{
var pubEvent = source.GetType().GetEvent("Pub");
pubEvent?.AddEventHandler(source, new ValueSignal(Sub));
}
2024-10-11 18:02:09 -07:00
public override void Init()
{
base.Init();
_buffer.Clear();
}
2024-10-05 15:20:13 -07:00
protected override void ManageState(bool isNew)
{
if (isNew)
2024-09-22 17:31:24 -07:00
{
2024-10-05 15:20:13 -07:00
_lastValidValue = Input.Value;
_index++;
2024-09-22 17:31:24 -07:00
}
2024-10-05 15:20:13 -07:00
}
2024-09-22 17:31:24 -07:00
2024-10-05 15:20:13 -07:00
protected override double Calculation()
{
ManageState(Input.IsNew);
_buffer.Add(Input.Value, Input.IsNew);
double median;
if (_index >= Period)
2024-09-22 17:31:24 -07:00
{
2024-10-27 09:38:53 -07:00
// Get sorted copy of values
2024-10-05 15:20:13 -07:00
var sortedValues = _buffer.GetSpan().ToArray();
Array.Sort(sortedValues);
int middleIndex = sortedValues.Length / 2;
2024-10-27 09:38:53 -07:00
// Calculate median based on odd/even count
median = (sortedValues.Length % 2 == 0)
? (sortedValues[middleIndex - 1] + sortedValues[middleIndex]) / 2.0
: sortedValues[middleIndex];
2024-09-22 17:31:24 -07:00
}
2024-10-05 15:20:13 -07:00
else
{
// Not enough data, use average as temporary measure
median = _buffer.Average();
}
IsHot = _index >= WarmupPeriod;
return median;
2024-09-22 17:31:24 -07:00
}
2024-10-05 15:20:13 -07:00
}