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
+205
View File
@@ -0,0 +1,205 @@
using Xunit;
using TradingPlatform.BusinessLayer;
namespace QuanTAlib.Tests;
public class TdistIndicatorTests
{
[Fact]
public void TdistIndicator_Constructor_SetsDefaults()
{
var indicator = new TdistIndicator();
Assert.Equal(SourceType.Close, indicator.Source);
Assert.Equal(10, indicator.Nu);
Assert.Equal(14, indicator.Period);
Assert.True(indicator.ShowColdValues);
Assert.Equal("TDIST - Student's t-Distribution CDF", indicator.Name);
Assert.True(indicator.SeparateWindow);
Assert.True(indicator.OnBackGround);
}
[Fact]
public void TdistIndicator_MinHistoryDepths_EqualsPeriod()
{
var indicator = new TdistIndicator { Period = 30 };
Assert.Equal(30, indicator.MinHistoryDepths);
}
[Fact]
public void TdistIndicator_ShortName_IsCorrect()
{
var indicator = new TdistIndicator { Nu = 5, Period = 20 };
Assert.Equal("TDIST(5,20)", indicator.ShortName);
}
[Fact]
public void TdistIndicator_Initialize_CreatesTwoLineSeries()
{
var indicator = new TdistIndicator();
indicator.Initialize();
Assert.Equal(2, indicator.LinesSeries.Count);
Assert.Equal("TDist", indicator.LinesSeries[0].Name);
Assert.Equal("Mid", indicator.LinesSeries[1].Name);
}
[Fact]
public void TdistIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
{
var indicator = new TdistIndicator { Nu = 10, Period = 5 };
indicator.Initialize();
var now = DateTime.UtcNow;
for (int i = 0; i < 5; i++)
{
indicator.HistoricalData.AddBar(now.AddMinutes(i), 0, 105 + i, 95 - i, 100 + i);
var args = new UpdateArgs(UpdateReason.HistoricalBar);
indicator.ProcessUpdate(args);
}
double val = indicator.LinesSeries[0].GetValue(0);
Assert.True(double.IsFinite(val), "Output must be finite after warmup");
Assert.True(val >= 0.0 && val <= 1.0, $"Output {val} must be in [0,1]");
}
[Fact]
public void TdistIndicator_ProcessUpdate_NewBar_AddsNewValue()
{
var indicator = new TdistIndicator { Nu = 10, Period = 3 };
indicator.Initialize();
var now = DateTime.UtcNow;
for (int i = 0; i < 3; i++)
{
indicator.HistoricalData.AddBar(now.AddMinutes(i), 0, 105, 95, 100 + i);
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
}
indicator.HistoricalData.AddBar(now.AddMinutes(3), 0, 106, 96, 103);
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.NewBar));
Assert.Equal(4, indicator.LinesSeries[0].Count);
}
[Fact]
public void TdistIndicator_ProcessUpdate_NewTick_ProcessesWithoutError()
{
var indicator = new TdistIndicator { Period = 3 };
indicator.Initialize();
var now = DateTime.UtcNow;
indicator.HistoricalData.AddBar(now, 0, 105, 95, 100);
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.NewTick));
Assert.Equal(2, indicator.LinesSeries[0].Count);
}
[Fact]
public void TdistIndicator_MidLine_IsAlwaysHalf()
{
var indicator = new TdistIndicator { Period = 3 };
indicator.Initialize();
var now = DateTime.UtcNow;
for (int i = 0; i < 5; i++)
{
indicator.HistoricalData.AddBar(now.AddMinutes(i), 0, 105, 95, 100 + i);
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
}
for (int i = 0; i < indicator.LinesSeries[1].Count; i++)
{
double mid = indicator.LinesSeries[1].GetValue(i);
Assert.Equal(0.5, mid, 1e-10);
}
}
[Fact]
public void TdistIndicator_DifferentSourceType_Works()
{
var indicator = new TdistIndicator { Period = 3, Source = SourceType.High };
indicator.Initialize();
var now = DateTime.UtcNow;
for (int i = 0; i < 3; i++)
{
indicator.HistoricalData.AddBar(now.AddMinutes(i), 0, 110 + i, 90, 100);
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
}
double val = indicator.LinesSeries[0].GetValue(0);
Assert.True(double.IsFinite(val));
}
[Fact]
public void TdistIndicator_OutputInRange_AfterManyBars()
{
var indicator = new TdistIndicator { Nu = 10, Period = 20 };
indicator.Initialize();
var now = DateTime.UtcNow;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 71001);
var bars = gbm.Fetch(50, now.Ticks, TimeSpan.FromMinutes(1));
for (int i = 0; i < bars.Close.Count; i++)
{
double price = bars.Close[i].Value;
indicator.HistoricalData.AddBar(
new DateTime(bars.Close[i].Time, DateTimeKind.Utc),
0, price * 1.01, price * 0.99, price);
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
}
for (int i = 0; i < indicator.LinesSeries[0].Count; i++)
{
double val = indicator.LinesSeries[0].GetValue(i);
Assert.True(val >= 0.0 && val <= 1.0, $"Value {val} at index {i} out of range");
}
}
[Fact]
public void TdistIndicator_HighNu_ValidOutput()
{
var indicator = new TdistIndicator { Nu = 100, Period = 5 };
indicator.Initialize();
var now = DateTime.UtcNow;
for (int i = 0; i < 5; i++)
{
indicator.HistoricalData.AddBar(now.AddMinutes(i), 0, 101 + i, 99 + i, 100 + i);
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
}
double val = indicator.LinesSeries[0].GetValue(0);
Assert.True(double.IsFinite(val));
Assert.True(val >= 0.0 && val <= 1.0);
}
[Fact]
public void TdistIndicator_CauchyNu1_ValidOutput()
{
// nu=1 is the Cauchy distribution — heavier tails, should still be in [0,1]
var indicator = new TdistIndicator { Nu = 1, Period = 5 };
indicator.Initialize();
var now = DateTime.UtcNow;
for (int i = 0; i < 5; i++)
{
indicator.HistoricalData.AddBar(now.AddMinutes(i), 0, 105 + i, 95, 100 + i);
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
}
double val = indicator.LinesSeries[0].GetValue(0);
Assert.True(double.IsFinite(val));
Assert.True(val >= 0.0 && val <= 1.0);
}
[Fact]
public void TdistIndicator_CustomNu_ShortNameReflects()
{
var indicator = new TdistIndicator { Nu = 5, Period = 14 };
Assert.Equal("TDIST(5,14)", indicator.ShortName);
}
}
+69
View File
@@ -0,0 +1,69 @@
using System.Drawing;
using TradingPlatform.BusinessLayer;
using static QuanTAlib.IndicatorExtensions;
namespace QuanTAlib;
/// <summary>
/// TDIST (Student's t-Distribution CDF) Quantower indicator.
/// Computes the one-tailed t-CDF applied to a min-max normalized price series
/// scaled to t ∈ [-3, +3] over a rolling lookback window.
/// </summary>
public class TdistIndicator : Indicator, IWatchlistIndicator
{
[DataSourceInput]
public SourceType Source { get; set; } = SourceType.Close;
[InputParameter("Degrees of Freedom (ν)", sortIndex: 0, minimum: 1, maximum: 999, increment: 1)]
public int Nu { get; set; } = 10;
[InputParameter("Period", sortIndex: 1, minimum: 2, maximum: 2000, increment: 1)]
public int Period { get; set; } = 14;
[InputParameter("Show Cold Values", sortIndex: 100)]
public bool ShowColdValues { get; set; } = true;
private Tdist? _tdist;
private Func<IHistoryItem, double>? _selector;
public int MinHistoryDepths => Period;
public override string ShortName => $"TDIST({Nu},{Period})";
public TdistIndicator()
{
Name = "TDIST - Student's t-Distribution CDF";
Description = "Applies the Student's t-Distribution CDF to a min-max normalized price series";
SeparateWindow = true;
OnBackGround = true;
}
protected override void OnInit()
{
_tdist = new Tdist(Nu, Period);
_selector = Source.GetPriceSelector();
AddLineSeries(new LineSeries("TDist", Color.Cyan, 2, LineStyle.Solid));
// Reference level at 0.5 (symmetric midpoint of t-distribution)
AddLineSeries(new LineSeries("Mid", Color.Gray, 1, LineStyle.Dash));
}
protected override void OnUpdate(UpdateArgs args)
{
if (_tdist == null || _selector == null)
{
return;
}
var item = HistoricalData[0, SeekOriginHistory.End];
double value = _selector(item);
bool isNew = args.IsNewBar();
TValue input = new(item.TimeLeft, value);
_tdist.Update(input, isNew);
bool isHot = _tdist.IsHot;
LinesSeries[0].SetValue(_tdist.Last.Value, isHot, ShowColdValues);
LinesSeries[1].SetValue(0.5, isHot, ShowColdValues);
}
}
+646
View File
@@ -0,0 +1,646 @@
using Xunit;
namespace QuanTAlib.Tests;
public class TdistTests
{
private const double Tolerance = 1e-10;
// ─── A) Constructor validation ────────────────────────────────────────────
[Fact]
public void Constructor_DefaultParameters_SetsProperties()
{
var indicator = new Tdist();
Assert.Equal("Tdist(10,14)", indicator.Name);
Assert.Equal(14, indicator.WarmupPeriod);
Assert.False(indicator.IsHot);
}
[Fact]
public void Constructor_CustomParameters_SetsName()
{
var indicator = new Tdist(nu: 5, period: 20);
Assert.Equal("Tdist(5,20)", indicator.Name);
Assert.Equal(20, indicator.WarmupPeriod);
}
[Fact]
public void Constructor_NuZero_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentException>(() => new Tdist(nu: 0));
Assert.Equal("nu", ex.ParamName);
}
[Fact]
public void Constructor_NuNegative_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentException>(() => new Tdist(nu: -1));
Assert.Equal("nu", ex.ParamName);
}
[Fact]
public void Constructor_PeriodOne_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentException>(() => new Tdist(period: 1));
Assert.Equal("period", ex.ParamName);
}
[Fact]
public void Constructor_PeriodZero_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentException>(() => new Tdist(period: 0));
Assert.Equal("period", ex.ParamName);
}
[Fact]
public void Constructor_PeriodNegative_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentException>(() => new Tdist(period: -5));
Assert.Equal("period", ex.ParamName);
}
// ─── B) Basic calculation ─────────────────────────────────────────────────
[Fact]
public void Update_ReturnsValidTValue()
{
var indicator = new Tdist(period: 5);
var time = DateTime.UtcNow;
var input = new TValue(time, 100.0);
var result = indicator.Update(input);
Assert.Equal(input.Time, result.Time);
Assert.True(double.IsFinite(result.Value));
}
[Fact]
public void Update_OutputInRange()
{
var indicator = new Tdist(nu: 10, period: 5);
var time = DateTime.UtcNow;
double[] prices = { 100.0, 102.0, 98.0, 105.0, 103.0 };
foreach (var p in prices)
{
indicator.Update(new TValue(time, p));
time = time.AddMinutes(1);
}
Assert.True(indicator.Last.Value >= 0.0, "Output must be >= 0");
Assert.True(indicator.Last.Value <= 1.0, "Output must be <= 1");
}
[Fact]
public void Last_IsAccessible_AfterUpdate()
{
var indicator = new Tdist(period: 3);
var time = DateTime.UtcNow;
indicator.Update(new TValue(time, 50.0));
Assert.NotEqual(default, indicator.Last);
}
[Fact]
public void IsHot_Property_ReflectsWarmup()
{
var indicator = new Tdist(period: 5);
var time = DateTime.UtcNow;
for (int i = 0; i < 4; i++)
{
indicator.Update(new TValue(time.AddMinutes(i), 100.0 + i));
Assert.False(indicator.IsHot);
}
indicator.Update(new TValue(time.AddMinutes(4), 104.0));
Assert.True(indicator.IsHot);
}
[Fact]
public void Update_AtMaxOfWindow_ReturnsHighValue()
{
// When current value == window max, xNorm=1, t=+3 → CDF near 1
var indicator = new Tdist(nu: 10, period: 5);
var time = DateTime.UtcNow;
double[] prices = { 100.0, 102.0, 98.0, 101.0, 110.0 };
foreach (var p in prices)
{
indicator.Update(new TValue(time, p));
time = time.AddMinutes(1);
}
Assert.True(indicator.Last.Value > 0.9, $"Expected near 1 but got {indicator.Last.Value}");
}
[Fact]
public void Update_AtMinOfWindow_ReturnsLowValue()
{
// When current value == window min, xNorm=0, t=-3 → CDF near 0
var indicator = new Tdist(nu: 10, period: 5);
var time = DateTime.UtcNow;
double[] prices = { 110.0, 102.0, 108.0, 101.0, 90.0 };
foreach (var p in prices)
{
indicator.Update(new TValue(time, p));
time = time.AddMinutes(1);
}
Assert.True(indicator.Last.Value < 0.1, $"Expected near 0 but got {indicator.Last.Value}");
}
// ─── C) State + bar correction ────────────────────────────────────────────
[Fact]
public void Update_IsNewTrue_AdvancesState()
{
var indicator = new Tdist(period: 5);
var time = DateTime.UtcNow;
double[] prices = { 100.0, 102.0, 98.0, 105.0, 103.0 };
foreach (var p in prices)
{
indicator.Update(new TValue(time, p));
time = time.AddMinutes(1);
}
double first = indicator.Last.Value;
indicator.Update(new TValue(time, 110.0));
double second = indicator.Last.Value;
Assert.NotEqual(first, second, Tolerance);
}
[Fact]
public void Update_IsNewFalse_RewritesLastBar()
{
var indicator = new Tdist(period: 5);
var time = DateTime.UtcNow;
double[] prices = { 100.0, 102.0, 98.0, 105.0, 103.0 };
foreach (var p in prices)
{
indicator.Update(new TValue(time, p));
time = time.AddMinutes(1);
}
// New bar with value A (high → near 1)
indicator.Update(new TValue(time, 120.0), true);
double valueA = indicator.Last.Value;
// Correct same bar with value B (low → near 0)
indicator.Update(new TValue(time, 80.0), false);
double valueB = indicator.Last.Value;
Assert.NotEqual(valueA, valueB, Tolerance);
}
[Fact]
public void Update_IterativeCorrection_RestoresState()
{
var time = DateTime.UtcNow;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 70001);
var bars = gbm.Fetch(20, time.Ticks, TimeSpan.FromMinutes(1));
// Streaming without corrections
var straight = new Tdist(nu: 10, period: 5);
for (int i = 0; i < bars.Close.Count; i++)
{
straight.Update(bars.Close[i]);
}
double finalStraight = straight.Last.Value;
// With corrections (wrong → corrected)
var corrected = new Tdist(nu: 10, period: 5);
for (int i = 0; i < bars.Close.Count; i++)
{
corrected.Update(new TValue(bars.Close[i].Time, 999.0), true);
corrected.Update(bars.Close[i], false);
}
Assert.Equal(finalStraight, corrected.Last.Value, Tolerance);
}
[Fact]
public void Reset_ClearsState()
{
var indicator = new Tdist(period: 5);
var time = DateTime.UtcNow;
double[] prices = { 100.0, 102.0, 98.0, 105.0, 103.0 };
foreach (var p in prices)
{
indicator.Update(new TValue(time, p));
time = time.AddMinutes(1);
}
Assert.True(indicator.IsHot);
indicator.Reset();
Assert.False(indicator.IsHot);
Assert.Equal(default, indicator.Last);
}
// ─── D) Warmup / convergence ──────────────────────────────────────────────
[Fact]
public void IsHot_FlipsAtPeriod()
{
int period = 10;
var indicator = new Tdist(period: period);
var time = DateTime.UtcNow;
for (int i = 0; i < period - 1; i++)
{
indicator.Update(new TValue(time.AddMinutes(i), 100.0 + i));
Assert.False(indicator.IsHot, $"Should not be hot at bar {i + 1}");
}
indicator.Update(new TValue(time.AddMinutes(period - 1), 100.0 + period));
Assert.True(indicator.IsHot, "Should be hot after period bars");
}
// ─── E) Robustness ────────────────────────────────────────────────────────
[Fact]
public void Update_NaN_UsesLastValidValue()
{
var indicator = new Tdist(period: 5);
var time = DateTime.UtcNow;
double[] prices = { 100.0, 102.0, 98.0, 105.0, 103.0 };
foreach (var p in prices)
{
indicator.Update(new TValue(time, p));
time = time.AddMinutes(1);
}
double before = indicator.Last.Value;
indicator.Update(new TValue(time, double.NaN));
Assert.Equal(before, indicator.Last.Value, Tolerance);
}
[Fact]
public void Update_PositiveInfinity_UsesLastValidValue()
{
var indicator = new Tdist(period: 5);
var time = DateTime.UtcNow;
double[] prices = { 100.0, 102.0, 98.0, 105.0, 103.0 };
foreach (var p in prices)
{
indicator.Update(new TValue(time, p));
time = time.AddMinutes(1);
}
double before = indicator.Last.Value;
indicator.Update(new TValue(time, double.PositiveInfinity));
Assert.Equal(before, indicator.Last.Value, Tolerance);
}
[Fact]
public void Update_NegativeInfinity_UsesLastValidValue()
{
var indicator = new Tdist(period: 5);
var time = DateTime.UtcNow;
double[] prices = { 100.0, 102.0, 98.0, 105.0, 103.0 };
foreach (var p in prices)
{
indicator.Update(new TValue(time, p));
time = time.AddMinutes(1);
}
double before = indicator.Last.Value;
indicator.Update(new TValue(time, double.NegativeInfinity));
Assert.Equal(before, indicator.Last.Value, Tolerance);
}
[Fact]
public void Update_BatchNaN_Stable()
{
var indicator = new Tdist(period: 5);
var time = DateTime.UtcNow;
double[] prices = { 100.0, double.NaN, 102.0, double.NaN, 98.0, 105.0, 103.0 };
foreach (var p in prices)
{
var result = indicator.Update(new TValue(time, p));
Assert.True(double.IsFinite(result.Value), "Output must always be finite");
time = time.AddMinutes(1);
}
}
[Fact]
public void Update_FlatRange_ReturnsMidpoint()
{
// All identical values → range=0 → xNorm=0.5 → t=0 → CDF=0.5
var indicator = new Tdist(nu: 10, period: 5);
var time = DateTime.UtcNow;
for (int i = 0; i < 10; i++)
{
indicator.Update(new TValue(time.AddMinutes(i), 100.0));
}
Assert.Equal(0.5, indicator.Last.Value, 1e-6);
}
// ─── F) Consistency: batch == streaming == span == eventing ──────────────
[Fact]
public void AllModes_ConsistencyCheck()
{
int count = 100;
int period = 20;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 70002);
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
var source = bars.Close;
// Streaming
var streaming = new Tdist(nu: 10, period: period);
for (int i = 0; i < source.Count; i++)
{
streaming.Update(source[i]);
}
// Batch (TSeries)
var batch = Tdist.Batch(source, nu: 10, period: period);
// Span
var rawValues = new double[source.Count];
for (int i = 0; i < source.Count; i++)
{
rawValues[i] = source[i].Value;
}
var spanOutput = new double[source.Count];
Tdist.Batch(rawValues, spanOutput, nu: 10, period: period);
// Eventing
var eventResults = new List<double>();
var eventSource = new TSeries();
var eventIndicator = new Tdist(eventSource, nu: 10, period: period);
eventIndicator.Pub += (object? s, in TValueEventArgs e) => eventResults.Add(e.Value.Value);
for (int i = 0; i < source.Count; i++)
{
eventSource.Add(source[i], true);
}
// Verify last value matches across all modes
double streamingLast = streaming.Last.Value;
double batchLast = batch[source.Count - 1].Value;
double spanLast = spanOutput[source.Count - 1];
double eventLast = eventResults[^1];
Assert.Equal(streamingLast, batchLast, Tolerance);
Assert.Equal(streamingLast, spanLast, Tolerance);
Assert.Equal(streamingLast, eventLast, Tolerance);
}
[Fact]
public void Streaming_VsBatch_AllValues_Match()
{
int count = 80;
int period = 15;
var gbm = new GBM(startPrice: 50, mu: 0.0, sigma: 0.3, seed: 70003);
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
var source = bars.Close;
var streaming = new Tdist(nu: 5, period: period);
var streamingVals = new double[count];
for (int i = 0; i < count; i++)
{
streaming.Update(source[i]);
streamingVals[i] = streaming.Last.Value;
}
var batch = Tdist.Batch(source, nu: 5, period: period);
for (int i = 0; i < count; i++)
{
Assert.Equal(streamingVals[i], batch[i].Value, Tolerance);
}
}
// ─── G) Span API tests ────────────────────────────────────────────────────
[Fact]
public void Batch_Span_EmptySource_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentException>(() =>
Tdist.Batch([], Array.Empty<double>()));
Assert.Equal("source", ex.ParamName);
}
[Fact]
public void Batch_Span_OutputTooShort_ThrowsArgumentException()
{
double[] src = { 1.0, 2.0, 3.0 };
double[] dst = new double[2];
var ex = Assert.Throws<ArgumentException>(() =>
Tdist.Batch(src, dst));
Assert.Equal("output", ex.ParamName);
}
[Fact]
public void Batch_Span_InvalidNu_ThrowsArgumentException()
{
double[] src = { 1.0, 2.0, 3.0 };
double[] dst = new double[3];
var ex = Assert.Throws<ArgumentException>(() =>
Tdist.Batch(src, dst, nu: 0));
Assert.Equal("nu", ex.ParamName);
}
[Fact]
public void Batch_Span_InvalidPeriod_ThrowsArgumentException()
{
double[] src = { 1.0, 2.0, 3.0 };
double[] dst = new double[3];
var ex = Assert.Throws<ArgumentException>(() =>
Tdist.Batch(src, dst, period: 1));
Assert.Equal("period", ex.ParamName);
}
[Fact]
public void Batch_Span_OutputInRange()
{
int count = 100;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 70004);
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
double[] src = new double[count];
for (int i = 0; i < count; i++)
{
src[i] = bars.Close[i].Value;
}
double[] dst = new double[count];
Tdist.Batch(src, dst, nu: 10, period: 20);
foreach (double v in dst)
{
Assert.True(v >= 0.0 && v <= 1.0, $"Output {v} out of [0,1] range");
}
}
[Fact]
public void Batch_Span_HandlesNaN()
{
double[] src = { 100.0, double.NaN, 102.0, 98.0, 105.0, 103.0 };
double[] dst = new double[src.Length];
Tdist.Batch(src, dst, period: 5);
foreach (double v in dst)
{
Assert.True(double.IsFinite(v), "Span output should always be finite");
}
}
[Fact]
public void Batch_Span_NoStackOverflow_LargeData()
{
int count = 5000;
double[] src = new double[count];
for (int i = 0; i < count; i++)
{
src[i] = 100.0 + Math.Sin(i * 0.1) * 10.0;
}
double[] dst = new double[count];
Tdist.Batch(src, dst, nu: 10, period: 300);
foreach (double v in dst)
{
Assert.True(double.IsFinite(v));
}
}
[Fact]
public void Batch_Span_MatchesStreaming()
{
int count = 60;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.25, seed: 70005);
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
double[] src = new double[count];
for (int i = 0; i < count; i++)
{
src[i] = bars.Close[i].Value;
}
double[] spanOut = new double[count];
Tdist.Batch(src, spanOut, nu: 10, period: 14);
var streaming = new Tdist(nu: 10, period: 14);
for (int i = 0; i < count; i++)
{
streaming.Update(bars.Close[i]);
Assert.Equal(streaming.Last.Value, spanOut[i], Tolerance);
}
}
// ─── H) Chainability ──────────────────────────────────────────────────────
[Fact]
public void Pub_EventFires()
{
var indicator = new Tdist(period: 3);
int count = 0;
indicator.Pub += (object? sender, in TValueEventArgs args) => count++;
var time = DateTime.UtcNow;
indicator.Update(new TValue(time, 100.0));
indicator.Update(new TValue(time.AddMinutes(1), 102.0));
indicator.Update(new TValue(time.AddMinutes(2), 98.0));
Assert.Equal(3, count);
}
[Fact]
public void Chaining_Constructor_Works()
{
int period = 5;
var source = new TSeries();
var indicator = new Tdist(source, period: period);
var time = DateTime.UtcNow;
double[] prices = { 100.0, 102.0, 98.0, 105.0, 103.0 };
foreach (var p in prices)
{
source.Add(new TValue(time, p), true);
time = time.AddMinutes(1);
}
Assert.True(indicator.IsHot);
Assert.True(indicator.Last.Value >= 0.0 && indicator.Last.Value <= 1.0);
}
[Fact]
public void Pub_EventValue_MatchesLast()
{
var indicator = new Tdist(period: 5);
TValue? lastEvent = null;
indicator.Pub += (object? s, in TValueEventArgs e) => lastEvent = e.Value;
var time = DateTime.UtcNow;
double[] prices = { 100.0, 102.0, 98.0, 105.0, 103.0 };
foreach (var p in prices)
{
indicator.Update(new TValue(time, p));
time = time.AddMinutes(1);
}
Assert.NotNull(lastEvent);
Assert.Equal(indicator.Last.Value, lastEvent.Value.Value, Tolerance);
}
// ─── Additional: DoF parameter effects ───────────────────────────────────
[Fact]
public void DifferentNu_ProduceDifferentResults()
{
int count = 60;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 70006);
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
var ind1 = new Tdist(nu: 1, period: 20);
var ind2 = new Tdist(nu: 10, period: 20);
var ind3 = new Tdist(nu: 100, period: 20);
for (int i = 0; i < count; i++)
{
ind1.Update(bars.Close[i]);
ind2.Update(bars.Close[i]);
ind3.Update(bars.Close[i]);
}
// Different nu produce different CDFs
Assert.False(
Math.Abs(ind1.Last.Value - ind2.Last.Value) < 1e-6 &&
Math.Abs(ind2.Last.Value - ind3.Last.Value) < 1e-6,
"Different nu should produce at least one distinct result");
}
[Fact]
public void Calculate_StaticMethod_ReturnsTuple()
{
int count = 50;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 70007);
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
var (results, instance) = Tdist.Calculate(bars.Close, nu: 10, period: 20);
Assert.Equal(count, results.Count);
Assert.True(instance.IsHot);
Assert.Equal(results[^1].Value, instance.Last.Value, Tolerance);
}
}
@@ -0,0 +1,276 @@
using Xunit;
namespace QuanTAlib.Tests;
/// <summary>
/// Mathematical validation of the Student's t-Distribution CDF implementation.
/// Validates known values, symmetry properties, and convergence to the normal distribution.
/// No external library required — all validations use mathematical identities.
/// </summary>
public class TdistValidationTests
{
private const double Tolerance = 1e-9;
private const double LooseTolerance = 1e-4;
// ─── CDF boundary properties ──────────────────────────────────────────────
[Theory]
[InlineData(1)]
[InlineData(5)]
[InlineData(10)]
[InlineData(30)]
[InlineData(100)]
public void StaticCdf_AlwaysInUnitInterval(int nu)
{
double[] tValues = { -10.0, -3.0, -1.96, -1.0, -0.5, 0.0, 0.5, 1.0, 1.96, 3.0, 10.0 };
foreach (double t in tValues)
{
double cdf = Tdist.StaticCdf(t, nu);
Assert.True(cdf >= 0.0 && cdf <= 1.0,
$"CDF({t}, ν={nu}) = {cdf} is outside [0,1]");
}
}
// ─── Symmetry and anti-symmetry ──────────────────────────────────────────
[Theory]
[InlineData(1)]
[InlineData(5)]
[InlineData(10)]
[InlineData(30)]
public void StaticCdf_AtZero_IsHalf(int nu)
{
double cdf = Tdist.StaticCdf(0.0, nu);
Assert.Equal(0.5, cdf, Tolerance);
}
[Theory]
[InlineData(1, 1.0)]
[InlineData(5, 1.5)]
[InlineData(10, 2.0)]
[InlineData(30, 1.96)]
[InlineData(100, 2.5)]
public void StaticCdf_Antisymmetry(int nu, double t)
{
double cdfPos = Tdist.StaticCdf(t, nu);
double cdfNeg = Tdist.StaticCdf(-t, nu);
Assert.Equal(1.0, cdfPos + cdfNeg, Tolerance);
}
// ─── Monotonicity ─────────────────────────────────────────────────────────
[Theory]
[InlineData(1)]
[InlineData(5)]
[InlineData(10)]
[InlineData(100)]
public void StaticCdf_IsMonotonicallyIncreasing(int nu)
{
double[] tValues = { -10.0, -5.0, -3.0, -2.0, -1.0, -0.5, 0.0, 0.5, 1.0, 2.0, 3.0, 5.0, 10.0 };
for (int i = 1; i < tValues.Length; i++)
{
double prev = Tdist.StaticCdf(tValues[i - 1], nu);
double curr = Tdist.StaticCdf(tValues[i], nu);
Assert.True(curr >= prev,
$"CDF not monotone at t={tValues[i]}, ν={nu}: prev={prev}, curr={curr}");
}
}
// ─── Known values: Cauchy (ν=1) ──────────────────────────────────────────
[Fact]
public void StaticCdf_Nu1_AtT1_IsThreeQuarters()
{
// t(ν=1) is Cauchy. CDF(1; 1) = 0.5 + (1/π)·arctan(1) = 0.5 + 1/4 = 0.75
double cdf = Tdist.StaticCdf(1.0, 1);
Assert.Equal(0.75, cdf, 1e-9);
}
[Fact]
public void StaticCdf_Nu1_AtTNeg1_IsOneQuarter()
{
double cdf = Tdist.StaticCdf(-1.0, 1);
Assert.Equal(0.25, cdf, 1e-9);
}
[Fact]
public void StaticCdf_Nu1_AtT0_IsHalf()
{
double cdf = Tdist.StaticCdf(0.0, 1);
Assert.Equal(0.5, cdf, Tolerance);
}
// ─── Convergence to Normal as ν → ∞ ─────────────────────────────────────
[Fact]
public void StaticCdf_LargeNu_ApproximatesNormal_1_96()
{
// Normal CDF(1.96) ≈ 0.97500210931...
// t(ν=1000) should be very close
double cdf = Tdist.StaticCdf(1.96, 1000);
Assert.Equal(0.975, cdf, 1e-3);
}
[Fact]
public void StaticCdf_LargeNu_ApproximatesNormal_1_645()
{
// Normal CDF(1.645) ≈ 0.95002...
double cdf = Tdist.StaticCdf(1.645, 1000);
Assert.Equal(0.95, cdf, 2e-3);
}
[Fact]
public void StaticCdf_LargeNu_ApproximatesNormal_Neg1_96()
{
// Normal CDF(-1.96) ≈ 0.025
double cdf = Tdist.StaticCdf(-1.96, 1000);
Assert.Equal(0.025, cdf, 1e-3);
}
// ─── Known values across different ν ─────────────────────────────────────
[Fact]
public void StaticCdf_Nu2_AtT1_KnownValue()
{
// t(ν=2): CDF(1; 2) = 0.5 + t/(2√(ν+t²)) = 0.5 + 1/(2√3) ≈ 0.78868...
// Verify it's between ν=1 (0.75) and ν→∞ (0.8413)
double cdf = Tdist.StaticCdf(1.0, 2);
Assert.True(cdf > 0.75 && cdf < 0.85,
$"CDF(1.0; ν=2) = {cdf}, expected between 0.75 and 0.85");
}
[Fact]
public void StaticCdf_HeavierTails_LowerCdfForPositiveT()
{
// Lower ν → heavier tails → lower CDF for positive t (mass in tails)
double cdf1 = Tdist.StaticCdf(2.0, 1); // Cauchy
double cdf5 = Tdist.StaticCdf(2.0, 5);
double cdf30 = Tdist.StaticCdf(2.0, 30);
double cdf1000 = Tdist.StaticCdf(2.0, 1000);
Assert.True(cdf1 < cdf5, $"ν=1 CDF should be < ν=5 CDF at t=2");
Assert.True(cdf5 < cdf30, $"ν=5 CDF should be < ν=30 CDF at t=2");
Assert.True(cdf30 < cdf1000, $"ν=30 CDF should be < ν=1000 CDF at t=2");
}
// ─── Known-value verification (values from this implementation, verified against
// Cauchy/t-distribution formula and cross-checked for mathematical consistency) ─────
[Theory]
// ν=1 (Cauchy): CDF(t;1) = 0.5 + (1/π)·arctan(t) — exact formula
[InlineData(1, -3.0, 0.10241638234956672)] // 0.5 + arctan(-3)/π
[InlineData(1, 0.0, 0.5)]
[InlineData(1, 1.0, 0.75)] // 0.5 + arctan(1)/π = 0.5 + 0.25
[InlineData(1, 3.0, 0.89758361765043328)] // 0.5 + arctan(3)/π
// ν=5: values verified self-consistently
[InlineData(5, 0.0, 0.5)]
// ν=10: values verified self-consistently
[InlineData(10, 0.0, 0.5)]
// ν=30: values verified self-consistently
[InlineData(30, 0.0, 0.5)]
public void StaticCdf_KnownValues_MatchExpected(int nu, double t, double expected)
{
double actual = Tdist.StaticCdf(t, nu);
Assert.Equal(expected, actual, 1e-9);
}
[Theory]
// Self-consistency: verify our implementation gives stable, bounded values
// at non-trivial t. Tolerance 1e-5 because these are reference vs computed.
[InlineData(5, -2.0, 0.0510)] // t(5): CDF(-2) ≈ 0.051
[InlineData(5, 2.0, 0.9490)] // t(5): CDF(+2) ≈ 0.949
[InlineData(10, -1.96, 0.0392)] // t(10): CDF(-1.96) ≈ 0.0392
[InlineData(10, 1.96, 0.9608)] // t(10): CDF(+1.96) ≈ 0.9608
[InlineData(30, -1.96, 0.0297)] // t(30): CDF(-1.96) ≈ 0.0297
[InlineData(30, 1.96, 0.9703)] // t(30): CDF(+1.96) ≈ 0.9703
public void StaticCdf_ApproximateValues_InExpectedRange(int nu, double t, double expected)
{
double actual = Tdist.StaticCdf(t, nu);
Assert.Equal(expected, actual, 1e-3);
}
// ─── Streaming output always in [0,1] ─────────────────────────────────────
[Fact]
public void Streaming_OutputAlwaysInUnitInterval()
{
int count = 200;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.3, seed: 71001);
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
int[] nuValues = { 1, 5, 10, 30, 100 };
foreach (int nu in nuValues)
{
var indicator = new Tdist(nu: nu, period: 20);
for (int i = 0; i < count; i++)
{
var result = indicator.Update(bars.Close[i]);
Assert.True(result.Value >= 0.0 && result.Value <= 1.0,
$"ν={nu}, bar={i}: output {result.Value} outside [0,1]");
}
}
}
// ─── Flat range → 0.5 ─────────────────────────────────────────────────────
[Theory]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
public void Streaming_FlatRange_ReturnsMidpoint(int nu)
{
var indicator = new Tdist(nu: nu, period: 5);
var time = DateTime.UtcNow;
for (int i = 0; i < 10; i++)
{
indicator.Update(new TValue(time.AddMinutes(i), 100.0));
}
Assert.Equal(0.5, indicator.Last.Value, 1e-6);
}
// ─── Extreme t-values ─────────────────────────────────────────────────────
[Theory]
[InlineData(5)]
[InlineData(30)]
public void StaticCdf_LargePositiveT_NearOne_HighNu(int nu)
{
// For ν ≥ 5, t=100 → CDF ≈ 1.0 (within 1e-6)
double cdf = Tdist.StaticCdf(100.0, nu);
Assert.Equal(1.0, cdf, 1e-6);
}
[Fact]
public void StaticCdf_LargePositiveT_Nu1_Cauchy()
{
// Cauchy (ν=1): CDF(100; 1) = 0.5 + arctan(100)/π ≈ 0.99681...
// Heavy tails — does NOT approach 1 quickly
double cdf = Tdist.StaticCdf(100.0, 1);
double expected = 0.5 + Math.Atan(100.0) / Math.PI;
Assert.Equal(expected, cdf, 1e-9);
Assert.True(cdf > 0.99 && cdf < 1.0, $"Cauchy CDF(100) = {cdf} should be in (0.99, 1.0)");
}
[Theory]
[InlineData(5)]
[InlineData(30)]
public void StaticCdf_LargeNegativeT_NearZero_HighNu(int nu)
{
// For ν ≥ 5, t=-100 → CDF ≈ 0.0 (within 1e-6)
double cdf = Tdist.StaticCdf(-100.0, nu);
Assert.Equal(0.0, cdf, 1e-6);
}
[Fact]
public void StaticCdf_LargeNegativeT_Nu1_Cauchy()
{
// Cauchy (ν=1): CDF(-100; 1) = 0.5 - arctan(100)/π ≈ 0.00319...
double cdf = Tdist.StaticCdf(-100.0, 1);
double expected = 0.5 - Math.Atan(100.0) / Math.PI;
Assert.Equal(expected, cdf, 1e-9);
Assert.True(cdf > 0.0 && cdf < 0.01, $"Cauchy CDF(-100) = {cdf} should be in (0, 0.01)");
}
}
+294
View File
@@ -0,0 +1,294 @@
// TDIST: Student's t-Distribution CDF
// Applies the one-tailed Student's t CDF F(t; ν) to a min-max normalized price series
// over a rolling lookback window.
// Pipeline: MinMax normalization → linear t-scaling to [-3,+3] → regularized incomplete beta.
// Reuses Betadist.IncompleteBeta internally — no gamma/CF reimplementation.
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace QuanTAlib;
/// <summary>
/// TDIST: Student's t-Distribution CDF
/// Computes the one-tailed CDF F(t; ν) via the regularized incomplete beta function,
/// applied to a min-max normalized price series mapped to t ∈ [-3, +3].
/// </summary>
/// <remarks>
/// Key properties:
/// - Output always in [0, 1]
/// - Rolling window tracks min/max for normalization; flat range returns 0.5
/// - ν=1: Cauchy distribution (heavy tails); ν→∞: converges to Normal
/// - Reuses <see cref="Betadist.IncompleteBeta"/> — no special-function duplication
/// - NaN/Infinity inputs use last-valid-value substitution
/// </remarks>
[SkipLocalsInit]
public sealed class Tdist : AbstractBase
{
private readonly int _period;
private readonly int _nu;
private readonly RingBuffer _buffer;
[StructLayout(LayoutKind.Auto)]
private record struct State(double LastValid);
private State _state, _p_state;
public override bool IsHot => _buffer.Count >= _period;
/// <summary>
/// Initializes a new Tdist indicator.
/// </summary>
/// <param name="nu">Degrees of freedom (integer ≥ 1, default 10)</param>
/// <param name="period">Lookback window for min-max normalization (default 14)</param>
public Tdist(int nu = 10, int period = 14)
{
if (nu < 1)
{
throw new ArgumentException("nu must be >= 1", nameof(nu));
}
if (period < 2)
{
throw new ArgumentException("Period must be >= 2", nameof(period));
}
_nu = nu;
_period = period;
_buffer = new RingBuffer(period);
Name = $"Tdist({nu},{period})";
WarmupPeriod = period;
_state = new State(0.5);
_p_state = _state;
}
/// <summary>
/// Initializes a new Tdist indicator with source for event-based chaining.
/// </summary>
/// <param name="source">Source indicator for chaining</param>
/// <param name="nu">Degrees of freedom (default 10)</param>
/// <param name="period">Lookback window (default 14)</param>
public Tdist(ITValuePublisher source, int nu = 10, int period = 14)
: this(nu, period)
{
source.Pub += HandleUpdate;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void HandleUpdate(object? sender, in TValueEventArgs e) => Update(e.Value, e.IsNew);
/// <summary>
/// One-tailed Student's t CDF via regularized incomplete beta:
/// bx = ν / (ν + t²)
/// if t ≥ 0: CDF = 1 - 0.5 × I(bx, ν/2, 0.5)
/// if t &lt; 0: CDF = 0.5 × I(bx, ν/2, 0.5)
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static double TDistCdf(double t, int nu)
{
double nuD = nu;
double t2 = t * t;
double bx = nuD / Math.FusedMultiplyAdd(1.0, t2, nuD); // ν / (ν + t²)
double ibeta = Betadist.IncompleteBeta(bx, nuD * 0.5, 0.5);
return t >= 0.0 ? 1.0 - 0.5 * ibeta : 0.5 * ibeta;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static (double min, double max) FindMinMax(ReadOnlySpan<double> values)
{
if (values.Length == 0)
{
return (double.MaxValue, double.MinValue);
}
double min = values[0];
double max = values[0];
for (int i = 1; i < values.Length; i++)
{
double v = values[i];
if (v < min)
{
min = v;
}
if (v > max)
{
max = v;
}
}
return (min, max);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override TValue Update(TValue input, bool isNew = true)
{
if (isNew)
{
_p_state = _state;
}
else
{
_state = _p_state;
}
double value = input.Value;
double result;
if (double.IsFinite(value))
{
_buffer.Add(value, isNew);
var (min, max) = FindMinMax(_buffer.GetSpan());
double range = max - min;
// Flat range → midpoint 0.5 → t=0 → CDF=0.5
double xNorm = range > 0.0 ? (value - min) / range : 0.5;
// Map [0,1] → [-3, +3]; covers ~99.7% of the std normal range
double tVal = (xNorm - 0.5) * 6.0;
result = TDistCdf(tVal, _nu);
_state = new State(result);
}
else
{
result = _state.LastValid;
}
Last = new TValue(input.Time, result);
PubEvent(Last, isNew);
return Last;
}
public override TSeries Update(TSeries source)
{
var result = new TSeries(source.Count);
ReadOnlySpan<double> values = source.Values;
ReadOnlySpan<long> times = source.Times;
for (int i = 0; i < source.Count; i++)
{
var tv = Update(new TValue(new DateTime(times[i], DateTimeKind.Utc), values[i]), true);
result.Add(tv, true);
}
return result;
}
public override void Prime(ReadOnlySpan<double> source, TimeSpan? step = null)
{
TimeSpan interval = step ?? TimeSpan.FromSeconds(1);
DateTime time = DateTime.UtcNow - (interval * source.Length);
for (int i = 0; i < source.Length; i++)
{
Update(new TValue(time, source[i]), true);
time += interval;
}
}
public static TSeries Batch(TSeries source, int nu = 10, int period = 14)
{
var indicator = new Tdist(nu, period);
return indicator.Update(source);
}
/// <summary>
/// Calculates Student's t-Distribution CDF over a span of values.
/// Uses a sliding window min-max normalization identical to the streaming path.
/// </summary>
public static void Batch(
ReadOnlySpan<double> source, Span<double> output,
int nu = 10, int period = 14)
{
if (source.Length == 0)
{
throw new ArgumentException("Source cannot be empty", nameof(source));
}
if (output.Length < source.Length)
{
throw new ArgumentException("Output length must be >= source length", nameof(output));
}
if (nu < 1)
{
throw new ArgumentException("nu must be >= 1", nameof(nu));
}
if (period < 2)
{
throw new ArgumentException("Period must be >= 2", nameof(period));
}
double lastValid = 0.5;
for (int i = 0; i < source.Length; i++)
{
double val = source[i];
if (!double.IsFinite(val))
{
output[i] = lastValid;
continue;
}
int start = Math.Max(0, i - period + 1);
double min = double.PositiveInfinity;
double max = double.NegativeInfinity;
for (int j = start; j <= i; j++)
{
double v = source[j];
if (double.IsFinite(v))
{
if (v < min)
{
min = v;
}
if (v > max)
{
max = v;
}
}
}
if (!double.IsFinite(min) || !double.IsFinite(max))
{
output[i] = lastValid;
continue;
}
double range = max - min;
double xNorm = range > 0.0 ? (val - min) / range : 0.5;
double tVal = (xNorm - 0.5) * 6.0;
double result = TDistCdf(tVal, nu);
lastValid = result;
output[i] = result;
}
}
/// <summary>
/// Pure static T-CDF helper. Identical to <see cref="TDistCdf"/> but exposed
/// with a more explicit name for downstream consumers and validation tests.
/// </summary>
public static double StaticCdf(double t, int nu) => TDistCdf(t, nu);
public static (TSeries Results, Tdist Indicator) Calculate(
TSeries source, int nu = 10, int period = 14)
{
var indicator = new Tdist(nu, period);
TSeries results = indicator.Update(source);
return (results, indicator);
}
public override void Reset()
{
_buffer.Clear();
_state = new State(0.5);
_p_state = _state;
Last = default;
}
}