docs: remove C# Implementation Considerations sections, clean up temp scripts, reorganize test files

- Remove 'C# Implementation Considerations' sections from 34 indicator .md files
- Delete 29 temp PowerShell scripts (_fix_mojibake.ps1, _hex_scan.ps1, etc.)
- Move test files into tests/ subdirectories for consistent project structure
- Add trader-focused bullet points to indicator documentation
This commit is contained in:
Miha Kralj
2026-03-12 12:34:16 -07:00
parent 8937b0c0fa
commit 060649192f
1149 changed files with 1780 additions and 3316 deletions
@@ -0,0 +1,157 @@
using TradingPlatform.BusinessLayer;
namespace QuanTAlib.Tests;
public class EriIndicatorTests
{
[Fact]
public void EriIndicator_Constructor_SetsDefaults()
{
var indicator = new EriIndicator();
Assert.Equal("ERI - Elder Ray Index", indicator.Name);
Assert.Equal(13, indicator.Period);
Assert.True(indicator.SeparateWindow);
Assert.True(indicator.OnBackGround);
Assert.Equal(13, indicator.MinHistoryDepths);
}
[Fact]
public void EriIndicator_ShortName_ReflectsPeriod()
{
var indicator = new EriIndicator { Period = 20 };
Assert.Equal("ERI(20)", indicator.ShortName);
}
[Fact]
public void EriIndicator_MinHistoryDepths_EqualsPeriod()
{
var indicator = new EriIndicator { Period = 26 };
Assert.Equal(26, indicator.MinHistoryDepths);
Assert.Equal(26, ((IWatchlistIndicator)indicator).MinHistoryDepths);
}
[Fact]
public void EriIndicator_Initialize_CreatesInternalEri()
{
var indicator = new EriIndicator();
// Initialize should not throw
indicator.Initialize();
// After init, two line series should exist (Bull Power + Bear Power)
Assert.Equal(2, indicator.LinesSeries.Count);
}
[Fact]
public void EriIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
{
var indicator = new EriIndicator();
indicator.Initialize();
var now = DateTime.UtcNow;
for (int i = 0; i < 30; i++)
{
indicator.HistoricalData.AddBar(now.AddMinutes(i), 100 + i, 110 + i, 90 + i, 105 + i, 1000 + (i * 100));
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
}
double bullVal = indicator.LinesSeries[0].GetValue(0);
double bearVal = indicator.LinesSeries[1].GetValue(0);
Assert.True(double.IsFinite(bullVal));
Assert.True(double.IsFinite(bearVal));
}
[Fact]
public void EriIndicator_ProcessUpdate_NewBar_ComputesValue()
{
var indicator = new EriIndicator();
indicator.Initialize();
var now = DateTime.UtcNow;
for (int i = 0; i < 30; i++)
{
indicator.HistoricalData.AddBar(now.AddMinutes(i), 100 + i, 110 + i, 90 + i, 105 + i, 1000 + (i * 100));
}
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
// Add new bar
indicator.HistoricalData.AddBar(now.AddMinutes(30), 130, 140, 120, 135, 1500);
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.NewBar));
Assert.Equal(2, indicator.LinesSeries[0].Count);
}
[Fact]
public void EriIndicator_Value_IsFinite()
{
var indicator = new EriIndicator();
indicator.Initialize();
var now = DateTime.UtcNow;
for (int i = 0; i < 50; i++)
{
double open = 100 + i;
double high = open + 10 + (i % 5);
double low = open - 5;
double close = (i % 2 == 0) ? high - 1 : low + 1;
double volume = 1000 + (i * 100);
indicator.HistoricalData.AddBar(now.AddMinutes(i), open, high, low, close, volume);
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
}
double bullVal = indicator.LinesSeries[0].GetValue(0);
double bearVal = indicator.LinesSeries[1].GetValue(0);
Assert.True(double.IsFinite(bullVal), $"Bull Power value {bullVal} should be finite");
Assert.True(double.IsFinite(bearVal), $"Bear Power value {bearVal} should be finite");
}
[Fact]
public void EriIndicator_BullPowerPositive_OnHighAboveEma()
{
var indicator = new EriIndicator { Period = 3 };
indicator.Initialize();
var now = DateTime.UtcNow;
// Feed bars with high consistently above close (and thus above EMA)
for (int i = 0; i < 20; i++)
{
double close = 100 + (i * 2);
double high = close + 15; // High well above close
double low = close - 5;
indicator.HistoricalData.AddBar(now.AddMinutes(i), close, high, low, close, 1000);
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
}
double bullVal = indicator.LinesSeries[0].GetValue(0);
Assert.True(bullVal > 0, $"Bull Power should be positive when High > EMA, got {bullVal}");
}
[Fact]
public void EriIndicator_BearPowerNegative_OnLowBelowEma()
{
var indicator = new EriIndicator { Period = 3 };
indicator.Initialize();
var now = DateTime.UtcNow;
// Feed bars with low consistently below close (and thus below EMA)
for (int i = 0; i < 20; i++)
{
double close = 100 + (i * 2);
double high = close + 5;
double low = close - 15; // Low well below close
indicator.HistoricalData.AddBar(now.AddMinutes(i), close, high, low, close, 1000);
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
}
double bearVal = indicator.LinesSeries[1].GetValue(0);
Assert.True(bearVal < 0, $"Bear Power should be negative when Low < EMA, got {bearVal}");
}
}
+563
View File
@@ -0,0 +1,563 @@
namespace QuanTAlib.Tests;
public class EriTests
{
// ── A) Constructor validation ──────────────────────────────────────
[Fact]
public void Eri_Constructor_DefaultPeriod_Is13()
{
var eri = new Eri();
Assert.Equal("Eri(13)", eri.Name);
Assert.Equal(13, eri.WarmupPeriod);
}
[Fact]
public void Eri_Constructor_CustomPeriod_SetsCorrectly()
{
var eri = new Eri(20);
Assert.Equal("Eri(20)", eri.Name);
Assert.Equal(20, eri.WarmupPeriod);
}
[Fact]
public void Eri_Constructor_InvalidPeriod_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentException>(() => new Eri(0));
Assert.Equal("period", ex.ParamName);
ex = Assert.Throws<ArgumentException>(() => new Eri(-1));
Assert.Equal("period", ex.ParamName);
}
[Fact]
public void Eri_Constructor_Period1_IsValid()
{
var eri = new Eri(1);
Assert.Equal("Eri(1)", eri.Name);
}
// ── B) Basic calculation ───────────────────────────────────────────
[Fact]
public void Eri_BasicCalculation_FirstBar_BullPowerIsHighMinusClose()
{
var eri = new Eri(3);
var time = DateTime.UtcNow;
// First bar: EMA = close = 100, Bull Power = high - EMA = 110 - 100 = 10
var bar = new TBar(time, 100.0, 110.0, 90.0, 100.0, 1000.0);
var val = eri.Update(bar);
Assert.Equal(10.0, val.Value, 10);
}
[Fact]
public void Eri_BasicCalculation_FirstBar_BearPowerIsLowMinusClose()
{
var eri = new Eri(3);
var time = DateTime.UtcNow;
// First bar: EMA = close = 100, Bear Power = low - EMA = 90 - 100 = -10
var bar = new TBar(time, 100.0, 110.0, 90.0, 100.0, 1000.0);
_ = eri.Update(bar);
Assert.Equal(-10.0, eri.BearPower, 10);
}
[Fact]
public void Eri_BasicCalculation_BullPowerPositive_InUptrend()
{
var eri = new Eri(3);
var time = DateTime.UtcNow;
// Feed rising prices — High should consistently be above EMA
for (int i = 0; i < 30; i++)
{
double close = 100.0 + (i * 2);
double high = close + 10;
double low = close - 5;
var bar = new TBar(time.AddMinutes(i), close, high, low, close, 1000.0);
eri.Update(bar);
}
// Bull power should be positive (High > EMA in uptrend)
Assert.True(eri.Last.Value > 0, $"Bull Power should be positive in uptrend, got {eri.Last.Value}");
}
[Fact]
public void Eri_BasicCalculation_BearPowerNegative_InDowntrend()
{
var eri = new Eri(3);
var time = DateTime.UtcNow;
// Feed declining prices — Low should consistently be below EMA
for (int i = 0; i < 30; i++)
{
double close = 200.0 - (i * 2);
double high = close + 5;
double low = close - 10;
var bar = new TBar(time.AddMinutes(i), close, high, low, close, 1000.0);
eri.Update(bar);
}
// Bear power should be negative (Low < EMA in downtrend)
Assert.True(eri.BearPower < 0, $"Bear Power should be negative in downtrend, got {eri.BearPower}");
}
[Fact]
public void Eri_BasicCalculation_AccessLast_Name_IsHot()
{
var eri = new Eri(3);
var time = DateTime.UtcNow;
var bar = new TBar(time, 100.0, 110.0, 90.0, 105.0, 1000.0);
var val = eri.Update(bar);
Assert.Equal(val.Value, eri.Last.Value);
Assert.Equal("Eri(3)", eri.Name);
Assert.False(eri.IsHot); // Only 1 bar, not yet warmed up for period=3
}
// ── C) State + bar correction ──────────────────────────────────────
[Fact]
public void Eri_IsNew_True_AdvancesState()
{
var eri = new Eri(3);
var time = DateTime.UtcNow;
var bar1 = new TBar(time, 100.0, 110.0, 90.0, 100.0, 1000.0);
var bar2 = new TBar(time.AddMinutes(1), 105.0, 115.0, 95.0, 110.0, 1000.0);
var val1 = eri.Update(bar1, isNew: true);
var val2 = eri.Update(bar2, isNew: true);
// Two distinct updates with different H/L/C should give different values
Assert.NotEqual(val1.Value, val2.Value);
}
[Fact]
public void Eri_IsNew_False_RollsBackState()
{
var eri = new Eri(3);
var time = DateTime.UtcNow;
var bar1 = new TBar(time, 100.0, 110.0, 90.0, 100.0, 1000.0);
_ = eri.Update(bar1, isNew: true);
var bar2 = new TBar(time.AddMinutes(1), 105.0, 115.0, 95.0, 110.0, 1000.0);
var val2 = eri.Update(bar2, isNew: true);
// Correction: isNew=false rolls back to state after bar 1
// Use significantly different close to shift EMA and produce divergent bull power
var bar2Corrected = new TBar(time.AddMinutes(1), 108.0, 150.0, 92.0, 140.0, 1000.0);
var val2Corrected = eri.Update(bar2Corrected, isNew: false);
// Different input => different result
Assert.NotEqual(val2.Value, val2Corrected.Value);
}
[Fact]
public void Eri_IterativeCorrections_RestoreState()
{
var eri = new Eri(5);
var time = DateTime.UtcNow;
// Build up state
var bar1 = new TBar(time, 100.0, 110.0, 90.0, 100.0, 1000.0);
_ = eri.Update(bar1, isNew: true);
var bar2 = new TBar(time.AddMinutes(1), 105.0, 115.0, 95.0, 110.0, 1000.0);
_ = eri.Update(bar2, isNew: true);
// Multiple corrections to bar 3
_ = eri.Update(new TBar(time.AddMinutes(2), 108.0, 118.0, 98.0, 105.0, 1000.0), isNew: true);
_ = eri.Update(new TBar(time.AddMinutes(2), 112.0, 122.0, 102.0, 112.0, 1000.0), isNew: false);
_ = eri.Update(new TBar(time.AddMinutes(2), 115.0, 125.0, 105.0, 118.0, 1000.0), isNew: false);
var finalBar = new TBar(time.AddMinutes(2), 120.0, 130.0, 110.0, 120.0, 1000.0);
var finalVal = eri.Update(finalBar, isNew: false);
// Should match a fresh computation with the final corrected value
var eri2 = new Eri(5);
_ = eri2.Update(bar1, isNew: true);
_ = eri2.Update(bar2, isNew: true);
var expected = eri2.Update(finalBar, isNew: true);
Assert.Equal(expected.Value, finalVal.Value, 10);
}
[Fact]
public void Eri_Reset_ClearsState()
{
var eri = new Eri(3);
var time = DateTime.UtcNow;
eri.Update(new TBar(time, 100.0, 110.0, 90.0, 105.0, 1000.0));
eri.Update(new TBar(time.AddMinutes(1), 110.0, 120.0, 100.0, 115.0, 1000.0));
Assert.NotEqual(0, eri.Last.Value);
eri.Reset();
Assert.False(eri.IsHot);
Assert.Equal(0, eri.Last.Value);
}
// ── D) Warmup/convergence ──────────────────────────────────────────
[Fact]
public void Eri_IsHot_FlipsWhenWarmupComplete()
{
var eri = new Eri(3);
var time = DateTime.UtcNow;
Assert.False(eri.IsHot);
// Feed enough data — warmup ends after WarmupPeriod bars
for (int i = 0; i < 50; i++)
{
double close = 100.0 + i;
eri.Update(new TBar(time.AddMinutes(i), close, close + 10, close - 5, close, 1000.0));
}
Assert.True(eri.IsHot);
}
[Fact]
public void Eri_WarmupPeriod_EqualsPeriod()
{
var eri = new Eri(7);
Assert.Equal(7, eri.WarmupPeriod);
}
[Fact]
public void Eri_ConvergesAfterManyBars_GBM()
{
var eri = new Eri(13);
var gbm = new GBM();
for (int i = 0; i < 200; i++)
{
var bar = gbm.Next(isNew: true);
eri.Update(bar);
}
Assert.True(eri.IsHot);
Assert.True(double.IsFinite(eri.Last.Value));
Assert.True(double.IsFinite(eri.BearPower));
}
// ── E) Robustness ──────────────────────────────────────────────────
[Fact]
public void Eri_NaN_Input_UsesLastValid()
{
var eri = new Eri(3);
var time = DateTime.UtcNow;
eri.Update(new TBar(time, 100.0, 110.0, 90.0, 100.0, 1000.0));
eri.Update(new TBar(time.AddMinutes(1), 105.0, 115.0, 95.0, 110.0, 1000.0));
// NaN close should use last valid value
var val = eri.Update(new TBar(time.AddMinutes(2), 108.0, double.NaN, 98.0, double.NaN, 1000.0));
Assert.True(double.IsFinite(val.Value));
Assert.True(double.IsFinite(eri.BearPower));
}
[Fact]
public void Eri_Infinity_Input_UsesLastValid()
{
var eri = new Eri(3);
var time = DateTime.UtcNow;
eri.Update(new TBar(time, 100.0, 110.0, 90.0, 100.0, 1000.0));
var val = eri.Update(new TBar(time.AddMinutes(1), 105.0, double.PositiveInfinity, 95.0, double.PositiveInfinity, 1000.0));
Assert.True(double.IsFinite(val.Value));
val = eri.Update(new TBar(time.AddMinutes(2), 108.0, 118.0, double.NegativeInfinity, double.NegativeInfinity, 1000.0));
Assert.True(double.IsFinite(val.Value));
Assert.True(double.IsFinite(eri.BearPower));
}
[Fact]
public void Eri_BatchNaN_Safe_GBM()
{
var eri = new Eri(5);
var gbm = new GBM();
for (int i = 0; i < 50; i++)
{
var bar = gbm.Next(isNew: true);
double close = (i % 7 == 3) ? double.NaN : bar.Close;
double high = (i % 11 == 5) ? double.NaN : bar.High;
double low = bar.Low;
eri.Update(new TBar(bar.Time, bar.Open, high, low, close, bar.Volume));
}
Assert.True(double.IsFinite(eri.Last.Value));
Assert.True(double.IsFinite(eri.BearPower));
}
// ── F) Consistency ─────────────────────────────────────────────────
[Fact]
public void Eri_Streaming_Matches_Batch()
{
int period = 5;
int count = 50;
var time = DateTime.UtcNow;
var source = new TSeries();
for (int i = 0; i < count; i++)
{
source.Add(new TValue(time.AddMinutes(i), 100.0 * Math.Sin(i * 0.2)));
}
// Streaming
var eri = new Eri(period);
var streamResults = new double[count];
for (int i = 0; i < count; i++)
{
var val = eri.Update(source[i], isNew: true);
streamResults[i] = val.Value;
}
// Batch
var batchSeries = Eri.Batch(source, period);
for (int i = 0; i < count; i++)
{
Assert.Equal(batchSeries[i].Value, streamResults[i], 10);
}
}
[Fact]
public void Eri_Streaming_Matches_SpanCalculate()
{
int period = 5;
int count = 50;
var time = DateTime.UtcNow;
var source = new TSeries();
for (int i = 0; i < count; i++)
{
source.Add(new TValue(time.AddMinutes(i), 100.0 * Math.Sin(i * 0.2)));
}
// Streaming
var eri = new Eri(period);
var streamResults = new double[count];
for (int i = 0; i < count; i++)
{
var val = eri.Update(source[i], isNew: true);
streamResults[i] = val.Value;
}
// Span calculate
var spanOutput = new double[count];
Eri.Calculate(source.Values, spanOutput, period);
for (int i = 0; i < count; i++)
{
Assert.Equal(spanOutput[i], streamResults[i], 10);
}
}
[Fact]
public void Eri_Eventing_Matches_Streaming()
{
int period = 5;
int count = 50;
var time = DateTime.UtcNow;
var source = new TSeries();
for (int i = 0; i < count; i++)
{
source.Add(new TValue(time.AddMinutes(i), 100.0 * Math.Sin(i * 0.2)));
}
// Streaming
var eri1 = new Eri(period);
var streamResults = new double[count];
for (int i = 0; i < count; i++)
{
var val = eri1.Update(source[i], isNew: true);
streamResults[i] = val.Value;
}
// Eventing via Update(TSeries) which resets and streams
var eri2 = new Eri(period);
var eventResults = eri2.Update(source);
for (int i = 0; i < count; i++)
{
Assert.Equal(eventResults[i].Value, streamResults[i], 10);
}
}
// ── G) Span API tests ──────────────────────────────────────────────
[Fact]
public void Eri_Calculate_MismatchedLengths_ThrowsArgumentException()
{
var src = new double[10];
var output = new double[5];
var ex = Assert.Throws<ArgumentException>(() => Eri.Calculate(src, output));
Assert.Equal("output", ex.ParamName);
}
[Fact]
public void Eri_Calculate_InvalidPeriod_ThrowsArgumentException()
{
var src = new double[10];
var output = new double[10];
var ex = Assert.Throws<ArgumentException>(() => Eri.Calculate(src, output, 0));
Assert.Equal("period", ex.ParamName);
}
[Fact]
public void Eri_Calculate_EmptyInput_NoOp()
{
ReadOnlySpan<double> src = [];
Span<double> output = [];
Eri.Calculate(src, output); // Should not throw
Assert.True(true); // S2699: assertion confirms no-exception completion
}
[Fact]
public void Eri_Calculate_NaN_HandledGracefully()
{
var src = new double[] { 100, double.NaN, 200, 300, double.NaN, 400 };
var output = new double[6];
Eri.Calculate(src, output, 3);
for (int i = 0; i < output.Length; i++)
{
Assert.True(double.IsFinite(output[i]), $"output[{i}] = {output[i]} should be finite");
}
}
[Fact]
public void Eri_Calculate_LargeData_NoStackOverflow()
{
int size = 10_000;
var src = new double[size];
var output = new double[size];
for (int i = 0; i < size; i++)
{
src[i] = Math.Sin(i * 0.1) * 100;
}
Eri.Calculate(src, output, 13);
Assert.True(double.IsFinite(output[size - 1]));
}
// ── H) Chainability ────────────────────────────────────────────────
[Fact]
public void Eri_PubEvent_FiresOnUpdate()
{
var eri = new Eri();
bool eventFired = false;
eri.Pub += (object? sender, in TValueEventArgs args) => eventFired = true;
eri.Update(new TBar(DateTime.UtcNow, 100.0, 110.0, 90.0, 105.0, 1000.0));
Assert.True(eventFired);
}
[Fact]
public void Eri_Chaining_EventBased()
{
var eri1 = new Eri(3);
var eri2 = new Eri(eri1, 5);
var time = DateTime.UtcNow;
for (int i = 0; i < 30; i++)
{
double close = 100.0 + (10.0 * Math.Sin(i * 0.3));
eri1.Update(new TBar(time.AddMinutes(i), close, close + 5, close - 5, close, 1000.0));
}
// eri2 should have received updates from eri1's Pub events
Assert.True(double.IsFinite(eri2.Last.Value));
}
[Fact]
public void Eri_Calculate_StaticFactory_ReturnsResultsAndIndicator()
{
var time = DateTime.UtcNow;
var source = new TSeries();
for (int i = 0; i < 100; i++)
{
source.Add(new TValue(time.AddMinutes(i), 100.0 + i));
}
var (results, indicator) = Eri.Calculate(source, 5);
Assert.Equal(100, results.Count);
Assert.True(indicator.IsHot);
}
[Fact]
public void Eri_Prime_InitializesState()
{
var eri = new Eri(5);
var source = new double[30];
for (int i = 0; i < 30; i++)
{
source[i] = 100.0 + i;
}
eri.Prime(source);
Assert.True(double.IsFinite(eri.Last.Value));
}
[Fact]
public void Eri_ConstantInput_BullBearPowerConverge()
{
var eri = new Eri(5);
var time = DateTime.UtcNow;
// When H=L=C=constant, EMA converges to constant, so Bull=Bear=0
for (int i = 0; i < 200; i++)
{
eri.Update(new TBar(time.AddMinutes(i), 42.0, 42.0, 42.0, 42.0, 1000.0));
}
Assert.Equal(0.0, eri.Last.Value, 6); // Bull Power = H - EMA = 0
Assert.Equal(0.0, eri.BearPower, 6); // Bear Power = L - EMA = 0
}
[Fact]
public void Eri_BearPower_IsAccessible()
{
var eri = new Eri(3);
var time = DateTime.UtcNow;
// High=110, Low=90, Close=100 → first bar EMA=100, Bull=10, Bear=-10
eri.Update(new TBar(time, 100.0, 110.0, 90.0, 100.0, 1000.0));
Assert.Equal(10.0, eri.Last.Value, 10); // Bull Power
Assert.Equal(-10.0, eri.BearPower, 10); // Bear Power
}
[Fact]
public void Eri_TBar_GBM_StreamingProducesFiniteResults()
{
var eri = new Eri(13);
var gbm = new GBM();
for (int i = 0; i < 100; i++)
{
var bar = gbm.Next(isNew: true);
eri.Update(bar);
}
Assert.True(double.IsFinite(eri.Last.Value), "Bull Power should be finite");
Assert.True(double.IsFinite(eri.BearPower), "Bear Power should be finite");
Assert.True(eri.IsHot, "Should be hot after 100 bars with period=13");
}
}
@@ -0,0 +1,508 @@
using System.Runtime.CompilerServices;
using Skender.Stock.Indicators;
using Xunit.Abstractions;
namespace QuanTAlib.Tests;
/// <summary>
/// Validation tests for ERI (Elder Ray Index).
/// ERI = Bull Power (High EMA) + Bear Power (Low EMA).
/// Skender.Stock.Indicators has GetElderRay() returning BullPower and BearPower.
///
/// NOTE: QuanTAlib uses an exponential warmup compensator (§2 pattern) for the
/// internal EMA; Skender uses a standard EMA seed. With 5000 bars of data and
/// comparisons limited to the final 100 converged bars, both implementations
/// agree within 1e-7.
/// </summary>
public sealed class EriValidationTests : IDisposable
{
private readonly ValidationTestData _data;
private readonly ITestOutputHelper _output;
private bool _disposed;
private const int DefaultPeriod = 13;
private const double Tolerance = ValidationHelper.SkenderTolerance;
public EriValidationTests(ITestOutputHelper output)
{
_output = output;
_data = new ValidationTestData();
}
public void Dispose()
{
Dispose(true);
}
private void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
_disposed = true;
if (disposing)
{
_data?.Dispose();
}
}
// ── A) Skender cross-validation: Batch ──────────────────────────────
[Fact]
public void Validate_Skender_BullPower_Batch()
{
int[] periods = { 13, 20 };
foreach (int period in periods)
{
int n = _data.Bars.Count;
var eri = new Eri(period);
var bullValues = new double[n];
for (int i = 0; i < n; i++)
{
bullValues[i] = eri.Update(_data.Bars[i], isNew: true).Value;
}
var sResults = _data.SkenderQuotes.GetElderRay(period).ToList();
int skip = ValidationHelper.DefaultVerificationCount;
int count = Math.Min(n, sResults.Count);
int start = count - skip;
int mismatches = 0;
for (int i = start; i < count; i++)
{
double qVal = bullValues[i];
double? sVal = sResults[i].BullPower;
if (!sVal.HasValue)
{
continue;
}
double diff = Math.Abs(qVal - sVal.Value);
if (diff > Tolerance)
{
mismatches++;
_output.WriteLine($"BullPower mismatch [period={period}, i={i}]: QL={qVal:F10}, Skender={sVal.Value:F10}, diff={diff:E3}");
}
}
Assert.Equal(0, mismatches);
}
_output.WriteLine($"Skender BullPower Batch validated for periods {string.Join(",", periods)}");
}
[Fact]
public void Validate_Skender_BearPower_Batch()
{
int[] periods = { 13, 20 };
foreach (int period in periods)
{
var eri = new Eri(period);
int n = _data.Bars.Count;
// Collect BearPower values using streaming to get all bar results
var bearValues = new double[n];
eri.Reset();
for (int i = 0; i < n; i++)
{
eri.Update(_data.Bars[i], isNew: true);
bearValues[i] = eri.BearPower;
}
var sResults = _data.SkenderQuotes.GetElderRay(period).ToList();
int skip = ValidationHelper.DefaultVerificationCount;
int count = Math.Min(n, sResults.Count);
int start = count - skip;
int mismatches = 0;
for (int i = start; i < count; i++)
{
double qVal = bearValues[i];
double? sVal = sResults[i].BearPower;
if (!sVal.HasValue)
{
continue;
}
double diff = Math.Abs(qVal - sVal.Value);
if (diff > Tolerance)
{
mismatches++;
_output.WriteLine($"BearPower mismatch [period={period}, i={i}]: QL={qVal:F10}, Skender={sVal.Value:F10}, diff={diff:E3}");
}
}
Assert.Equal(0, mismatches);
}
_output.WriteLine($"Skender BearPower Batch validated for periods {string.Join(",", periods)}");
}
// ── B) Skender cross-validation: Streaming ──────────────────────────
[Fact]
public void Validate_Skender_BullPower_Streaming()
{
int period = DefaultPeriod;
var eri = new Eri(period);
int n = _data.Bars.Count;
var streamBull = new double[n];
for (int i = 0; i < n; i++)
{
streamBull[i] = eri.Update(_data.Bars[i], isNew: true).Value;
}
var sResults = _data.SkenderQuotes.GetElderRay(period).ToList();
int skip = ValidationHelper.DefaultVerificationCount;
int count = Math.Min(n, sResults.Count);
int start = count - skip;
int mismatches = 0;
for (int i = start; i < count; i++)
{
double? sVal = sResults[i].BullPower;
if (!sVal.HasValue)
{
continue;
}
double diff = Math.Abs(streamBull[i] - sVal.Value);
if (diff > Tolerance)
{
mismatches++;
_output.WriteLine($"Streaming BullPower [i={i}]: QL={streamBull[i]:F10}, Skender={sVal.Value:F10}, diff={diff:E3}");
}
}
Assert.Equal(0, mismatches);
_output.WriteLine($"Skender BullPower Streaming validated (last {skip} bars)");
}
[Fact]
public void Validate_Skender_BearPower_Streaming()
{
int period = DefaultPeriod;
var eri = new Eri(period);
int n = _data.Bars.Count;
var streamBear = new double[n];
for (int i = 0; i < n; i++)
{
eri.Update(_data.Bars[i], isNew: true);
streamBear[i] = eri.BearPower;
}
var sResults = _data.SkenderQuotes.GetElderRay(period).ToList();
int skip = ValidationHelper.DefaultVerificationCount;
int count = Math.Min(n, sResults.Count);
int start = count - skip;
int mismatches = 0;
for (int i = start; i < count; i++)
{
double? sVal = sResults[i].BearPower;
if (!sVal.HasValue)
{
continue;
}
double diff = Math.Abs(streamBear[i] - sVal.Value);
if (diff > Tolerance)
{
mismatches++;
_output.WriteLine($"Streaming BearPower [i={i}]: QL={streamBear[i]:F10}, Skender={sVal.Value:F10}, diff={diff:E3}");
}
}
Assert.Equal(0, mismatches);
_output.WriteLine($"Skender BearPower Streaming validated (last {skip} bars)");
}
// ── C) Self-consistency: Streaming == Batch ─────────────────────────
[Fact]
[SkipLocalsInit]
public void Validate_Streaming_Equals_Batch_BullPower()
{
const int N = 300;
const int period = 13;
var gbm = new GBM(100.0, 0.05, 0.2, seed: 4001);
var bars = new TBar[N];
for (int i = 0; i < N; i++)
{
bars[i] = gbm.Next(isNew: true);
}
// Streaming
var eri = new Eri(period);
double streamBull = 0;
double streamBear = 0;
for (int i = 0; i < N; i++)
{
streamBull = eri.Update(bars[i], isNew: true).Value;
streamBear = eri.BearPower;
}
// Second independent streaming run — determinism check
var eri2 = new Eri(period);
double batchBull = 0;
double batchBear = 0;
for (int i = 0; i < N; i++)
{
batchBull = eri2.Update(bars[i], isNew: true).Value;
batchBear = eri2.BearPower;
}
_output.WriteLine($"Run1 BullPower={streamBull:F10}, Run2 BullPower={batchBull:F10}");
_output.WriteLine($"Run1 BearPower={streamBear:F10}, Run2 BearPower={batchBear:F10}");
Assert.Equal(streamBull, batchBull, 1e-14);
Assert.Equal(streamBear, batchBear, 1e-14);
}
// ── D) Self-consistency: Different periods produce different results ──
[Fact]
public void Validate_DifferentPeriods_ProduceDifferentResults()
{
const int N = 200;
int[] periods = { 5, 13, 21 };
var gbm = new GBM(100.0, 0.05, 0.2, seed: 4002);
var bars = new TBar[N];
for (int i = 0; i < N; i++)
{
bars[i] = gbm.Next(isNew: true);
}
var bullValues = new double[periods.Length];
var bearValues = new double[periods.Length];
for (int p = 0; p < periods.Length; p++)
{
var eri = new Eri(periods[p]);
for (int i = 0; i < N; i++)
{
eri.Update(bars[i], isNew: true);
}
bullValues[p] = eri.Last.Value;
bearValues[p] = eri.BearPower;
}
// Shorter periods should produce different values than longer periods
Assert.NotEqual(bullValues[0], bullValues[1]);
Assert.NotEqual(bullValues[1], bullValues[2]);
Assert.NotEqual(bearValues[0], bearValues[1]);
_output.WriteLine($"Bull: period5={bullValues[0]:F8}, period13={bullValues[1]:F8}, period21={bullValues[2]:F8}");
_output.WriteLine($"Bear: period5={bearValues[0]:F8}, period13={bearValues[1]:F8}, period21={bearValues[2]:F8}");
}
// ── E) Mathematical identity: constant prices → Bull=0, Bear=0 ──────
[Fact]
public void Validate_ConstantHighLow_BullBearPowerZero()
{
// When High = Low = Close = constant, EMA converges to that constant,
// so BullPower = High - EMA → 0, BearPower = Low - EMA → 0.
const int N = 500;
const double price = 100.0;
const int period = 13;
var eri = new Eri(period);
var time = DateTime.UtcNow;
for (int i = 0; i < N; i++)
{
eri.Update(new TBar(time.AddMinutes(i), price, price, price, price, 1000.0), isNew: true);
}
_output.WriteLine($"Constant price BullPower={eri.Last.Value:E6}, BearPower={eri.BearPower:E6}");
// After 500 bars the warmup compensator is fully converged
Assert.Equal(0.0, eri.Last.Value, 1e-6);
Assert.Equal(0.0, eri.BearPower, 1e-6);
}
// ── F) Mathematical identity: Bull > 0 in strong uptrend ────────────
[Fact]
public void Validate_Uptrend_BullPowerPositive()
{
const int N = 200;
const int period = 13;
var eri = new Eri(period);
var time = DateTime.UtcNow;
for (int i = 0; i < N; i++)
{
double close = 100.0 + (i * 0.5);
double high = close + 5.0;
double low = close - 2.0;
eri.Update(new TBar(time.AddMinutes(i), close, high, low, close, 1000.0), isNew: true);
}
// In a sustained uptrend, High should consistently exceed EMA → BullPower > 0
Assert.True(eri.Last.Value > 0, $"Expected BullPower > 0 in uptrend, got {eri.Last.Value}");
_output.WriteLine($"Uptrend BullPower={eri.Last.Value:F6}");
}
// ── G) Mathematical identity: Bear < 0 in strong downtrend ──────────
[Fact]
public void Validate_Downtrend_BearPowerNegative()
{
const int N = 200;
const int period = 13;
var eri = new Eri(period);
var time = DateTime.UtcNow;
for (int i = 0; i < N; i++)
{
double close = 500.0 - (i * 0.5);
double high = close + 2.0;
double low = close - 5.0;
eri.Update(new TBar(time.AddMinutes(i), close, high, low, close, 1000.0), isNew: true);
}
// In a sustained downtrend, Low should consistently be below EMA → BearPower < 0
Assert.True(eri.BearPower < 0, $"Expected BearPower < 0 in downtrend, got {eri.BearPower}");
_output.WriteLine($"Downtrend BearPower={eri.BearPower:F6}");
}
// ── H) Determinism: same seed → same result ─────────────────────────
[Fact]
public void Validate_Deterministic_SameSeed_SameResult()
{
const int N = 150;
const int period = 13;
static (double bull, double bear) Run(int seed)
{
var gbm = new GBM(100.0, 0.05, 0.2, seed: seed);
var eri = new Eri(period);
for (int i = 0; i < N; i++)
{
eri.Update(gbm.Next(isNew: true), isNew: true);
}
return (eri.Last.Value, eri.BearPower);
}
var (bull1, bear1) = Run(5555);
var (bull2, bear2) = Run(5555);
Assert.Equal(bull1, bull2, 1e-14);
Assert.Equal(bear1, bear2, 1e-14);
_output.WriteLine($"Deterministic BullPower={bull1:F10}, BearPower={bear1:F10}");
}
// ── I) Sign symmetry: Bull + Bear = High + Low 2×EMA ──────────────
[Fact]
public void Validate_BullPlusBear_Equals_HighPlusLowMinusTwoEma()
{
// BullPower = High - EMA, BearPower = Low - EMA
// Therefore BullPower + BearPower = High + Low - 2*EMA
// We cannot directly observe EMA, but we CAN validate via Skender's Ema field.
const int period = DefaultPeriod;
int n = _data.Bars.Count;
var eri = new Eri(period);
var bullSeries = new double[n];
var bearSeries = new double[n];
for (int i = 0; i < n; i++)
{
bullSeries[i] = eri.Update(_data.Bars[i], isNew: true).Value;
bearSeries[i] = eri.BearPower;
}
var sResults = _data.SkenderQuotes.GetElderRay(period).ToList();
int skip = ValidationHelper.DefaultVerificationCount;
int count = Math.Min(n, sResults.Count);
int start = count - skip;
int mismatches = 0;
for (int i = start; i < count; i++)
{
double? sEma = sResults[i].Ema;
if (!sEma.HasValue)
{
continue;
}
double high = _data.HighPrices.Span[i];
double low = _data.LowPrices.Span[i];
double expected = high + low - (2.0 * sEma.Value);
double actual = bullSeries[i] + bearSeries[i];
double diff = Math.Abs(actual - expected);
if (diff > Tolerance)
{
mismatches++;
_output.WriteLine($"Sum mismatch [i={i}]: actual={actual:F10}, expected={expected:F10}, diff={diff:E3}");
}
}
Assert.Equal(0, mismatches);
_output.WriteLine($"Bull+Bear = High+Low-2*EMA identity validated for last {skip} bars");
}
// ── J) Output finiteness after warmup ───────────────────────────────
[Fact]
public void Validate_AllOutputsFinite_AfterWarmup()
{
const int period = DefaultPeriod;
int n = _data.Bars.Count;
int warmup = period;
var eri = new Eri(period);
int nonFiniteCount = 0;
for (int i = 0; i < n; i++)
{
eri.Update(_data.Bars[i], isNew: true);
if (i >= warmup)
{
if (!double.IsFinite(eri.Last.Value))
{
nonFiniteCount++;
_output.WriteLine($"Non-finite BullPower at i={i}: {eri.Last.Value}");
}
if (!double.IsFinite(eri.BearPower))
{
nonFiniteCount++;
_output.WriteLine($"Non-finite BearPower at i={i}: {eri.BearPower}");
}
}
}
Assert.Equal(0, nonFiniteCount);
_output.WriteLine($"All {n - warmup} post-warmup bars have finite BullPower and BearPower");
}
}