Refactor and optimize various components of QuanTAlib

- Removed WmaVector class to streamline weighted moving average calculations.
- Simplified RingBuffer implementation by removing unnecessary comments and improving clarity.
- Enhanced SIMD extensions for better performance and readability.
- Updated TBar and TBarSeries classes to improve property calculations and reduce overhead.
- Cleaned up TValue struct by removing redundant comments.
- Added comprehensive unit tests for IndicatorExtensions and TrimaIndicator to ensure functionality and correctness.
This commit is contained in:
Miha Kralj
2025-12-04 13:49:05 -08:00
parent 3ed35322a5
commit 967096d4f5
27 changed files with 387 additions and 3367 deletions
+4 -1
View File
@@ -108,7 +108,6 @@ public class TrimaTests
trima.Update(new TValue(DateTime.UtcNow, 100));
trima.Update(new TValue(DateTime.UtcNow, 105));
double valueBefore = trima.Value;
trima.Reset();
@@ -151,20 +150,24 @@ public class TrimaTests
// Calculate iteratively
var iterativeResults = new TSeries();
#pragma warning disable S4158 // Collection is known to be empty
foreach (var item in series)
{
iterativeResults.Add(trimaIterative.Update(item));
}
#pragma warning restore S4158
// Calculate batch
var batchResults = trimaBatch.Update(series);
// Compare
Assert.Equal(iterativeResults.Count, batchResults.Count);
#pragma warning disable S2583 // Condition always evaluates to false
for (int i = 0; i < iterativeResults.Count; i++)
{
Assert.Equal(iterativeResults[i].Value, batchResults[i].Value, 1e-10);
}
#pragma warning restore S2583
}
[Fact]
+20 -106
View File
@@ -8,29 +8,17 @@ namespace QuanTAlib;
/// TRIMA: Triangular Moving Average
/// </summary>
/// <remarks>
/// TRIMA is a weighted moving average where the weights increase linearly to the middle
/// of the period and then decrease linearly. It places the most weight on the middle
/// portion of the data series.
/// TRIMA is a weighted moving average where weights increase linearly to the middle
/// and then decrease. It is equivalent to a double SMA: SMA(SMA(period1), period2).
///
/// Calculation:
/// TRIMA(period) = SMA(SMA(period1), period2)
/// where:
/// period1 = period / 2 + 1
/// period2 = (period + 1) / 2
///
/// This implementation uses a flattened structure with two internal SMA buffers
/// to ensure correct handling of warmup periods and bar corrections without
/// the overhead of composed objects.
///
/// Key characteristics:
/// - Smoother than SMA
/// - Double smoothing (lag is higher than SMA)
/// - Weights form a triangle
/// Characteristics:
/// - Smoother than SMA, higher lag
/// - O(1) time complexity
/// - O(period) space complexity
///
/// Sources:
/// - https://www.investopedia.com/terms/t/triangularaverage.asp
/// </remarks>
[SkipLocalsInit]
public sealed class Trima
@@ -41,36 +29,22 @@ public sealed class Trima
private readonly RingBuffer _buffer1;
private readonly RingBuffer _buffer2;
// SMA1 State
private double _sum1;
private double _p_sum1;
private double _p_lastInput1;
private double _lastValidValue1;
private double _p_lastValidValue1;
private double _sum1, _p_sum1, _p_lastInput1, _lastValidValue1, _p_lastValidValue1;
private int _tickCount1;
// SMA2 State
private double _sum2;
private double _p_sum2;
private double _p_lastInput2;
private double _sum2, _p_sum2, _p_lastInput2;
private int _tickCount2;
private int _sampleCount;
private const int ResyncInterval = 1000;
/// <summary>
/// Display name for the indicator.
/// </summary>
public string Name { get; }
public TValue Value { get; private set; }
public bool IsHot => _sampleCount >= _period;
/// <summary>
/// Creates TRIMA with specified period.
/// </summary>
/// <param name="period">Number of values to average (must be > 0)</param>
public Trima(int period)
{
if (period <= 0)
throw new ArgumentException("Period must be greater than 0", nameof(period));
if (period <= 0) throw new ArgumentException("Period must be greater than 0", nameof(period));
_period = period;
_p1 = period / 2 + 1;
@@ -82,19 +56,6 @@ public sealed class Trima
Name = $"Trima({period})";
}
/// <summary>
/// Current TRIMA value.
/// </summary>
public TValue Value { get; private set; }
/// <summary>
/// True if the TRIMA has enough data to produce valid results.
/// </summary>
public bool IsHot => _sampleCount >= _period;
/// <summary>
/// Gets a valid input value, using last-value substitution for non-finite inputs.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private double GetValidValue(double input)
{
@@ -106,12 +67,6 @@ public sealed class Trima
return _lastValidValue1;
}
/// <summary>
/// Updates TRIMA with the given value.
/// </summary>
/// <param name="input">Input value</param>
/// <param name="isNew">True for new bar, false for update to current bar (default: true)</param>
/// <returns>Current TRIMA value</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TValue Update(TValue input, bool isNew = true)
{
@@ -119,13 +74,12 @@ public sealed class Trima
{
_sampleCount++;
// SMA 1 Update
// SMA 1
double val1 = GetValidValue(input.Value);
double removed1 = _buffer1.Count == _buffer1.Capacity ? _buffer1.Oldest : 0.0;
_sum1 = _sum1 - removed1 + val1;
_buffer1.Add(val1);
// Resync SMA1
_tickCount1++;
if (_buffer1.IsFull && _tickCount1 >= ResyncInterval)
{
@@ -133,21 +87,17 @@ public sealed class Trima
_sum1 = _buffer1.Sum();
}
// Save SMA1 state
_p_sum1 = _sum1;
_p_lastInput1 = val1;
_p_lastValidValue1 = _lastValidValue1;
// SMA 1 Result
double sma1Result = _sum1 / _buffer1.Count;
// SMA 2 Update (Input is sma1Result)
// Note: sma1Result is always finite if input stream has at least one finite value
// SMA 2
double removed2 = _buffer2.Count == _buffer2.Capacity ? _buffer2.Oldest : 0.0;
_sum2 = _sum2 - removed2 + sma1Result;
_buffer2.Add(sma1Result);
// Resync SMA2
_tickCount2++;
if (_buffer2.IsFull && _tickCount2 >= ResyncInterval)
{
@@ -155,13 +105,10 @@ public sealed class Trima
_sum2 = _buffer2.Sum();
}
// Save SMA2 state
_p_sum2 = _sum2;
_p_lastInput2 = sma1Result;
// Final Result
double trimaResult = _sum2 / _buffer2.Count;
Value = new TValue(input.Time, trimaResult);
Value = new TValue(input.Time, _sum2 / _buffer2.Count);
}
else
{
@@ -177,23 +124,16 @@ public sealed class Trima
_sum2 = _p_sum2 - _p_lastInput2 + sma1Result;
_buffer2.UpdateNewest(sma1Result);
double trimaResult = _sum2 / _buffer2.Count;
Value = new TValue(input.Time, trimaResult);
Value = new TValue(input.Time, _sum2 / _buffer2.Count);
}
return Value;
}
/// <summary>
/// Updates TRIMA with the entire series.
/// </summary>
/// <param name="source">Input series</param>
/// <returns>TRIMA series</returns>
public TSeries Update(TSeries source)
{
if (source.Count == 0) return new TSeries(new List<long>(), new List<double>());
// Use the static Calculate method for performance
int len = source.Count;
var t = new List<long>(len);
var v = new List<double>(len);
@@ -202,43 +142,30 @@ public sealed class Trima
var tSpan = CollectionsMarshal.AsSpan(t);
var vSpan = CollectionsMarshal.AsSpan(v);
var sourceValues = source.Values;
var sourceTimes = source.Times;
Calculate(source.Values, vSpan, _period);
source.Times.CopyTo(tSpan);
Calculate(sourceValues, vSpan, _period);
sourceTimes.CopyTo(tSpan);
// Restore state by replaying the last part
// We need to replay enough to fill both SMAs
// Restore state
int lookback = _p1 + _p2;
int startIndex = Math.Max(0, len - lookback);
// Reset internal state
Reset();
// Replay
for (int i = startIndex; i < len; i++)
{
Update(new TValue(sourceTimes[i], sourceValues[i]), isNew: true);
Update(new TValue(source.Times[i], source.Values[i]), isNew: true);
}
Value = new TValue(tSpan[len - 1], vSpan[len - 1]);
return new TSeries(t, v);
}
/// <summary>
/// Calculates TRIMA for the entire series using a new instance.
/// </summary>
public static TSeries Calculate(TSeries source, int period)
{
var trima = new Trima(period);
return trima.Update(source);
}
/// <summary>
/// Calculates TRIMA in-place.
/// Uses ArrayPool to allocate temporary buffer and chains optimized SMA calculations.
/// </summary>
public static void Calculate(ReadOnlySpan<double> source, Span<double> output, int period)
{
if (source.Length != output.Length)
@@ -249,16 +176,12 @@ public sealed class Trima
int p1 = period / 2 + 1;
int p2 = (period + 1) / 2;
// Rent a temporary buffer for the intermediate SMA
double[] tempArray = ArrayPool<double>.Shared.Rent(source.Length);
Span<double> tempSpan = tempArray.AsSpan(0, source.Length);
try
{
// SMA 1
Sma.Calculate(source, tempSpan, p1);
// SMA 2 (TRIMA)
Sma.Calculate(tempSpan, output, p2);
}
finally
@@ -267,24 +190,15 @@ public sealed class Trima
}
}
/// <summary>
/// Resets the TRIMA state.
/// </summary>
public void Reset()
{
_buffer1.Clear();
_buffer2.Clear();
_sum1 = 0;
_p_sum1 = 0;
_p_lastInput1 = 0;
_lastValidValue1 = 0;
_p_lastValidValue1 = 0;
_sum1 = _p_sum1 = _p_lastInput1 = _lastValidValue1 = _p_lastValidValue1 = 0;
_tickCount1 = 0;
_sum2 = 0;
_p_sum2 = 0;
_p_lastInput2 = 0;
_sum2 = _p_sum2 = _p_lastInput2 = 0;
_tickCount2 = 0;
_sampleCount = 0;
-363
View File
@@ -1,363 +0,0 @@
namespace QuanTAlib.Tests;
public class TrimaVectorTests
{
[Fact]
public void Initialization_WithPeriods_Works()
{
int[] periods = { 5, 10, 20 };
var trimaVector = new TrimaVector(periods);
var res = trimaVector.Update(new TValue(DateTime.UtcNow, 100.0));
Assert.Equal(3, res.Length);
Assert.Equal(100.0, res[0].Value, 1e-9);
Assert.Equal(100.0, res[1].Value, 1e-9);
Assert.Equal(100.0, res[2].Value, 1e-9);
}
[Fact]
public void Initialization_WithZeroPeriod_ThrowsArgumentException()
{
int[] periods = { 10, 0, 20 };
Assert.Throws<ArgumentOutOfRangeException>(() => new TrimaVector(periods));
}
[Fact]
public void Initialization_WithNegativePeriod_ThrowsArgumentException()
{
int[] periods = { 10, -5, 20 };
Assert.Throws<ArgumentOutOfRangeException>(() => new TrimaVector(periods));
}
[Fact]
public void Calc_Streaming_MatchesSingleTrima()
{
int[] periods = { 5, 10, 20 };
var trimaVector = new TrimaVector(periods);
var trimaSingles = periods.Select(p => new Trima(p)).ToArray();
var values = new double[] { 10, 20, 30, 40, 50, 40, 30, 20, 10 };
var time = DateTime.UtcNow;
foreach (var val in values)
{
var tVal = new TValue(time, val);
var multiRes = trimaVector.Update(tVal);
for (int i = 0; i < periods.Length; i++)
{
var singleRes = trimaSingles[i].Update(tVal);
Assert.Equal(singleRes.Value, multiRes[i].Value, 1e-9);
Assert.Equal(singleRes.Time, multiRes[i].Time);
}
time = time.AddMinutes(1);
}
}
[Fact]
public void Calc_Series_MatchesSingleTrima()
{
int[] periods = { 5, 10, 20 };
var trimaVector = new TrimaVector(periods);
int len = 100;
var t = new System.Collections.Generic.List<long>(len);
var v = new System.Collections.Generic.List<double>(len);
var now = DateTime.UtcNow;
for (int i = 0; i < len; i++)
{
t.Add(now.AddMinutes(i).Ticks);
v.Add(Math.Sin(i * 0.1) * 100);
}
var series = new TSeries(t, v);
var multiRes = trimaVector.Calculate(series);
// Reset and recalculate for comparison
var trimaSingles = periods.Select(p => new Trima(p)).ToArray();
for (int j = 0; j < len; j++)
{
var tVal = new TValue(new DateTime(t[j], DateTimeKind.Utc), v[j]);
for (int i = 0; i < periods.Length; i++)
{
var singleRes = trimaSingles[i].Update(tVal);
Assert.Equal(singleRes.Value, multiRes[i].Values[j], 1e-8);
}
}
}
[Fact]
public void Calc_Series_MatchesStreaming()
{
int[] periods = { 5, 10, 20 };
var trimaVectorBatch = new TrimaVector(periods);
var trimaVectorStream = new TrimaVector(periods);
int len = 100;
var t = new System.Collections.Generic.List<long>(len);
var v = new System.Collections.Generic.List<double>(len);
var now = DateTime.UtcNow;
for (int i = 0; i < len; i++)
{
t.Add(now.AddMinutes(i).Ticks);
v.Add(Math.Sin(i * 0.1) * 100);
}
var series = new TSeries(t, v);
var batchRes = trimaVectorBatch.Calculate(series);
for (int i = 0; i < len; i++)
{
var tVal = new TValue(new DateTime(t[i], DateTimeKind.Utc), v[i]);
var streamRes = trimaVectorStream.Update(tVal);
for (int j = 0; j < periods.Length; j++)
{
Assert.Equal(batchRes[j].Values[i], streamRes[j].Value, 1e-9);
}
}
}
[Fact]
public void Calculate_Static_MatchesInstanceMethod()
{
int[] periods = { 5, 10, 20 };
int len = 50;
var t = new System.Collections.Generic.List<long>(len);
var v = new System.Collections.Generic.List<double>(len);
var now = DateTime.UtcNow;
for (int i = 0; i < len; i++)
{
t.Add(now.AddMinutes(i).Ticks);
v.Add(Math.Sin(i * 0.1) * 100);
}
var series = new TSeries(t, v);
var instanceTrima = new TrimaVector(periods);
var instanceRes = instanceTrima.Calculate(series);
var staticRes = TrimaVector.Calculate(series, periods);
for (int i = 0; i < periods.Length; i++)
{
Assert.Equal(instanceRes[i].Count, staticRes[i].Count);
for (int j = 0; j < len; j++)
{
Assert.Equal(instanceRes[i].Values[j], staticRes[i].Values[j], 1e-9);
}
}
}
[Fact]
public void Reset_ClearsState()
{
int[] periods = { 10 };
var trimaVector = new TrimaVector(periods);
trimaVector.Update(new TValue(DateTime.UtcNow, 100.0));
trimaVector.Update(new TValue(DateTime.UtcNow, 200.0));
trimaVector.Reset();
var res = trimaVector.Update(new TValue(DateTime.UtcNow, 50.0));
Assert.Equal(50.0, res[0].Value, 1e-9);
}
[Fact]
public void Update_NaN_Input_UsesLastValidValue()
{
int[] periods = { 10, 20 };
var trimaVector = new TrimaVector(periods);
trimaVector.Update(new TValue(DateTime.UtcNow, 100.0));
trimaVector.Update(new TValue(DateTime.UtcNow, 110.0));
var resultAfterNaN = trimaVector.Update(new TValue(DateTime.UtcNow, double.NaN));
foreach (var result in resultAfterNaN)
{
Assert.True(double.IsFinite(result.Value), $"Expected finite value but got {result.Value}");
}
}
[Fact]
public void Update_Infinity_Input_UsesLastValidValue()
{
int[] periods = { 10, 20 };
var trimaVector = new TrimaVector(periods);
trimaVector.Update(new TValue(DateTime.UtcNow, 100.0));
trimaVector.Update(new TValue(DateTime.UtcNow, 110.0));
var resultAfterPosInf = trimaVector.Update(new TValue(DateTime.UtcNow, double.PositiveInfinity));
foreach (var result in resultAfterPosInf)
{
Assert.True(double.IsFinite(result.Value));
}
var resultAfterNegInf = trimaVector.Update(new TValue(DateTime.UtcNow, double.NegativeInfinity));
foreach (var result in resultAfterNegInf)
{
Assert.True(double.IsFinite(result.Value));
}
}
[Fact]
public void Update_MultipleNaN_ContinuesWithLastValid()
{
int[] periods = { 5, 10 };
var trimaVector = new TrimaVector(periods);
trimaVector.Update(new TValue(DateTime.UtcNow, 100.0));
trimaVector.Update(new TValue(DateTime.UtcNow, 110.0));
trimaVector.Update(new TValue(DateTime.UtcNow, 120.0));
var r1 = trimaVector.Update(new TValue(DateTime.UtcNow, double.NaN));
var r2 = trimaVector.Update(new TValue(DateTime.UtcNow, double.NaN));
var r3 = trimaVector.Update(new TValue(DateTime.UtcNow, double.NaN));
foreach (var result in r1) Assert.True(double.IsFinite(result.Value));
foreach (var result in r2) Assert.True(double.IsFinite(result.Value));
foreach (var result in r3) Assert.True(double.IsFinite(result.Value));
}
[Fact]
public void Calculate_Series_HandlesNaN()
{
int[] periods = { 5, 10 };
var trimaVector = new TrimaVector(periods);
var t = new System.Collections.Generic.List<long>();
var v = new System.Collections.Generic.List<double>();
var now = DateTime.UtcNow;
t.Add(now.Ticks); v.Add(100.0);
t.Add(now.AddMinutes(1).Ticks); v.Add(110.0);
t.Add(now.AddMinutes(2).Ticks); v.Add(double.NaN);
t.Add(now.AddMinutes(3).Ticks); v.Add(120.0);
t.Add(now.AddMinutes(4).Ticks); v.Add(double.PositiveInfinity);
t.Add(now.AddMinutes(5).Ticks); v.Add(130.0);
var series = new TSeries(t, v);
var results = trimaVector.Calculate(series);
foreach (var periodResults in results)
{
foreach (var val in periodResults.Values)
{
Assert.True(double.IsFinite(val), $"Expected finite value but got {val}");
}
}
}
[Fact]
public void Reset_ClearsLastValidValue()
{
int[] periods = { 10 };
var trimaVector = new TrimaVector(periods);
trimaVector.Update(new TValue(DateTime.UtcNow, 100.0));
trimaVector.Update(new TValue(DateTime.UtcNow, double.NaN));
trimaVector.Reset();
var result = trimaVector.Update(new TValue(DateTime.UtcNow, 50.0));
Assert.Equal(50.0, result[0].Value, 1e-9);
}
[Fact]
public void NaN_Handling_MatchesSingleTrima()
{
int[] periods = { 5, 10, 20 };
var trimaVector = new TrimaVector(periods);
var trimaSingles = periods.Select(p => new Trima(p)).ToArray();
var values = new double[] { 10, 20, double.NaN, 40, double.PositiveInfinity, 60, 70 };
var time = DateTime.UtcNow;
foreach (var val in values)
{
var tVal = new TValue(time, val);
var multiRes = trimaVector.Update(tVal);
for (int i = 0; i < periods.Length; i++)
{
var singleRes = trimaSingles[i].Update(tVal);
Assert.Equal(singleRes.Value, multiRes[i].Value, 1e-9);
}
time = time.AddMinutes(1);
}
}
[Fact]
public void Values_Property_UpdatesAfterUpdate()
{
int[] periods = { 5, 10 };
var trimaVector = new TrimaVector(periods);
var result = trimaVector.Update(new TValue(DateTime.UtcNow, 100.0));
Assert.Equal(result[0].Value, trimaVector.Values[0].Value);
Assert.Equal(result[1].Value, trimaVector.Values[1].Value);
}
[Fact]
public void Values_Property_UpdatesAfterCalculate()
{
int[] periods = { 5, 10 };
var trimaVector = new TrimaVector(periods);
var t = new System.Collections.Generic.List<long> { 100, 200, 300 };
var v = new System.Collections.Generic.List<double> { 10.0, 20.0, 30.0 };
var series = new TSeries(t, v);
var results = trimaVector.Calculate(series);
Assert.Equal(results[0].Last.Value, trimaVector.Values[0].Value, 1e-9);
Assert.Equal(results[1].Last.Value, trimaVector.Values[1].Value, 1e-9);
}
[Fact]
public void Update_BarCorrection_WorksCorrectly()
{
int[] periods = { 3 };
var trimaVector = new TrimaVector(periods);
// TRIMA(3) = SMA(SMA(3, 2), 2)
// p1 = 3/2 + 1 = 2
// p2 = (3+1)/2 = 2
// SMA1(2): 10 -> 10
// SMA2(2): 10 -> 10
trimaVector.Update(new TValue(DateTime.UtcNow, 10.0), isNew: true);
// SMA1(2): 10, 20 -> 15
// SMA2(2): 10, 15 -> 12.5
trimaVector.Update(new TValue(DateTime.UtcNow, 20.0), isNew: true);
// SMA1(2): 20, 30 -> 25
// SMA2(2): 15, 25 -> 20
trimaVector.Update(new TValue(DateTime.UtcNow, 30.0), isNew: true);
var res1 = trimaVector.Values[0].Value;
Assert.Equal(20.0, res1, 1e-9);
// Correct the last bar: 30 -> 60
// SMA1(2): 20, 60 -> 40
// SMA2(2): 15, 40 -> 27.5
var res2 = trimaVector.Update(new TValue(DateTime.UtcNow, 60.0), isNew: false);
Assert.Equal(27.5, res2[0].Value, 1e-9);
}
}
-241
View File
@@ -1,241 +0,0 @@
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace QuanTAlib;
/// <summary>
/// Multi-Period Triangular Moving Average (TRIMA) - SIMD optimized.
/// Calculates multiple TRIMAs with different periods for the same input series in parallel.
/// Uses last-value substitution for invalid inputs (NaN/Infinity).
/// </summary>
[SkipLocalsInit]
public class TrimaVector
{
private readonly SmaVector _sma1;
private readonly int _count;
private readonly TValue[] _values;
// Internal state for second stage
private readonly RingBuffer[] _buffers2;
private readonly RingBuffer[] _p_buffers2;
private readonly double[] _lastValidValues2;
/// <summary>
/// Current TRIMA values for all periods.
/// </summary>
public ReadOnlySpan<TValue> Values => _values;
/// <summary>
/// Initializes TrimaVector with specified periods.
/// </summary>
/// <param name="periods">Array of periods (each must be > 0)</param>
public TrimaVector(int[] periods)
{
_count = periods.Length;
_values = new TValue[_count];
_buffers2 = new RingBuffer[_count];
_p_buffers2 = new RingBuffer[_count];
_lastValidValues2 = new double[_count];
int[] p1 = new int[_count];
for (int i = 0; i < _count; i++)
{
ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(periods[i], 0);
p1[i] = periods[i] / 2 + 1;
int p2 = (periods[i] + 1) / 2;
_buffers2[i] = new RingBuffer(p2);
_p_buffers2[i] = new RingBuffer(p2);
}
_sma1 = new SmaVector(p1);
}
/// <summary>
/// Resets all TRIMA states.
/// </summary>
public void Reset()
{
_sma1.Reset();
for (int i = 0; i < _count; i++)
{
_buffers2[i].Clear();
_p_buffers2[i].Clear();
}
Array.Clear(_lastValidValues2);
Array.Clear(_values);
}
/// <summary>
/// Updates TRIMAs with the given value.
/// Uses last-value substitution: invalid inputs (NaN/Infinity) are replaced with
/// the last known good value, providing continuity in the output series.
/// </summary>
/// <param name="input">Input value</param>
/// <param name="isNew">True for new bar, false for update to current bar (default: true)</param>
/// <returns>Array of TRIMA values</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TValue[] Update(TValue input, bool isNew = true)
{
// First pass: SMA1
var sma1Results = _sma1.Update(input, isNew);
// Second pass: SMA2 (TRIMA)
// We need to feed each SMA1 result into the corresponding SMA2
// Since SmaVector.Update takes a single input, we can't use it directly for vector-to-vector
// However, SmaVector is designed for single input -> multiple periods
// Here we have multiple inputs (from SMA1) -> multiple periods (for SMA2)
// This means we need to update each SMA2 individually, but SmaVector doesn't support that directly
// Wait, SmaVector structure is: one input -> N periods.
// Here we have N inputs (one for each period from SMA1) -> N periods (one for each period in SMA2).
// So we can't use a single SmaVector for the second stage if the inputs are different.
// We need N separate SMAs for the second stage, OR we need to modify SmaVector to support vector input.
// But wait, TrimaVector is supposed to be optimized.
// Let's look at how we can implement this efficiently.
// Actually, since each period in TRIMA maps to a specific pair of (p1, p2),
// and the input to the second SMA depends on the output of the first SMA,
// the inputs to the second stage are indeed all different.
// So we can't use SmaVector for the second stage in the same way (single input broadcast to all).
// We have two options:
// 1. Use an array of Sma objects for the second stage.
// 2. Implement a custom vector-input SMA logic here.
// Given the goal of high performance and vectorization, option 2 is better but more complex.
// However, for now, to match the structure and ensure correctness, let's use the fact that
// we already have SmaVector which is optimized for ring buffers.
// But SmaVector assumes a single input value for all buffers.
// Here, _sma1 produces an array of values, one for each period.
// _sma2 needs to take these DIFFERENT values.
// So, we cannot use SmaVector for the second stage if it only supports single input.
// Let's check SmaVector again. Yes, Update takes `TValue input`.
// So we need to implement the second stage manually using RingBuffers, similar to SmaVector
// but accepting a vector of inputs.
// Let's refactor:
// Instead of using _sma2 as SmaVector, we'll manage the second stage buffers directly here.
// This duplicates some logic from SmaVector but allows vector-to-vector processing.
// Actually, since we are implementing TrimaVector, maybe we should just use arrays of RingBuffers
// for both stages directly, to avoid the mismatch.
// But _sma1 is fine because it takes the single external input.
// It's only the second stage that is problematic.
// Let's implement the second stage buffers directly.
// Wait, I can't change the class structure mid-method.
// I will implement the class using _sma1 for the first stage, and manual buffers for the second stage.
// Re-reading my own thought process:
// _sma1.Update(input) returns TValue[] with results for each period.
// We need to feed result[i] into buffer2[i].
return UpdateInternal(sma1Results, isNew);
}
private TValue[] UpdateInternal(TValue[] inputs, bool isNew)
{
if (isNew)
{
for (int i = 0; i < _count; i++)
{
_p_buffers2[i].CopyFrom(_buffers2[i]);
}
}
else
{
for (int i = 0; i < _count; i++)
{
_buffers2[i].CopyFrom(_p_buffers2[i]);
}
}
for (int i = 0; i < _count; i++)
{
double val = inputs[i].Value;
// Last-value substitution for the second stage
if (double.IsFinite(val))
{
_lastValidValues2[i] = val;
}
else
{
val = _lastValidValues2[i];
}
_buffers2[i].Add(val);
_values[i] = new TValue(inputs[i].Time, _buffers2[i].Average);
}
return _values;
}
/// <summary>
/// Calculates TRIMAs for the entire series.
/// </summary>
/// <param name="source">Input series</param>
/// <returns>Array of TRIMA series</returns>
public TSeries[] Calculate(TSeries source)
{
// We can use the Update method for simplicity and correctness,
// or implement a batch calculation for performance.
// Given the complexity of double smoothing, using Update in a loop is safer and cleaner.
// SmaVector.Calculate is optimized, but we have the two-stage issue.
// Let's use the Update loop approach for now to ensure correctness.
// It will be reasonably fast.
int len = source.Count;
var resultSeries = new TSeries[_count];
// Pre-allocate lists
var tLists = new List<long>[_count];
var vLists = new List<double>[_count];
for (int i = 0; i < _count; i++)
{
tLists[i] = new List<long>(len);
vLists[i] = new List<double>(len);
CollectionsMarshal.SetCount(tLists[i], len);
CollectionsMarshal.SetCount(vLists[i], len);
}
Reset();
for (int t = 0; t < len; t++)
{
var tVal = new TValue(source.Times[t], source.Values[t]);
var results = Update(tVal, isNew: true);
for (int i = 0; i < _count; i++)
{
CollectionsMarshal.AsSpan(tLists[i])[t] = results[i].Time;
CollectionsMarshal.AsSpan(vLists[i])[t] = results[i].Value;
}
}
for (int i = 0; i < _count; i++)
{
resultSeries[i] = new TSeries(tLists[i], vLists[i]);
}
return resultSeries;
}
/// <summary>
/// Calculates TRIMAs for the entire series using specified periods.
/// </summary>
/// <param name="source">Input series</param>
/// <param name="periods">Array of periods</param>
/// <returns>Array of TRIMA series</returns>
public static TSeries[] Calculate(TSeries source, int[] periods)
{
var trimaVector = new TrimaVector(periods);
return trimaVector.Calculate(source);
}
}