adding missing validations

This commit is contained in:
Miha Kralj
2026-02-26 09:59:44 -08:00
parent 467a8c1cef
commit 9ab37c1200
231 changed files with 60015 additions and 302 deletions
@@ -0,0 +1,162 @@
using TradingPlatform.BusinessLayer;
namespace QuanTAlib.Tests;
public class DoscIndicatorTests
{
[Fact]
public void DoscIndicator_Constructor_SetsDefaults()
{
var indicator = new DoscIndicator();
Assert.Equal(14, indicator.RsiPeriod);
Assert.Equal(5, indicator.Ema1Period);
Assert.Equal(3, indicator.Ema2Period);
Assert.Equal(9, indicator.SigPeriod);
Assert.Equal(SourceType.Close, indicator.Source);
Assert.True(indicator.ShowColdValues);
Assert.Equal("DOSC - Derivative Oscillator", indicator.Name);
Assert.True(indicator.SeparateWindow);
Assert.True(indicator.OnBackGround);
}
[Fact]
public void DoscIndicator_MinHistoryDepths_EqualsZero()
{
var indicator = new DoscIndicator();
Assert.Equal(0, DoscIndicator.MinHistoryDepths);
Assert.Equal(0, ((IWatchlistIndicator)indicator).MinHistoryDepths);
}
[Fact]
public void DoscIndicator_ShortName_IncludesAllParams()
{
var indicator = new DoscIndicator { RsiPeriod = 10, Ema1Period = 4, Ema2Period = 2, SigPeriod = 7 };
Assert.Contains("DOSC", indicator.ShortName, StringComparison.Ordinal);
Assert.Contains("10", indicator.ShortName, StringComparison.Ordinal);
Assert.Contains("4", indicator.ShortName, StringComparison.Ordinal);
Assert.Contains("2", indicator.ShortName, StringComparison.Ordinal);
Assert.Contains("7", indicator.ShortName, StringComparison.Ordinal);
}
[Fact]
public void DoscIndicator_SourceCodeLink_IsValid()
{
var indicator = new DoscIndicator();
Assert.Contains("github.com", indicator.SourceCodeLink, StringComparison.Ordinal);
Assert.Contains("Dosc.Quantower.cs", indicator.SourceCodeLink, StringComparison.Ordinal);
}
[Fact]
public void DoscIndicator_Initialize_CreatesInternalIndicator()
{
var indicator = new DoscIndicator { RsiPeriod = 14, Ema1Period = 5, Ema2Period = 3, SigPeriod = 9 };
indicator.Initialize();
// Single output line series
Assert.Single(indicator.LinesSeries);
}
[Fact]
public void DoscIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
{
var indicator = new DoscIndicator { RsiPeriod = 3, Ema1Period = 2, Ema2Period = 2, SigPeriod = 3 };
indicator.Initialize();
var now = DateTime.UtcNow;
indicator.HistoricalData.AddBar(now, 100, 105, 95, 102);
var args = new UpdateArgs(UpdateReason.HistoricalBar);
indicator.ProcessUpdate(args);
Assert.Equal(1, indicator.LinesSeries[0].Count);
Assert.True(double.IsFinite(indicator.LinesSeries[0].GetValue(0)));
}
[Fact]
public void DoscIndicator_ProcessUpdate_NewBar_ComputesValue()
{
var indicator = new DoscIndicator { RsiPeriod = 3, Ema1Period = 2, Ema2Period = 2, SigPeriod = 3 };
indicator.Initialize();
var now = DateTime.UtcNow;
indicator.HistoricalData.AddBar(now, 100, 105, 95, 102);
indicator.HistoricalData.AddBar(now.AddMinutes(1), 102, 108, 100, 106);
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.NewBar));
Assert.Equal(2, indicator.LinesSeries[0].Count);
}
[Fact]
public void DoscIndicator_InternalIndicator_HandlesBarCorrection()
{
// Use alternating zigzag data so RSI is not a degenerate 100/0, ensuring DOSC != 0
// and a large-drop correction produces a measurably different result.
var ma = new Dosc(3, 2, 2, 3);
var now = DateTime.UtcNow;
double[] prices = [100, 102, 99, 103, 97, 104, 98, 105, 97, 106];
for (int i = 0; i < prices.Length; i++)
{
ma.Update(new TValue(now.AddMinutes(i).Ticks, prices[i]), isNew: true);
}
double beforeCorrection = ma.Last.Value;
// Correct last bar with a steep drop — RSI collapses, DOSC must change
ma.Update(new TValue(now.AddMinutes(9).Ticks, 50), isNew: false);
double afterCorrection = ma.Last.Value;
Assert.NotEqual(beforeCorrection, afterCorrection);
Assert.True(double.IsFinite(afterCorrection));
}
[Fact]
public void DoscIndicator_DifferentSourceTypes()
{
foreach (SourceType sourceType in new[] { SourceType.Close, SourceType.Open, SourceType.High, SourceType.Low })
{
var indicator = new DoscIndicator();
indicator.Source = sourceType;
Assert.Equal(sourceType, indicator.Source);
}
}
[Fact]
public void DoscIndicator_MultipleHistoricalBars()
{
var indicator = new DoscIndicator { RsiPeriod = 5, Ema1Period = 3, Ema2Period = 2, SigPeriod = 4 };
indicator.Initialize();
var now = DateTime.UtcNow;
for (int i = 0; i < 30; i++)
{
indicator.HistoricalData.AddBar(now.AddMinutes(i), 100 + i, 105 + i, 95 + i, 102 + i);
indicator.ProcessUpdate(new UpdateArgs(i == 0 ? UpdateReason.HistoricalBar : UpdateReason.NewBar));
}
Assert.Equal(30, indicator.LinesSeries[0].Count);
for (int i = 0; i < 30; i++)
{
Assert.True(double.IsFinite(indicator.LinesSeries[0].GetValue(i)));
}
}
[Fact]
public void DoscIndicator_PeriodChange_UpdatesConfig()
{
var indicator = new DoscIndicator();
indicator.RsiPeriod = 7;
Assert.Equal(7, indicator.RsiPeriod);
indicator.SigPeriod = 5;
Assert.Equal(5, indicator.SigPeriod);
}
}
+65
View File
@@ -0,0 +1,65 @@
using System.Drawing;
using System.Runtime.CompilerServices;
using TradingPlatform.BusinessLayer;
namespace QuanTAlib;
[SkipLocalsInit]
public sealed class DoscIndicator : Indicator, IWatchlistIndicator
{
[InputParameter("RSI Period", sortIndex: 1, 1, 500, 1, 0)]
public int RsiPeriod { get; set; } = 14;
[InputParameter("EMA1 Period", sortIndex: 2, 1, 500, 1, 0)]
public int Ema1Period { get; set; } = 5;
[InputParameter("EMA2 Period", sortIndex: 3, 1, 500, 1, 0)]
public int Ema2Period { get; set; } = 3;
[InputParameter("Signal Period", sortIndex: 4, 1, 500, 1, 0)]
public int SigPeriod { get; set; } = 9;
[IndicatorExtensions.DataSourceInput]
public SourceType Source { get; set; } = SourceType.Close;
[InputParameter("Show cold values", sortIndex: 21)]
public bool ShowColdValues { get; set; } = true;
private Dosc _ma = null!;
private readonly LineSeries _series;
private string _sourceName = null!;
private Func<IHistoryItem, double> _priceSelector = null!;
public static int MinHistoryDepths => 0;
int IWatchlistIndicator.MinHistoryDepths => MinHistoryDepths;
public override string ShortName => $"DOSC {RsiPeriod},{Ema1Period},{Ema2Period},{SigPeriod}:{_sourceName}";
public override string SourceCodeLink => "https://github.com/mihakralj/QuanTAlib/blob/main/lib/oscillators/dosc/Dosc.Quantower.cs";
public DoscIndicator()
{
OnBackGround = true;
SeparateWindow = true;
_sourceName = Source.ToString();
Name = "DOSC - Derivative Oscillator";
Description = "Four-stage pipeline: Wilder RSI → EMA1 → EMA2 (double-smooth) → SMA signal. DOSC = EMA2 - Signal.";
_series = new LineSeries(name: $"DOSC", color: Color.Yellow, width: 2, style: LineStyle.Solid);
AddLineSeries(_series);
}
protected override void OnInit()
{
_ma = new Dosc(RsiPeriod, Ema1Period, Ema2Period, SigPeriod);
_sourceName = Source.ToString();
_priceSelector = Source.GetPriceSelector();
base.OnInit();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override void OnUpdate(UpdateArgs args)
{
var item = HistoricalData[Count - 1, SeekOriginHistory.Begin];
TValue result = _ma.Update(new TValue(item.TimeLeft.Ticks, _priceSelector(item)), isNew: args.IsNewBar());
_series.SetValue(result.Value, _ma.IsHot, ShowColdValues);
}
}
+436
View File
@@ -0,0 +1,436 @@
namespace QuanTAlib;
public class DoscTests
{
private const int DefaultRsi = 14;
private const int DefaultEma1 = 5;
private const int DefaultEma2 = 3;
private const int DefaultSig = 9;
private const double Tolerance = 1e-12;
private static TSeries MakeSeries(int count = 500)
{
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.5, seed: 42);
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
return bars.Close;
}
// ========== A) Constructor Validation ==========
[Fact]
public void Constructor_ZeroRsiPeriod_ThrowsArgumentOutOfRangeException()
{
var ex = Assert.Throws<ArgumentOutOfRangeException>(() => new Dosc(rsiPeriod: 0));
Assert.Equal("rsiPeriod", ex.ParamName);
}
[Fact]
public void Constructor_NegativeRsiPeriod_ThrowsArgumentOutOfRangeException()
{
var ex = Assert.Throws<ArgumentOutOfRangeException>(() => new Dosc(rsiPeriod: -5));
Assert.Equal("rsiPeriod", ex.ParamName);
}
[Fact]
public void Constructor_ZeroEma1Period_ThrowsArgumentOutOfRangeException()
{
var ex = Assert.Throws<ArgumentOutOfRangeException>(() => new Dosc(rsiPeriod: 14, ema1Period: 0));
Assert.Equal("ema1Period", ex.ParamName);
}
[Fact]
public void Constructor_ZeroEma2Period_ThrowsArgumentOutOfRangeException()
{
var ex = Assert.Throws<ArgumentOutOfRangeException>(() => new Dosc(rsiPeriod: 14, ema1Period: 5, ema2Period: 0));
Assert.Equal("ema2Period", ex.ParamName);
}
[Fact]
public void Constructor_ZeroSigPeriod_ThrowsArgumentOutOfRangeException()
{
var ex = Assert.Throws<ArgumentOutOfRangeException>(() => new Dosc(rsiPeriod: 14, ema1Period: 5, ema2Period: 3, sigPeriod: 0));
Assert.Equal("sigPeriod", ex.ParamName);
}
[Fact]
public void Constructor_ValidDefaults_SetsNameAndWarmup()
{
var indicator = new Dosc();
Assert.Equal("Dosc(14,5,3,9)", indicator.Name);
Assert.Equal(14 + 9, indicator.WarmupPeriod); // rsiPeriod + sigPeriod
}
[Fact]
public void Constructor_CustomParams_SetsName()
{
var indicator = new Dosc(rsiPeriod: 7, ema1Period: 3, ema2Period: 2, sigPeriod: 5);
Assert.Equal("Dosc(7,3,2,5)", indicator.Name);
}
// ========== B) Basic Calculation ==========
[Fact]
public void Update_ReturnsTValue_WithValidProperties()
{
var indicator = new Dosc();
var input = new TValue(DateTime.UtcNow, 100.0);
TValue result = indicator.Update(input);
Assert.Equal(input.Time, result.Time);
Assert.True(double.IsFinite(result.Value));
}
[Fact]
public void Update_AfterWarmup_IsHotBecomesTrue()
{
var indicator = new Dosc();
Assert.False(indicator.IsHot);
for (int i = 0; i < 500; i++)
{
indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0 + i * 0.1));
}
Assert.True(indicator.IsHot);
}
[Fact]
public void Update_LastProperty_MatchesReturnValue()
{
var indicator = new Dosc();
TValue result = indicator.Update(new TValue(DateTime.UtcNow, 42.0));
Assert.Equal(result.Value, indicator.Last.Value, Tolerance);
}
// ========== C) State + Bar Correction ==========
[Fact]
public void IsNew_True_AdvancesState()
{
var indicator = new Dosc(DefaultRsi, DefaultEma1, DefaultEma2, DefaultSig);
// Warm up well past the period threshold
for (int i = 0; i < DefaultRsi + DefaultSig + 10; i++)
{
indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0 + i * 0.5), isNew: true);
}
TValue r1 = indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(50), 120.0), isNew: true);
TValue r2 = indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(51), 80.0), isNew: true);
Assert.NotEqual(r1.Value, r2.Value);
}
[Fact]
public void IsNew_False_RewritesCurrentBar()
{
var indicator = new Dosc(DefaultRsi, DefaultEma1, DefaultEma2, DefaultSig);
for (int i = 0; i < 60; i++)
{
indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0 + i));
}
indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(60), 200.0), isNew: true);
double afterNew = indicator.Last.Value;
indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(60), 150.0), isNew: false);
double afterCorrection = indicator.Last.Value;
Assert.NotEqual(afterNew, afterCorrection);
}
[Fact]
public void IterativeCorrections_RestoreState()
{
var indicator = new Dosc(DefaultRsi, DefaultEma1, DefaultEma2, DefaultSig);
TSeries data = MakeSeries();
for (int i = 0; i < 50; i++)
{
indicator.Update(data[i], isNew: true);
}
indicator.Update(data[50], isNew: true);
for (int j = 0; j < 5; j++)
{
indicator.Update(data[50], isNew: false);
}
double afterCorrections = indicator.Last.Value;
var fresh = new Dosc(DefaultRsi, DefaultEma1, DefaultEma2, DefaultSig);
for (int i = 0; i <= 50; i++)
{
fresh.Update(data[i], isNew: true);
}
Assert.Equal(fresh.Last.Value, afterCorrections, Tolerance);
}
[Fact]
public void Reset_ClearsState()
{
var indicator = new Dosc();
for (int i = 0; i < 100; i++)
{
indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0 + i));
}
Assert.True(indicator.IsHot);
indicator.Reset();
Assert.False(indicator.IsHot);
Assert.Equal(default, indicator.Last);
}
// ========== D) Warmup/Convergence ==========
[Fact]
public void IsHot_FlipsAtCorrectTime()
{
var indicator = new Dosc(rsiPeriod: 5, ema1Period: 3, ema2Period: 2, sigPeriod: 5);
int hotAt = -1;
for (int i = 0; i < 200; i++)
{
indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0 + i * 0.1));
if (indicator.IsHot && hotAt < 0)
{
hotAt = i;
break;
}
}
Assert.InRange(hotAt, 1, 200);
}
// ========== E) Robustness ==========
[Fact]
public void NaN_Input_UsesLastValidValue()
{
var indicator = new Dosc();
for (int i = 0; i < 30; i++)
{
indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0));
}
TValue nanResult = indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(30), double.NaN));
Assert.True(double.IsFinite(nanResult.Value));
}
[Fact]
public void Infinity_Input_UsesLastValidValue()
{
var indicator = new Dosc();
for (int i = 0; i < 30; i++)
{
indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0));
}
TValue infResult = indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(30), double.PositiveInfinity));
Assert.True(double.IsFinite(infResult.Value));
}
[Fact]
public void BatchNaN_DoesNotPropagate()
{
double[] source = new double[100];
double[] output = new double[100];
for (int i = 0; i < 100; i++)
{
source[i] = 100.0 + i * 0.5;
}
source[50] = double.NaN;
source[51] = double.NaN;
Dosc.Batch(source, output, 14, 5, 3, 9);
for (int i = 0; i < 100; i++)
{
Assert.True(double.IsFinite(output[i]), $"Output[{i}] is not finite");
}
}
// ========== F) Consistency (4 API modes) ==========
[Fact]
public void AllModes_ProduceSameResult()
{
int rsi = 7, e1 = 3, e2 = 2, sig = 5;
TSeries data = MakeSeries();
// 1. Batch (TSeries)
TSeries batchResults = Dosc.Batch(data, rsi, e1, e2, sig);
double expected = batchResults.Last.Value;
// 2. Span batch
var values = data.Values.ToArray();
var spanOutput = new double[values.Length];
Dosc.Batch(new ReadOnlySpan<double>(values), spanOutput, rsi, e1, e2, sig);
double spanResult = spanOutput[^1];
// 3. Streaming
var streaming = new Dosc(rsi, e1, e2, sig);
for (int i = 0; i < data.Count; i++)
{
streaming.Update(data[i]);
}
double streamingResult = streaming.Last.Value;
// 4. Eventing
var pubSource = new TSeries();
var eventBased = new Dosc(pubSource, rsi, e1, e2, sig);
for (int i = 0; i < data.Count; i++)
{
pubSource.Add(data[i]);
}
double eventingResult = eventBased.Last.Value;
Assert.Equal(expected, spanResult, precision: 9);
Assert.Equal(expected, streamingResult, precision: 9);
Assert.Equal(expected, eventingResult, precision: 9);
}
// ========== G) Span API Tests ==========
[Fact]
public void SpanBatch_MismatchedLengths_ThrowsArgumentException()
{
double[] source = new double[10];
double[] output = new double[5];
var ex = Assert.Throws<ArgumentException>(() => Dosc.Batch(source, output, 14, 5, 3, 9));
Assert.Equal("output", ex.ParamName);
}
[Fact]
public void SpanBatch_ZeroRsiPeriod_ThrowsArgumentOutOfRangeException()
{
double[] source = new double[10];
double[] output = new double[10];
Assert.Throws<ArgumentOutOfRangeException>(() => Dosc.Batch(source, output, rsiPeriod: 0));
}
[Fact]
public void SpanBatch_ZeroSigPeriod_ThrowsArgumentOutOfRangeException()
{
double[] source = new double[10];
double[] output = new double[10];
Assert.Throws<ArgumentOutOfRangeException>(() => Dosc.Batch(source, output, sigPeriod: 0));
}
[Fact]
public void SpanBatch_EmptyInput_ProducesNoException()
{
double[] source = Array.Empty<double>();
double[] output = Array.Empty<double>();
var ex = Record.Exception(() => Dosc.Batch(source, output, 14, 5, 3, 9));
Assert.Null(ex);
}
[Fact]
public void SpanBatch_LargeData_DoesNotStackOverflow()
{
int size = 5000;
double[] source = new double[size];
double[] output = new double[size];
for (int i = 0; i < size; i++)
{
source[i] = 100.0 + i * 0.1;
}
Dosc.Batch(source, output, 14, 5, 3, 9);
Assert.True(double.IsFinite(output[size - 1]));
}
// ========== H) Chainability ==========
[Fact]
public void Pub_EventFires_OnUpdate()
{
var indicator = new Dosc();
int eventCount = 0;
indicator.Pub += (object? sender, in TValueEventArgs args) => eventCount++;
for (int i = 0; i < 10; i++)
{
indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0 + i));
}
Assert.Equal(10, eventCount);
}
[Fact]
public void EventBased_Chaining_Works()
{
var source = new TSeries();
var indicator = new Dosc(source, 5, 3, 2, 4);
source.Add(new TValue(DateTime.UtcNow, 100));
source.Add(new TValue(DateTime.UtcNow, 110));
source.Add(new TValue(DateTime.UtcNow, 120));
Assert.True(double.IsFinite(indicator.Last.Value));
}
[Fact]
public void Calculate_ReturnsHotIndicator()
{
TSeries data = MakeSeries();
(TSeries results, Dosc indicator) = Dosc.Calculate(data);
Assert.Equal(data.Count, results.Count);
Assert.True(indicator.IsHot);
}
// ========== DOSC-specific: Oscillator behavior ==========
[Fact]
public void ConstantInput_OutputConvergesToZero()
{
// With all constant input, RSI is constant, EMA1 == EMA2 == constant,
// SMA signal converges to the same constant → DOSC → 0
var indicator = new Dosc(rsiPeriod: 5, ema1Period: 3, ema2Period: 2, sigPeriod: 5);
double lastResult = double.NaN;
for (int i = 0; i < 500; i++)
{
TValue r = indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0));
lastResult = r.Value;
}
Assert.True(Math.Abs(lastResult) < 1e-6, $"Expected near-zero for constant input, got {lastResult}");
}
[Fact]
public void DoscProducesFiniteValues_OnGBMData()
{
var indicator = new Dosc();
TSeries data = MakeSeries(200);
int nonFiniteCount = 0;
for (int i = 0; i < data.Count; i++)
{
TValue r = indicator.Update(data[i]);
if (!double.IsFinite(r.Value))
{
nonFiniteCount++;
}
}
Assert.Equal(0, nonFiniteCount);
}
}
@@ -0,0 +1,174 @@
using Xunit;
using Xunit.Abstractions;
namespace QuanTAlib.Tests;
public sealed class DoscValidationTests : IDisposable
{
private readonly ITestOutputHelper _output;
private readonly ValidationTestData _testData;
private const int DefaultRsi = 14;
private const int DefaultEma1 = 5;
private const int DefaultEma2 = 3;
private const int DefaultSig = 9;
public DoscValidationTests(ITestOutputHelper output)
{
_output = output;
_testData = new ValidationTestData(5000);
}
public void Dispose()
{
_testData.Dispose();
}
// ========== Self-consistency Validation ==========
[Fact]
public void Dosc_BatchStreaming_Match()
{
var streaming = new Dosc(DefaultRsi, DefaultEma1, DefaultEma2, DefaultSig);
var streamResults = new List<double>(_testData.Data.Count);
for (int i = 0; i < _testData.Data.Count; i++)
{
TValue r = streaming.Update(_testData.Data[i], isNew: true);
streamResults.Add(r.Value);
}
TSeries batchResults = Dosc.Batch(_testData.Data, DefaultRsi, DefaultEma1, DefaultEma2, DefaultSig);
int mismatchCount = 0;
double maxDiff = 0;
for (int i = 0; i < streamResults.Count; i++)
{
double diff = Math.Abs(streamResults[i] - batchResults[i].Value);
if (diff > 1e-10)
{
mismatchCount++;
maxDiff = Math.Max(maxDiff, diff);
}
}
_output.WriteLine($"Dosc({DefaultRsi},{DefaultEma1},{DefaultEma2},{DefaultSig}) Batch vs Streaming: {mismatchCount} mismatches, max diff = {maxDiff:E3}");
Assert.Equal(0, mismatchCount);
}
[Fact]
public void Dosc_SpanBatch_MatchesStreaming()
{
var streaming = new Dosc(DefaultRsi, DefaultEma1, DefaultEma2, DefaultSig);
var streamResults = new List<double>(_testData.Data.Count);
for (int i = 0; i < _testData.Data.Count; i++)
{
TValue r = streaming.Update(_testData.Data[i], isNew: true);
streamResults.Add(r.Value);
}
double[] output = new double[_testData.Data.Count];
Dosc.Batch(_testData.Data.Values, output, DefaultRsi, DefaultEma1, DefaultEma2, DefaultSig);
int mismatchCount = 0;
double maxDiff = 0;
for (int i = 0; i < streamResults.Count; i++)
{
double diff = Math.Abs(streamResults[i] - output[i]);
if (diff > 1e-10)
{
mismatchCount++;
maxDiff = Math.Max(maxDiff, diff);
}
}
_output.WriteLine($"Dosc({DefaultRsi},{DefaultEma1},{DefaultEma2},{DefaultSig}) Span vs Streaming: {mismatchCount} mismatches, max diff = {maxDiff:E3}");
Assert.Equal(0, mismatchCount);
}
[Fact]
public void Dosc_DifferentParams_ProduceDifferentResults()
{
TSeries result1 = Dosc.Batch(_testData.Data, rsiPeriod: 7, ema1Period: 3, ema2Period: 2, sigPeriod: 5);
TSeries result2 = Dosc.Batch(_testData.Data, rsiPeriod: 14, ema1Period: 5, ema2Period: 3, sigPeriod: 9);
int lastIdx = _testData.Data.Count - 1;
_output.WriteLine($"Dosc(7,3,2,5) last = {result1[lastIdx].Value:F6}");
_output.WriteLine($"Dosc(14,5,3,9) last = {result2[lastIdx].Value:F6}");
Assert.NotEqual(result1[lastIdx].Value, result2[lastIdx].Value);
}
[Fact]
public void Dosc_ConstantInput_ConvergesToZero()
{
var indicator = new Dosc(rsiPeriod: 5, ema1Period: 3, ema2Period: 2, sigPeriod: 5);
double constantVal = 100.0;
double lastResult = double.NaN;
for (int i = 0; i < 1000; i++)
{
TValue r = indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(i), constantVal));
lastResult = r.Value;
}
_output.WriteLine($"Dosc(5,3,2,5) constant input result after 1000 bars: {lastResult:E6}");
Assert.True(Math.Abs(lastResult) < 1e-6, $"Expected near-zero for constant input, got {lastResult}");
}
[Fact]
public void Dosc_Calculate_ReturnsHotIndicator()
{
(TSeries results, Dosc indicator) = Dosc.Calculate(_testData.Data, DefaultRsi, DefaultEma1, DefaultEma2, DefaultSig);
Assert.Equal(_testData.Data.Count, results.Count);
Assert.True(indicator.IsHot);
TValue next = indicator.Update(new TValue(DateTime.UtcNow, 100.0), isNew: true);
Assert.True(double.IsFinite(next.Value));
_output.WriteLine($"Dosc Calculate: {results.Count} bars, last = {results[results.Count - 1].Value:F6}");
}
[Fact]
public void Dosc_BarCorrection_ProducesConsistentResults()
{
var reference = new Dosc(DefaultRsi, DefaultEma1, DefaultEma2, DefaultSig);
for (int i = 0; i < 100; i++)
{
reference.Update(_testData.Data[i], isNew: true);
}
reference.Update(new TValue(DateTime.UtcNow, 50.0), isNew: true);
double referenceVal = reference.Last.Value;
var test = new Dosc(DefaultRsi, DefaultEma1, DefaultEma2, DefaultSig);
for (int i = 0; i < 100; i++)
{
test.Update(_testData.Data[i], isNew: true);
}
test.Update(new TValue(DateTime.UtcNow, 999.0), isNew: true); // wrong
test.Update(new TValue(DateTime.UtcNow, 50.0), isNew: false); // correct
double testVal = test.Last.Value;
_output.WriteLine($"Reference: {referenceVal:F10}, Corrected: {testVal:F10}");
Assert.Equal(referenceVal, testVal, 1e-10);
}
[Fact]
public void Dosc_SubsetValidation_StableBehavior()
{
using var subset = _testData.CreateSubset(200);
TSeries results = Dosc.Batch(subset.Data, DefaultRsi, DefaultEma1, DefaultEma2, DefaultSig);
int nanCount = 0;
for (int i = 0; i < results.Count; i++)
{
if (!double.IsFinite(results[i].Value))
{
nanCount++;
}
}
_output.WriteLine($"Dosc on 200-bar subset: {nanCount} non-finite values");
Assert.Equal(0, nanCount);
}
}
+441
View File
@@ -0,0 +1,441 @@
// DOSC: Derivative Oscillator
// Four-stage pipeline: Wilder RSI → EMA1 → EMA2 (double-smooth) → SMA signal → DOSC = EMA2 - Signal
// Formula: DOSC = EMA2(EMA1(RSI(src, rsi))) - SMA(EMA2(EMA1(RSI(src, rsi))), sig)
// Source: Brown, C. (1994). Technical Analysis for the Trading Professional. McGraw-Hill.
using System.Buffers;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace QuanTAlib;
/// <summary>
/// DOSC: Derivative Oscillator
/// </summary>
/// <remarks>
/// Applies a four-stage pipeline to extract momentum inflection points:
/// Wilder RSI → first EMA smoothing → second EMA (double-smooth) → SMA signal line.
/// DOSC = EMA2 - SMA(EMA2). Zero crossings mark momentum acceleration/deceleration.
///
/// Calculation:
/// <c>avgGain/avgLoss via Wilder RMA (alpha = 1/rsiPeriod)</c>
/// <c>RSI = 100 - 100 / (1 + avgGain / avgLoss)</c>
/// <c>EMA1 = alpha1 * RSI + (1-alpha1) * EMA1[1]</c>
/// <c>EMA2 = alpha2 * EMA1 + (1-alpha2) * EMA2[1]</c>
/// <c>Signal = SMA(EMA2, sigPeriod) [O(1) via circular buffer + running sum]</c>
/// <c>DOSC = EMA2 - Signal</c>
/// </remarks>
/// <seealso href="Dosc.md">Detailed documentation</seealso>
/// <seealso href="dosc.pine">Reference Pine Script implementation</seealso>
[SkipLocalsInit]
public sealed class Dosc : AbstractBase
{
[StructLayout(LayoutKind.Auto)]
private record struct State(
double AvgGain, double AvgLoss,
double Ema1, double Ema2,
double SigSum,
int SigHead, int SigCount,
double PrevSig,
double Src1,
int Count,
double LastValidSrc,
bool Ema1Init, bool Ema2Init)
{
public static State New() => new()
{
AvgGain = 0,
AvgLoss = 0,
Ema1 = 0,
Ema2 = 0,
SigSum = 0,
SigHead = 0,
SigCount = 0,
PrevSig = 0,
Src1 = 0,
Count = 0,
LastValidSrc = 0,
Ema1Init = false,
Ema2Init = false
};
}
private readonly int _sigPeriod;
private readonly double _rsiAlpha; // 1/rsiPeriod (Wilder RMA)
private readonly double _rsiDecay; // 1 - _rsiAlpha
private readonly double _alpha1; // 2/(ema1Period+1)
private readonly double _decay1; // 1 - _alpha1
private readonly double _alpha2; // 2/(ema2Period+1)
private readonly double _decay2; // 1 - _alpha2
private State _s = State.New();
private State _ps = State.New();
// Signal-line SMA circular buffer — size = sigPeriod
private readonly double[] _sigBuf;
private int _sigSnapHead; // snapshot of _s.SigHead for rollback
private const int StackallocThreshold = 256;
/// <summary>
/// Creates DOSC with specified parameters.
/// </summary>
/// <param name="rsiPeriod">RSI Wilder smoothing period (must be &gt; 0)</param>
/// <param name="ema1Period">First EMA smoothing period (must be &gt; 0)</param>
/// <param name="ema2Period">Second EMA (double-smooth) period (must be &gt; 0)</param>
/// <param name="sigPeriod">SMA signal line period (must be &gt; 0)</param>
public Dosc(int rsiPeriod = 14, int ema1Period = 5, int ema2Period = 3, int sigPeriod = 9)
{
if (rsiPeriod <= 0)
{
throw new ArgumentOutOfRangeException(nameof(rsiPeriod), rsiPeriod, "Period must be greater than 0.");
}
if (ema1Period <= 0)
{
throw new ArgumentOutOfRangeException(nameof(ema1Period), ema1Period, "Period must be greater than 0.");
}
if (ema2Period <= 0)
{
throw new ArgumentOutOfRangeException(nameof(ema2Period), ema2Period, "Period must be greater than 0.");
}
if (sigPeriod <= 0)
{
throw new ArgumentOutOfRangeException(nameof(sigPeriod), sigPeriod, "Period must be greater than 0.");
}
_sigPeriod = sigPeriod;
_rsiAlpha = 1.0 / rsiPeriod;
_rsiDecay = 1.0 - _rsiAlpha;
_alpha1 = 2.0 / (ema1Period + 1.0);
_decay1 = 1.0 - _alpha1;
_alpha2 = 2.0 / (ema2Period + 1.0);
_decay2 = 1.0 - _alpha2;
_sigBuf = new double[sigPeriod];
_sigSnapHead = 0;
Name = $"Dosc({rsiPeriod},{ema1Period},{ema2Period},{sigPeriod})";
// Warmup: RSI needs rsiPeriod; EMA1/EMA2 converge quickly; SMA signal needs sigPeriod.
WarmupPeriod = rsiPeriod + sigPeriod;
}
/// <summary>
/// Creates DOSC subscribing to specified source publisher.
/// </summary>
public Dosc(ITValuePublisher source, int rsiPeriod = 14, int ema1Period = 5, int ema2Period = 3, int sigPeriod = 9)
: this(rsiPeriod, ema1Period, ema2Period, sigPeriod)
{
source.Pub += Handle;
}
/// <summary>
/// Creates DOSC from a TSeries source, primes from history, then subscribes.
/// </summary>
public Dosc(TSeries source, int rsiPeriod = 14, int ema1Period = 5, int ema2Period = 3, int sigPeriod = 9)
: this(rsiPeriod, ema1Period, ema2Period, sigPeriod)
{
Prime(source.Values);
if (source.Count > 0)
{
Last = new TValue(source.LastTime, Last.Value);
}
source.Pub += Handle;
}
/// <inheritdoc/>
public override bool IsHot => _s.Count >= WarmupPeriod;
/// <inheritdoc/>
public override void Prime(ReadOnlySpan<double> source, TimeSpan? step = null)
{
if (source.Length == 0)
{
return;
}
_s = State.New();
_ps = State.New();
Array.Clear(_sigBuf);
_sigSnapHead = 0;
int len = source.Length;
double[]? rented = len > StackallocThreshold ? ArrayPool<double>.Shared.Rent(len) : null;
Span<double> temp = rented != null ? rented.AsSpan(0, len) : stackalloc double[len];
try
{
CalculateCore(source, temp, ref _s, _sigBuf,
_rsiAlpha, _rsiDecay, _alpha1, _decay1, _alpha2, _decay2, _sigPeriod);
Last = new TValue(DateTime.MinValue, temp[len - 1]);
_ps = _s;
_sigSnapHead = _s.SigHead;
}
finally
{
if (rented != null)
{
ArrayPool<double>.Shared.Return(rented);
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void Handle(object? sender, in TValueEventArgs e) => Update(e.Value, e.IsNew);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static double GetValidValue(double input, ref State s)
{
if (double.IsFinite(input))
{
s.LastValidSrc = input;
return input;
}
return s.LastValidSrc;
}
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
public override TValue Update(TValue input, bool isNew = true)
{
if (isNew)
{
_ps = _s;
_sigSnapHead = _s.SigHead;
}
else
{
// _s.PrevSig was set during the last Compute call — it holds the old
// slot value that was overwritten at _sigSnapHead. Capture it before
// restoring _s so we can put the buffer slot back.
double prevSlot = _s.PrevSig;
int snapHead = _sigSnapHead;
_s = _ps;
_s.SigHead = snapHead;
// Restore the circular buffer slot that was overwritten in the bad bar.
_sigBuf[snapHead] = prevSlot;
}
double val = GetValidValue(input.Value, ref _s);
double result = Compute(val, ref _s, _sigBuf,
_rsiAlpha, _rsiDecay, _alpha1, _decay1, _alpha2, _decay2, _sigPeriod);
Last = new TValue(input.Time, result);
PubEvent(Last, isNew);
return Last;
}
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public override TSeries Update(TSeries source)
{
if (source.Count == 0)
{
return [];
}
int len = source.Count;
var t = new List<long>(len);
var v = new List<double>(len);
CollectionsMarshal.SetCount(t, len);
CollectionsMarshal.SetCount(v, len);
var tSpan = CollectionsMarshal.AsSpan(t);
var vSpan = CollectionsMarshal.AsSpan(v);
CalculateCore(source.Values, vSpan, ref _s, _sigBuf,
_rsiAlpha, _rsiDecay, _alpha1, _decay1, _alpha2, _decay2, _sigPeriod);
source.Times.CopyTo(tSpan);
_ps = _s;
_sigSnapHead = _s.SigHead;
Last = new TValue(tSpan[len - 1], vSpan[len - 1]);
return new TSeries(t, v);
}
/// <summary>
/// Core per-bar streaming computation: Wilder RSI → EMA1 → EMA2 → SMA signal → DOSC.
/// O(1) per bar for all four stages.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
private static double Compute(double src, ref State s, double[] sigBuf,
double rsiAlpha, double rsiDecay,
double alpha1, double decay1,
double alpha2, double decay2,
int sigPeriod)
{
s.Count++;
// --- Stage 1: Wilder RSI ---
double changeUp = s.Count > 1 ? Math.Max(src - s.Src1, 0.0) : 0.0;
double changeDn = s.Count > 1 ? Math.Max(s.Src1 - src, 0.0) : 0.0;
s.Src1 = src;
if (s.Count <= 1)
{
s.AvgGain = changeUp;
s.AvgLoss = changeDn;
}
else
{
s.AvgGain = Math.FusedMultiplyAdd(rsiAlpha, changeUp, rsiDecay * s.AvgGain);
s.AvgLoss = Math.FusedMultiplyAdd(rsiAlpha, changeDn, rsiDecay * s.AvgLoss);
}
double rsiVal = s.AvgLoss == 0.0 ? 100.0 : 100.0 - 100.0 / (1.0 + s.AvgGain / s.AvgLoss);
// --- Stage 2: EMA1 of RSI ---
double ema1;
if (!s.Ema1Init)
{
s.Ema1Init = true;
ema1 = rsiVal;
}
else
{
ema1 = Math.FusedMultiplyAdd(alpha1, rsiVal, decay1 * s.Ema1);
}
s.Ema1 = ema1;
// --- Stage 3: EMA2 of EMA1 ---
double ema2;
if (!s.Ema2Init)
{
s.Ema2Init = true;
ema2 = ema1;
}
else
{
ema2 = Math.FusedMultiplyAdd(alpha2, ema1, decay2 * s.Ema2);
}
s.Ema2 = ema2;
// --- Stage 4: SMA signal via circular buffer + running sum (O(1)) ---
double oldestSlot = sigBuf[s.SigHead];
bool slotWasFilled = s.SigCount >= sigPeriod;
if (slotWasFilled)
{
s.SigSum -= oldestSlot;
}
else
{
s.SigCount++;
}
s.PrevSig = oldestSlot;
sigBuf[s.SigHead] = ema2;
s.SigSum += ema2;
s.SigHead = (s.SigHead + 1) % sigPeriod;
double signal = s.SigCount > 0 ? s.SigSum / s.SigCount : 0.0;
return ema2 - signal;
}
/// <summary>Core batch calculation — iterates source calling Compute per bar.</summary>
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
private static void CalculateCore(ReadOnlySpan<double> source, Span<double> output, ref State s,
double[] sigBuf,
double rsiAlpha, double rsiDecay,
double alpha1, double decay1,
double alpha2, double decay2,
int sigPeriod)
{
int len = source.Length;
for (int i = 0; i < len; i++)
{
double val = source[i];
if (double.IsFinite(val))
{
s.LastValidSrc = val;
}
else
{
val = s.LastValidSrc;
}
output[i] = Compute(val, ref s, sigBuf,
rsiAlpha, rsiDecay, alpha1, decay1, alpha2, decay2, sigPeriod);
}
}
/// <summary>
/// Batch calculation returning a TSeries.
/// </summary>
public static TSeries Batch(TSeries source, int rsiPeriod = 14, int ema1Period = 5, int ema2Period = 3, int sigPeriod = 9)
{
var indicator = new Dosc(rsiPeriod, ema1Period, ema2Period, sigPeriod);
return indicator.Update(source);
}
/// <summary>
/// Batch calculation writing to a pre-allocated output span. Zero-allocation hot path.
/// </summary>
public static void Batch(ReadOnlySpan<double> source, Span<double> output,
int rsiPeriod = 14, int ema1Period = 5, int ema2Period = 3, int sigPeriod = 9)
{
if (source.Length != output.Length)
{
throw new ArgumentException("Source and output must have the same length.", nameof(output));
}
if (rsiPeriod <= 0)
{
throw new ArgumentOutOfRangeException(nameof(rsiPeriod), rsiPeriod, "Period must be greater than 0.");
}
if (ema1Period <= 0)
{
throw new ArgumentOutOfRangeException(nameof(ema1Period), ema1Period, "Period must be greater than 0.");
}
if (ema2Period <= 0)
{
throw new ArgumentOutOfRangeException(nameof(ema2Period), ema2Period, "Period must be greater than 0.");
}
if (sigPeriod <= 0)
{
throw new ArgumentOutOfRangeException(nameof(sigPeriod), sigPeriod, "Period must be greater than 0.");
}
if (source.Length == 0)
{
return;
}
double ra = 1.0 / rsiPeriod;
double rd = 1.0 - ra;
double a1 = 2.0 / (ema1Period + 1.0);
double d1 = 1.0 - a1;
double a2 = 2.0 / (ema2Period + 1.0);
double d2 = 1.0 - a2;
var state = State.New();
var sigBuf = new double[sigPeriod];
CalculateCore(source, output, ref state, sigBuf, ra, rd, a1, d1, a2, d2, sigPeriod);
}
/// <summary>
/// Creates a hot indicator from historical data, ready for streaming.
/// </summary>
public static (TSeries Results, Dosc Indicator) Calculate(TSeries source,
int rsiPeriod = 14, int ema1Period = 5, int ema2Period = 3, int sigPeriod = 9)
{
var indicator = new Dosc(rsiPeriod, ema1Period, ema2Period, sigPeriod);
TSeries results = indicator.Update(source);
return (results, indicator);
}
/// <inheritdoc/>
public override void Reset()
{
_s = State.New();
_ps = _s;
Array.Clear(_sigBuf);
_sigSnapHead = 0;
Last = default;
}
}