Files
QuanTAlib/Source/Statistics/MAPE_Series.cs
T

42 lines
1.2 KiB
C#
Raw Normal View History

2022-04-19 22:34:42 -07:00
namespace QuanTAlib;
using System;
2022-11-17 07:53:45 -08:00
using System.Linq;
2022-04-19 14:35:10 -07:00
2022-04-19 22:34:42 -07:00
/* <summary>
MAPE: Mean Absolute Percentage Error
Measures the size of the error in percentage terms
2022-04-19 14:35:10 -07:00
Calculation:
MAPE = Σ(|close SMA| / |close|) / n
Sources:
https://en.wikipedia.org/wiki/Mean_absolute_percentage_error
2022-04-19 22:34:42 -07:00
Remark:
returns infinity if any of observations is 0.
Use SMAPE or WMAPE instead to avoid division-by-zero in MAPE
2022-04-19 14:35:10 -07:00
2022-04-19 22:34:42 -07:00
</summary> */
2022-04-19 14:35:10 -07:00
public class MAPE_Series : Single_TSeries_Indicator
{
public MAPE_Series(TSeries source, int period, bool useNaN = false) : base(source, period, useNaN)
{
if (base._data.Count > 0) { base.Add(base._data); }
}
private readonly System.Collections.Generic.List<double> _buffer = new();
2022-04-19 23:29:04 -07:00
public override void Add((System.DateTime t, double v) TValue, bool update)
2022-04-19 14:35:10 -07:00
{
2022-11-17 07:53:45 -08:00
Add_Replace_Trim(_buffer, TValue.v, _p, update);
double _sma = _buffer.Average();
2022-04-19 14:35:10 -07:00
double _mape = 0;
2022-11-17 07:53:45 -08:00
for (int i = 0; i < _buffer.Count; i++) {
_mape += (_buffer[i] != 0) ? Math.Abs(_buffer[i] - _sma) / Math.Abs(_buffer[i]) : double.PositiveInfinity;
}
_mape /= (_buffer.Count>0) ? _buffer.Count : 1;
2022-04-19 14:35:10 -07:00
2022-11-17 07:53:45 -08:00
base.Add((TValue.t, _mape), update, _NaN);
2022-04-19 14:35:10 -07:00
}
}