refactoring

This commit is contained in:
Miha Kralj
2025-12-16 21:16:50 -08:00
parent a67ad65fa5
commit d277e08056
137 changed files with 5074 additions and 3178 deletions
+1 -1
View File
@@ -116,7 +116,7 @@ public class TrimaIndicatorTests
{
var indicator = new TrimaIndicator();
indicator.Initialize();
var method = indicator.GetType().GetMethod("OnPaintChart");
Assert.NotNull(method);
Assert.Equal(typeof(TrimaIndicator), method.DeclaringType);
+7 -7
View File
@@ -101,7 +101,7 @@ public class TrimaTests
}
[Fact]
public void StaticCalculate_Matches_Streaming()
public void BatchCalculate_Matches_Streaming()
{
var gbm = new GBM();
var bars = gbm.Fetch(200, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
@@ -114,17 +114,17 @@ public class TrimaTests
streamingResults.Add(trima.Update(series[i]).Value);
}
var staticResults = Trima.Calculate(series, 10);
var batchResults = Trima.Batch(series, 10);
Assert.Equal(streamingResults.Count, staticResults.Count);
for (int i = 0; i < staticResults.Count; i++)
Assert.Equal(streamingResults.Count, batchResults.Count);
for (int i = 0; i < batchResults.Count; i++)
{
Assert.Equal(streamingResults[i], staticResults.Values[i], 1e-9);
Assert.Equal(streamingResults[i], batchResults.Values[i], 1e-9);
}
}
[Fact]
public void StaticCalculateSpan_Matches_Streaming()
public void BatchCalculateSpan_Matches_Streaming()
{
var gbm = new GBM();
var bars = gbm.Fetch(200, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
@@ -138,7 +138,7 @@ public class TrimaTests
}
var spanResults = new double[series.Count];
Trima.Calculate(series.Values, spanResults, 10);
Trima.Batch(series.Values, spanResults, 10);
for (int i = 0; i < spanResults.Length; i++)
{
+1 -1
View File
@@ -126,7 +126,7 @@ public class TrimaValidationTests
{
// Calculate QuanTAlib TRIMA (Span API)
double[] qOutput = new double[_testData.RawData.Length];
global::QuanTAlib.Trima.Calculate(_testData.RawData.Span, qOutput.AsSpan(), period);
global::QuanTAlib.Trima.Batch(_testData.RawData.Span, qOutput.AsSpan(), period);
// Calculate TA-Lib TRIMA
var retCode = TALib.Functions.Trima<double>(_testData.RawData.Span, 0..^0, talibOutput, out var outRange, period);
+59 -133
View File
@@ -1,4 +1,6 @@
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
@@ -20,44 +22,28 @@ namespace QuanTAlib;
/// Uses two SMA instances, each with O(1) update complexity.
///
/// IsHot:
/// Becomes true when the buffer is full (period samples processed).
/// Becomes true when both internal SMAs are hot.
/// </remarks>
[SkipLocalsInit]
public sealed class Trima : ITValuePublisher
public sealed class Trima : AbstractBase
{
private readonly int _period;
private readonly int _p1;
private readonly int _p2;
private readonly RingBuffer _buffer1;
private readonly RingBuffer _buffer2;
private record struct State(
double Sum1, double LastInput1, double LastValidValue1, int TickCount1, double NextRemoved1,
double Sum2, double LastInput2, int TickCount2, double NextRemoved2,
int SampleCount
);
private State _state;
private State _p_state;
private const int ResyncInterval = 1000;
public string Name { get; }
public TValue Last { get; private set; }
public bool IsHot => _state.SampleCount >= _period;
public event Action<TValue>? Pub;
private readonly Sma _sma1;
private readonly Sma _sma2;
public Trima(int period)
{
if (period <= 0) throw new ArgumentException("Period must be greater than 0", nameof(period));
_period = period;
_p1 = period / 2 + 1;
_p2 = (period + 1) / 2;
_buffer1 = new RingBuffer(_p1);
_buffer2 = new RingBuffer(_p2);
int p1 = period / 2 + 1;
int p2 = (period + 1) / 2;
_sma1 = new Sma(p1);
_sma2 = new Sma(p2);
Name = $"Trima({period})";
WarmupPeriod = p1 + p2 - 1;
}
public Trima(ITValuePublisher source, int period) : this(period)
@@ -65,129 +51,78 @@ public sealed class Trima : ITValuePublisher
source.Pub += (item) => Update(item);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private double GetValidValue(double input)
{
if (double.IsFinite(input))
{
_state.LastValidValue1 = input;
return input;
}
return _state.LastValidValue1;
}
public override bool IsHot => _sma1.IsHot && _sma2.IsHot;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TValue Update(TValue input, bool isNew = true)
public override TValue Update(TValue input, bool isNew = true)
{
if (isNew)
{
_p_state = _state;
_state.SampleCount++;
}
else
{
_state = _p_state;
}
TValue v1 = _sma1.Update(input, isNew);
TValue v2 = _sma2.Update(v1, isNew);
// SMA 1
double val1 = GetValidValue(input.Value);
if (isNew)
{
double removed1 = _buffer1.Count == _buffer1.Capacity ? _buffer1.Oldest : 0.0;
_state.Sum1 = _state.Sum1 - removed1 + val1;
_buffer1.Add(val1);
// Store NextRemoved1 for next step
_state.NextRemoved1 = _buffer1.Count == _buffer1.Capacity ? _buffer1.Oldest : 0.0;
_state.TickCount1++;
if (_buffer1.IsFull && _state.TickCount1 >= ResyncInterval)
{
_state.TickCount1 = 0;
_state.Sum1 = _buffer1.Sum();
}
}
else
{
// Use NextRemoved1 from _p_state
double removed1 = _p_state.NextRemoved1;
_state.Sum1 = _p_state.Sum1 - removed1 + val1;
_buffer1.UpdateNewest(val1);
}
_state.LastInput1 = val1;
double sma1Result = _state.Sum1 / _buffer1.Count;
// SMA 2
if (isNew)
{
double removed2 = _buffer2.Count == _buffer2.Capacity ? _buffer2.Oldest : 0.0;
_state.Sum2 = _state.Sum2 - removed2 + sma1Result;
_buffer2.Add(sma1Result);
// Store NextRemoved2 for next step
_state.NextRemoved2 = _buffer2.Count == _buffer2.Capacity ? _buffer2.Oldest : 0.0;
_state.TickCount2++;
if (_buffer2.IsFull && _state.TickCount2 >= ResyncInterval)
{
_state.TickCount2 = 0;
_state.Sum2 = _buffer2.Sum();
}
}
else
{
// Use NextRemoved2 from _p_state
double removed2 = _p_state.NextRemoved2;
_state.Sum2 = _p_state.Sum2 - removed2 + sma1Result;
_buffer2.UpdateNewest(sma1Result);
}
_state.LastInput2 = sma1Result;
Last = new TValue(input.Time, _state.Sum2 / _buffer2.Count);
Pub?.Invoke(Last);
Last = v2;
PubEvent(Last);
return Last;
}
public TSeries Update(TSeries source)
public override TSeries Update(TSeries source)
{
if (source.Count == 0) return [];
int len = source.Count;
List<long> t = new(len);
List<double> v = new(len);
var t = new List<long>(len);
var v = new List<double>(len);
CollectionsMarshal.SetCount(t, len);
CollectionsMarshal.SetCount(v, len);
var tSpan = CollectionsMarshal.AsSpan(t);
var vSpan = CollectionsMarshal.AsSpan(v);
Calculate(source.Values, vSpan, _period);
Batch(source.Values, vSpan, _period);
source.Times.CopyTo(tSpan);
// Restore state
int lookback = _p1 + _p2 - 2;
int startIndex = Math.Max(0, len - lookback);
Reset();
for (int i = startIndex; i < len; i++)
{
Update(new TValue(source.Times[i], source.Values[i]), isNew: true);
}
Prime(source.Values);
Last = new TValue(tSpan[len - 1], vSpan[len - 1]);
return new TSeries(t, v);
}
public static TSeries Calculate(TSeries source, int period)
public override void Prime(ReadOnlySpan<double> source)
{
_sma1.Reset();
_sma2.Reset();
_sma1.Prime(source);
// Calculate intermediate SMA series to prime the second SMA
int p1 = _period / 2 + 1;
double[] tempArray = ArrayPool<double>.Shared.Rent(source.Length);
Span<double> tempSpan = tempArray.AsSpan(0, source.Length);
try
{
Sma.Batch(source, tempSpan, p1);
_sma2.Prime(tempSpan);
}
finally
{
ArrayPool<double>.Shared.Return(tempArray);
}
}
public override void Reset()
{
_sma1.Reset();
_sma2.Reset();
Last = default;
}
public static TSeries Batch(TSeries source, int period)
{
var trima = new Trima(period);
return trima.Update(source);
}
public static void Calculate(ReadOnlySpan<double> source, Span<double> output, int period)
public static void Batch(ReadOnlySpan<double> source, Span<double> output, int period)
{
if (source.Length != output.Length)
throw new ArgumentException("Source and output must have the same length");
@@ -202,21 +137,12 @@ public sealed class Trima : ITValuePublisher
try
{
Sma.Calculate(source, tempSpan, p1);
Sma.Calculate(tempSpan, output, p2);
Sma.Batch(source, tempSpan, p1);
Sma.Batch(tempSpan, output, p2);
}
finally
{
ArrayPool<double>.Shared.Return(tempArray);
}
}
public void Reset()
{
_buffer1.Clear();
_buffer2.Clear();
_state = default;
_p_state = default;
Last = default;
}
}
+23
View File
@@ -43,6 +43,29 @@ TRIMA(source, p) = SMA(SMA(source, (p+1)/2), (p+1)/2)
## C# Implementation
### Standard Usage
```csharp
using QuanTAlib;
// Create TRIMA with period 14
var trima = new Trima(14);
// Update with new value
var result = trima.Update(new TValue(DateTime.UtcNow, 100.0));
Console.WriteLine($"TRIMA: {result.Value}");
```
### Static API (High Performance)
```csharp
// Calculate TRIMA for an entire array
double[] prices = { ... };
double[] results = new double[prices.Length];
Trima.Batch(prices, results, 14);
```
### Eventing and Reactive Support
This indicator implements the `ITValuePublisher` interface, enabling event-driven and reactive workflows.