adding missing validations

This commit is contained in:
Miha Kralj
2026-02-26 09:59:44 -08:00
parent 467a8c1cef
commit 9ab37c1200
231 changed files with 60015 additions and 302 deletions
+213
View File
@@ -0,0 +1,213 @@
using Xunit;
using TradingPlatform.BusinessLayer;
namespace QuanTAlib.Tests;
public class DwtIndicatorTests
{
[Fact]
public void DwtIndicator_Constructor_SetsDefaults()
{
var indicator = new DwtIndicator();
Assert.Equal(SourceType.Close, indicator.Source);
Assert.Equal(4, indicator.Levels);
Assert.Equal(0, indicator.OutputComponent);
Assert.True(indicator.ShowColdValues);
Assert.Equal("DWT - Discrete Wavelet Transform", indicator.Name);
Assert.True(indicator.SeparateWindow);
Assert.True(indicator.OnBackGround);
}
[Fact]
public void DwtIndicator_MinHistoryDepths_CorrectForLevel4()
{
// levels=4: bufferSize = 2^4 = 16
var indicator = new DwtIndicator { Levels = 4 };
Assert.Equal(16, indicator.MinHistoryDepths);
}
[Fact]
public void DwtIndicator_MinHistoryDepths_CorrectForLevel2()
{
// levels=2: bufferSize = 2^2 = 4
var indicator = new DwtIndicator { Levels = 2 };
Assert.Equal(4, indicator.MinHistoryDepths);
}
[Fact]
public void DwtIndicator_MinHistoryDepths_CorrectForLevel8()
{
// levels=8: bufferSize = 2^8 = 256
var indicator = new DwtIndicator { Levels = 8 };
Assert.Equal(256, indicator.MinHistoryDepths);
}
[Fact]
public void DwtIndicator_ShortName_IsCorrect()
{
var indicator = new DwtIndicator { Levels = 3, OutputComponent = 1 };
Assert.Equal("DWT(3,1)", indicator.ShortName);
}
[Fact]
public void DwtIndicator_Initialize_CreatesTwoLineSeries()
{
var indicator = new DwtIndicator();
indicator.Initialize();
Assert.Equal(2, indicator.LinesSeries.Count);
Assert.Equal("DWT Component", indicator.LinesSeries[0].Name);
Assert.Equal("Zero", indicator.LinesSeries[1].Name);
}
[Fact]
public void DwtIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
{
// levels=2: warmup = 4 bars
var indicator = new DwtIndicator { Levels = 2 };
indicator.Initialize();
var now = DateTime.UtcNow;
int warmup = indicator.MinHistoryDepths;
for (int i = 0; i < warmup; i++)
{
indicator.HistoricalData.AddBar(now.AddMinutes(i), 0, 105 + i, 95 - i, 100 + i);
var args = new UpdateArgs(UpdateReason.HistoricalBar);
indicator.ProcessUpdate(args);
}
// After warmup, should have valid (non-cold) output
double val = indicator.LinesSeries[0].GetValue(0);
Assert.True(double.IsFinite(val), "Output must be finite after warmup");
}
[Fact]
public void DwtIndicator_ProcessUpdate_NewBar_AddsNewValue()
{
var indicator = new DwtIndicator { Levels = 2 };
indicator.Initialize();
var now = DateTime.UtcNow;
int warmup = indicator.MinHistoryDepths;
for (int i = 0; i < warmup; i++)
{
indicator.HistoricalData.AddBar(now.AddMinutes(i), 0, 105, 95, 100 + i);
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
}
// Feed a new bar
indicator.HistoricalData.AddBar(now.AddMinutes(warmup), 0, 106, 96, 103);
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.NewBar));
Assert.Equal(warmup + 1, indicator.LinesSeries[0].Count);
}
[Fact]
public void DwtIndicator_ProcessUpdate_NewTick_ProcessesWithoutError()
{
var indicator = new DwtIndicator { Levels = 2 };
indicator.Initialize();
var now = DateTime.UtcNow;
indicator.HistoricalData.AddBar(now, 0, 105, 95, 100);
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.NewTick));
// 2 values: one historical, one intra-bar update
Assert.Equal(2, indicator.LinesSeries[0].Count);
}
[Fact]
public void DwtIndicator_ZeroLine_IsAlwaysZero()
{
var indicator = new DwtIndicator { Levels = 2 };
indicator.Initialize();
var now = DateTime.UtcNow;
int warmup = indicator.MinHistoryDepths;
for (int i = 0; i < warmup + 5; i++)
{
indicator.HistoricalData.AddBar(now.AddMinutes(i), 0, 105, 95, 100 + i);
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
}
for (int i = 0; i < indicator.LinesSeries[1].Count; i++)
{
double zero = indicator.LinesSeries[1].GetValue(i);
Assert.Equal(0.0, zero, 1e-10);
}
}
[Fact]
public void DwtIndicator_DifferentSourceType_Works()
{
var indicator = new DwtIndicator { Levels = 2, Source = SourceType.High };
indicator.Initialize();
var now = DateTime.UtcNow;
int warmup = indicator.MinHistoryDepths;
for (int i = 0; i < warmup; i++)
{
indicator.HistoricalData.AddBar(now.AddMinutes(i), 0, 110 + i, 90, 100);
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
}
double val = indicator.LinesSeries[0].GetValue(0);
Assert.True(double.IsFinite(val));
}
[Fact]
public void DwtIndicator_DetailOutput_Works()
{
// OutputComponent = 1 → detail at level 1
var indicator = new DwtIndicator { Levels = 3, OutputComponent = 1 };
indicator.Initialize();
var now = DateTime.UtcNow;
int warmup = indicator.MinHistoryDepths;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 83001);
var bars = gbm.Fetch(warmup + 5, now.Ticks, TimeSpan.FromMinutes(1));
for (int i = 0; i < bars.Close.Count; i++)
{
double price = bars.Close[i].Value;
indicator.HistoricalData.AddBar(
new DateTime(bars.Close[i].Time, DateTimeKind.Utc),
0, price * 1.01, price * 0.99, price);
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
}
double val = indicator.LinesSeries[0].GetValue(0);
Assert.True(double.IsFinite(val), $"DWT detail output {val} must be finite");
}
[Fact]
public void DwtIndicator_OutputNonCold_AfterManyBars()
{
var indicator = new DwtIndicator { Levels = 3 };
indicator.Initialize();
var now = DateTime.UtcNow;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 83002);
var bars = gbm.Fetch(50, now.Ticks, TimeSpan.FromMinutes(1));
for (int i = 0; i < bars.Close.Count; i++)
{
double price = bars.Close[i].Value;
indicator.HistoricalData.AddBar(
new DateTime(bars.Close[i].Time, DateTimeKind.Utc),
0, price * 1.01, price * 0.99, price);
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
}
// All computed values should be finite
for (int i = 0; i < indicator.LinesSeries[0].Count; i++)
{
double val = indicator.LinesSeries[0].GetValue(i);
Assert.True(double.IsFinite(val), $"DWT value {val} at index {i} must be finite");
}
}
}
+70
View File
@@ -0,0 +1,70 @@
using System.Drawing;
using TradingPlatform.BusinessLayer;
using static QuanTAlib.IndicatorExtensions;
namespace QuanTAlib;
/// <summary>
/// DWT (Discrete Wavelet Transform) Quantower indicator.
/// Decomposes the input series using the à trous stationary Haar wavelet,
/// outputting either the approximation (trend) or a detail coefficient (cycles/noise).
/// </summary>
public class DwtIndicator : Indicator, IWatchlistIndicator
{
[DataSourceInput]
public SourceType Source { get; set; } = SourceType.Close;
[InputParameter("Decomposition Levels", sortIndex: 0, minimum: 1, maximum: 8, increment: 1, decimalPlaces: 0)]
public int Levels { get; set; } = 4;
[InputParameter("Output Component (0=approx, 1..levels=detail)", sortIndex: 1, minimum: 0, maximum: 8, increment: 1, decimalPlaces: 0)]
public int OutputComponent { get; set; } = 0;
[InputParameter("Show Cold Values", sortIndex: 100)]
public bool ShowColdValues { get; set; } = true;
private Dwt? _dwt;
private Func<IHistoryItem, double>? _selector;
public int MinHistoryDepths => 1 << Levels; // 2^Levels
public override string ShortName => $"DWT({Levels},{OutputComponent})";
public DwtIndicator()
{
Name = "DWT - Discrete Wavelet Transform";
Description = "À trous stationary Haar DWT — approximation (trend) or detail (cycles/noise) at selected level";
SeparateWindow = true;
OnBackGround = true;
}
protected override void OnInit()
{
int clampedOutput = Math.Clamp(OutputComponent, 0, Levels);
_dwt = new Dwt(Levels, clampedOutput);
_selector = Source.GetPriceSelector();
AddLineSeries(new LineSeries("DWT Component", Color.Yellow, 2, LineStyle.Solid));
// Reference level at 0 (baseline for detail components)
AddLineSeries(new LineSeries("Zero", Color.Gray, 1, LineStyle.Dash));
}
protected override void OnUpdate(UpdateArgs args)
{
if (_dwt == null || _selector == null)
{
return;
}
var item = HistoricalData[0, SeekOriginHistory.End];
double value = _selector(item);
bool isNew = args.IsNewBar();
TValue input = new(item.TimeLeft, value);
_dwt.Update(input, isNew);
bool isHot = _dwt.IsHot;
LinesSeries[0].SetValue(_dwt.Last.Value, isHot, ShowColdValues);
LinesSeries[1].SetValue(0.0, isHot, ShowColdValues);
}
}
+672
View File
@@ -0,0 +1,672 @@
using Xunit;
namespace QuanTAlib.Tests;
public class DwtTests
{
private const double Tolerance = 1e-10;
// ─── A) Constructor validation ────────────────────────────────────────────
[Fact]
public void Constructor_DefaultParameters_SetsProperties()
{
var indicator = new Dwt();
Assert.Equal("Dwt(4,0)", indicator.Name);
Assert.False(indicator.IsHot);
}
[Fact]
public void Constructor_CustomParameters_SetsName()
{
var indicator = new Dwt(levels: 3, output: 1);
Assert.Equal("Dwt(3,1)", indicator.Name);
}
[Fact]
public void Constructor_ZeroLevel_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentException>(() => new Dwt(levels: 0));
Assert.Equal("levels", ex.ParamName);
}
[Fact]
public void Constructor_NegativeLevel_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentException>(() => new Dwt(levels: -1));
Assert.Equal("levels", ex.ParamName);
}
[Fact]
public void Constructor_LevelAboveMax_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentException>(() => new Dwt(levels: 9));
Assert.Equal("levels", ex.ParamName);
}
[Fact]
public void Constructor_OutputNegative_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentException>(() => new Dwt(levels: 4, output: -1));
Assert.Equal("output", ex.ParamName);
}
[Fact]
public void Constructor_OutputAboveLevels_ThrowsArgumentException()
{
// levels=3, output=4 is invalid
var ex = Assert.Throws<ArgumentException>(() => new Dwt(levels: 3, output: 4));
Assert.Equal("output", ex.ParamName);
}
[Fact]
public void Constructor_OutputEqualToLevels_IsValid()
{
// output == levels is valid (detail at deepest level)
var indicator = new Dwt(levels: 3, output: 3);
Assert.NotNull(indicator);
}
[Fact]
public void Constructor_WarmupPeriod_IsPowerOfTwo()
{
// WarmupPeriod = 2^levels
Assert.Equal(2, new Dwt(levels: 1).WarmupPeriod);
Assert.Equal(4, new Dwt(levels: 2).WarmupPeriod);
Assert.Equal(8, new Dwt(levels: 3).WarmupPeriod);
Assert.Equal(16, new Dwt(levels: 4).WarmupPeriod);
Assert.Equal(32, new Dwt(levels: 5).WarmupPeriod);
Assert.Equal(64, new Dwt(levels: 6).WarmupPeriod);
Assert.Equal(128, new Dwt(levels: 7).WarmupPeriod);
Assert.Equal(256, new Dwt(levels: 8).WarmupPeriod);
}
// ─── B) Basic calculation ─────────────────────────────────────────────────
[Fact]
public void Update_ReturnsValidTValue()
{
var indicator = new Dwt(levels: 2);
var time = DateTime.UtcNow;
var input = new TValue(time, 100.0);
var result = indicator.Update(input);
Assert.Equal(input.Time, result.Time);
Assert.True(double.IsFinite(result.Value));
}
[Fact]
public void Update_ApproximationOutput_IsFinite()
{
var indicator = new Dwt(levels: 2, output: 0);
var time = DateTime.UtcNow;
int warmup = indicator.WarmupPeriod;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 80001);
var bars = gbm.Fetch(warmup + 10, time.Ticks, TimeSpan.FromMinutes(1));
for (int i = 0; i < bars.Close.Count; i++)
{
var result = indicator.Update(bars.Close[i]);
Assert.True(double.IsFinite(result.Value),
$"DWT approximation must be finite at bar {i}, got {result.Value}");
}
}
[Fact]
public void Update_DetailOutput_IsFinite()
{
var indicator = new Dwt(levels: 3, output: 1); // detail at level 1
var time = DateTime.UtcNow;
int warmup = indicator.WarmupPeriod;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 80002);
var bars = gbm.Fetch(warmup + 10, time.Ticks, TimeSpan.FromMinutes(1));
for (int i = 0; i < bars.Close.Count; i++)
{
var result = indicator.Update(bars.Close[i]);
Assert.True(double.IsFinite(result.Value),
$"DWT detail must be finite at bar {i}, got {result.Value}");
}
}
[Fact]
public void Last_IsAccessible_AfterUpdate()
{
var indicator = new Dwt(levels: 2);
var time = DateTime.UtcNow;
indicator.Update(new TValue(time, 50.0));
Assert.NotEqual(default, indicator.Last);
}
[Fact]
public void Name_Accessible_AndContainsDwt()
{
var indicator = new Dwt(levels: 4, output: 0);
Assert.NotNull(indicator.Name);
Assert.Contains("Dwt", indicator.Name, StringComparison.Ordinal);
}
// ─── C) State + bar correction ────────────────────────────────────────────
[Fact]
public void Update_IsNewTrue_AdvancesState()
{
var indicator = new Dwt(levels: 2);
var time = DateTime.UtcNow;
int warmup = indicator.WarmupPeriod;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 80003);
var bars = gbm.Fetch(warmup + 5, time.Ticks, TimeSpan.FromMinutes(1));
for (int i = 0; i < warmup; i++)
{
indicator.Update(bars.Close[i]);
}
double before = indicator.Last.Value;
indicator.Update(new TValue(time.AddMinutes(warmup), 9999.0), true);
double after = indicator.Last.Value;
Assert.True(double.IsFinite(after));
Assert.NotEqual(before, after, 1.0); // extreme value should change result
}
[Fact]
public void Update_IsNewFalse_RewritesLastBar()
{
var indicator = new Dwt(levels: 2);
var time = DateTime.UtcNow;
int warmup = indicator.WarmupPeriod;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 80004);
var bars = gbm.Fetch(warmup + 2, time.Ticks, TimeSpan.FromMinutes(1));
for (int i = 0; i < warmup; i++)
{
indicator.Update(bars.Close[i]);
}
// New bar with extreme value A
indicator.Update(new TValue(time.AddMinutes(warmup), 9999.0), true);
double valueA = indicator.Last.Value;
// Correct same bar with very different value B
indicator.Update(new TValue(time.AddMinutes(warmup), 0.001), false);
double valueB = indicator.Last.Value;
Assert.NotEqual(valueA, valueB, 1e-6);
}
[Fact]
public void Update_IterativeCorrection_RestoresState()
{
var time = DateTime.UtcNow;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 80005);
int count = 30;
var bars = gbm.Fetch(count, time.Ticks, TimeSpan.FromMinutes(1));
// Streaming without corrections
var straight = new Dwt(levels: 2);
for (int i = 0; i < bars.Close.Count; i++)
{
straight.Update(bars.Close[i]);
}
double finalStraight = straight.Last.Value;
// With corrections (wrong → corrected to same value)
var corrected = new Dwt(levels: 2);
for (int i = 0; i < bars.Close.Count; i++)
{
corrected.Update(new TValue(bars.Close[i].Time, 999.0), true);
corrected.Update(bars.Close[i], false);
}
Assert.Equal(finalStraight, corrected.Last.Value, Tolerance);
}
[Fact]
public void Reset_ClearsState()
{
var indicator = new Dwt(levels: 2);
var time = DateTime.UtcNow;
int warmup = indicator.WarmupPeriod;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 80006);
var bars = gbm.Fetch(warmup, time.Ticks, TimeSpan.FromMinutes(1));
for (int i = 0; i < bars.Close.Count; i++)
{
indicator.Update(bars.Close[i]);
}
Assert.True(indicator.IsHot);
indicator.Reset();
Assert.False(indicator.IsHot);
Assert.Equal(default, indicator.Last);
}
// ─── D) Warmup / convergence ──────────────────────────────────────────────
[Fact]
public void IsHot_FlipsAtBufferSize()
{
// levels=2: bufferSize=4
var indicator = new Dwt(levels: 2);
var time = DateTime.UtcNow;
int warmup = indicator.WarmupPeriod; // 4
for (int i = 0; i < warmup - 1; i++)
{
indicator.Update(new TValue(time.AddMinutes(i), 100.0 + i));
Assert.False(indicator.IsHot, $"Should not be hot at bar {i + 1}");
}
indicator.Update(new TValue(time.AddMinutes(warmup - 1), 100.0 + warmup));
Assert.True(indicator.IsHot, "Should be hot after warmup bars");
}
[Fact]
public void WarmupPeriod_LevelsDependent()
{
Assert.Equal(4, new Dwt(levels: 2).WarmupPeriod);
Assert.Equal(16, new Dwt(levels: 4).WarmupPeriod);
Assert.Equal(64, new Dwt(levels: 6).WarmupPeriod);
}
// ─── E) Robustness ────────────────────────────────────────────────────────
[Fact]
public void Update_NaN_UsesLastValidValue()
{
var indicator = new Dwt(levels: 2);
var time = DateTime.UtcNow;
int warmup = indicator.WarmupPeriod;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 80007);
var bars = gbm.Fetch(warmup, time.Ticks, TimeSpan.FromMinutes(1));
for (int i = 0; i < warmup; i++)
{
indicator.Update(bars.Close[i]);
}
double before = indicator.Last.Value;
indicator.Update(new TValue(time.AddMinutes(warmup), double.NaN));
Assert.Equal(before, indicator.Last.Value, Tolerance);
}
[Fact]
public void Update_PositiveInfinity_UsesLastValidValue()
{
var indicator = new Dwt(levels: 2);
var time = DateTime.UtcNow;
int warmup = indicator.WarmupPeriod;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 80008);
var bars = gbm.Fetch(warmup, time.Ticks, TimeSpan.FromMinutes(1));
for (int i = 0; i < warmup; i++)
{
indicator.Update(bars.Close[i]);
}
double before = indicator.Last.Value;
indicator.Update(new TValue(time.AddMinutes(warmup), double.PositiveInfinity));
Assert.Equal(before, indicator.Last.Value, Tolerance);
}
[Fact]
public void Update_NegativeInfinity_UsesLastValidValue()
{
var indicator = new Dwt(levels: 2);
var time = DateTime.UtcNow;
int warmup = indicator.WarmupPeriod;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 80009);
var bars = gbm.Fetch(warmup, time.Ticks, TimeSpan.FromMinutes(1));
for (int i = 0; i < warmup; i++)
{
indicator.Update(bars.Close[i]);
}
double before = indicator.Last.Value;
indicator.Update(new TValue(time.AddMinutes(warmup), double.NegativeInfinity));
Assert.Equal(before, indicator.Last.Value, Tolerance);
}
[Fact]
public void Update_BatchNaN_AlwaysFinite()
{
var indicator = new Dwt(levels: 1); // warmup = 2
var time = DateTime.UtcNow;
double[] prices = { 100.0, double.NaN, 102.0, double.NaN, 98.0, 105.0, 103.0, 99.0 };
for (int i = 0; i < prices.Length; i++)
{
var result = indicator.Update(new TValue(time.AddMinutes(i), prices[i]));
Assert.True(double.IsFinite(result.Value),
$"Output must be finite at {i}, got {result.Value}");
}
}
// ─── F) Consistency: batch == streaming == span == eventing ──────────────
[Fact]
public void AllModes_ConsistencyCheck()
{
int levels = 2;
int count = 50;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 80010);
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
var source = bars.Close;
// Streaming
var streaming = new Dwt(levels);
for (int i = 0; i < source.Count; i++)
{
streaming.Update(source[i]);
}
// Batch (TSeries)
var batch = Dwt.Batch(source, levels);
// Span
var rawValues = new double[source.Count];
for (int i = 0; i < source.Count; i++)
{
rawValues[i] = source[i].Value;
}
var spanOutput = new double[source.Count];
Dwt.Batch(rawValues, spanOutput, levels);
// Eventing
var eventResults = new List<double>();
var eventSource = new TSeries();
var eventIndicator = new Dwt(eventSource, levels);
eventIndicator.Pub += (object? s, in TValueEventArgs e) => eventResults.Add(e.Value.Value);
for (int i = 0; i < source.Count; i++)
{
eventSource.Add(source[i], true);
}
double streamingLast = streaming.Last.Value;
double batchLast = batch[source.Count - 1].Value;
double spanLast = spanOutput[source.Count - 1];
double eventLast = eventResults[^1];
Assert.Equal(streamingLast, batchLast, Tolerance);
Assert.Equal(streamingLast, spanLast, Tolerance);
Assert.Equal(streamingLast, eventLast, Tolerance);
}
[Fact]
public void Streaming_VsBatch_AllValues_Match()
{
int count = 50;
int levels = 2;
var gbm = new GBM(startPrice: 50, mu: 0.0, sigma: 0.3, seed: 80011);
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
var source = bars.Close;
var streaming = new Dwt(levels);
var streamingVals = new double[count];
for (int i = 0; i < count; i++)
{
streaming.Update(source[i]);
streamingVals[i] = streaming.Last.Value;
}
var batch = Dwt.Batch(source, levels);
for (int i = 0; i < count; i++)
{
Assert.Equal(streamingVals[i], batch[i].Value, Tolerance);
}
}
// ─── G) Span API tests ────────────────────────────────────────────────────
[Fact]
public void Batch_Span_EmptySource_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentException>(() =>
Dwt.Batch([], Array.Empty<double>()));
Assert.Equal("source", ex.ParamName);
}
[Fact]
public void Batch_Span_OutputTooShort_ThrowsArgumentException()
{
double[] src = { 1.0, 2.0, 3.0 };
double[] dst = new double[2];
var ex = Assert.Throws<ArgumentException>(() =>
Dwt.Batch(src, dst));
Assert.Equal("output", ex.ParamName);
}
[Fact]
public void Batch_Span_InvalidLevels_ThrowsArgumentException()
{
double[] src = { 1.0, 2.0, 3.0 };
double[] dst = new double[3];
var ex = Assert.Throws<ArgumentException>(() =>
Dwt.Batch(src, dst, levels: 0));
Assert.Equal("levels", ex.ParamName);
}
[Fact]
public void Batch_Span_InvalidOutput_ThrowsArgumentException()
{
double[] src = { 1.0, 2.0, 3.0 };
double[] dst = new double[3];
var ex = Assert.Throws<ArgumentException>(() =>
Dwt.Batch(src, dst, levels: 2, outputComponent: 5));
Assert.Equal("outputComponent", ex.ParamName);
}
[Fact]
public void Batch_Span_OutputIsFinite()
{
int count = 100;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 80012);
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
double[] src = new double[count];
for (int i = 0; i < count; i++)
{
src[i] = bars.Close[i].Value;
}
double[] dst = new double[count];
Dwt.Batch(src, dst, levels: 3);
foreach (double v in dst)
{
Assert.True(double.IsFinite(v), $"DWT output {v} must be finite");
}
}
[Fact]
public void Batch_Span_HandlesNaN()
{
// levels=1: bufferSize=2
double[] src = new double[20];
for (int i = 0; i < src.Length; i++)
{
src[i] = 100.0 + i;
}
src[3] = double.NaN;
double[] dst = new double[src.Length];
Dwt.Batch(src, dst, levels: 1);
foreach (double v in dst)
{
Assert.True(double.IsFinite(v), $"Span output should be finite, got {v}");
}
}
[Fact]
public void Batch_Span_NoStackOverflow_Level8()
{
// levels=8: bufferSize=256 — exactly at StackallocThreshold boundary
int count = 500;
double[] src = new double[count];
for (int i = 0; i < count; i++)
{
src[i] = 100.0 + Math.Sin(i * 0.1) * 10.0;
}
double[] dst = new double[count];
Dwt.Batch(src, dst, levels: 8);
foreach (double v in dst)
{
Assert.True(double.IsFinite(v));
}
}
[Fact]
public void Batch_Span_MatchesStreaming()
{
int count = 60;
int levels = 2;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.25, seed: 80013);
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
double[] src = new double[count];
for (int i = 0; i < count; i++)
{
src[i] = bars.Close[i].Value;
}
double[] spanOut = new double[count];
Dwt.Batch(src, spanOut, levels: levels);
var streaming = new Dwt(levels);
for (int i = 0; i < count; i++)
{
streaming.Update(bars.Close[i]);
Assert.Equal(streaming.Last.Value, spanOut[i], Tolerance);
}
}
// ─── H) Chainability ──────────────────────────────────────────────────────
[Fact]
public void Pub_EventFires()
{
var indicator = new Dwt(levels: 2);
int count = 0;
indicator.Pub += (object? sender, in TValueEventArgs args) => count++;
var time = DateTime.UtcNow;
for (int i = 0; i < 5; i++)
{
indicator.Update(new TValue(time.AddMinutes(i), 100.0 + i));
}
Assert.Equal(5, count);
}
[Fact]
public void Chaining_Constructor_Works()
{
int levels = 2;
var source = new TSeries();
var indicator = new Dwt(source, levels);
int warmup = indicator.WarmupPeriod;
var time = DateTime.UtcNow;
for (int i = 0; i < warmup; i++)
{
source.Add(new TValue(time.AddMinutes(i), 100.0 + i), true);
}
Assert.True(indicator.IsHot);
Assert.True(double.IsFinite(indicator.Last.Value));
}
[Fact]
public void Pub_EventValue_MatchesLast()
{
var indicator = new Dwt(levels: 2);
TValue? lastEvent = null;
indicator.Pub += (object? s, in TValueEventArgs e) => lastEvent = e.Value;
var time = DateTime.UtcNow;
int warmup = indicator.WarmupPeriod;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 80014);
var bars = gbm.Fetch(warmup + 2, time.Ticks, TimeSpan.FromMinutes(1));
for (int i = 0; i < bars.Close.Count; i++)
{
indicator.Update(bars.Close[i]);
}
Assert.NotNull(lastEvent);
Assert.Equal(indicator.Last.Value, lastEvent.Value.Value, Tolerance);
}
// ─── Additional: static Calculate method ─────────────────────────────────
[Fact]
public void Calculate_StaticMethod_ReturnsTuple()
{
int count = 50;
int levels = 2;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 80015);
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
var (results, instance) = Dwt.Calculate(bars.Close, levels);
Assert.Equal(count, results.Count);
Assert.Equal(results[^1].Value, instance.Last.Value, Tolerance);
}
[Fact]
public void AllLevels_Approximation_IsFinite()
{
int count = 300;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 80016);
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
for (int level = 1; level <= 8; level++)
{
var ind = new Dwt(levels: level, output: 0);
for (int i = 0; i < bars.Close.Count; i++)
{
var result = ind.Update(bars.Close[i]);
Assert.True(double.IsFinite(result.Value),
$"Level {level} approximation must be finite at bar {i}");
}
}
}
[Fact]
public void AllDetailLevels_AreFinite()
{
int count = 300;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 80017);
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
// Test detail output at each level
for (int maxLevels = 1; maxLevels <= 5; maxLevels++)
{
for (int detail = 1; detail <= maxLevels; detail++)
{
var ind = new Dwt(levels: maxLevels, output: detail);
for (int i = 0; i < bars.Close.Count; i++)
{
var result = ind.Update(bars.Close[i]);
Assert.True(double.IsFinite(result.Value),
$"Detail level {detail}/{maxLevels} must be finite at bar {i}");
}
}
}
}
}
+344
View File
@@ -0,0 +1,344 @@
using Xunit;
namespace QuanTAlib.Tests;
/// <summary>
/// Validation tests for Dwt using known mathematical properties of the
/// à trous Haar wavelet decomposition. No external library reference —
/// validates against first-principles mathematical invariants.
/// </summary>
public class DwtValidationTests
{
private const double Tolerance = 1e-10;
private const double CoarseTolerance = 1e-6;
// ─── Property 1: Constant signal → approximation = constant, detail ≈ 0 ──
[Fact]
public void HaarDwt_ConstantSignal_ApproximationEqualsConstant()
{
// À trous Haar: avg of identical samples = the sample itself
const double constantValue = 42.0;
var indicator = new Dwt(levels: 4, output: 0); // approximation
var time = DateTime.UtcNow;
int warmup = indicator.WarmupPeriod;
for (int i = 0; i < warmup + 10; i++)
{
indicator.Update(new TValue(time.AddMinutes(i), constantValue));
}
// After warmup, approximation of constant signal = constant
Assert.Equal(constantValue, indicator.Last.Value, CoarseTolerance);
}
[Fact]
public void HaarDwt_ConstantSignal_DetailEqualsZero()
{
// Detail = c[j-1] - c[j]; for constant input, both levels equal constant → detail = 0
const double constantValue = 100.0;
var time = DateTime.UtcNow;
for (int level = 1; level <= 5; level++)
{
var indicator = new Dwt(levels: level, output: level); // detail at deepest level
int warmup = indicator.WarmupPeriod;
for (int i = 0; i < warmup + 5; i++)
{
indicator.Update(new TValue(time.AddMinutes(i), constantValue));
}
Assert.Equal(0.0, indicator.Last.Value, CoarseTolerance);
}
}
[Fact]
public void HaarDwt_ConstantSignal_AllDetailLevelsZero()
{
// Every detail level of a constant signal should be zero
const double constantValue = 50.0;
var time = DateTime.UtcNow;
int maxLevels = 4;
int warmup = 1 << maxLevels; // 16
for (int detail = 1; detail <= maxLevels; detail++)
{
var indicator = new Dwt(levels: maxLevels, output: detail);
for (int i = 0; i < warmup + 5; i++)
{
indicator.Update(new TValue(time.AddMinutes(i), constantValue));
}
Assert.Equal(0.0, indicator.Last.Value, CoarseTolerance);
}
}
// ─── Property 2: Zero input → zero output ────────────────────────────────
[Fact]
public void HaarDwt_ZeroInput_ZeroApproximation()
{
var indicator = new Dwt(levels: 3, output: 0);
var time = DateTime.UtcNow;
int warmup = indicator.WarmupPeriod;
for (int i = 0; i < warmup + 5; i++)
{
indicator.Update(new TValue(time.AddMinutes(i), 0.0));
}
Assert.Equal(0.0, indicator.Last.Value, Tolerance);
}
[Fact]
public void HaarDwt_ZeroInput_ZeroDetail()
{
var indicator = new Dwt(levels: 3, output: 1);
var time = DateTime.UtcNow;
int warmup = indicator.WarmupPeriod;
for (int i = 0; i < warmup + 5; i++)
{
indicator.Update(new TValue(time.AddMinutes(i), 0.0));
}
Assert.Equal(0.0, indicator.Last.Value, Tolerance);
}
// ─── Property 3: Perfect reconstruction ──────────────────────────────────
[Fact]
public void PerfectReconstruction_ApproxPlusSumOfDetails_EqualsInput()
{
// x[n] = c[L][n] + sum(d[j][n], j=1..L)
// All components computed at the same time = same input, so their sum = input.
int levels = 3;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 90001);
int count = 50;
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
// Run all components simultaneously on same data
var approxInd = new Dwt(levels, output: 0);
var detail1Ind = new Dwt(levels, output: 1);
var detail2Ind = new Dwt(levels, output: 2);
var detail3Ind = new Dwt(levels, output: 3);
for (int i = 0; i < count; i++)
{
approxInd.Update(bars.Close[i]);
detail1Ind.Update(bars.Close[i]);
detail2Ind.Update(bars.Close[i]);
detail3Ind.Update(bars.Close[i]);
}
// Only check after full warmup
double reconstructed = approxInd.Last.Value
+ detail1Ind.Last.Value
+ detail2Ind.Last.Value
+ detail3Ind.Last.Value;
double original = bars.Close[^1].Value;
Assert.Equal(original, reconstructed, 1e-8);
}
[Fact]
public void PerfectReconstruction_Level2_HoldsForMultipleBars()
{
int levels = 2;
int warmup = 1 << levels; // 4
int count = 30;
var gbm = new GBM(startPrice: 100, mu: 0.0, sigma: 0.15, seed: 90002);
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
var approxInd = new Dwt(levels, output: 0);
var detail1Ind = new Dwt(levels, output: 1);
var detail2Ind = new Dwt(levels, output: 2);
for (int i = 0; i < count; i++)
{
approxInd.Update(bars.Close[i]);
detail1Ind.Update(bars.Close[i]);
detail2Ind.Update(bars.Close[i]);
if (i >= warmup - 1)
{
double reconstructed = approxInd.Last.Value
+ detail1Ind.Last.Value
+ detail2Ind.Last.Value;
double original = bars.Close[i].Value;
Assert.Equal(original, reconstructed, 1e-8);
}
}
}
// ─── Property 4: Approximation smooths variance ───────────────────────────
[Fact]
public void Approximation_HasLowerVariance_ThanInput()
{
// By design, Haar averaging reduces high-frequency variance.
int levels = 3;
int count = 200;
var gbm = new GBM(startPrice: 100, mu: 0.0, sigma: 0.3, seed: 90003);
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
int warmup = 1 << levels;
var approxInd = new Dwt(levels, output: 0);
var approxVals = new List<double>();
var inputVals = new List<double>();
for (int i = 0; i < count; i++)
{
approxInd.Update(bars.Close[i]);
if (i >= warmup)
{
approxVals.Add(approxInd.Last.Value);
inputVals.Add(bars.Close[i].Value);
}
}
double inputVar = Variance(inputVals);
double approxVar = Variance(approxVals);
Assert.True(approxVar <= inputVar,
$"Approximation variance {approxVar:F6} should be <= input variance {inputVar:F6}");
}
// ─── Property 5: Linearity of the transform ───────────────────────────────
[Fact]
public void DwtApproximation_IsLinear_ScaledInputScalesOutput()
{
// DWT is a linear operator: DWT(k*x) = k*DWT(x)
const double scale = 2.5;
int levels = 2;
int count = 20;
var gbm = new GBM(startPrice: 100, mu: 0.0, sigma: 0.1, seed: 90004);
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
var ind1 = new Dwt(levels, output: 0);
var ind2 = new Dwt(levels, output: 0);
for (int i = 0; i < count; i++)
{
ind1.Update(bars.Close[i]);
ind2.Update(new TValue(bars.Close[i].Time, bars.Close[i].Value * scale));
}
// ind2.Last ≈ scale * ind1.Last
Assert.Equal(ind1.Last.Value * scale, ind2.Last.Value, 1e-8);
}
// ─── Property 6: Span API perfect-reconstruction ─────────────────────────
[Fact]
public void Batch_Span_PerfectReconstruction_Level2()
{
int levels = 2;
int count = 40;
var gbm = new GBM(startPrice: 100, mu: 0.0, sigma: 0.2, seed: 90005);
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
int warmup = 1 << levels;
double[] src = new double[count];
for (int i = 0; i < count; i++) { src[i] = bars.Close[i].Value; }
double[] approx = new double[count];
double[] d1 = new double[count];
double[] d2 = new double[count];
Dwt.Batch(src, approx, levels, 0);
Dwt.Batch(src, d1, levels, 1);
Dwt.Batch(src, d2, levels, 2);
for (int i = warmup - 1; i < count; i++)
{
double reconstructed = approx[i] + d1[i] + d2[i];
Assert.Equal(src[i], reconstructed, 1e-8);
}
}
// ─── Property 7: Detail level 1 captures 2-bar differences ───────────────
[Fact]
public void Detail1_CapturesHighFrequency_LargerThanDetail2()
{
// For GBM noise: detail level 1 (2-bar scale) has larger variance than detail level 2 (4-bar scale)
// because lower-frequency details progressively smooth
int levels = 3;
int count = 200;
var gbm = new GBM(startPrice: 100, mu: 0.0, sigma: 0.3, seed: 90006);
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
int warmup = 1 << levels;
var d1Ind = new Dwt(levels, output: 1);
var d2Ind = new Dwt(levels, output: 2);
var d1Vals = new List<double>();
var d2Vals = new List<double>();
for (int i = 0; i < count; i++)
{
d1Ind.Update(bars.Close[i]);
d2Ind.Update(bars.Close[i]);
if (i >= warmup)
{
d1Vals.Add(d1Ind.Last.Value);
d2Vals.Add(d2Ind.Last.Value);
}
}
double d1Var = Variance(d1Vals);
double d2Var = Variance(d2Vals);
// d1 captures finer-scale variation → should have higher energy than d2
Assert.True(d1Var >= d2Var * 0.5,
$"Detail 1 variance {d1Var:F6} should be >= 50% of detail 2 variance {d2Var:F6}");
}
// ─── Property 8: Span vs streaming consistency across all levels ──────────
[Fact]
public void Batch_Span_MatchesStreaming_AllLevels()
{
int count = 100;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 90007);
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
double[] src = new double[count];
for (int i = 0; i < count; i++) { src[i] = bars.Close[i].Value; }
for (int levels = 1; levels <= 5; levels++)
{
double[] spanOut = new double[count];
Dwt.Batch(src, spanOut, levels, 0);
var streaming = new Dwt(levels, 0);
for (int i = 0; i < count; i++)
{
streaming.Update(bars.Close[i]);
Assert.Equal(streaming.Last.Value, spanOut[i], Tolerance);
}
}
}
// ─── Helper ──────────────────────────────────────────────────────────────
private static double Variance(List<double> vals)
{
if (vals.Count < 2) { return 0.0; }
double mean = 0.0;
for (int i = 0; i < vals.Count; i++) { mean += vals[i]; }
mean /= vals.Count;
double ss = 0.0;
for (int i = 0; i < vals.Count; i++)
{
double d = vals[i] - mean;
ss = Math.FusedMultiplyAdd(d, d, ss);
}
return ss / (vals.Count - 1);
}
}
+548
View File
@@ -0,0 +1,548 @@
// DWT: Discrete Wavelet Transform (À trous / Stationary Haar)
// Decomposes a signal into multi-resolution approximation and detail coefficients
// using the stationary (non-decimated) Haar wavelet. No downsampling: every output
// sample aligns precisely with its input bar. Lookback at level L = 2^L bars.
//
// Algorithm (à trous unrolled cascade, mirrors dwt.pine):
// c[0] = input
// c[j] = 0.5 * (c[j-1] + c[j-1][2^(j-1)]) — approximation at level j
// d[j] = c[j-1] - c[j] — detail at level j
//
// output=0 → deepest approximation (trend)
// output=1..levels → detail at that level (noise/cycles)
//
// State stores all 8 level-approximation values and their delayed counterparts
// via a RingBuffer sized 2^levels. O(levels) per Update.
using System.Buffers;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace QuanTAlib;
/// <summary>
/// DWT: Discrete Wavelet Transform (À trous Stationary Haar)
/// Decomposes a price series into multi-resolution approximation and detail
/// coefficients without downsampling, preserving exact bar alignment.
/// </summary>
/// <remarks>
/// Key properties:
/// - À trous (stationary) variant: no downsampling, every bar produces output
/// - Level j effective window: 2^j bars; max lookback = 2^levels bars
/// - output=0: deepest approximation (trend signal, lowest frequency)
/// - output=1..levels: detail at that level (cycles/noise at 2^j-bar scale)
/// - WarmupPeriod = 2^levels (buffer must be full for all lags to resolve)
/// - Perfect reconstruction: input = approx[L] + sum(detail[1..L])
/// - O(levels) per Update — levels ∈ [1,8]
/// </remarks>
[SkipLocalsInit]
public sealed class Dwt : AbstractBase
{
private readonly int _levels;
private readonly int _output;
private readonly int _bufferSize; // 2^levels
private readonly RingBuffer _buffer;
// State: all 8 level-approximation values (c1..c8) in current cascade.
// Only levels 1.._levels are meaningful; higher levels are carried as-is.
[StructLayout(LayoutKind.Auto)]
private record struct State(double LastValid);
private State _state, _p_state;
public override bool IsHot => _buffer.Count >= _bufferSize;
/// <summary>
/// Initializes a new Dwt indicator.
/// </summary>
/// <param name="levels">Decomposition levels 1-8. Level j captures structure at 2^j bars.
/// WarmupPeriod = 2^levels (e.g., levels=4 → 16 bars). Default 4.</param>
/// <param name="output">Output component: 0 = approximation (trend), 1..levels = detail at that level.
/// Default 0.</param>
public Dwt(int levels = 4, int output = 0)
{
if (levels < 1 || levels > 8)
{
throw new ArgumentException("Levels must be between 1 and 8", nameof(levels));
}
if (output < 0 || output > levels)
{
throw new ArgumentException("Output must be 0 (approximation) or 1..levels (detail)", nameof(output));
}
_levels = levels;
_output = output;
_bufferSize = 1 << levels; // 2^levels
_buffer = new RingBuffer(_bufferSize);
Name = $"Dwt({levels},{output})";
WarmupPeriod = _bufferSize;
_state = new State(0.0);
_p_state = _state;
}
/// <summary>
/// Initializes a new Dwt indicator with source for event-based chaining.
/// </summary>
/// <param name="source">Source indicator for chaining</param>
/// <param name="levels">Decomposition levels 1-8. Default 4.</param>
/// <param name="output">Output component: 0=approximation, 1..levels=detail. Default 0.</param>
public Dwt(ITValuePublisher source, int levels = 4, int output = 0)
: this(levels, output)
{
source.Pub += HandleUpdate;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void HandleUpdate(object? sender, in TValueEventArgs e) => Update(e.Value, e.IsNew);
/// <summary>
/// Performs the à trous Haar DWT cascade over the ring buffer.
/// Only the levels actually requested are computed; the rest short-circuit.
/// Returns the selected output component (approximation or detail at chosen level).
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private double ComputeDwt()
{
// c0 = newest sample in buffer (index Count-1 = oldest at 0, newest at bufferSize-1)
double c0 = _buffer[_buffer.Count - 1];
// Level 1: lag = 2^0 = 1
double prev1 = _buffer.Count >= 2 ? _buffer[_buffer.Count - 2] : c0;
double c1 = Math.FusedMultiplyAdd(c0 + prev1, 0.5, 0.0);
double d1 = c0 - c1;
if (_levels == 1)
{
return _output == 0 ? c1 : d1;
}
// Level 2: lag = 2^1 = 2 (in c1 history, equivalent to lag 2 in c1 series)
// In RingBuffer terms: we need c1 from 2 bars ago.
// To get c1[2], we recompute c1 at position (bufferSize-3..bufferSize-2).
// Rather than storing all level history, recompute cascade at required offsets.
double c1_lag2 = ComputeC1AtLag(2);
double c2 = Math.FusedMultiplyAdd(c1 + c1_lag2, 0.5, 0.0);
double d2 = c1 - c2;
if (_levels == 2)
{
return _output switch { 0 => c2, 1 => d1, 2 => d2, _ => d2 };
}
// Level 3: lag = 2^2 = 4
double c2_lag4 = ComputeC2AtLag(4);
double c3 = Math.FusedMultiplyAdd(c2 + c2_lag4, 0.5, 0.0);
double d3 = c2 - c3;
if (_levels == 3)
{
return _output switch { 0 => c3, 1 => d1, 2 => d2, 3 => d3, _ => d3 };
}
// Level 4: lag = 2^3 = 8
double c3_lag8 = ComputeC3AtLag(8);
double c4 = Math.FusedMultiplyAdd(c3 + c3_lag8, 0.5, 0.0);
double d4 = c3 - c4;
if (_levels == 4)
{
return _output switch { 0 => c4, 1 => d1, 2 => d2, 3 => d3, 4 => d4, _ => d4 };
}
// Level 5: lag = 2^4 = 16
double c4_lag16 = ComputeC4AtLag(16);
double c5 = Math.FusedMultiplyAdd(c4 + c4_lag16, 0.5, 0.0);
double d5 = c4 - c5;
if (_levels == 5)
{
return _output switch { 0 => c5, 1 => d1, 2 => d2, 3 => d3, 4 => d4, 5 => d5, _ => d5 };
}
// Level 6: lag = 2^5 = 32
double c5_lag32 = ComputeC5AtLag(32);
double c6 = Math.FusedMultiplyAdd(c5 + c5_lag32, 0.5, 0.0);
double d6 = c5 - c6;
if (_levels == 6)
{
return _output switch { 0 => c6, 1 => d1, 2 => d2, 3 => d3, 4 => d4, 5 => d5, 6 => d6, _ => d6 };
}
// Level 7: lag = 2^6 = 64
double c6_lag64 = ComputeC6AtLag(64);
double c7 = Math.FusedMultiplyAdd(c6 + c6_lag64, 0.5, 0.0);
double d7 = c6 - c7;
if (_levels == 7)
{
return _output switch { 0 => c7, 1 => d1, 2 => d2, 3 => d3, 4 => d4, 5 => d5, 6 => d6, 7 => d7, _ => d7 };
}
// Level 8: lag = 2^7 = 128
double c7_lag128 = ComputeC7AtLag(128);
double c8 = Math.FusedMultiplyAdd(c7 + c7_lag128, 0.5, 0.0);
double d8 = c7 - c8;
return _output switch { 0 => c8, 1 => d1, 2 => d2, 3 => d3, 4 => d4, 5 => d5, 6 => d6, 7 => d7, _ => d8 };
}
// Helpers: compute c1..c7 at a buffer offset (lag from newest).
// These are inlined by the JIT since they're small.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private double GetBuf(int lag)
{
int idx = _buffer.Count - 1 - lag;
return idx >= 0 ? _buffer[idx] : _buffer[0]; // boundary: use oldest
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private double ComputeC1At(int lag)
{
double a = GetBuf(lag);
double b = GetBuf(lag + 1);
return Math.FusedMultiplyAdd(a + b, 0.5, 0.0);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private double ComputeC1AtLag(int lag) => ComputeC1At(lag);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private double ComputeC2AtLag(int lag)
{
double a = ComputeC1At(lag);
double b = ComputeC1At(lag + 2);
return Math.FusedMultiplyAdd(a + b, 0.5, 0.0);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private double ComputeC3AtLag(int lag)
{
double a = ComputeC2AtLag(lag);
double b = ComputeC2AtLag(lag + 4);
return Math.FusedMultiplyAdd(a + b, 0.5, 0.0);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private double ComputeC4AtLag(int lag)
{
double a = ComputeC3AtLag(lag);
double b = ComputeC3AtLag(lag + 8);
return Math.FusedMultiplyAdd(a + b, 0.5, 0.0);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private double ComputeC5AtLag(int lag)
{
double a = ComputeC4AtLag(lag);
double b = ComputeC4AtLag(lag + 16);
return Math.FusedMultiplyAdd(a + b, 0.5, 0.0);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private double ComputeC6AtLag(int lag)
{
double a = ComputeC5AtLag(lag);
double b = ComputeC5AtLag(lag + 32);
return Math.FusedMultiplyAdd(a + b, 0.5, 0.0);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private double ComputeC7AtLag(int lag)
{
double a = ComputeC6AtLag(lag);
double b = ComputeC6AtLag(lag + 64);
return Math.FusedMultiplyAdd(a + b, 0.5, 0.0);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override TValue Update(TValue input, bool isNew = true)
{
if (isNew)
{
_p_state = _state;
}
else
{
_state = _p_state;
}
var s = _state;
double value = input.Value;
double result;
if (double.IsFinite(value))
{
_buffer.Add(value, isNew);
if (_buffer.Count >= _bufferSize)
{
result = ComputeDwt();
s = s with { LastValid = result };
}
else
{
result = s.LastValid;
}
}
else
{
result = s.LastValid;
}
_state = s;
Last = new TValue(input.Time, result);
PubEvent(Last, isNew);
return Last;
}
public override TSeries Update(TSeries source)
{
var result = new TSeries(source.Count);
ReadOnlySpan<double> values = source.Values;
ReadOnlySpan<long> times = source.Times;
for (int i = 0; i < source.Count; i++)
{
var tv = Update(new TValue(new DateTime(times[i], DateTimeKind.Utc), values[i]), true);
result.Add(tv, true);
}
return result;
}
public override void Prime(ReadOnlySpan<double> source, TimeSpan? step = null)
{
TimeSpan interval = step ?? TimeSpan.FromSeconds(1);
DateTime time = DateTime.UtcNow - (interval * source.Length);
for (int i = 0; i < source.Length; i++)
{
Update(new TValue(time, source[i]), true);
time += interval;
}
}
public static TSeries Batch(TSeries source, int levels = 4, int output = 0)
{
var indicator = new Dwt(levels, output);
return indicator.Update(source);
}
/// <summary>
/// Calculates DWT over a span of values using the à trous Haar cascade.
/// Uses stackalloc for small buffers (≤ 256 doubles), ArrayPool above that.
/// </summary>
public static void Batch(
ReadOnlySpan<double> source, Span<double> output,
int levels = 4, int outputComponent = 0)
{
if (source.Length == 0)
{
throw new ArgumentException("Source cannot be empty", nameof(source));
}
if (output.Length < source.Length)
{
throw new ArgumentException("Output length must be >= source length", nameof(output));
}
if (levels < 1 || levels > 8)
{
throw new ArgumentException("Levels must be between 1 and 8", nameof(levels));
}
if (outputComponent < 0 || outputComponent > levels)
{
throw new ArgumentException("Output must be 0 (approximation) or 1..levels (detail)", nameof(outputComponent));
}
int bufferSize = 1 << levels; // 2^levels
double lastValid = 0.0;
const int StackallocThreshold = 256;
double[]? rented = null;
scoped Span<double> buf;
if (bufferSize <= StackallocThreshold)
{
buf = stackalloc double[bufferSize];
}
else
{
rented = ArrayPool<double>.Shared.Rent(bufferSize);
buf = rented.AsSpan(0, bufferSize);
}
try
{
buf.Clear();
int head = 0;
int count = 0;
for (int i = 0; i < source.Length; i++)
{
double val = source[i];
if (!double.IsFinite(val))
{
output[i] = lastValid;
continue;
}
// Write into circular buffer
buf[head] = val;
head = (head + 1) % bufferSize;
if (count < bufferSize)
{
count++;
}
if (count < bufferSize)
{
output[i] = lastValid;
continue;
}
// Compute the full cascade from circular buffer.
// newest = head-1 (mod bufferSize), oldest = head (mod bufferSize)
double result = ComputeDwtFromSpan(buf, head, bufferSize, levels, outputComponent);
lastValid = result;
output[i] = result;
}
}
finally
{
if (rented != null)
{
ArrayPool<double>.Shared.Return(rented);
}
}
}
/// <summary>
/// Performs the à trous cascade over a span-based circular buffer.
/// head is one past the newest element (next write position).
/// Index mapping: newest = (head-1+cap)%cap, lag k → (head-1-k+cap)%cap.
/// </summary>
private static double ComputeDwtFromSpan(
Span<double> buf, int head, int cap, int levels, int outputComponent)
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static double Get(Span<double> b, int h, int c, int lag)
{
int idx = ((h - 1 - lag) % c + c) % c;
int maxLag = c - 1;
if (lag > maxLag) { idx = ((h - 1 - maxLag) % c + c) % c; }
return b[idx];
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static double C1(Span<double> b, int h, int c, int lag)
{
double a = Get(b, h, c, lag);
double bv = Get(b, h, c, lag + 1);
return Math.FusedMultiplyAdd(a + bv, 0.5, 0.0);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static double C2(Span<double> b, int h, int c, int lag)
{
double a = C1(b, h, c, lag);
double bv = C1(b, h, c, lag + 2);
return Math.FusedMultiplyAdd(a + bv, 0.5, 0.0);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static double C3(Span<double> b, int h, int c, int lag)
{
double a = C2(b, h, c, lag);
double bv = C2(b, h, c, lag + 4);
return Math.FusedMultiplyAdd(a + bv, 0.5, 0.0);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static double C4(Span<double> b, int h, int c, int lag)
{
double a = C3(b, h, c, lag);
double bv = C3(b, h, c, lag + 8);
return Math.FusedMultiplyAdd(a + bv, 0.5, 0.0);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static double C5(Span<double> b, int h, int c, int lag)
{
double a = C4(b, h, c, lag);
double bv = C4(b, h, c, lag + 16);
return Math.FusedMultiplyAdd(a + bv, 0.5, 0.0);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static double C6(Span<double> b, int h, int c, int lag)
{
double a = C5(b, h, c, lag);
double bv = C5(b, h, c, lag + 32);
return Math.FusedMultiplyAdd(a + bv, 0.5, 0.0);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static double C7(Span<double> b, int h, int c, int lag)
{
double a = C6(b, h, c, lag);
double bv = C6(b, h, c, lag + 64);
return Math.FusedMultiplyAdd(a + bv, 0.5, 0.0);
}
double c0 = Get(buf, head, cap, 0);
double c1v = C1(buf, head, cap, 0);
double d1 = c0 - c1v;
if (levels == 1) { return outputComponent == 0 ? c1v : d1; }
double c2v = C2(buf, head, cap, 0);
double d2 = c1v - c2v;
if (levels == 2) { return outputComponent switch { 0 => c2v, 1 => d1, _ => d2 }; }
double c3v = C3(buf, head, cap, 0);
double d3 = c2v - c3v;
if (levels == 3) { return outputComponent switch { 0 => c3v, 1 => d1, 2 => d2, _ => d3 }; }
double c4v = C4(buf, head, cap, 0);
double d4 = c3v - c4v;
if (levels == 4) { return outputComponent switch { 0 => c4v, 1 => d1, 2 => d2, 3 => d3, _ => d4 }; }
double c5v = C5(buf, head, cap, 0);
double d5 = c4v - c5v;
if (levels == 5) { return outputComponent switch { 0 => c5v, 1 => d1, 2 => d2, 3 => d3, 4 => d4, _ => d5 }; }
double c6v = C6(buf, head, cap, 0);
double d6 = c5v - c6v;
if (levels == 6) { return outputComponent switch { 0 => c6v, 1 => d1, 2 => d2, 3 => d3, 4 => d4, 5 => d5, _ => d6 }; }
double c7v = C7(buf, head, cap, 0);
double d7 = c6v - c7v;
if (levels == 7) { return outputComponent switch { 0 => c7v, 1 => d1, 2 => d2, 3 => d3, 4 => d4, 5 => d5, 6 => d6, _ => d7 }; }
double c7lag = C7(buf, head, cap, 128);
double c8v = Math.FusedMultiplyAdd(c7v + c7lag, 0.5, 0.0);
double d8 = c7v - c8v;
return outputComponent switch { 0 => c8v, 1 => d1, 2 => d2, 3 => d3, 4 => d4, 5 => d5, 6 => d6, 7 => d7, _ => d8 };
}
public static (TSeries Results, Dwt Indicator) Calculate(
TSeries source, int levels = 4, int output = 0)
{
var indicator = new Dwt(levels, output);
TSeries results = indicator.Update(source);
return (results, indicator);
}
public override void Reset()
{
_buffer.Clear();
_state = new State(0.0);
_p_state = _state;
Last = default;
}
}