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
+194
View File
@@ -0,0 +1,194 @@
using Xunit;
using TradingPlatform.BusinessLayer;
namespace QuanTAlib.Tests;
public class FdistIndicatorTests
{
[Fact]
public void FdistIndicator_Constructor_SetsDefaults()
{
var indicator = new FdistIndicator();
Assert.Equal(SourceType.Close, indicator.Source);
Assert.Equal(1, indicator.D1);
Assert.Equal(1, indicator.D2);
Assert.Equal(14, indicator.Period);
Assert.True(indicator.ShowColdValues);
Assert.Equal("FDIST - F-Distribution CDF", indicator.Name);
Assert.True(indicator.SeparateWindow);
Assert.True(indicator.OnBackGround);
}
[Fact]
public void FdistIndicator_MinHistoryDepths_EqualsPeriod()
{
var indicator = new FdistIndicator { Period = 30 };
Assert.Equal(30, indicator.MinHistoryDepths);
}
[Fact]
public void FdistIndicator_ShortName_IsCorrect()
{
var indicator = new FdistIndicator { D1 = 5, D2 = 10, Period = 20 };
Assert.Equal("FDIST(5,10,20)", indicator.ShortName);
}
[Fact]
public void FdistIndicator_Initialize_CreatesTwoLineSeries()
{
var indicator = new FdistIndicator();
indicator.Initialize();
Assert.Equal(2, indicator.LinesSeries.Count);
Assert.Equal("FDist", indicator.LinesSeries[0].Name);
Assert.Equal("Mid", indicator.LinesSeries[1].Name);
}
[Fact]
public void FdistIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
{
var indicator = new FdistIndicator { D1 = 5, D2 = 5, 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);
}
// After period bars, should have valid output
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 FdistIndicator_ProcessUpdate_NewBar_AddsNewValue()
{
var indicator = new FdistIndicator { D1 = 5, D2 = 5, Period = 3 };
indicator.Initialize();
var now = DateTime.UtcNow;
// Feed 3 historical bars
for (int i = 0; i < 3; i++)
{
indicator.HistoricalData.AddBar(now.AddMinutes(i), 0, 105, 95, 100 + i);
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
}
// Feed a new bar
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 FdistIndicator_ProcessUpdate_NewTick_ProcessesWithoutError()
{
var indicator = new FdistIndicator { 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));
// 2 values: one historical, one intra-bar update
Assert.Equal(2, indicator.LinesSeries[0].Count);
}
[Fact]
public void FdistIndicator_MidLine_IsAlwaysHalf()
{
var indicator = new FdistIndicator { 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));
}
// Mid line should always be 0.5
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 FdistIndicator_DifferentSourceType_Works()
{
var indicator = new FdistIndicator { Period = 3, Source = SourceType.High };
indicator.Initialize();
var now = DateTime.UtcNow;
for (int i = 0; i < 3; i++)
{
// High = 110+i, Low = 90, Close = 100
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 FdistIndicator_OutputInRange_AfterManyBars()
{
var indicator = new FdistIndicator { D1 = 5, D2 = 5, Period = 20 };
indicator.Initialize();
var now = DateTime.UtcNow;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 67001);
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));
}
// Check all computed values are in [0, 1]
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 FdistIndicator_HighDoF_ValidOutput()
{
var indicator = new FdistIndicator { D1 = 10, D2 = 10, 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 FdistIndicator_CustomDoF_ShortNameReflects()
{
var indicator = new FdistIndicator { D1 = 3, D2 = 7, Period = 14 };
Assert.Equal("FDIST(3,7,14)", indicator.ShortName);
}
}
+72
View File
@@ -0,0 +1,72 @@
using System.Drawing;
using TradingPlatform.BusinessLayer;
using static QuanTAlib.IndicatorExtensions;
namespace QuanTAlib;
/// <summary>
/// FDIST (F-Distribution CDF) Quantower indicator.
/// Computes F(x; d1, d2) = I(d1·x/(d1·x+d2), d1/2, d2/2) applied to a
/// min-max normalized price series over a rolling lookback window.
/// </summary>
public class FdistIndicator : Indicator, IWatchlistIndicator
{
[DataSourceInput]
public SourceType Source { get; set; } = SourceType.Close;
[InputParameter("Numerator DoF (d1)", sortIndex: 0, minimum: 1, maximum: 999, increment: 1)]
public int D1 { get; set; } = 1;
[InputParameter("Denominator DoF (d2)", sortIndex: 1, minimum: 1, maximum: 999, increment: 1)]
public int D2 { get; set; } = 1;
[InputParameter("Period", sortIndex: 2, 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 Fdist? _fdist;
private Func<IHistoryItem, double>? _selector;
public int MinHistoryDepths => Period;
public override string ShortName => $"FDIST({D1},{D2},{Period})";
public FdistIndicator()
{
Name = "FDIST - F-Distribution CDF";
Description = "Applies the F-Distribution (Fisher-Snedecor) CDF to a min-max normalized price series";
SeparateWindow = true;
OnBackGround = true;
}
protected override void OnInit()
{
_fdist = new Fdist(D1, D2, Period);
_selector = Source.GetPriceSelector();
AddLineSeries(new LineSeries("FDist", Color.Cyan, 2, LineStyle.Solid));
// Reference level at 0.5 (midpoint)
AddLineSeries(new LineSeries("Mid", Color.Gray, 1, LineStyle.Dash));
}
protected override void OnUpdate(UpdateArgs args)
{
if (_fdist == null || _selector == null)
{
return;
}
var item = HistoricalData[0, SeekOriginHistory.End];
double value = _selector(item);
bool isNew = args.IsNewBar();
TValue input = new(item.TimeLeft, value);
_fdist.Update(input, isNew);
bool isHot = _fdist.IsHot;
LinesSeries[0].SetValue(_fdist.Last.Value, isHot, ShowColdValues);
LinesSeries[1].SetValue(0.5, isHot, ShowColdValues);
}
}
+671
View File
@@ -0,0 +1,671 @@
using Xunit;
namespace QuanTAlib.Tests;
public class FdistTests
{
private const double Tolerance = 1e-10;
// ─── A) Constructor validation ────────────────────────────────────────────
[Fact]
public void Constructor_DefaultParameters_SetsProperties()
{
var indicator = new Fdist();
Assert.Equal("Fdist(1,1,14)", indicator.Name);
Assert.Equal(14, indicator.WarmupPeriod);
Assert.False(indicator.IsHot);
}
[Fact]
public void Constructor_CustomParameters_SetsName()
{
var indicator = new Fdist(d1: 5, d2: 10, period: 20);
Assert.Equal("Fdist(5,10,20)", indicator.Name);
Assert.Equal(20, indicator.WarmupPeriod);
}
[Fact]
public void Constructor_D1Zero_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentException>(() => new Fdist(d1: 0));
Assert.Equal("d1", ex.ParamName);
}
[Fact]
public void Constructor_D1Negative_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentException>(() => new Fdist(d1: -1));
Assert.Equal("d1", ex.ParamName);
}
[Fact]
public void Constructor_D2Zero_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentException>(() => new Fdist(d2: 0));
Assert.Equal("d2", ex.ParamName);
}
[Fact]
public void Constructor_D2Negative_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentException>(() => new Fdist(d2: -1));
Assert.Equal("d2", ex.ParamName);
}
[Fact]
public void Constructor_PeriodOne_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentException>(() => new Fdist(period: 1));
Assert.Equal("period", ex.ParamName);
}
[Fact]
public void Constructor_PeriodZero_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentException>(() => new Fdist(period: 0));
Assert.Equal("period", ex.ParamName);
}
[Fact]
public void Constructor_PeriodNegative_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentException>(() => new Fdist(period: -5));
Assert.Equal("period", ex.ParamName);
}
// ─── B) Basic calculation ─────────────────────────────────────────────────
[Fact]
public void Update_ReturnsValidTValue()
{
var indicator = new Fdist(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 Fdist(d1: 5, d2: 5, 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 Fdist(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 Fdist(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 equals window max, xNorm=1, xF=10 → F-CDF near 1
var indicator = new Fdist(d1: 5, d2: 5, 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_ReturnsZero()
{
// When current value equals window min, xNorm=0, xF=0 → F-CDF(0) = 0
var indicator = new Fdist(d1: 5, d2: 5, period: 5);
var time = DateTime.UtcNow;
double[] prices = { 110.0, 102.0, 98.0, 101.0, 90.0 };
foreach (var p in prices)
{
indicator.Update(new TValue(time, p));
time = time.AddMinutes(1);
}
Assert.Equal(0.0, indicator.Last.Value, Tolerance);
}
// ─── C) State + bar correction ────────────────────────────────────────────
[Fact]
public void Update_IsNewTrue_AdvancesState()
{
var indicator = new Fdist(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 Fdist(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
indicator.Update(new TValue(time, 110.0), true);
double valueA = indicator.Last.Value;
// Correct same bar with value B (min of window → 0)
indicator.Update(new TValue(time, 90.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: 65001);
var bars = gbm.Fetch(20, time.Ticks, TimeSpan.FromMinutes(1));
// Streaming without corrections
var straight = new Fdist(d1: 5, d2: 5, 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 Fdist(d1: 5, d2: 5, 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 Fdist(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 Fdist(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 Fdist(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 Fdist(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 Fdist(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 Fdist(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_ReturnsStableValue()
{
// All identical values → range=0 → xNorm=0.5 → xF=5 → F-CDF(5; d1, d2)
var indicator = new Fdist(d1: 5, d2: 5, period: 5);
var time = DateTime.UtcNow;
for (int i = 0; i < 10; i++)
{
indicator.Update(new TValue(time.AddMinutes(i), 100.0));
}
double expected = Fdist.FCdf(5.0, 5, 5);
Assert.Equal(expected, 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: 65002);
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
var source = bars.Close;
// Streaming
var streaming = new Fdist(d1: 5, d2: 5, period: period);
for (int i = 0; i < source.Count; i++)
{
streaming.Update(source[i]);
}
// Batch (TSeries)
var batch = Fdist.Batch(source, d1: 5, d2: 5, 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];
Fdist.Batch(rawValues, spanOutput, d1: 5, d2: 5, period: period);
// Eventing
var eventResults = new List<double>();
var eventSource = new TSeries();
var eventIndicator = new Fdist(eventSource, d1: 5, d2: 5, 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: 65003);
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
var source = bars.Close;
var streaming = new Fdist(d1: 3, d2: 7, 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 = Fdist.Batch(source, d1: 3, d2: 7, 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>(() =>
Fdist.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>(() =>
Fdist.Batch(src, dst));
Assert.Equal("output", ex.ParamName);
}
[Fact]
public void Batch_Span_InvalidD1_ThrowsArgumentException()
{
double[] src = { 1.0, 2.0, 3.0 };
double[] dst = new double[3];
var ex = Assert.Throws<ArgumentException>(() =>
Fdist.Batch(src, dst, d1: 0));
Assert.Equal("d1", ex.ParamName);
}
[Fact]
public void Batch_Span_InvalidD2_ThrowsArgumentException()
{
double[] src = { 1.0, 2.0, 3.0 };
double[] dst = new double[3];
var ex = Assert.Throws<ArgumentException>(() =>
Fdist.Batch(src, dst, d2: 0));
Assert.Equal("d2", 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>(() =>
Fdist.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: 65004);
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];
Fdist.Batch(src, dst, d1: 5, d2: 5, 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];
Fdist.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];
Fdist.Batch(src, dst, d1: 5, d2: 5, 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: 65005);
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];
Fdist.Batch(src, spanOut, d1: 5, d2: 5, period: 14);
var streaming = new Fdist(d1: 5, d2: 5, 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 Fdist(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 Fdist(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 Fdist(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 DifferentDoF_ProduceDifferentResults()
{
int count = 60;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 65006);
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
var ind1 = new Fdist(d1: 1, d2: 1, period: 20);
var ind2 = new Fdist(d1: 5, d2: 5, period: 20);
var ind3 = new Fdist(d1: 10, d2: 2, 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 DoFs 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 DoFs 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: 65007);
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
var (results, instance) = Fdist.Calculate(bars.Close, d1: 5, d2: 5, period: 20);
Assert.Equal(count, results.Count);
Assert.True(instance.IsHot);
Assert.Equal(results[^1].Value, instance.Last.Value, Tolerance);
}
}
@@ -0,0 +1,298 @@
using Xunit;
using MathNet.Numerics.Distributions;
namespace QuanTAlib.Tests;
/// <summary>
/// FdistValidationTests — validates against known mathematical properties
/// of the F-Distribution CDF and against MathNet.Numerics FisherSnedecor.
/// Known-value tests call Fdist.FCdf directly (bypassing windowing) so results
/// are exact closed-form comparisons with tolerance 1e-9.
/// </summary>
public class FdistValidationTests
{
private const double Tolerance = 1e-9;
private const double LooseTolerance = 1e-6;
// ─── Known-value tests via FCdf static method vs MathNet ─────────────────
// F(x; d1, d2) = I(d1*x/(d1*x+d2), d1/2, d2/2)
[Theory]
[InlineData(0.0, 1, 1)] // F(0; d1, d2) = 0 always
[InlineData(0.0, 5, 5)]
[InlineData(0.0, 10, 2)]
public void FCdf_AtZero_IsAlwaysZero(double x, int d1, int d2)
{
Assert.Equal(0.0, Fdist.FCdf(x, d1, d2), Tolerance);
}
[Theory]
[InlineData(-0.1, 1, 1)]
[InlineData(-1.0, 5, 5)]
[InlineData(-100.0, 2, 3)]
public void FCdf_Negative_IsAlwaysZero(double x, int d1, int d2)
{
Assert.Equal(0.0, Fdist.FCdf(x, d1, d2), Tolerance);
}
[Theory]
[InlineData(100.0, 1, 1, 0.90)] // F(1,1) is heavy-tailed; F(100) ≈ 0.936
[InlineData(100.0, 5, 5, 0.99)]
[InlineData(100.0, 10, 2, 0.99)]
public void FCdf_AtLargeX_ApproachesOne(double x, int d1, int d2, double minExpected)
{
double cdf = Fdist.FCdf(x, d1, d2);
Assert.True(cdf > minExpected, $"F({x}; {d1},{d2}) = {cdf} should be > {minExpected}");
}
// ─── MathNet.Numerics cross-validation ───────────────────────────────────
[Theory]
[InlineData(1.0, 1, 1)]
[InlineData(2.0, 1, 1)]
[InlineData(0.5, 2, 3)]
[InlineData(1.5, 5, 5)]
[InlineData(0.8, 10, 2)]
[InlineData(3.0, 3, 7)]
[InlineData(0.25, 2, 10)]
[InlineData(5.0, 5, 10)]
[InlineData(0.1, 1, 5)]
[InlineData(2.5, 8, 4)]
public void FCdf_VsMathNet_KnownValues(double x, int d1, int d2)
{
var dist = new FisherSnedecor(d1, d2);
double expected = dist.CumulativeDistribution(x);
double actual = Fdist.FCdf(x, d1, d2);
Assert.Equal(expected, actual, Tolerance);
}
[Theory]
[InlineData(1.0, 1, 1)]
[InlineData(2.0, 5, 5)]
[InlineData(0.5, 2, 3)]
[InlineData(1.5, 10, 10)]
[InlineData(0.8, 3, 7)]
public void StaticCdf_VsMathNet_KnownValues(double x, int d1, int d2)
{
var dist = new FisherSnedecor(d1, d2);
double expected = dist.CumulativeDistribution(x);
double actual = Fdist.StaticCdf(x, d1, d2);
Assert.Equal(expected, actual, Tolerance);
}
// ─── Monotonicity ─────────────────────────────────────────────────────────
[Theory]
[InlineData(1, 1)]
[InlineData(5, 5)]
[InlineData(2, 10)]
[InlineData(10, 3)]
public void FCdf_MonotonicIncreasing(int d1, int d2)
{
double prev = -1.0;
for (int i = 0; i <= 30; i++)
{
double x = i * 0.2;
double cdf = Fdist.FCdf(x, d1, d2);
Assert.True(cdf >= prev - LooseTolerance,
$"CDF not monotonic at x={x} (d1={d1}, d2={d2}): got {cdf}, prev={prev}");
prev = cdf;
}
}
// ─── Output bounded [0, 1] ────────────────────────────────────────────────
[Fact]
public void FdistCdf_OutputBounded_Zero_To_One()
{
int count = 200;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.3, seed: 66001);
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
var indicator = new Fdist(d1: 5, d2: 5, period: 20);
for (int i = 0; i < count; i++)
{
indicator.Update(bars.Close[i]);
double v = indicator.Last.Value;
Assert.True(v >= 0.0 && v <= 1.0, $"Output {v} at bar {i} out of [0,1]");
}
}
// ─── Flat range → F-CDF at 5.0 (xNorm=0.5, xF=5) ────────────────────────
[Theory]
[InlineData(1, 1)]
[InlineData(5, 5)]
[InlineData(2, 3)]
[InlineData(10, 5)]
public void FdistCdf_FlatRange_ReturnsCdfAtFive(int d1, int d2)
{
var ind = new Fdist(d1, d2, period: 20);
var time = DateTime.UtcNow;
for (int i = 0; i < 20; i++)
{
ind.Update(new TValue(time.AddSeconds(i), 100.0));
}
double expected = Fdist.FCdf(5.0, d1, d2);
Assert.Equal(expected, ind.Last.Value, LooseTolerance);
}
// ─── Streaming vs MathNet on raw (unnormalized) values ───────────────────
[Fact]
public void FCdf_MultiplePoints_AllMatchMathNet()
{
int d1 = 5, d2 = 5;
var dist = new FisherSnedecor(d1, d2);
double[] testX = { 0.0, 0.1, 0.5, 1.0, 2.0, 5.0, 10.0 };
foreach (double x in testX)
{
double expected = dist.CumulativeDistribution(x);
double actual = Fdist.FCdf(x, d1, d2);
Assert.Equal(expected, actual, Tolerance);
}
}
// ─── Span batch consistency ───────────────────────────────────────────────
[Fact]
public void Batch_Span_MatchesTSeries()
{
int count = 150;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.25, seed: 66002);
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
double[] rawValues = new double[count];
for (int i = 0; i < count; i++)
{
rawValues[i] = bars.Close[i].Value;
}
var tseriesResult = Fdist.Batch(bars.Close, d1: 5, d2: 5, period: 30);
double[] spanResult = new double[count];
Fdist.Batch(rawValues, spanResult, d1: 5, d2: 5, period: 30);
for (int i = 0; i < count; i++)
{
Assert.Equal(tseriesResult[i].Value, spanResult[i], Tolerance);
}
}
// ─── Streaming convergence ────────────────────────────────────────────────
[Fact]
public void FdistCdf_HighPeriod_StillConverges()
{
int period = 200;
var indicator = new Fdist(d1: 5, d2: 5, period: period);
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.3, seed: 66003);
var bars = gbm.Fetch(period + 50, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
for (int i = 0; i < bars.Close.Count; i++)
{
indicator.Update(bars.Close[i]);
Assert.True(double.IsFinite(indicator.Last.Value),
$"Non-finite output at bar {i}");
}
}
// ─── Parameter combos all within [0,1] ────────────────────────────────────
[Theory]
[InlineData(1, 1, 5)]
[InlineData(2, 3, 14)]
[InlineData(5, 5, 20)]
[InlineData(10, 2, 30)]
[InlineData(1, 10, 10)]
public void FdistCdf_ParameterCombos_OutputBounded(int d1, int d2, int period)
{
int count = period + 50;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 66004 + d1 * 100 + d2);
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
var indicator = new Fdist(d1, d2, period);
for (int i = 0; i < count; i++)
{
indicator.Update(bars.Close[i]);
double v = indicator.Last.Value;
Assert.True(v >= 0.0 && v <= 1.0,
$"Out of [0,1] at bar {i}: {v} (d1={d1}, d2={d2}, period={period})");
}
}
// ─── Large dataset stable ─────────────────────────────────────────────────
[Fact]
public void FdistCdf_LargeDataset_Stable()
{
int count = 2000;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 66005);
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
var indicator = new Fdist(d1: 5, d2: 5, period: 50);
for (int i = 0; i < count; i++)
{
indicator.Update(bars.Close[i]);
double v = indicator.Last.Value;
Assert.True(double.IsFinite(v) && v >= 0.0 && v <= 1.0,
$"Invalid output {v} at bar {i}");
}
}
// ─── Complementary property F(x;d1,d2) = 1 - G(1/x;d2,d1) ──────────────
[Theory]
[InlineData(0.5, 5, 5)]
[InlineData(1.0, 3, 7)]
[InlineData(2.0, 2, 4)]
[InlineData(0.25, 4, 8)]
public void FCdf_ComplementaryProperty(double x, int d1, int d2)
{
// F(x; d1, d2) = 1 - F(1/x; d2, d1) — the reciprocal (swapped-DoF) relation
double direct = Fdist.FCdf(x, d1, d2);
// Use local variables to avoid S2234 name-order false positive when intentionally swapping d1/d2
double xRecip = 1.0 / x;
int swappedD1 = d2;
int swappedD2 = d1;
double reciprocal = Fdist.FCdf(xRecip, swappedD1, swappedD2);
Assert.Equal(1.0, direct + reciprocal, LooseTolerance);
}
// ─── Symmetric case (d1=d2=n) median near 1 ──────────────────────────────
[Theory]
[InlineData(1)]
[InlineData(5)]
[InlineData(10)]
public void FCdf_SymmetricDoF_MedianIsOne(int n)
{
// When d1==d2, the F distribution median is 1.0 (approx) → CDF(1) ≈ 0.5
double cdf = Fdist.FCdf(1.0, n, n);
Assert.Equal(0.5, cdf, 1e-6);
}
// ─── Extreme prices don't blow up ─────────────────────────────────────────
[Fact]
public void FdistCdf_ExtremePrices_StillInRange()
{
var indicator = new Fdist(d1: 5, d2: 5, period: 20);
var time = DateTime.UtcNow;
for (int i = 0; i < 20; i++)
{
double price = (i % 2 == 0) ? 1e10 : 1e-10;
indicator.Update(new TValue(time.AddMinutes(i), price));
double v = indicator.Last.Value;
Assert.True(v >= 0.0 && v <= 1.0, $"Out of range at {i}: {v}");
}
}
}
+311
View File
@@ -0,0 +1,311 @@
// FDIST: F-Distribution CDF
// Applies the Fisher-Snedecor CDF F(x; d1, d2) = I(d1*x/(d1*x+d2), d1/2, d2/2)
// to a min-max normalized price series over a rolling lookback window.
// Pipeline: MinMax normalization → scaling → regularized incomplete beta function.
// Reuses Betadist.IncompleteBeta internally — no gamma/CF reimplementation.
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace QuanTAlib;
/// <summary>
/// FDIST: F-Distribution (Fisher-Snedecor) CDF
/// Computes F(x; d1, d2) = I(d1·x/(d1·x+d2), d1/2, d2/2) applied to a
/// min-max normalized price series scaled to a positive real via a 10× factor.
/// </summary>
/// <remarks>
/// Key properties:
/// - Output always in [0, 1]
/// - Rolling window tracks min/max for normalization; flat range returns F(0.5·10; d1, d2)
/// - d1/d2 degrees of freedom control the shape: equal df → symmetric response,
/// d1 &gt; d2 → right-skewed, d1 &lt; d2 → left-skewed
/// - Reuses <see cref="Betadist.IncompleteBeta"/> — no special-function duplication
/// - NaN/Infinity inputs use last-valid-value substitution
/// </remarks>
[SkipLocalsInit]
public sealed class Fdist : AbstractBase
{
private readonly int _period;
private readonly int _d1;
private readonly int _d2;
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 Fdist indicator.
/// </summary>
/// <param name="d1">Numerator degrees of freedom (integer ≥ 1, default 1)</param>
/// <param name="d2">Denominator degrees of freedom (integer ≥ 1, default 1)</param>
/// <param name="period">Lookback window for min-max normalization (default 14)</param>
public Fdist(int d1 = 1, int d2 = 1, int period = 14)
{
if (d1 < 1)
{
throw new ArgumentException("d1 must be >= 1", nameof(d1));
}
if (d2 < 1)
{
throw new ArgumentException("d2 must be >= 1", nameof(d2));
}
if (period < 2)
{
throw new ArgumentException("Period must be >= 2", nameof(period));
}
_d1 = d1;
_d2 = d2;
_period = period;
_buffer = new RingBuffer(period);
Name = $"Fdist({d1},{d2},{period})";
WarmupPeriod = period;
_state = new State(0.5);
_p_state = _state;
}
/// <summary>
/// Initializes a new Fdist indicator with source for event-based chaining.
/// </summary>
/// <param name="source">Source indicator for chaining</param>
/// <param name="d1">Numerator degrees of freedom (default 1)</param>
/// <param name="d2">Denominator degrees of freedom (default 1)</param>
/// <param name="period">Lookback window (default 14)</param>
public Fdist(ITValuePublisher source, int d1 = 1, int d2 = 1, int period = 14)
: this(d1, d2, period)
{
source.Pub += HandleUpdate;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void HandleUpdate(object? sender, in TValueEventArgs e) => Update(e.Value, e.IsNew);
/// <summary>
/// F-Distribution CDF: F(x; d1, d2) = I(d1·x/(d1·x+d2), d1/2, d2/2).
/// Returns 0 for x ≤ 0, uses regularized incomplete beta for x > 0.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static double FCdf(double x, int d1, int d2)
{
if (x <= 0.0)
{
return 0.0;
}
double d1d = d1;
double d2d = d2;
double xBeta = d1d * x / Math.FusedMultiplyAdd(d1d, x, d2d);
return Betadist.IncompleteBeta(xBeta, d1d * 0.5, d2d * 0.5);
}
[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 → use midpoint 0.5; scale by 10 to spread F-CDF response across (0,∞)
double xNorm = range > 0.0 ? (value - min) / range : 0.5;
// Map [0,1] → [0,10] to place output in a useful part of the F-CDF response curve
double xF = xNorm * 10.0;
result = FCdf(xF, _d1, _d2);
_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 d1 = 1, int d2 = 1, int period = 14)
{
var indicator = new Fdist(d1, d2, period);
return indicator.Update(source);
}
/// <summary>
/// Calculates F-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 d1 = 1, int d2 = 1, 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 (d1 < 1)
{
throw new ArgumentException("d1 must be >= 1", nameof(d1));
}
if (d2 < 1)
{
throw new ArgumentException("d2 must be >= 1", nameof(d2));
}
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 xF = xNorm * 10.0;
double result = FCdf(xF, d1, d2);
lastValid = result;
output[i] = result;
}
}
/// <summary>
/// Pure static F-CDF helper. Identical to <see cref="FCdf"/> but exposed
/// with a more explicit name for downstream consumers and validation tests.
/// </summary>
public static double StaticCdf(double x, int d1, int d2) => FCdf(x, d1, d2);
public static (TSeries Results, Fdist Indicator) Calculate(
TSeries source, int d1 = 1, int d2 = 1, int period = 14)
{
var indicator = new Fdist(d1, d2, 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;
}
}