using System; namespace QuanTAlib; /// /// MAE: Mean Absolute Error /// A straightforward error metric that measures the average magnitude of errors /// between predicted and actual values, without considering their direction. /// MAE treats all individual differences equally in the average. /// /// /// The MAE calculation process: /// 1. Calculates absolute difference between each actual and predicted value /// 2. Sums all absolute differences /// 3. Divides by the number of observations /// /// Key characteristics: /// - Linear scale (all differences weighted equally) /// - Robust to outliers compared to MSE /// - Easy to interpret (same units as data) /// - Constant gradient for optimization /// - Less sensitive to large errors than MSE /// /// Formula: /// MAE = (1/n) * Σ|actual - predicted| /// /// Sources: /// https://en.wikipedia.org/wiki/Mean_absolute_error /// https://www.statisticshowto.com/absolute-error/ /// public class Mae : AbstractBase { private readonly CircularBuffer _actualBuffer; private readonly CircularBuffer _predictedBuffer; /// The number of points over which to calculate the MAE. /// Thrown when period is less than 1. public Mae(int period) { if (period < 1) { throw new ArgumentOutOfRangeException(nameof(period), "Period must be greater than or equal to 1."); } WarmupPeriod = period; _actualBuffer = new CircularBuffer(period); _predictedBuffer = new CircularBuffer(period); Name = $"Mae(period={period})"; Init(); } /// The data source object that publishes updates. /// The number of points over which to calculate the MAE. public Mae(object source, int period) : this(period) { var pubEvent = source.GetType().GetEvent("Pub"); pubEvent?.AddEventHandler(source, new ValueSignal(Sub)); } public override void Init() { base.Init(); _actualBuffer.Clear(); _predictedBuffer.Clear(); } protected override void ManageState(bool isNew) { if (isNew) { _lastValidValue = Input.Value; _index++; } } protected override double Calculation() { ManageState(Input.IsNew); double actual = Input.Value; _actualBuffer.Add(actual, Input.IsNew); // If no predicted value provided, use mean of actual values double predicted = double.IsNaN(Input2.Value) ? _actualBuffer.Average() : Input2.Value; _predictedBuffer.Add(predicted, Input.IsNew); double mae = 0; if (_actualBuffer.Count > 0) { var actualValues = _actualBuffer.GetSpan().ToArray(); var predictedValues = _predictedBuffer.GetSpan().ToArray(); double sumAbsoluteError = 0; for (int i = 0; i < _actualBuffer.Count; i++) { sumAbsoluteError += Math.Abs(actualValues[i] - predictedValues[i]); } mae = sumAbsoluteError / _actualBuffer.Count; } IsHot = _index >= WarmupPeriod; return mae; } }