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,207 @@
using TradingPlatform.BusinessLayer;
namespace QuanTAlib.Tests;
public class RemaIndicatorTests
{
[Fact]
public void RemaIndicator_Constructor_SetsDefaults()
{
var indicator = new RemaIndicator();
Assert.Equal(10, indicator.Period);
Assert.Equal(0.5, indicator.Lambda);
Assert.Equal(SourceType.Close, indicator.Source);
Assert.True(indicator.ShowColdValues);
Assert.Equal("REMA - Regularized Exponential Moving Average", indicator.Name);
Assert.False(indicator.SeparateWindow);
Assert.True(indicator.OnBackGround);
}
[Fact]
public void RemaIndicator_MinHistoryDepths_EqualsZero()
{
var indicator = new RemaIndicator { Period = 20 };
Assert.Equal(0, RemaIndicator.MinHistoryDepths);
Assert.Equal(0, ((IWatchlistIndicator)indicator).MinHistoryDepths);
}
[Fact]
public void RemaIndicator_ShortName_IncludesPeriodLambdaAndSource()
{
var indicator = new RemaIndicator { Period = 15, Lambda = 0.7 };
Assert.Contains("REMA", indicator.ShortName, StringComparison.Ordinal);
Assert.Contains("15", indicator.ShortName, StringComparison.Ordinal);
Assert.Contains("0.70", indicator.ShortName, StringComparison.Ordinal);
}
[Fact]
public void RemaIndicator_Initialize_CreatesInternalRema()
{
var indicator = new RemaIndicator { Period = 10, Lambda = 0.5 };
// Initialize should not throw
indicator.Initialize();
// After init, line series should exist
Assert.Single(indicator.LinesSeries);
}
[Fact]
public void RemaIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
{
var indicator = new RemaIndicator { Period = 3, Lambda = 0.5 };
indicator.Initialize();
// Add historical data
var now = DateTime.UtcNow;
indicator.HistoricalData.AddBar(now, 100, 105, 95, 102);
// Process update
var args = new UpdateArgs(UpdateReason.HistoricalBar);
indicator.ProcessUpdate(args);
// Line series should have a value
Assert.Equal(1, indicator.LinesSeries[0].Count);
Assert.True(double.IsFinite(indicator.LinesSeries[0].GetValue(0)));
}
[Fact]
public void RemaIndicator_ProcessUpdate_NewBar_ComputesValue()
{
var indicator = new RemaIndicator { Period = 3, Lambda = 0.5 };
indicator.Initialize();
// Add historical data
var now = DateTime.UtcNow;
indicator.HistoricalData.AddBar(now, 100, 105, 95, 102);
indicator.HistoricalData.AddBar(now.AddMinutes(1), 102, 108, 100, 106);
// Process first update
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.NewBar));
// Line series should have values
Assert.Equal(2, indicator.LinesSeries[0].Count);
}
[Fact]
public void RemaIndicator_ProcessUpdate_NewTick_ProcessesWithoutError()
{
var indicator = new RemaIndicator { Period = 3, Lambda = 0.5 };
indicator.Initialize();
// Add historical data
var now = DateTime.UtcNow;
indicator.HistoricalData.AddBar(now, 100, 105, 95, 102);
// Process historical bar first
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
double firstValue = indicator.LinesSeries[0].GetValue(0);
// Update with new tick (same bar data - simulates intrabar update)
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.NewTick));
double secondValue = indicator.LinesSeries[0].GetValue(0);
// Both values should be finite
Assert.True(double.IsFinite(firstValue));
Assert.True(double.IsFinite(secondValue));
}
[Fact]
public void RemaIndicator_MultipleUpdates_ProducesCorrectRemaSequence()
{
var indicator = new RemaIndicator { Period = 3, Lambda = 0.5 };
indicator.Initialize();
var now = DateTime.UtcNow;
double[] closes = { 100, 102, 104, 103, 105, 107, 106 };
foreach (var close in closes)
{
indicator.HistoricalData.AddBar(now, close, close + 2, close - 2, close);
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
now = now.AddMinutes(1);
}
// All values should be finite
for (int i = 0; i < closes.Length; i++)
{
Assert.True(double.IsFinite(indicator.LinesSeries[0].GetValue(closes.Length - 1 - i)));
}
// REMA should be smoothing the values
// Last REMA value should be between first and last close
double lastRema = indicator.LinesSeries[0].GetValue(0);
Assert.True(lastRema >= 100 && lastRema <= 110);
}
[Fact]
public void RemaIndicator_DifferentSourceTypes_Work()
{
var sources = new[] { SourceType.Open, SourceType.High, SourceType.Low, SourceType.Close, SourceType.HL2, SourceType.HLC3 };
foreach (var source in sources)
{
var indicator = new RemaIndicator { Period = 3, Lambda = 0.5, Source = source };
indicator.Initialize();
var now = DateTime.UtcNow;
indicator.HistoricalData.AddBar(now, 100, 110, 90, 105);
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
Assert.True(double.IsFinite(indicator.LinesSeries[0].GetValue(0)),
$"Source {source} should produce finite value");
}
}
[Fact]
public void RemaIndicator_Period_CanBeChanged()
{
var indicator = new RemaIndicator { Period = 5 };
Assert.Equal(5, indicator.Period);
indicator.Period = 20;
Assert.Equal(20, indicator.Period);
Assert.Equal(0, RemaIndicator.MinHistoryDepths);
}
[Fact]
public void RemaIndicator_Lambda_CanBeChanged()
{
var indicator = new RemaIndicator { Lambda = 0.5 };
Assert.Equal(0.5, indicator.Lambda);
indicator.Lambda = 0.8;
Assert.Equal(0.8, indicator.Lambda);
}
[Fact]
public void RemaIndicator_DifferentLambdaValues_ProduceDifferentResults()
{
var now = DateTime.UtcNow;
double[] closes = { 100, 102, 104, 103, 105, 107, 106 };
var indicator1 = new RemaIndicator { Period = 3, Lambda = 0.3 };
var indicator2 = new RemaIndicator { Period = 3, Lambda = 0.7 };
indicator1.Initialize();
indicator2.Initialize();
foreach (var close in closes)
{
indicator1.HistoricalData.AddBar(now, close, close + 2, close - 2, close);
indicator2.HistoricalData.AddBar(now, close, close + 2, close - 2, close);
indicator1.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
indicator2.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
now = now.AddMinutes(1);
}
// Different lambda values should produce different results
double result1 = indicator1.LinesSeries[0].GetValue(0);
double result2 = indicator2.LinesSeries[0].GetValue(0);
Assert.NotEqual(result1, result2);
}
}
+702
View File
@@ -0,0 +1,702 @@
namespace QuanTAlib.Tests;
public class RemaTests
{
[Fact]
public void Rema_Constructor_Period_ValidatesInput()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new Rema(0));
Assert.Throws<ArgumentOutOfRangeException>(() => new Rema(-1));
var rema = new Rema(10);
Assert.NotNull(rema);
}
[Fact]
public void Rema_Constructor_Lambda_ValidatesInput()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new Rema(10, -0.1));
Assert.Throws<ArgumentOutOfRangeException>(() => new Rema(10, 1.1));
var rema1 = new Rema(10, 0.0);
var rema2 = new Rema(10, 1.0);
var rema3 = new Rema(10, 0.5);
Assert.NotNull(rema1);
Assert.NotNull(rema2);
Assert.NotNull(rema3);
}
[Fact]
public void Rema_Calc_ReturnsValue()
{
var rema = new Rema(10);
Assert.Equal(0, rema.Last.Value);
TValue result = rema.Update(new TValue(DateTime.UtcNow, 100));
Assert.True(result.Value > 0);
Assert.Equal(result.Value, rema.Last.Value);
}
[Fact]
public void Rema_Calc_IsNew_AcceptsParameter()
{
var rema = new Rema(10);
rema.Update(new TValue(DateTime.UtcNow, 100), isNew: true);
double value1 = rema.Last.Value;
rema.Update(new TValue(DateTime.UtcNow, 105), isNew: true);
double value2 = rema.Last.Value;
// Values should change with new bars
Assert.NotEqual(value1, value2);
}
[Fact]
public void Rema_Calc_IsNew_False_UpdatesValue()
{
var rema = new Rema(10);
rema.Update(new TValue(DateTime.UtcNow, 100));
rema.Update(new TValue(DateTime.UtcNow, 110), isNew: true);
double beforeUpdate = rema.Last.Value;
rema.Update(new TValue(DateTime.UtcNow, 120), isNew: false);
double afterUpdate = rema.Last.Value;
// Update should change the value
Assert.NotEqual(beforeUpdate, afterUpdate);
}
[Fact]
public void Rema_Reset_ClearsState()
{
var rema = new Rema(10);
rema.Update(new TValue(DateTime.UtcNow, 100));
rema.Update(new TValue(DateTime.UtcNow, 105));
double valueBefore = rema.Last.Value;
rema.Reset();
Assert.Equal(0, rema.Last.Value);
// After reset, should accept new values
rema.Update(new TValue(DateTime.UtcNow, 50));
Assert.NotEqual(0, rema.Last.Value);
Assert.NotEqual(valueBefore, rema.Last.Value);
}
[Fact]
public void Rema_Properties_Accessible()
{
var rema = new Rema(10);
Assert.Equal(0, rema.Last.Value);
Assert.False(rema.IsHot);
rema.Update(new TValue(DateTime.UtcNow, 100));
Assert.NotEqual(0, rema.Last.Value);
}
[Fact]
public void Rema_IsHot_BecomesTrueAfterWarmup()
{
var rema = new Rema(10);
// Initially IsHot should be false
Assert.False(rema.IsHot);
int steps = 0;
while (!rema.IsHot && steps < 1000)
{
rema.Update(new TValue(DateTime.UtcNow, 100));
steps++;
}
Assert.True(rema.IsHot);
Assert.True(steps > 0);
// Similar to EMA, should become hot around 15 bars for period 10
Assert.InRange(steps, 14, 17);
}
[Fact]
public void Rema_IsHot_IsPeriodDependent()
{
int[] periods = [10, 20, 50];
int[] expectedSteps = new int[periods.Length];
for (int i = 0; i < periods.Length; i++)
{
int period = periods[i];
var rema = new Rema(period);
int steps = 0;
while (!rema.IsHot && steps < 500)
{
rema.Update(new TValue(DateTime.UtcNow, 100));
steps++;
}
expectedSteps[i] = steps;
}
// Verify warmup times increase with period
Assert.True(expectedSteps[0] < expectedSteps[1], $"Period 10 ({expectedSteps[0]}) should be less than Period 20 ({expectedSteps[1]})");
Assert.True(expectedSteps[1] < expectedSteps[2], $"Period 20 ({expectedSteps[1]}) should be less than Period 50 ({expectedSteps[2]})");
}
[Fact]
public void Rema_Lambda1_ApproachesEma()
{
// With lambda=1, REMA should behave similarly to EMA
var rema = new Rema(10, lambda: 1.0);
var ema = new Ema(10);
var gbm = new GBM(startPrice: 100.0, mu: 0.02, sigma: 0.1, seed: 42);
for (int i = 0; i < 100; i++)
{
var bar = gbm.Next(isNew: true);
var input = new TValue(bar.Time, bar.Close);
rema.Update(input);
ema.Update(input);
}
// With lambda=1, REMA should be very close to EMA
Assert.Equal(ema.Last.Value, rema.Last.Value, 1e-6);
}
[Fact]
public void Rema_Lambda0_MaxRegularization()
{
// With lambda=0, REMA uses pure momentum continuation
var rema0 = new Rema(10, lambda: 0.0);
var rema05 = new Rema(10, lambda: 0.5);
var rema1 = new Rema(10, lambda: 1.0);
var gbm = new GBM(startPrice: 100.0, mu: 0.02, sigma: 0.1, seed: 42);
for (int i = 0; i < 50; i++)
{
var bar = gbm.Next(isNew: true);
var input = new TValue(bar.Time, bar.Close);
rema0.Update(input);
rema05.Update(input);
rema1.Update(input);
}
// All should produce finite values
Assert.True(double.IsFinite(rema0.Last.Value));
Assert.True(double.IsFinite(rema05.Last.Value));
Assert.True(double.IsFinite(rema1.Last.Value));
// They should generally differ (lambda affects behavior)
// Note: exact equality is unlikely with different lambdas
}
[Fact]
public void Rema_IterativeCorrections_RestoreToOriginalState()
{
var rema = new Rema(10);
var gbm = new GBM(startPrice: 100.0, mu: 0.02, sigma: 0.1);
// Feed 10 new values
TValue tenthInput = default;
for (int i = 0; i < 10; i++)
{
var bar = gbm.Next(isNew: true);
tenthInput = new TValue(bar.Time, bar.Close);
rema.Update(tenthInput, isNew: true);
}
// Remember state after 10 values
double remaAfterTen = rema.Last.Value;
// Generate 9 corrections with isNew=false (different values)
for (int i = 0; i < 9; i++)
{
var bar = gbm.Next(isNew: false);
rema.Update(new TValue(bar.Time, bar.Close), isNew: false);
}
// Feed the remembered 10th input again with isNew=false
TValue finalRema = rema.Update(tenthInput, isNew: false);
// Should match the original state after 10 values
Assert.Equal(remaAfterTen, finalRema.Value, 1e-10);
}
[Fact]
public void Rema_BatchCalc_MatchesIterativeCalc()
{
var remaIterative = new Rema(10);
var remaBatch = new Rema(10);
var gbm = new GBM(startPrice: 100.0, mu: 0.02, sigma: 0.1);
// Generate data
var series = new TSeries();
for (int i = 0; i < 100; i++)
{
var bar = gbm.Next(isNew: true);
series.Add(bar.Time, bar.Close);
}
Assert.True(series.Count > 0);
// Calculate iteratively
var iterativeResults = new TSeries();
foreach (var item in series)
{
iterativeResults.Add(remaIterative.Update(item));
}
// Calculate batch
var batchResults = remaBatch.Update(series);
// Compare
Assert.Equal(iterativeResults.Count, batchResults.Count);
for (int i = 0; i < iterativeResults.Count; i++)
{
Assert.Equal(iterativeResults[i].Value, batchResults[i].Value, 1e-10);
Assert.Equal(iterativeResults[i].Time, batchResults[i].Time);
}
}
[Fact]
public void Rema_NaN_Input_UsesLastValidValue()
{
var rema = new Rema(10);
// Feed some valid values
rema.Update(new TValue(DateTime.UtcNow, 100));
rema.Update(new TValue(DateTime.UtcNow, 110));
// Feed NaN - should use last valid value (110)
var resultAfterNaN = rema.Update(new TValue(DateTime.UtcNow, double.NaN));
// Result should be finite (not NaN)
Assert.True(double.IsFinite(resultAfterNaN.Value));
Assert.NotEqual(0, resultAfterNaN.Value);
}
[Fact]
public void Rema_Infinity_Input_UsesLastValidValue()
{
var rema = new Rema(10);
// Feed some valid values
rema.Update(new TValue(DateTime.UtcNow, 100));
rema.Update(new TValue(DateTime.UtcNow, 110));
// Feed positive infinity - should use last valid value
var resultAfterPosInf = rema.Update(new TValue(DateTime.UtcNow, double.PositiveInfinity));
Assert.True(double.IsFinite(resultAfterPosInf.Value));
// Feed negative infinity - should use last valid value
var resultAfterNegInf = rema.Update(new TValue(DateTime.UtcNow, double.NegativeInfinity));
Assert.True(double.IsFinite(resultAfterNegInf.Value));
}
[Fact]
public void Rema_MultipleNaN_ContinuesWithLastValid()
{
var rema = new Rema(10);
// Feed valid values
rema.Update(new TValue(DateTime.UtcNow, 100));
rema.Update(new TValue(DateTime.UtcNow, 110));
rema.Update(new TValue(DateTime.UtcNow, 120));
// Feed multiple NaN values
var r1 = rema.Update(new TValue(DateTime.UtcNow, double.NaN));
var r2 = rema.Update(new TValue(DateTime.UtcNow, double.NaN));
var r3 = rema.Update(new TValue(DateTime.UtcNow, double.NaN));
// All results should be finite
Assert.True(double.IsFinite(r1.Value));
Assert.True(double.IsFinite(r2.Value));
Assert.True(double.IsFinite(r3.Value));
}
[Fact]
public void Rema_BatchCalc_HandlesNaN()
{
var rema = new Rema(10);
// Create series with NaN values interspersed
var series = new TSeries();
series.Add(DateTime.UtcNow.Ticks, 100);
series.Add(DateTime.UtcNow.Ticks + 1, 110);
series.Add(DateTime.UtcNow.Ticks + 2, double.NaN);
series.Add(DateTime.UtcNow.Ticks + 3, 120);
series.Add(DateTime.UtcNow.Ticks + 4, double.PositiveInfinity);
series.Add(DateTime.UtcNow.Ticks + 5, 130);
var results = rema.Update(series);
// All results should be finite
foreach (var result in results)
{
Assert.True(double.IsFinite(result.Value), $"Expected finite value but got {result.Value}");
}
}
[Fact]
public void Rema_Reset_ClearsLastValidValue()
{
var rema = new Rema(10);
// Feed values including NaN
rema.Update(new TValue(DateTime.UtcNow, 100));
rema.Update(new TValue(DateTime.UtcNow, double.NaN));
// Reset
rema.Reset();
// After reset, first valid value should establish new baseline
var result = rema.Update(new TValue(DateTime.UtcNow, 50));
Assert.Equal(50.0, result.Value, 1e-10);
}
// ============== Span API Tests ==============
[Fact]
public void Rema_SpanBatch_Period_ValidatesInput()
{
double[] source = [1, 2, 3, 4, 5];
double[] output = new double[5];
double[] wrongSizeOutput = new double[3];
// Period must be > 0
Assert.Throws<ArgumentException>(() => Rema.Batch(source.AsSpan(), output.AsSpan(), 0));
Assert.Throws<ArgumentException>(() => Rema.Batch(source.AsSpan(), output.AsSpan(), -1));
// Output must be same length as source
Assert.Throws<ArgumentException>(() => Rema.Batch(source.AsSpan(), wrongSizeOutput.AsSpan(), 3));
}
[Fact]
public void Rema_SpanBatch_Lambda_ValidatesInput()
{
double[] source = [1, 2, 3, 4, 5];
double[] output = new double[5];
// Lambda must be >= 0 and <= 1
Assert.Throws<ArgumentOutOfRangeException>(() => Rema.Batch(source.AsSpan(), output.AsSpan(), 3, -0.1));
Assert.Throws<ArgumentOutOfRangeException>(() => Rema.Batch(source.AsSpan(), output.AsSpan(), 3, 1.1));
}
[Fact]
public void Rema_SpanBatch_MatchesTSeriesBatch()
{
var series = new TSeries();
double[] source = new double[100];
double[] output = new double[100];
var gbm = new GBM(startPrice: 100.0, mu: 0.02, sigma: 0.1, seed: 42);
for (int i = 0; i < 100; i++)
{
var bar = gbm.Next(isNew: true);
source[i] = bar.Close;
series.Add(bar.Time, bar.Close);
}
// Calculate with TSeries API
var tseriesResult = Rema.Batch(series, 10);
// Calculate with Span API
Rema.Batch(source.AsSpan(), output.AsSpan(), 10);
// Compare results
for (int i = 0; i < 100; i++)
{
Assert.Equal(tseriesResult[i].Value, output[i], 1e-9);
}
}
[Fact]
public void Rema_SpanBatch_DifferentLambdas()
{
double[] source = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100];
double[] output0 = new double[10];
double[] output05 = new double[10];
double[] output1 = new double[10];
Rema.Batch(source.AsSpan(), output0.AsSpan(), 5, 0.0);
Rema.Batch(source.AsSpan(), output05.AsSpan(), 5, 0.5);
Rema.Batch(source.AsSpan(), output1.AsSpan(), 5, 1.0);
// All should produce finite results
for (int i = 0; i < 10; i++)
{
Assert.True(double.IsFinite(output0[i]));
Assert.True(double.IsFinite(output05[i]));
Assert.True(double.IsFinite(output1[i]));
}
}
[Fact]
public void Rema_SpanBatch_ZeroAllocation()
{
double[] source = new double[10000];
double[] output = new double[10000];
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 42);
for (int i = 0; i < source.Length; i++)
{
source[i] = gbm.Next().Close;
}
// Warm up
Rema.Batch(source.AsSpan(), output.AsSpan(), 100);
// This test verifies the method runs without throwing
Assert.True(double.IsFinite(output[^1]));
}
[Fact]
public void Rema_SpanBatch_HandlesNaN()
{
double[] source = [100, 110, double.NaN, 120, 130];
double[] output = new double[5];
Rema.Batch(source.AsSpan(), output.AsSpan(), 3);
// All outputs should be finite
foreach (var val in output)
{
Assert.True(double.IsFinite(val), $"Expected finite value but got {val}");
}
}
[Fact]
public void Chainability_Works()
{
var source = new TSeries();
var rema = new Rema(source, 10);
source.Add(new TValue(DateTime.UtcNow, 100));
Assert.Equal(100, rema.Last.Value, 1e-10);
}
[Fact]
public void Prime_SetsStateCorrectly()
{
var rema = new Rema(5);
double[] history = [10, 20, 30, 40, 50];
rema.Prime(history);
// Verify against a fresh REMA fed with same data
var verifyRema = new Rema(5);
foreach (var val in history)
{
verifyRema.Update(new TValue(DateTime.UtcNow, val));
}
Assert.Equal(verifyRema.Last.Value, rema.Last.Value, 1e-10);
Assert.Equal(verifyRema.IsHot, rema.IsHot);
// Verify it continues correctly
rema.Update(new TValue(DateTime.UtcNow, 60));
verifyRema.Update(new TValue(DateTime.UtcNow, 60));
Assert.Equal(verifyRema.Last.Value, rema.Last.Value, 1e-10);
}
[Fact]
public void Prime_HandlesNaN_InHistory()
{
var rema = new Rema(5);
double[] history = [10, 20, double.NaN, 40, 50];
rema.Prime(history);
var verifyRema = new Rema(5);
foreach (var val in history)
{
verifyRema.Update(new TValue(DateTime.UtcNow, val));
}
Assert.Equal(verifyRema.Last.Value, rema.Last.Value, 1e-10);
}
[Fact]
public void Prime_AllNaNs_ReturnsNaN()
{
var rema = new Rema(5);
double[] history = [double.NaN, double.NaN, double.NaN];
rema.Prime(history);
Assert.True(double.IsNaN(rema.Last.Value));
}
[Fact]
public void Calculate_ReturnsCorrectResultsAndHotIndicator()
{
var series = new TSeries();
for (int i = 1; i <= 20; i++)
{
series.Add(DateTime.UtcNow, i * 10);
}
var (results, indicator) = Rema.Calculate(series, 5);
// Check results
Assert.Equal(20, results.Count);
// Verify against standard calculation
var verifyRema = new Rema(5);
var verifyResults = verifyRema.Update(series);
Assert.Equal(verifyResults.Last.Value, results.Last.Value, 1e-10);
Assert.Equal(verifyRema.Last.Value, indicator.Last.Value, 1e-10);
// Check indicator state
Assert.True(indicator.IsHot);
// Verify indicator continues correctly
indicator.Update(new TValue(DateTime.UtcNow, 210));
verifyRema.Update(new TValue(DateTime.UtcNow, 210));
Assert.Equal(verifyRema.Last.Value, indicator.Last.Value, 1e-10);
}
[Fact]
public void Rema_Batch_AllNaNs_ReturnsNaN()
{
double[] source = [double.NaN, double.NaN, double.NaN];
double[] output = new double[3];
Rema.Batch(source.AsSpan(), output.AsSpan(), 5);
// Should be all NaNs, not 0s
foreach (var val in output)
{
Assert.True(double.IsNaN(val), $"Expected NaN but got {val}");
}
}
[Fact]
public void Rema_AllModes_ProduceSameResult()
{
// Arrange
int period = 10;
double lambda = 0.5;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 123);
var bars = gbm.Fetch(1000, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
var series = bars.Close;
// 1. Batch Mode
var batchSeries = Rema.Batch(series, period, lambda);
double expected = batchSeries.Last.Value;
// 2. Span Mode
var tValues = series.Values.ToArray();
var spanInput = new ReadOnlySpan<double>(tValues);
var spanOutput = new double[tValues.Length];
Rema.Batch(spanInput, spanOutput, period, lambda);
double spanResult = spanOutput[^1];
// 3. Streaming Mode
var streamingInd = new Rema(period, lambda);
for (int i = 0; i < series.Count; i++)
{
streamingInd.Update(series[i]);
}
double streamingResult = streamingInd.Last.Value;
// 4. Eventing Mode
var pubSource = new TSeries();
var eventingInd = new Rema(pubSource, period, lambda);
for (int i = 0; i < series.Count; i++)
{
pubSource.Add(series[i]);
}
double eventingResult = eventingInd.Last.Value;
// Assert
Assert.Equal(expected, spanResult, precision: 9);
Assert.Equal(expected, streamingResult, precision: 9);
Assert.Equal(expected, eventingResult, precision: 9);
}
[Fact]
public void Rema_AllModes_ProduceSameResult_AfterResyncInterval()
{
// This guards against implementation drift between CalculateCore (batch/span)
// and Update(TValue) (streaming/eventing) when internal counters wrap/reset.
int period = 10;
double lambda = 0.5;
int count = 12050; // > ResyncInterval (10,000)
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 321);
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
var series = bars.Close;
// 1. Batch Mode
var batchSeries = Rema.Batch(series, period, lambda);
double expected = batchSeries.Last.Value;
// 2. Span Mode
var tValues = series.Values.ToArray();
var spanInput = new ReadOnlySpan<double>(tValues);
var spanOutput = new double[tValues.Length];
Rema.Batch(spanInput, spanOutput, period, lambda);
double spanResult = spanOutput[^1];
// 3. Streaming Mode
var streamingInd = new Rema(period, lambda);
for (int i = 0; i < series.Count; i++)
{
streamingInd.Update(series[i]);
}
double streamingResult = streamingInd.Last.Value;
// 4. Eventing Mode
var pubSource = new TSeries();
var eventingInd = new Rema(pubSource, period, lambda);
for (int i = 0; i < series.Count; i++)
{
pubSource.Add(series[i]);
}
double eventingResult = eventingInd.Last.Value;
Assert.Equal(expected, spanResult, precision: 9);
Assert.Equal(expected, streamingResult, precision: 9);
Assert.Equal(expected, eventingResult, precision: 9);
}
[Fact]
public void Prime_ThenUpdate_StateWorksCorrectly()
{
var rema = new Rema(5);
double[] history = [10, 20, 30, 40, 50];
rema.Prime(history);
double afterPrime = rema.Last.Value;
// After Prime, an isNew=true should advance the state
rema.Update(new TValue(DateTime.UtcNow, 60), isNew: true);
double afterNewBar = rema.Last.Value;
// Values should be different
Assert.NotEqual(afterPrime, afterNewBar);
// isNew=false with a different value should recalculate from previous state
rema.Update(new TValue(DateTime.UtcNow, 70), isNew: false);
double afterCorrection = rema.Last.Value;
// Correction with 70 should give different result than 60
Assert.NotEqual(afterNewBar, afterCorrection);
// isNew=false with original value (60) should restore to afterNewBar
rema.Update(new TValue(DateTime.UtcNow, 60), isNew: false);
Assert.Equal(afterNewBar, rema.Last.Value, 1e-10);
}
}
@@ -0,0 +1,354 @@
using Xunit.Abstractions;
using OoplesFinance.StockIndicators;
using OoplesFinance.StockIndicators.Models;
namespace QuanTAlib.Tests;
/// <summary>
/// Validation tests for REMA (Regularized Exponential Moving Average).
/// Since REMA is a custom indicator not found in external libraries like TA-Lib, Skender, Tulip, or Ooples,
/// these tests validate internal consistency across different calculation modes and against known mathematical properties.
/// </summary>
public sealed class RemaValidationTests : IDisposable
{
private readonly ValidationTestData _testData;
private readonly ITestOutputHelper _output;
private bool _disposed;
public RemaValidationTests(ITestOutputHelper output)
{
_output = output;
_testData = new ValidationTestData();
}
public void Dispose()
{
Dispose(true);
}
private void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
_disposed = true;
if (disposing)
{
_testData?.Dispose();
}
}
[Fact]
public void Validate_Lambda1_MatchesEma_Batch()
{
// When lambda=1, REMA should produce results very close to EMA
int[] periods = { 5, 10, 20, 50 };
foreach (var period in periods)
{
var rema = new Rema(period, lambda: 1.0);
var ema = new Ema(period);
var remaResult = rema.Update(_testData.Data);
var emaResult = ema.Update(_testData.Data);
// Compare last 100 records - they should be very close
int compareCount = Math.Min(100, remaResult.Count);
int startIdx = remaResult.Count - compareCount;
for (int i = startIdx; i < remaResult.Count; i++)
{
Assert.Equal(emaResult[i].Value, remaResult[i].Value, 1e-8);
}
}
_output.WriteLine("REMA(lambda=1) Batch validated successfully against EMA");
}
[Fact]
public void Validate_Lambda1_MatchesEma_Streaming()
{
int[] periods = { 5, 10, 20, 50 };
foreach (var period in periods)
{
var rema = new Rema(period, lambda: 1.0);
var ema = new Ema(period);
var remaResults = new List<double>();
var emaResults = new List<double>();
foreach (var item in _testData.Data)
{
remaResults.Add(rema.Update(item).Value);
emaResults.Add(ema.Update(item).Value);
}
// Compare last 100 records
int compareCount = Math.Min(100, remaResults.Count);
int startIdx = remaResults.Count - compareCount;
for (int i = startIdx; i < remaResults.Count; i++)
{
Assert.Equal(emaResults[i], remaResults[i], 1e-8);
}
}
_output.WriteLine("REMA(lambda=1) Streaming validated successfully against EMA");
}
[Fact]
public void Validate_Lambda1_MatchesEma_Span()
{
int[] periods = { 5, 10, 20, 50 };
double[] sourceData = _testData.RawData.ToArray();
foreach (var period in periods)
{
double[] remaOutput = new double[sourceData.Length];
double[] emaOutput = new double[sourceData.Length];
Rema.Batch(sourceData.AsSpan(), remaOutput.AsSpan(), period, lambda: 1.0);
Ema.Batch(sourceData.AsSpan(), emaOutput.AsSpan(), period);
// Compare last 100 records
int compareCount = Math.Min(100, sourceData.Length);
int startIdx = sourceData.Length - compareCount;
for (int i = startIdx; i < sourceData.Length; i++)
{
Assert.Equal(emaOutput[i], remaOutput[i], 1e-8);
}
}
_output.WriteLine("REMA(lambda=1) Span validated successfully against EMA");
}
[Fact]
public void Validate_BatchStreamingSpan_Consistency()
{
// Validate that all three modes produce identical results
int[] periods = { 5, 10, 20, 50 };
double[] lambdas = { 0.0, 0.25, 0.5, 0.75, 1.0 };
double[] sourceData = _testData.RawData.ToArray();
foreach (var period in periods)
{
foreach (var lambda in lambdas)
{
// Batch (TSeries)
var remaBatch = new Rema(period, lambda);
var batchResult = remaBatch.Update(_testData.Data);
// Streaming
var remaStream = new Rema(period, lambda);
var streamResults = new List<double>();
foreach (var item in _testData.Data)
{
streamResults.Add(remaStream.Update(item).Value);
}
// Span
double[] spanOutput = new double[sourceData.Length];
Rema.Batch(sourceData.AsSpan(), spanOutput.AsSpan(), period, lambda);
// Compare all three
int compareCount = Math.Min(100, sourceData.Length);
int startIdx = sourceData.Length - compareCount;
for (int i = startIdx; i < sourceData.Length; i++)
{
Assert.Equal(batchResult[i].Value, streamResults[i], 1e-10);
Assert.Equal(batchResult[i].Value, spanOutput[i], 1e-10);
}
}
}
_output.WriteLine("REMA Batch/Streaming/Span consistency validated successfully");
}
[Fact]
public void Validate_SmoothingBehavior()
{
// Validate that lower lambda produces smoother output (less variance)
int period = 10;
double[] sourceData = _testData.RawData.ToArray();
double[] output0 = new double[sourceData.Length];
double[] output05 = new double[sourceData.Length];
double[] output1 = new double[sourceData.Length];
Rema.Batch(sourceData.AsSpan(), output0.AsSpan(), period, lambda: 0.0);
Rema.Batch(sourceData.AsSpan(), output05.AsSpan(), period, lambda: 0.5);
Rema.Batch(sourceData.AsSpan(), output1.AsSpan(), period, lambda: 1.0);
// Calculate variance of differences (measure of smoothness)
// Skip warmup period
int startIdx = period * 3;
int len = sourceData.Length - startIdx;
double var0 = CalculateDiffVariance(output0, startIdx, len);
double var05 = CalculateDiffVariance(output05, startIdx, len);
double var1 = CalculateDiffVariance(output1, startIdx, len);
// Lower lambda should generally produce smoother (lower variance) output
// Note: This is a statistical property that may not always hold for all data
_output.WriteLine($"Variance of differences - lambda=0: {var0:F6}, lambda=0.5: {var05:F6}, lambda=1: {var1:F6}");
// At minimum, all should produce finite positive variance
Assert.True(double.IsFinite(var0) && var0 > 0);
Assert.True(double.IsFinite(var05) && var05 > 0);
Assert.True(double.IsFinite(var1) && var1 > 0);
}
[Fact]
public void Validate_PrimeConsistency()
{
// Validate that Prime produces same state as streaming through same data
int[] periods = { 5, 10, 20 };
double[] lambdas = { 0.0, 0.5, 1.0 };
double[] sourceData = _testData.RawData.Span.Slice(0, 100).ToArray();
foreach (var period in periods)
{
foreach (var lambda in lambdas)
{
// Via Prime
var remaPrime = new Rema(period, lambda);
remaPrime.Prime(sourceData);
// Via streaming
var remaStream = new Rema(period, lambda);
foreach (var val in sourceData)
{
remaStream.Update(new TValue(DateTime.UtcNow, val));
}
Assert.Equal(remaStream.Last.Value, remaPrime.Last.Value, 1e-10);
Assert.Equal(remaStream.IsHot, remaPrime.IsHot);
// Verify they continue correctly
double nextVal = sourceData[^1] * 1.05; // 5% increase
remaPrime.Update(new TValue(DateTime.UtcNow, nextVal));
remaStream.Update(new TValue(DateTime.UtcNow, nextVal));
Assert.Equal(remaStream.Last.Value, remaPrime.Last.Value, 1e-10);
}
}
_output.WriteLine("REMA Prime consistency validated successfully");
}
[Fact]
public void Validate_ConstantInput_ConvergesToInput()
{
// With constant input, REMA should converge to that value when lambda > 0
// Note: lambda=0 is pure momentum and may not converge to constant value
double constantValue = 100.0;
int[] periods = { 5, 10, 20 };
double[] lambdas = { 0.5, 1.0 }; // Exclude lambda=0 (pure momentum)
foreach (var period in periods)
{
foreach (var lambda in lambdas)
{
var rema = new Rema(period, lambda);
// Feed constant values until well past warmup
for (int i = 0; i < period * 10; i++)
{
rema.Update(new TValue(DateTime.UtcNow, constantValue));
}
// Should converge to the constant value (within tolerance)
Assert.Equal(constantValue, rema.Last.Value, 1e-4);
}
}
_output.WriteLine("REMA constant input convergence validated successfully");
}
[Fact]
public void Validate_BarCorrection_Consistency()
{
// Validate that bar correction (isNew=false) works correctly
int period = 10;
double lambda = 0.5;
var gbm = new GBM(startPrice: 100.0, mu: 0.02, sigma: 0.1, seed: 42);
var rema = new Rema(period, lambda);
// Feed 20 bars
for (int i = 0; i < 20; i++)
{
var bar = gbm.Next(isNew: true);
rema.Update(new TValue(bar.Time, bar.Close), isNew: true);
}
double valueAfter20 = rema.Last.Value;
// Apply 5 corrections
for (int i = 0; i < 5; i++)
{
var bar = gbm.Next(isNew: false);
rema.Update(new TValue(bar.Time, bar.Close), isNew: false);
}
// The value should have changed
Assert.NotEqual(valueAfter20, rema.Last.Value);
// Now restore by using the same correction with original value
// We need to track the original 20th bar value for this
// Since we can't easily do that, we just verify the mechanism works
Assert.True(double.IsFinite(rema.Last.Value));
_output.WriteLine("REMA bar correction consistency validated successfully");
}
private static double CalculateDiffVariance(double[] values, int startIdx, int count)
{
if (count < 2)
{
return 0;
}
// Calculate differences
double sumDiff = 0;
double sumDiffSq = 0;
int n = 0;
for (int i = startIdx + 1; i < startIdx + count && i < values.Length; i++)
{
double diff = values[i] - values[i - 1];
sumDiff += diff;
sumDiffSq += diff * diff;
n++;
}
if (n < 2)
{
return 0;
}
double mean = sumDiff / n;
double variance = (sumDiffSq / n) - (mean * mean);
return Math.Max(0, variance); // Ensure non-negative due to floating point
}
[Fact]
public void Rema_MatchesOoples_Structural()
{
var gbm = new GBM(startPrice: 100.0, mu: 0.02, sigma: 0.15, seed: 42);
var bars = gbm.Fetch(500, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
var ooplesData = bars.Select(b => new TickerData
{
Date = new DateTime(b.Time, DateTimeKind.Utc),
Open = b.Open, High = b.High, Low = b.Low,
Close = b.Close, Volume = b.Volume
}).ToList();
var result = new StockData(ooplesData).CalculateRegularizedExponentialMovingAverage();
var values = result.CustomValuesList;
int finiteCount = values.Count(v => double.IsFinite(v));
Assert.True(finiteCount > 100, $"Expected >100 finite values, got {finiteCount}");
}
}