mirror of
https://github.com/mihakralj/QuanTAlib.git
synced 2026-08-23 21:18:04 +00:00
fix: resolve build and test errors
- Sar.Quantower.Tests.cs: add missing opening quote on string literal (line 48) - Exports.cs: rename Correlation.Batch → Correl.Batch (CS0103) - Ad.Validation.Tests.cs: fix Ooples OutputValues key "Ad" → "Adl"
This commit is contained in:
@@ -0,0 +1,133 @@
|
||||
using TradingPlatform.BusinessLayer;
|
||||
using QuanTAlib;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public sealed class SarIndicatorTests
|
||||
{
|
||||
[Fact]
|
||||
public void SarIndicator_Constructor_SetsDefaults()
|
||||
{
|
||||
var indicator = new SarIndicator();
|
||||
|
||||
Assert.Equal(0.02, indicator.AfStart);
|
||||
Assert.Equal(0.02, indicator.AfIncrement);
|
||||
Assert.Equal(0.20, indicator.AfMax);
|
||||
Assert.True(indicator.ShowColdValues);
|
||||
Assert.Contains("SAR", indicator.Name, StringComparison.Ordinal);
|
||||
Assert.False(indicator.SeparateWindow);
|
||||
Assert.True(indicator.OnBackGround);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SarIndicator_MinHistoryDepths_EqualsZero()
|
||||
{
|
||||
var indicator = new SarIndicator();
|
||||
|
||||
Assert.Equal(0, SarIndicator.MinHistoryDepths);
|
||||
IWatchlistIndicator watchlistIndicator = indicator;
|
||||
Assert.Equal(0, watchlistIndicator.MinHistoryDepths);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SarIndicator_ShortName_IncludesParameters()
|
||||
{
|
||||
var indicator = new SarIndicator { AfStart = 0.02, AfMax = 0.20 };
|
||||
indicator.Initialize();
|
||||
|
||||
Assert.Contains("SAR", indicator.ShortName, StringComparison.Ordinal);
|
||||
Assert.Contains("0.02", indicator.ShortName, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SarIndicator_SourceCodeLink_IsValid()
|
||||
{
|
||||
var indicator = new SarIndicator();
|
||||
|
||||
Assert.Contains("github.com", indicator.SourceCodeLink, StringComparison.Ordinal);
|
||||
Assert.Contains("Sar", indicator.SourceCodeLink, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SarIndicator_Initialize_CreatesInternalIndicator()
|
||||
{
|
||||
var indicator = new SarIndicator();
|
||||
|
||||
indicator.Initialize();
|
||||
|
||||
// After init, line series should exist (SAR only)
|
||||
Assert.Single(indicator.LinesSeries);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SarIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
|
||||
{
|
||||
var indicator = new SarIndicator { AfStart = 0.02, AfIncrement = 0.02, AfMax = 0.20 };
|
||||
indicator.Initialize();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
indicator.HistoricalData.AddBar(now.AddMinutes(i), 100 + i, 110 + i, 90 + i, 105 + i);
|
||||
|
||||
var args = new UpdateArgs(UpdateReason.HistoricalBar);
|
||||
indicator.ProcessUpdate(args);
|
||||
}
|
||||
|
||||
double sar = indicator.LinesSeries[0].GetValue(0);
|
||||
|
||||
Assert.True(double.IsFinite(sar));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SarIndicator_ProcessUpdate_NewBar_ComputesValue()
|
||||
{
|
||||
var indicator = new SarIndicator { AfStart = 0.02, AfIncrement = 0.02, AfMax = 0.20 };
|
||||
indicator.Initialize();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
indicator.HistoricalData.AddBar(now.AddMinutes(i), 100 + i, 110 + i, 90 + i, 105 + i);
|
||||
var args = new UpdateArgs(UpdateReason.HistoricalBar);
|
||||
indicator.ProcessUpdate(args);
|
||||
}
|
||||
|
||||
// Simulate a new bar
|
||||
indicator.HistoricalData.AddBar(now.AddMinutes(10), 110, 120, 100, 115);
|
||||
var newArgs = new UpdateArgs(UpdateReason.NewBar);
|
||||
indicator.ProcessUpdate(newArgs);
|
||||
|
||||
double sar = indicator.LinesSeries[0].GetValue(0);
|
||||
|
||||
Assert.True(double.IsFinite(sar));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SarIndicator_SingleLineSeries_IsPresent()
|
||||
{
|
||||
var indicator = new SarIndicator();
|
||||
indicator.Initialize();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
indicator.HistoricalData.AddBar(now.AddMinutes(i), 100 + i, 110 + i, 90 + i, 105 + i);
|
||||
var args = new UpdateArgs(UpdateReason.HistoricalBar);
|
||||
indicator.ProcessUpdate(args);
|
||||
}
|
||||
|
||||
Assert.Single(indicator.LinesSeries);
|
||||
Assert.True(double.IsFinite(indicator.LinesSeries[0].GetValue(0)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SarIndicator_Description_IsSet()
|
||||
{
|
||||
var indicator = new SarIndicator();
|
||||
|
||||
Assert.NotNull(indicator.Description);
|
||||
Assert.NotEmpty(indicator.Description);
|
||||
Assert.Contains("stop", indicator.Description, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,560 @@
|
||||
// SAR Tests - Parabolic Stop And Reverse
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
// ── A) Constructor Validation ────────────────────────────────────────────
|
||||
public sealed class SarConstructorTests
|
||||
{
|
||||
[Fact]
|
||||
public void Constructor_ZeroAfStart_Throws()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Sar(afStart: 0));
|
||||
Assert.Equal("afStart", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_NegativeAfStart_Throws()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Sar(afStart: -0.01));
|
||||
Assert.Equal("afStart", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_ZeroAfIncrement_Throws()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Sar(afIncrement: 0));
|
||||
Assert.Equal("afIncrement", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_NegativeAfIncrement_Throws()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Sar(afIncrement: -0.01));
|
||||
Assert.Equal("afIncrement", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_AfMaxEqualAfStart_Throws()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Sar(afStart: 0.02, afMax: 0.02));
|
||||
Assert.Equal("afMax", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_AfMaxLessThanAfStart_Throws()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Sar(afStart: 0.10, afMax: 0.05));
|
||||
Assert.Equal("afStart", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_ValidDefaults_SetsProperties()
|
||||
{
|
||||
var sar = new Sar();
|
||||
|
||||
Assert.Equal(0.02, sar.AfStart);
|
||||
Assert.Equal(0.02, sar.AfIncrement);
|
||||
Assert.Equal(0.20, sar.AfMax);
|
||||
Assert.Equal(1, sar.WarmupPeriod);
|
||||
Assert.Contains("Sar", sar.Name, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_CustomParams_SetsProperties()
|
||||
{
|
||||
var sar = new Sar(afStart: 0.01, afIncrement: 0.01, afMax: 0.10);
|
||||
|
||||
Assert.Equal(0.01, sar.AfStart);
|
||||
Assert.Equal(0.01, sar.AfIncrement);
|
||||
Assert.Equal(0.10, sar.AfMax);
|
||||
}
|
||||
}
|
||||
|
||||
// ── B) Basic Calculation ─────────────────────────────────────────────────
|
||||
public sealed class SarBasicTests
|
||||
{
|
||||
[Fact]
|
||||
public void Update_ReturnsTValue()
|
||||
{
|
||||
var sar = new Sar();
|
||||
var bar = new TBar(DateTime.UtcNow, 100, 95, 98, 97, 1000);
|
||||
|
||||
TValue result = sar.Update(bar);
|
||||
|
||||
Assert.IsType<TValue>(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Update_Last_IsAccessible()
|
||||
{
|
||||
var sar = new Sar();
|
||||
var bar = new TBar(DateTime.UtcNow, 100, 95, 98, 97, 1000);
|
||||
|
||||
_ = sar.Update(bar);
|
||||
|
||||
Assert.True(double.IsFinite(sar.Last.Value) || double.IsNaN(sar.Last.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Update_Sar_IsAccessible()
|
||||
{
|
||||
var sar = new Sar();
|
||||
|
||||
// Feed enough bars
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
double price = 100.0 + i;
|
||||
_ = sar.Update(new TBar(DateTime.UtcNow.AddMinutes(i),
|
||||
price + 2, price - 2, price + 1, price, 1000));
|
||||
}
|
||||
|
||||
Assert.True(double.IsFinite(sar.SarValue));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Name_ContainsParameters()
|
||||
{
|
||||
var sar = new Sar(afStart: 0.01, afIncrement: 0.02, afMax: 0.10);
|
||||
|
||||
Assert.Contains("0.01", sar.Name, StringComparison.Ordinal);
|
||||
Assert.Contains("0.10", sar.Name, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FirstBar_Uptrend_SarEqualsLow()
|
||||
{
|
||||
var sar = new Sar();
|
||||
// Close(105) > Open(95) → long mode → SAR = low(90)
|
||||
_ = sar.Update(new TBar(DateTime.UtcNow, 95, 110, 90, 105, 1000));
|
||||
|
||||
Assert.Equal(90.0, sar.SarValue);
|
||||
Assert.True(sar.IsLong);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FirstBar_Downtrend_SarEqualsHigh()
|
||||
{
|
||||
var sar = new Sar();
|
||||
// Close(90) < Open(105) → short mode → SAR = high(110)
|
||||
_ = sar.Update(new TBar(DateTime.UtcNow, 105, 110, 85, 90, 1000));
|
||||
|
||||
Assert.Equal(110.0, sar.SarValue);
|
||||
Assert.False(sar.IsLong);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sar_BelowPrice_InUptrend()
|
||||
{
|
||||
var sar = new Sar();
|
||||
|
||||
// Steady uptrend - SAR should trail below
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
double price = 100.0 + i * 2;
|
||||
_ = sar.Update(new TBar(DateTime.UtcNow.AddMinutes(i),
|
||||
price + 1, price - 1, price + 0.5, price, 1000));
|
||||
}
|
||||
|
||||
double lastClose = 100.0 + 19 * 2;
|
||||
Assert.True(sar.SarValue < lastClose, "SAR should be below price in uptrend");
|
||||
Assert.True(sar.IsLong, "Should be in long mode during uptrend");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sar_AbovePrice_InDowntrend()
|
||||
{
|
||||
var sar = new Sar();
|
||||
|
||||
// Steady downtrend - SAR should trail above
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
double price = 200.0 - i * 2;
|
||||
_ = sar.Update(new TBar(DateTime.UtcNow.AddMinutes(i),
|
||||
price + 1, price - 1, price + 0.5, price, 1000));
|
||||
}
|
||||
|
||||
double lastClose = 200.0 - 19 * 2;
|
||||
Assert.True(sar.SarValue > lastClose, "SAR should be above price in downtrend");
|
||||
Assert.False(sar.IsLong, "Should be in short mode during downtrend");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsHot_TrueAfterFirstBar()
|
||||
{
|
||||
var sar = new Sar();
|
||||
|
||||
Assert.False(sar.IsHot);
|
||||
|
||||
_ = sar.Update(new TBar(DateTime.UtcNow, 100, 95, 98, 97, 1000));
|
||||
|
||||
Assert.True(sar.IsHot);
|
||||
}
|
||||
}
|
||||
|
||||
// ── C) State + Bar Correction ────────────────────────────────────────────
|
||||
public sealed class SarStateCorrectionTests
|
||||
{
|
||||
[Fact]
|
||||
public void IsNew_True_AdvancesState()
|
||||
{
|
||||
var sar = new Sar();
|
||||
|
||||
_ = sar.Update(new TBar(DateTime.UtcNow, 105, 95, 100, 100, 1000), isNew: true);
|
||||
var first = sar.Last;
|
||||
|
||||
_ = sar.Update(new TBar(DateTime.UtcNow.AddMinutes(1), 110, 100, 105, 105, 1000), isNew: true);
|
||||
var second = sar.Last;
|
||||
|
||||
Assert.NotEqual(first.Time, second.Time);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsNew_False_CorrectionRestoresState()
|
||||
{
|
||||
var sar = new Sar();
|
||||
var dt = DateTime.UtcNow;
|
||||
|
||||
// Feed some bars to warm up
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
double price = 100.0 + i;
|
||||
_ = sar.Update(new TBar(dt.AddMinutes(i), price + 2, price - 2, price + 1, price, 1000), isNew: true);
|
||||
}
|
||||
|
||||
// New bar
|
||||
_ = sar.Update(new TBar(dt.AddMinutes(5), 110, 105, 108, 107, 1000), isNew: true);
|
||||
|
||||
// Correct the bar (isNew=false with different values)
|
||||
_ = sar.Update(new TBar(dt.AddMinutes(5), 111, 104, 109, 108, 1000), isNew: false);
|
||||
|
||||
// Another correction should produce same result
|
||||
_ = sar.Update(new TBar(dt.AddMinutes(5), 111, 104, 109, 108, 1000), isNew: false);
|
||||
var corrected1 = sar.SarValue;
|
||||
|
||||
_ = sar.Update(new TBar(dt.AddMinutes(5), 111, 104, 109, 108, 1000), isNew: false);
|
||||
var corrected2 = sar.SarValue;
|
||||
|
||||
Assert.Equal(corrected1, corrected2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IterativeCorrections_ProduceSameResult()
|
||||
{
|
||||
var sar = new Sar();
|
||||
var dt = DateTime.UtcNow;
|
||||
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
double price = 100.0 + i;
|
||||
_ = sar.Update(new TBar(dt.AddMinutes(i), price + 2, price - 2, price + 1, price, 1000), isNew: true);
|
||||
}
|
||||
|
||||
// Add new bar then correct 3 times
|
||||
_ = sar.Update(new TBar(dt.AddMinutes(5), 110, 100, 108, 105, 1000), isNew: true);
|
||||
|
||||
double[] results = new double[3];
|
||||
for (int i = 0; i < 3; i++)
|
||||
{
|
||||
_ = sar.Update(new TBar(dt.AddMinutes(5), 112, 101, 110, 107, 1000), isNew: false);
|
||||
results[i] = sar.SarValue;
|
||||
}
|
||||
|
||||
Assert.Equal(results[0], results[1]);
|
||||
Assert.Equal(results[1], results[2]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reset_ClearsAllState()
|
||||
{
|
||||
var sar = new Sar();
|
||||
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
double price = 100.0 + i;
|
||||
_ = sar.Update(new TBar(DateTime.UtcNow.AddMinutes(i), price + 2, price - 2, price + 1, price, 1000));
|
||||
}
|
||||
|
||||
Assert.True(sar.IsHot);
|
||||
|
||||
sar.Reset();
|
||||
|
||||
Assert.False(sar.IsHot);
|
||||
Assert.True(double.IsNaN(sar.SarValue));
|
||||
}
|
||||
}
|
||||
|
||||
// ── D) Warmup / Convergence ──────────────────────────────────────────────
|
||||
public sealed class SarWarmupTests
|
||||
{
|
||||
[Fact]
|
||||
public void IsHot_FlipsAfterFirstBar()
|
||||
{
|
||||
var sar = new Sar();
|
||||
|
||||
Assert.False(sar.IsHot);
|
||||
|
||||
_ = sar.Update(new TBar(DateTime.UtcNow, 100, 95, 98, 97, 1000));
|
||||
|
||||
Assert.True(sar.IsHot);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WarmupPeriod_EqualsOne()
|
||||
{
|
||||
var sar = new Sar();
|
||||
|
||||
Assert.Equal(1, sar.WarmupPeriod);
|
||||
}
|
||||
}
|
||||
|
||||
// ── E) Robustness ────────────────────────────────────────────────────────
|
||||
public sealed class SarRobustnessTests
|
||||
{
|
||||
[Fact]
|
||||
public void NaN_Input_UsesLastValidValue()
|
||||
{
|
||||
var sar = new Sar();
|
||||
var dt = DateTime.UtcNow;
|
||||
|
||||
// Feed valid bars
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
double price = 100.0 + i;
|
||||
_ = sar.Update(new TBar(dt.AddMinutes(i), price + 2, price - 2, price + 1, price, 1000));
|
||||
}
|
||||
|
||||
// Feed NaN bar
|
||||
_ = sar.Update(new TBar(dt.AddMinutes(5), double.NaN, double.NaN, double.NaN, double.NaN, 0));
|
||||
|
||||
Assert.True(double.IsFinite(sar.SarValue));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Infinity_Input_UsesLastValidValue()
|
||||
{
|
||||
var sar = new Sar();
|
||||
var dt = DateTime.UtcNow;
|
||||
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
double price = 100.0 + i;
|
||||
_ = sar.Update(new TBar(dt.AddMinutes(i), price + 2, price - 2, price + 1, price, 1000));
|
||||
}
|
||||
|
||||
_ = sar.Update(new TBar(dt.AddMinutes(5),
|
||||
double.PositiveInfinity, double.NegativeInfinity, double.PositiveInfinity, double.PositiveInfinity, 0));
|
||||
|
||||
Assert.True(double.IsFinite(sar.SarValue));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FirstBar_NaN_ReturnsNaN()
|
||||
{
|
||||
var sar = new Sar();
|
||||
|
||||
_ = sar.Update(new TBar(DateTime.UtcNow, double.NaN, double.NaN, double.NaN, double.NaN, 0));
|
||||
|
||||
Assert.True(double.IsNaN(sar.Last.Value));
|
||||
}
|
||||
}
|
||||
|
||||
// ── F) Consistency ───────────────────────────────────────────────────────
|
||||
public sealed class SarConsistencyTests
|
||||
{
|
||||
private static TBarSeries CreateGbmBars(int count = 500)
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100.0, mu: 0.05, sigma: 0.20, seed: 42);
|
||||
return gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Streaming_MatchesBatch()
|
||||
{
|
||||
var bars = CreateGbmBars();
|
||||
|
||||
// Streaming
|
||||
var streaming = new Sar();
|
||||
var streamResults = new double[bars.Count];
|
||||
for (int i = 0; i < bars.Count; i++)
|
||||
{
|
||||
_ = streaming.Update(bars[i], isNew: true);
|
||||
streamResults[i] = streaming.SarValue;
|
||||
}
|
||||
|
||||
// Batch
|
||||
var batchResults = Sar.Batch(bars);
|
||||
|
||||
for (int i = 0; i < bars.Count; i++)
|
||||
{
|
||||
Assert.Equal(streamResults[i], batchResults[i].Value, precision: 10);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TValue_Update_MatchesTBar_Update()
|
||||
{
|
||||
var ch1 = new Sar();
|
||||
var ch2 = new Sar();
|
||||
|
||||
double[] prices = [100, 102, 98, 105, 99, 103, 107, 95, 110, 108];
|
||||
|
||||
for (int i = 0; i < prices.Length; i++)
|
||||
{
|
||||
double p = prices[i];
|
||||
// TBar with equal OHLC
|
||||
_ = ch1.Update(new TBar(DateTime.UtcNow.AddMinutes(i), p, p, p, p, 0), isNew: true);
|
||||
// TValue
|
||||
_ = ch2.Update(new TValue(DateTime.UtcNow.AddMinutes(i), p), isNew: true);
|
||||
}
|
||||
|
||||
Assert.Equal(ch1.SarValue, ch2.SarValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reversal_DetectedOnPriceCrossover()
|
||||
{
|
||||
var sar = new Sar();
|
||||
var dt = DateTime.UtcNow;
|
||||
|
||||
// Start in uptrend
|
||||
_ = sar.Update(new TBar(dt, 100, 90, 95, 105, 1000), isNew: true);
|
||||
Assert.True(sar.IsLong);
|
||||
|
||||
// Continue uptrend
|
||||
for (int i = 1; i <= 5; i++)
|
||||
{
|
||||
double price = 105 + i * 2;
|
||||
_ = sar.Update(new TBar(dt.AddMinutes(i),
|
||||
price + 1, price - 1, price + 0.5, price, 1000), isNew: true);
|
||||
}
|
||||
Assert.True(sar.IsLong);
|
||||
|
||||
// Sharp reversal — price drops below SAR
|
||||
double sarBeforeReversal = sar.SarValue;
|
||||
_ = sar.Update(new TBar(dt.AddMinutes(10),
|
||||
sarBeforeReversal - 5, sarBeforeReversal - 20,
|
||||
sarBeforeReversal - 18, sarBeforeReversal - 15, 1000), isNew: true);
|
||||
|
||||
Assert.False(sar.IsLong, "Should reverse to short after price crosses below SAR");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Update_TSeries_MatchesStreaming()
|
||||
{
|
||||
var bars = CreateGbmBars(100);
|
||||
|
||||
// Streaming
|
||||
var streaming = new Sar();
|
||||
for (int i = 0; i < bars.Count; i++)
|
||||
{
|
||||
_ = streaming.Update(bars[i], isNew: true);
|
||||
}
|
||||
double streamLast = streaming.SarValue;
|
||||
|
||||
// TSeries batch
|
||||
var batch = new Sar();
|
||||
_ = batch.Update(bars);
|
||||
|
||||
Assert.Equal(streamLast, batch.SarValue, precision: 10);
|
||||
}
|
||||
}
|
||||
|
||||
// ── G) Span API Tests ────────────────────────────────────────────────────
|
||||
public sealed class SarSpanTests
|
||||
{
|
||||
[Fact]
|
||||
public void Batch_Span_InvalidAfStart_Throws()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() =>
|
||||
Sar.Batch(new double[10], new double[10], new double[10], new double[10], new double[10], afStart: 0));
|
||||
Assert.Equal("afStart", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Batch_Span_MismatchedLengths_Throws()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() =>
|
||||
Sar.Batch(new double[10], new double[10], new double[5], new double[10], new double[10]));
|
||||
Assert.Equal("high", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Batch_Span_OutputTooShort_Throws()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() =>
|
||||
Sar.Batch(new double[10], new double[10], new double[10], new double[10], new double[5]));
|
||||
Assert.Equal("output", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Batch_Span_Empty_NoException()
|
||||
{
|
||||
var output = Array.Empty<double>();
|
||||
var ex = Record.Exception(() =>
|
||||
Sar.Batch(ReadOnlySpan<double>.Empty, ReadOnlySpan<double>.Empty,
|
||||
ReadOnlySpan<double>.Empty, ReadOnlySpan<double>.Empty, output.AsSpan()));
|
||||
Assert.Null(ex);
|
||||
}
|
||||
}
|
||||
|
||||
// ── H) Event / Chainability ──────────────────────────────────────────────
|
||||
public sealed class SarEventTests
|
||||
{
|
||||
[Fact]
|
||||
public void Pub_FiresOnUpdate()
|
||||
{
|
||||
var sar = new Sar();
|
||||
int fireCount = 0;
|
||||
|
||||
sar.Pub += (object? _, in TValueEventArgs _e) => { fireCount++; };
|
||||
|
||||
_ = sar.Update(new TBar(DateTime.UtcNow, 100, 95, 98, 97, 1000));
|
||||
|
||||
Assert.Equal(1, fireCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pub_FiresOnEachUpdate()
|
||||
{
|
||||
var sar = new Sar();
|
||||
int fireCount = 0;
|
||||
|
||||
sar.Pub += (object? _, in TValueEventArgs _e) => { fireCount++; };
|
||||
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
double price = 100.0 + i;
|
||||
_ = sar.Update(new TBar(DateTime.UtcNow.AddMinutes(i), price + 2, price - 2, price + 1, price, 1000));
|
||||
}
|
||||
|
||||
Assert.Equal(5, fireCount);
|
||||
}
|
||||
}
|
||||
|
||||
// ── I) Prime Tests ───────────────────────────────────────────────────────
|
||||
public sealed class SarPrimeTests
|
||||
{
|
||||
[Fact]
|
||||
public void Prime_TBarSeries_SetsState()
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100.0, mu: 0.05, sigma: 0.20, seed: 42);
|
||||
var bars = gbm.Fetch(50, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
|
||||
var sar = new Sar();
|
||||
sar.Prime(bars);
|
||||
|
||||
Assert.True(sar.IsHot);
|
||||
Assert.True(double.IsFinite(sar.SarValue));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Prime_EmptySource_NoException()
|
||||
{
|
||||
var sar = new Sar();
|
||||
var bars = new TBarSeries();
|
||||
|
||||
var ex = Record.Exception(() => sar.Prime(bars));
|
||||
Assert.Null(ex);
|
||||
Assert.False(sar.IsHot);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
// SAR Validation Tests - Parabolic Stop And Reverse
|
||||
// Cross-validated against Skender.Stock.Indicators GetParabolicSar(), TALib SAR, and OoplesFinance CalculateParabolicSAR.
|
||||
|
||||
using OoplesFinance.StockIndicators;
|
||||
using OoplesFinance.StockIndicators.Models;
|
||||
using Skender.Stock.Indicators;
|
||||
using TALib;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public sealed class SarValidationTests
|
||||
{
|
||||
private static TBarSeries CreateGbmBars(int count = 500, int seed = 42)
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100.0, mu: 0.05, sigma: 0.20, seed: seed);
|
||||
return gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
}
|
||||
|
||||
// ── Cross-library: Skender ───────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void StreamingMatchesSkender()
|
||||
{
|
||||
var _data = new ValidationTestData();
|
||||
|
||||
// Skender: GetParabolicSar(accelerationStep, maxAccelerationFactor, initialFactor)
|
||||
var skenderResults = _data.SkenderQuotes
|
||||
.GetParabolicSar(0.02, 0.2, 0.02)
|
||||
.ToList();
|
||||
|
||||
// QuanTAlib streaming
|
||||
var sar = new Sar(afStart: 0.02, afIncrement: 0.02, afMax: 0.20);
|
||||
var ourValues = new double[_data.Bars.Count];
|
||||
for (int i = 0; i < _data.Bars.Count; i++)
|
||||
{
|
||||
_ = sar.Update(_data.Bars[i], isNew: true);
|
||||
ourValues[i] = sar.SarValue;
|
||||
}
|
||||
|
||||
// Compare warm values (skip first bar where SAR is initialization)
|
||||
int matched = 0;
|
||||
for (int i = 2; i < skenderResults.Count && i < _data.Bars.Count; i++)
|
||||
{
|
||||
if (skenderResults[i].Sar.HasValue && double.IsFinite(ourValues[i]))
|
||||
{
|
||||
Assert.Equal(
|
||||
skenderResults[i].Sar!.Value,
|
||||
ourValues[i],
|
||||
precision: 6);
|
||||
matched++;
|
||||
}
|
||||
}
|
||||
|
||||
Assert.True(matched > 0, "Should have matched at least one warm value");
|
||||
_data.Dispose();
|
||||
}
|
||||
|
||||
// ── Self-Consistency: Streaming == Batch ──────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void StreamingMatchesBatch()
|
||||
{
|
||||
var bars = CreateGbmBars();
|
||||
|
||||
// Streaming
|
||||
var streaming = new Sar();
|
||||
var streamValues = new double[bars.Count];
|
||||
for (int i = 0; i < bars.Count; i++)
|
||||
{
|
||||
_ = streaming.Update(bars[i], isNew: true);
|
||||
streamValues[i] = streaming.SarValue;
|
||||
}
|
||||
|
||||
// Batch
|
||||
var batchResults = Sar.Batch(bars);
|
||||
|
||||
for (int i = 0; i < bars.Count; i++)
|
||||
{
|
||||
Assert.Equal(streamValues[i], batchResults[i].Value, precision: 10);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Self-Consistency: Streaming == Span ───────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void StreamingMatchesSpan()
|
||||
{
|
||||
var bars = CreateGbmBars();
|
||||
|
||||
// Streaming
|
||||
var streaming = new Sar();
|
||||
var streamValues = new double[bars.Count];
|
||||
for (int i = 0; i < bars.Count; i++)
|
||||
{
|
||||
_ = streaming.Update(bars[i], isNew: true);
|
||||
streamValues[i] = streaming.SarValue;
|
||||
}
|
||||
|
||||
// Span
|
||||
var spanOutput = new double[bars.Count];
|
||||
Sar.Batch(bars.OpenValues, bars.HighValues, bars.LowValues, bars.CloseValues, spanOutput);
|
||||
|
||||
for (int i = 0; i < bars.Count; i++)
|
||||
{
|
||||
Assert.Equal(streamValues[i], spanOutput[i], precision: 10);
|
||||
}
|
||||
}
|
||||
|
||||
// ── AF Sensitivity ───────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void HigherAfStart_TighterTrailingStop()
|
||||
{
|
||||
var bars = CreateGbmBars(count: 100);
|
||||
|
||||
var slow = new Sar(afStart: 0.01, afIncrement: 0.01, afMax: 0.20);
|
||||
var fast = new Sar(afStart: 0.10, afIncrement: 0.05, afMax: 0.50);
|
||||
|
||||
for (int i = 0; i < bars.Count; i++)
|
||||
{
|
||||
_ = slow.Update(bars[i], isNew: true);
|
||||
_ = fast.Update(bars[i], isNew: true);
|
||||
}
|
||||
|
||||
// Higher AF = more responsive = SAR closer to price
|
||||
// Just verify both produce finite output (direction depends on data)
|
||||
Assert.True(double.IsFinite(slow.SarValue));
|
||||
Assert.True(double.IsFinite(fast.SarValue));
|
||||
}
|
||||
|
||||
// ── Determinism ──────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void SameInput_ProducesSameOutput()
|
||||
{
|
||||
var bars = CreateGbmBars(count: 200, seed: 123);
|
||||
|
||||
var psar1 = new Sar();
|
||||
var psar2 = new Sar();
|
||||
|
||||
for (int i = 0; i < bars.Count; i++)
|
||||
{
|
||||
_ = psar1.Update(bars[i], isNew: true);
|
||||
_ = psar2.Update(bars[i], isNew: true);
|
||||
}
|
||||
|
||||
Assert.Equal(psar1.SarValue, psar2.SarValue);
|
||||
}
|
||||
|
||||
// ── Calculate Returns Valid Indicator ─────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Calculate_ReturnsValidIndicatorAndResults()
|
||||
{
|
||||
var bars = CreateGbmBars(count: 100);
|
||||
|
||||
var (results, indicator) = Sar.Calculate(bars);
|
||||
|
||||
Assert.NotNull(results);
|
||||
Assert.Equal(bars.Count, results.Count);
|
||||
Assert.True(indicator.IsHot);
|
||||
Assert.True(double.IsFinite(indicator.SarValue));
|
||||
}
|
||||
|
||||
// ── Reversal Count Is Reasonable ─────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void ReversalCount_IsReasonable()
|
||||
{
|
||||
var bars = CreateGbmBars(count: 500);
|
||||
var sar = new Sar();
|
||||
|
||||
int reversals = 0;
|
||||
bool prevIsLong = true;
|
||||
|
||||
for (int i = 0; i < bars.Count; i++)
|
||||
{
|
||||
_ = sar.Update(bars[i], isNew: true);
|
||||
|
||||
if (i > 0 && sar.IsLong != prevIsLong)
|
||||
{
|
||||
reversals++;
|
||||
}
|
||||
prevIsLong = sar.IsLong;
|
||||
}
|
||||
|
||||
// In 500 bars of GBM data, expect several reversals but not every bar
|
||||
Assert.True(reversals > 5, $"Expected > 5 reversals, got {reversals}");
|
||||
Assert.True(reversals < 250, $"Expected < 250 reversals, got {reversals}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void StreamingMatchesTalib()
|
||||
{
|
||||
/* TALib SAR uses the same Wilder parabolic SAR formula as QuanTAlib.
|
||||
Parameters: accelerationFactor=0.02 (step), maximum=0.20 (cap).
|
||||
Initialization differences produce a short divergence; values converge after first reversal.
|
||||
We accept up to 2% mismatch for edge-of-reversal rounding at period boundaries. */
|
||||
|
||||
var _data = new ValidationTestData();
|
||||
|
||||
double[] highData = _data.Bars.High.Values.ToArray();
|
||||
double[] lowData = _data.Bars.Low.Values.ToArray();
|
||||
double[] taOut = new double[_data.Bars.Count];
|
||||
|
||||
const double afStep = 0.02;
|
||||
const double afMax = 0.20;
|
||||
|
||||
var retCode = Functions.Sar<double>(
|
||||
highData, lowData,
|
||||
0..^0, taOut, out var outRange,
|
||||
afStep, afMax);
|
||||
Assert.Equal(TALib.Core.RetCode.Success, retCode);
|
||||
|
||||
(int offset, int length) = outRange.GetOffsetAndLength(taOut.Length);
|
||||
Assert.True(length > 100, $"TALib SAR produced only {length} values");
|
||||
|
||||
// QuanTAlib streaming
|
||||
var sar = new Sar(afStart: afStep, afIncrement: afStep, afMax: afMax);
|
||||
var qlSar = new double[_data.Bars.Count];
|
||||
for (int i = 0; i < _data.Bars.Count; i++)
|
||||
{
|
||||
_ = sar.Update(_data.Bars[i], isNew: true);
|
||||
qlSar[i] = sar.SarValue;
|
||||
}
|
||||
|
||||
// Skip the first ~5 bars (initialization divergence), then require exact match.
|
||||
int skipBars = 5;
|
||||
int compared = 0;
|
||||
int matched = 0;
|
||||
for (int j = skipBars; j < length; j++)
|
||||
{
|
||||
int qi = j + offset;
|
||||
if (!double.IsFinite(qlSar[qi]) || !double.IsFinite(taOut[j])) { continue; }
|
||||
compared++;
|
||||
double diff = Math.Abs(qlSar[qi] - taOut[j]);
|
||||
if (diff <= 1e-9) { matched++; }
|
||||
}
|
||||
|
||||
// After initialization, QuanTAlib and TALib SAR should converge fully.
|
||||
// Accept up to 2% mismatch for edge-of-reversal rounding at period boundaries.
|
||||
double matchRate = compared > 0 ? (double)matched / compared : 0;
|
||||
Assert.True(matchRate >= 0.98,
|
||||
$"TALib SAR match rate {matchRate:P1} ({matched}/{compared}) < 98% — unexpected divergence");
|
||||
|
||||
_data.Dispose();
|
||||
}
|
||||
|
||||
// ── Cross-library: OoplesFinance ────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Structural validation against Ooples <c>CalculateParabolicSAR</c>.
|
||||
/// Ooples SAR uses the same Wilder acceleration factor algorithm (start=0.02, increment=0.02, max=0.2).
|
||||
/// Cross-library numeric equality is not asserted because reversal-point initialization
|
||||
/// diverges across implementations when the very first bar direction is ambiguous.
|
||||
/// Both must produce finite, positive output on the same OHLCV data.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Sar_MatchesOoples_Structural()
|
||||
{
|
||||
var _data = new ValidationTestData();
|
||||
|
||||
var ooplesData = _data.SkenderQuotes.Select(q => new TickerData
|
||||
{
|
||||
Date = q.Date,
|
||||
Open = (double)q.Open,
|
||||
High = (double)q.High,
|
||||
Low = (double)q.Low,
|
||||
Close = (double)q.Close,
|
||||
Volume = (double)q.Volume
|
||||
}).ToList();
|
||||
|
||||
var stockData = new StockData(ooplesData);
|
||||
var oResult = stockData.CalculateParabolicSAR(start: 0.02, increment: 0.02, maximum: 0.2);
|
||||
var oValues = oResult.OutputValues.Values.First();
|
||||
|
||||
var sar = new Sar(afStart: 0.02, afIncrement: 0.02, afMax: 0.20);
|
||||
var qValues = new System.Collections.Generic.List<double>();
|
||||
foreach (var bar in _data.Data)
|
||||
{
|
||||
qValues.Add(sar.Update(bar).Value);
|
||||
}
|
||||
|
||||
Assert.True(oValues.Count > 0, "Ooples SAR must produce output");
|
||||
|
||||
int finiteCount = 0;
|
||||
int warmup = 5;
|
||||
for (int i = warmup; i < Math.Min(oValues.Count, qValues.Count); i++)
|
||||
{
|
||||
if (double.IsFinite(oValues[i]) && double.IsFinite(qValues[i]) && qValues[i] > 0)
|
||||
{
|
||||
finiteCount++;
|
||||
}
|
||||
}
|
||||
|
||||
Assert.True(finiteCount > 100, $"Expected >100 finite positive SAR pairs, got {finiteCount}");
|
||||
|
||||
_data.Dispose();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user