refactoring

This commit is contained in:
Miha Kralj
2022-11-26 22:04:26 -08:00
parent 570a7896df
commit 58694a9600
22 changed files with 1397 additions and 1186 deletions
+40 -15
View File
@@ -1,6 +1,5 @@
namespace QuanTAlib;
using System;
using System.Linq;
/* <summary>
SMA: Simple Moving Average
@@ -19,19 +18,45 @@ Remark:
public class SMA_Series : Single_TSeries_Indicator
{
public SMA_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();
private readonly System.Collections.Generic.List<double> _buffer = new();
private double _sma, _oldsma;
private double _topv, _oldtopv;
public SMA_Series(TSeries source, int period, bool useNaN = false) : base(source, period, useNaN)
{
if (base._data.Count > 0)
{ base.Add(base._data); }
}
public override void Add((System.DateTime t, double v) TValue, bool update)
{
_topv = Add_Replace_Trim(_buffer, TValue.v, _p, update);
public override void Add((System.DateTime t, double v) TValue, bool update)
{
Add_Replace_Trim(_buffer, TValue.v, _p, update);
double _sma = 0;
for (int i=0; i<_buffer.Count; i++) { _sma+= _buffer[i]; }
_sma /= _buffer.Count;
// rolling back if update, storing data for potential future update
if (update)
{
_sma = _oldsma;
_topv = _oldtopv;
}
else
{
_oldsma = _sma;
_oldtopv = _topv;
}
base.Add((TValue.t, _sma), update, _NaN);
}
}
// main additive calculation of SMA - for data points that are larger than _p period
// this.Count > _p
if (this.Count > _p)
{
_sma += (TValue.v - _topv) / _p;
}
else
{
// calculate SMA the traditional way (sum all, divide with _p) for data points within _p period
_sma = 0;
for (int i = 0; i < _buffer.Count; i++)
{ _sma += _buffer[i]; }
_sma /= _buffer.Count;
}
base.Add((TValue.t, _sma), update, _NaN);
}
}