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
+7 -7
View File
@@ -100,7 +100,7 @@ public class VidyaTests
}
[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));
@@ -113,17 +113,17 @@ public class VidyaTests
streamingResults.Add(vidya.Update(series[i]).Value);
}
var staticResults = Vidya.Calculate(series, 10);
var batchResults = Vidya.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));
@@ -137,7 +137,7 @@ public class VidyaTests
}
var spanResults = new double[series.Count];
Vidya.Calculate(series.Values, spanResults, 10);
Vidya.Batch(series.Values, spanResults, 10);
for (int i = 0; i < spanResults.Length; i++)
{
@@ -49,6 +49,22 @@ public class VidyaValidationTests
_output.WriteLine("VIDYA validated successfully against reference implementation");
}
[Fact]
public void ValidateBatchAgainstReference()
{
var period = 14;
// QuanTAlib Batch
var qResults = Vidya.Batch(_testData.Data, period);
// Reference Implementation
var refResults = CalculateVidyaReference(_testData.Data, period);
// Compare
ValidationHelper.VerifyData(qResults, refResults, x => x);
_output.WriteLine("VIDYA Batch validated successfully against reference implementation");
}
private static List<double> CalculateVidyaReference(TSeries data, int period)
{
+159 -93
View File
@@ -1,3 +1,5 @@
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
@@ -24,8 +26,9 @@ namespace QuanTAlib;
/// - Reacts quickly in trending markets (high volatility)
/// </remarks>
[SkipLocalsInit]
public sealed class Vidya : ITValuePublisher
public sealed class Vidya : AbstractBase
{
private readonly int _period;
private readonly double _alpha;
private readonly RingBuffer _ups;
private readonly RingBuffer _downs;
@@ -38,42 +41,28 @@ public sealed class Vidya : ITValuePublisher
private State _state;
private State _p_state;
/// <summary>
/// Display name for the indicator.
/// </summary>
public string Name { get; }
public event Action<TValue>? Pub;
public TValue Last { get; private set; }
/// <summary>
/// Creates VIDYA with specified period.
/// </summary>
/// <param name="period">Period for calculation (must be > 0)</param>
public Vidya(int period)
{
if (period <= 0)
throw new ArgumentException("Period must be greater than 0", nameof(period));
_period = period;
_alpha = 2.0 / (period + 1);
_ups = new RingBuffer(period);
_downs = new RingBuffer(period);
Name = $"Vidya({period})";
WarmupPeriod = period;
}
/// <summary>
/// Creates VIDYA with specified source and period.
/// </summary>
/// <param name="source">Source to subscribe to</param>
/// <param name="period">Period for calculation</param>
public Vidya(ITValuePublisher source, int period) : this(period)
{
source.Pub += (item) => Update(item);
}
public override bool IsHot => _state.BarCount >= _period;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TValue Update(TValue input, bool isNew = true)
public override TValue Update(TValue input, bool isNew = true)
{
if (isNew)
{
@@ -84,7 +73,8 @@ public sealed class Vidya : ITValuePublisher
_state = _p_state;
}
_state.BarCount++;
if (isNew) _state.BarCount++;
if (_state.IsInitialized)
{
_state.PrevClose = _state.CurrentClose;
@@ -94,10 +84,8 @@ public sealed class Vidya : ITValuePublisher
double price = input.Value;
if (!double.IsFinite(price))
{
// Handle NaN/Infinity by using the last known valid values
// If not initialized, we can't do much, just return input
if (!_state.IsInitialized) return input;
price = _state.CurrentClose; // Use last valid close
price = _state.CurrentClose;
}
if (_state.BarCount <= 1)
@@ -110,7 +98,7 @@ public sealed class Vidya : ITValuePublisher
_ups.Add(0, isNew);
_downs.Add(0, isNew);
Last = new TValue(input.Time, _state.CurrentVidya);
Pub?.Invoke(Last);
PubEvent(Last);
return Last;
}
@@ -136,11 +124,11 @@ public sealed class Vidya : ITValuePublisher
_state.CurrentClose = price;
Last = new TValue(input.Time, _state.CurrentVidya);
Pub?.Invoke(Last);
PubEvent(Last);
return Last;
}
public TSeries Update(TSeries source)
public override TSeries Update(TSeries source)
{
if (source.Count == 0) return [];
@@ -152,31 +140,101 @@ public sealed class Vidya : ITValuePublisher
var tSpan = CollectionsMarshal.AsSpan(t);
var vSpan = CollectionsMarshal.AsSpan(v);
var sourceValues = source.Values;
var sourceTimes = source.Times;
sourceTimes.CopyTo(tSpan);
Batch(source.Values, vSpan, _period);
source.Times.CopyTo(tSpan);
Reset();
for (int i = 0; i < len; i++)
{
var val = Update(new TValue(sourceTimes[i], sourceValues[i]), true);
vSpan[i] = val.Value;
}
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)
{
if (source.Length == 0) return;
// Reset state
Reset();
// Process all data to build up state
// For recursive indicators like VIDYA, we generally need to process from the start
// or at least a significant warmup period.
// Given we don't know the "correct" previous VIDYA without processing,
// we process the whole provided history.
double prevClose = source[0];
double lastVidya = source[0];
// Initialize state
_state.PrevClose = prevClose;
_state.LastVidya = lastVidya;
_state.CurrentClose = prevClose;
_state.CurrentVidya = lastVidya;
_state.IsInitialized = true;
_state.BarCount = 1;
_ups.Add(0);
_downs.Add(0);
for (int i = 1; i < source.Length; i++)
{
double price = source[i];
if (!double.IsFinite(price)) price = prevClose;
double change = price - prevClose;
double up = change > 0 ? change : 0;
double down = change < 0 ? -change : 0;
_ups.Add(up);
_downs.Add(down);
_state.BarCount++;
double sumUp = _ups.Sum;
double sumDown = _downs.Sum;
double sum = sumUp + sumDown;
double vi = 0;
if (sum > double.Epsilon)
{
vi = Math.Abs(sumUp - sumDown) / sum;
}
double dynamicAlpha = _alpha * vi;
double currentVidya = dynamicAlpha * price + (1.0 - dynamicAlpha) * lastVidya;
_state.CurrentVidya = currentVidya;
_state.CurrentClose = price;
prevClose = price;
lastVidya = currentVidya;
}
_state.PrevClose = prevClose;
_state.LastVidya = lastVidya;
// Set Last
// Note: Time is not available in Span, so we use MinValue.
// It will be updated on next Update.
Last = new TValue(DateTime.MinValue, _state.CurrentVidya);
_p_state = _state;
}
public override void Reset()
{
_ups.Clear();
_downs.Clear();
_state = default;
_p_state = default;
Last = default;
}
public static TSeries Batch(TSeries source, int period)
{
var vidya = new Vidya(period);
return vidya.Update(source);
}
/// <summary>
/// Calculates VIDYA for the entire series.
/// </summary>
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 (period <= 0)
throw new ArgumentException("Period must be greater than 0", nameof(period));
@@ -187,63 +245,71 @@ public sealed class Vidya : ITValuePublisher
double alpha = 2.0 / (period + 1);
double[] ups = new double[period];
double[] downs = new double[period];
int head = 0;
double sumUp = 0;
double sumDown = 0;
// Use arrays for buffers to avoid heap allocations if possible,
// but period is dynamic.
// We can use ArrayPool or just new double[period] if period is small.
// For simplicity and safety with large periods, let's use ArrayPool.
double prevClose = source[0];
double lastVidya = source[0];
double[] ups = System.Buffers.ArrayPool<double>.Shared.Rent(period);
double[] downs = System.Buffers.ArrayPool<double>.Shared.Rent(period);
Array.Clear(ups, 0, period);
Array.Clear(downs, 0, period);
output[0] = source[0];
for (int i = 1; i < source.Length; i++)
try
{
double price = source[i];
if (!double.IsFinite(price))
int head = 0;
double sumUp = 0;
double sumDown = 0;
double prevClose = source[0];
double lastVidya = source[0];
output[0] = source[0];
for (int i = 1; i < source.Length; i++)
{
price = prevClose;
double price = source[i];
if (!double.IsFinite(price))
{
price = prevClose;
}
double change = price - prevClose;
double up = change > 0 ? change : 0;
double down = change < 0 ? -change : 0;
sumUp -= ups[head];
sumDown -= downs[head];
ups[head] = up;
downs[head] = down;
sumUp += up;
sumDown += down;
head = (head + 1);
if (head >= period) head = 0;
double sum = sumUp + sumDown;
double vi = 0;
if (sum > double.Epsilon)
{
vi = Math.Abs(sumUp - sumDown) / sum;
}
double dynamicAlpha = alpha * vi;
double currentVidya = dynamicAlpha * price + (1.0 - dynamicAlpha) * lastVidya;
output[i] = currentVidya;
prevClose = price;
lastVidya = currentVidya;
}
double change = price - prevClose;
double up = change > 0 ? change : 0;
double down = change < 0 ? -change : 0;
sumUp -= ups[head];
sumDown -= downs[head];
ups[head] = up;
downs[head] = down;
sumUp += up;
sumDown += down;
head = (head + 1) % period;
double sum = sumUp + sumDown;
double vi = 0;
if (sum > double.Epsilon)
{
vi = Math.Abs(sumUp - sumDown) / sum;
}
double dynamicAlpha = alpha * vi;
double currentVidya = dynamicAlpha * price + (1.0 - dynamicAlpha) * lastVidya;
output[i] = currentVidya;
prevClose = price;
lastVidya = currentVidya;
}
finally
{
System.Buffers.ArrayPool<double>.Shared.Return(ups);
System.Buffers.ArrayPool<double>.Shared.Return(downs);
}
}
public void Reset()
{
_ups.Clear();
_downs.Clear();
_state = default;
_p_state = default;
Last = default;
}
}
+1 -1
View File
@@ -71,7 +71,7 @@ Console.WriteLine($"VIDYA: {result.Value}");
double[] prices = { ... };
double[] results = new double[prices.Length];
Vidya.Calculate(prices, results, 14);
Vidya.Batch(prices, results, 14);
```
### Bar Correction (Streaming)