mirror of
https://github.com/mihakralj/QuanTAlib.git
synced 2026-08-22 04:28:04 +00:00
adding missing validations
This commit is contained in:
@@ -0,0 +1,172 @@
|
||||
using Xunit;
|
||||
using TradingPlatform.BusinessLayer;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public class BinomdistIndicatorTests
|
||||
{
|
||||
[Fact]
|
||||
public void BinomdistIndicator_Constructor_SetsDefaults()
|
||||
{
|
||||
var indicator = new BinomdistIndicator();
|
||||
|
||||
Assert.Equal(SourceType.Close, indicator.Source);
|
||||
Assert.Equal(50, indicator.Period);
|
||||
Assert.Equal(20, indicator.Trials);
|
||||
Assert.Equal(10, indicator.Threshold);
|
||||
Assert.True(indicator.ShowColdValues);
|
||||
Assert.Equal("BINOMDIST - Binomial Distribution CDF", indicator.Name);
|
||||
Assert.True(indicator.SeparateWindow);
|
||||
Assert.True(indicator.OnBackGround);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BinomdistIndicator_MinHistoryDepths_EqualsPeriod()
|
||||
{
|
||||
var indicator = new BinomdistIndicator { Period = 30 };
|
||||
Assert.Equal(30, indicator.MinHistoryDepths);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BinomdistIndicator_ShortName_IsCorrect()
|
||||
{
|
||||
var indicator = new BinomdistIndicator { Period = 20, Trials = 15, Threshold = 7 };
|
||||
Assert.Equal("BINOMDIST(20,15,7)", indicator.ShortName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BinomdistIndicator_Initialize_CreatesTwoLineSeries()
|
||||
{
|
||||
var indicator = new BinomdistIndicator();
|
||||
indicator.Initialize();
|
||||
|
||||
Assert.Equal(2, indicator.LinesSeries.Count);
|
||||
Assert.Equal("BinomDist", indicator.LinesSeries[0].Name);
|
||||
Assert.Equal("Mid", indicator.LinesSeries[1].Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BinomdistIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
|
||||
{
|
||||
var indicator = new BinomdistIndicator { Period = 5, Trials = 10, Threshold = 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 BinomdistIndicator_ProcessUpdate_NewBar_AddsNewValue()
|
||||
{
|
||||
var indicator = new BinomdistIndicator { Period = 3, Trials = 10, Threshold = 5 };
|
||||
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 BinomdistIndicator_ProcessUpdate_NewTick_ProcessesWithoutError()
|
||||
{
|
||||
var indicator = new BinomdistIndicator { Period = 3, Trials = 10, Threshold = 5 };
|
||||
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 BinomdistIndicator_MidLine_IsAlwaysHalf()
|
||||
{
|
||||
var indicator = new BinomdistIndicator { Period = 3, Trials = 10, Threshold = 5 };
|
||||
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 BinomdistIndicator_DifferentSourceType_Works()
|
||||
{
|
||||
var indicator = new BinomdistIndicator { Period = 3, Trials = 10, Threshold = 5, 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 BinomdistIndicator_OutputInRange_AfterManyBars()
|
||||
{
|
||||
var indicator = new BinomdistIndicator { Period = 20, Trials = 10, Threshold = 5 };
|
||||
indicator.Initialize();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 62001);
|
||||
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 BinomdistIndicator_ParameterChange_ReflectsInShortName()
|
||||
{
|
||||
var indicator = new BinomdistIndicator();
|
||||
indicator.Period = 10;
|
||||
indicator.Trials = 5;
|
||||
indicator.Threshold = 2;
|
||||
Assert.Equal("BINOMDIST(10,5,2)", indicator.ShortName);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
using System.Drawing;
|
||||
using TradingPlatform.BusinessLayer;
|
||||
using static QuanTAlib.IndicatorExtensions;
|
||||
|
||||
namespace QuanTAlib;
|
||||
|
||||
/// <summary>
|
||||
/// BINOMDIST (Binomial Distribution CDF) Quantower indicator.
|
||||
/// Computes P(X ≤ k) for X ~ Binomial(n, p), where p is derived from the
|
||||
/// min-max normalized price within a rolling lookback window.
|
||||
/// </summary>
|
||||
public class BinomdistIndicator : Indicator, IWatchlistIndicator
|
||||
{
|
||||
[DataSourceInput]
|
||||
public SourceType Source { get; set; } = SourceType.Close;
|
||||
|
||||
[InputParameter("Period", sortIndex: 0, minimum: 1, maximum: 2000, increment: 1)]
|
||||
public int Period { get; set; } = 50;
|
||||
|
||||
[InputParameter("Trials (n)", sortIndex: 1, minimum: 1, maximum: 1000, increment: 1)]
|
||||
public int Trials { get; set; } = 20;
|
||||
|
||||
[InputParameter("Threshold (k)", sortIndex: 2, minimum: 0, maximum: 1000, increment: 1)]
|
||||
public int Threshold { get; set; } = 10;
|
||||
|
||||
[InputParameter("Show Cold Values", sortIndex: 100)]
|
||||
public bool ShowColdValues { get; set; } = true;
|
||||
|
||||
private Binomdist? _binomdist;
|
||||
private Func<IHistoryItem, double>? _selector;
|
||||
|
||||
public int MinHistoryDepths => Period;
|
||||
public override string ShortName => $"BINOMDIST({Period},{Trials},{Threshold})";
|
||||
|
||||
public BinomdistIndicator()
|
||||
{
|
||||
Name = "BINOMDIST - Binomial Distribution CDF";
|
||||
Description = "Computes P(X ≤ k) for X ~ Binomial(n, p) from min-max normalized price";
|
||||
SeparateWindow = true;
|
||||
OnBackGround = true;
|
||||
}
|
||||
|
||||
protected override void OnInit()
|
||||
{
|
||||
_binomdist = new Binomdist(Period, Trials, Threshold);
|
||||
_selector = Source.GetPriceSelector();
|
||||
|
||||
AddLineSeries(new LineSeries("BinomDist", Color.Yellow, 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 (_binomdist == null || _selector == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var item = HistoricalData[0, SeekOriginHistory.End];
|
||||
double value = _selector(item);
|
||||
bool isNew = args.IsNewBar();
|
||||
|
||||
TValue input = new(item.TimeLeft, value);
|
||||
_binomdist.Update(input, isNew);
|
||||
|
||||
bool isHot = _binomdist.IsHot;
|
||||
|
||||
LinesSeries[0].SetValue(_binomdist.Last.Value, isHot, ShowColdValues);
|
||||
LinesSeries[1].SetValue(0.5, isHot, ShowColdValues);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,656 @@
|
||||
using Xunit;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public class BinomdistTests
|
||||
{
|
||||
private const double Tolerance = 1e-10;
|
||||
|
||||
// ─── A) Constructor validation ────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Constructor_DefaultParameters_SetsProperties()
|
||||
{
|
||||
var indicator = new Binomdist();
|
||||
Assert.Equal("Binomdist(50,20,10)", indicator.Name);
|
||||
Assert.Equal(50, indicator.WarmupPeriod);
|
||||
Assert.False(indicator.IsHot);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_CustomParameters_SetsName()
|
||||
{
|
||||
var indicator = new Binomdist(30, 15, 7);
|
||||
Assert.Equal("Binomdist(30,15,7)", indicator.Name);
|
||||
Assert.Equal(30, indicator.WarmupPeriod);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_InvalidPeriod_ThrowsArgumentException()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Binomdist(period: 0));
|
||||
Assert.Equal("period", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_NegativePeriod_ThrowsArgumentException()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Binomdist(period: -1));
|
||||
Assert.Equal("period", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_ZeroTrials_ThrowsArgumentException()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Binomdist(trials: 0));
|
||||
Assert.Equal("trials", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_NegativeTrials_ThrowsArgumentException()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Binomdist(trials: -5));
|
||||
Assert.Equal("trials", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_NegativeThreshold_ThrowsArgumentException()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Binomdist(threshold: -1));
|
||||
Assert.Equal("threshold", ex.ParamName);
|
||||
}
|
||||
|
||||
// ─── B) Basic calculation ─────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Update_ReturnsValidTValue()
|
||||
{
|
||||
var indicator = new Binomdist(period: 5, trials: 10, threshold: 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 Binomdist(period: 5, trials: 10, threshold: 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 Binomdist(period: 3, trials: 10, threshold: 5);
|
||||
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 Binomdist(period: 5, trials: 10, threshold: 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);
|
||||
}
|
||||
|
||||
// ─── C) State + bar correction ────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Update_IsNewTrue_AdvancesState()
|
||||
{
|
||||
var indicator = new Binomdist(period: 5, trials: 10, threshold: 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 Binomdist(period: 5, trials: 10, threshold: 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
|
||||
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: 43001);
|
||||
var bars = gbm.Fetch(20, time.Ticks, TimeSpan.FromMinutes(1));
|
||||
|
||||
// Streaming without corrections
|
||||
var straight = new Binomdist(period: 5, trials: 10, threshold: 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 Binomdist(period: 5, trials: 10, threshold: 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 Binomdist(period: 5, trials: 10, threshold: 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 Binomdist(period, trials: 10, threshold: 5);
|
||||
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 Binomdist(period: 5, trials: 10, threshold: 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 Binomdist(period: 5, trials: 10, threshold: 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 Binomdist(period: 5, trials: 10, threshold: 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 Binomdist(period: 5, trials: 10, threshold: 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_ReturnsExpectedCdf()
|
||||
{
|
||||
// When all values in window are identical, range=0 → p=0.5
|
||||
// P(X≤5; n=10, p=0.5) = 0.623046875 (exact)
|
||||
var indicator = new Binomdist(period: 5, trials: 10, threshold: 5);
|
||||
var time = DateTime.UtcNow;
|
||||
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
indicator.Update(new TValue(time.AddMinutes(i), 100.0));
|
||||
}
|
||||
|
||||
// p=0.5, n=10, k=5: exact = 0.623046875
|
||||
Assert.True(Math.Abs(indicator.Last.Value - 0.623046875) < 1e-9,
|
||||
$"Expected ~0.623046875 but got {indicator.Last.Value}");
|
||||
}
|
||||
|
||||
// ─── 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: 43002);
|
||||
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
var source = bars.Close;
|
||||
|
||||
// Streaming
|
||||
var streaming = new Binomdist(period, trials: 15, threshold: 7);
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
streaming.Update(source[i]);
|
||||
}
|
||||
|
||||
// Batch (TSeries)
|
||||
var batch = Binomdist.Batch(source, period, trials: 15, threshold: 7);
|
||||
|
||||
// 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];
|
||||
Binomdist.Batch(rawValues, spanOutput, period, trials: 15, threshold: 7);
|
||||
|
||||
// Eventing
|
||||
var eventResults = new List<double>();
|
||||
var eventSource = new TSeries();
|
||||
var eventIndicator = new Binomdist(eventSource, period, trials: 15, threshold: 7);
|
||||
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: 43003);
|
||||
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
var source = bars.Close;
|
||||
|
||||
var streaming = new Binomdist(period, trials: 10, threshold: 5);
|
||||
var streamingVals = new double[count];
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
streaming.Update(source[i]);
|
||||
streamingVals[i] = streaming.Last.Value;
|
||||
}
|
||||
|
||||
var batch = Binomdist.Batch(source, period, trials: 10, threshold: 5);
|
||||
|
||||
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>(() =>
|
||||
Binomdist.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>(() =>
|
||||
Binomdist.Batch(src, dst));
|
||||
Assert.Equal("output", 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>(() =>
|
||||
Binomdist.Batch(src, dst, period: 0));
|
||||
Assert.Equal("period", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Batch_Span_InvalidTrials_ThrowsArgumentException()
|
||||
{
|
||||
double[] src = { 1.0, 2.0, 3.0 };
|
||||
double[] dst = new double[3];
|
||||
var ex = Assert.Throws<ArgumentException>(() =>
|
||||
Binomdist.Batch(src, dst, trials: 0));
|
||||
Assert.Equal("trials", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Batch_Span_InvalidThreshold_ThrowsArgumentException()
|
||||
{
|
||||
double[] src = { 1.0, 2.0, 3.0 };
|
||||
double[] dst = new double[3];
|
||||
var ex = Assert.Throws<ArgumentException>(() =>
|
||||
Binomdist.Batch(src, dst, threshold: -1));
|
||||
Assert.Equal("threshold", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Batch_Span_OutputInRange()
|
||||
{
|
||||
int count = 100;
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 43004);
|
||||
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];
|
||||
Binomdist.Batch(src, dst, period: 20, trials: 10, threshold: 5);
|
||||
|
||||
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];
|
||||
Binomdist.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];
|
||||
Binomdist.Batch(src, dst, period: 300, trials: 20, threshold: 10);
|
||||
|
||||
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: 43005);
|
||||
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];
|
||||
Binomdist.Batch(src, spanOut, period: 14, trials: 10, threshold: 5);
|
||||
|
||||
var streaming = new Binomdist(period: 14, trials: 10, threshold: 5);
|
||||
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 Binomdist(period: 3, trials: 10, threshold: 5);
|
||||
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 Binomdist(source, period, trials: 10, threshold: 5);
|
||||
|
||||
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 Binomdist(period: 5, trials: 10, threshold: 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: Parameter combinations ───────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void DifferentTrialsThreshold_ProduceDifferentResults()
|
||||
{
|
||||
int count = 60;
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 43006);
|
||||
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
|
||||
var ind1 = new Binomdist(period: 20, trials: 10, threshold: 3);
|
||||
var ind2 = new Binomdist(period: 20, trials: 10, threshold: 5);
|
||||
var ind3 = new Binomdist(period: 20, trials: 20, threshold: 5);
|
||||
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
ind1.Update(bars.Close[i]);
|
||||
ind2.Update(bars.Close[i]);
|
||||
ind3.Update(bars.Close[i]);
|
||||
}
|
||||
|
||||
Assert.NotEqual(ind1.Last.Value, ind2.Last.Value, 1e-4);
|
||||
Assert.NotEqual(ind2.Last.Value, ind3.Last.Value, 1e-4);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Calculate_StaticMethod_ReturnsTuple()
|
||||
{
|
||||
int count = 50;
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 43007);
|
||||
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
|
||||
var (results, instance) = Binomdist.Calculate(bars.Close, period: 20);
|
||||
|
||||
Assert.Equal(count, results.Count);
|
||||
Assert.True(instance.IsHot);
|
||||
Assert.Equal(results[^1].Value, instance.Last.Value, Tolerance);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ThresholdZero_ProbabilityIsNearZeroForMidP()
|
||||
{
|
||||
// P(X<=0; n=10, p=0.5) = 0.5^10 ≈ 0.000977
|
||||
double cdf = Binomdist.BinomialCdf(0.5, 10, 0);
|
||||
Assert.True(Math.Abs(cdf - 0.0009765625) < 1e-10, $"Expected 0.0009765625 got {cdf}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ThresholdEqualN_ProbabilityIsOne()
|
||||
{
|
||||
// P(X<=n; n, p) = 1 for any p in (0,1)
|
||||
double cdf = Binomdist.BinomialCdf(0.7, 10, 10);
|
||||
Assert.Equal(1.0, cdf, 1e-10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ProbabilityZero_AlwaysReturnsOne()
|
||||
{
|
||||
// p=0: all mass at X=0, so P(X<=k) = 1 for k >= 0
|
||||
double cdf = Binomdist.BinomialCdf(0.0, 10, 5);
|
||||
Assert.Equal(1.0, cdf, Tolerance);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ProbabilityOne_ReturnsOneOnlyIfKGreaterEqualN()
|
||||
{
|
||||
// p=1: all mass at X=n, so P(X<=k) = 1 iff k >= n
|
||||
double cdfAtN = Binomdist.BinomialCdf(1.0, 10, 10);
|
||||
double cdfBelowN = Binomdist.BinomialCdf(1.0, 10, 5);
|
||||
Assert.Equal(1.0, cdfAtN, Tolerance);
|
||||
Assert.Equal(0.0, cdfBelowN, Tolerance);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
using Xunit;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Binomdist validation tests — validates PMF/CDF against exact combinatorial values.
|
||||
/// Known-value tests call Binomdist.BinomialCdf directly (bypassing windowing) so
|
||||
/// results are exact. Streaming/batch tests check invariants that hold regardless
|
||||
/// of window state.
|
||||
/// </summary>
|
||||
public class BinomdistValidationTests
|
||||
{
|
||||
private const double Tolerance = 1e-9;
|
||||
private const double LooseTolerance = 1e-6;
|
||||
|
||||
// ─── PMF known values ────────────────────────────────────────────────────
|
||||
// P(X=k; n, p) = C(n,k) * p^k * (1-p)^(n-k)
|
||||
// CDF P(X<=k) = sum_{i=0}^{k} P(X=i)
|
||||
|
||||
[Theory]
|
||||
// P(X=3; n=10, p=0.5) = C(10,3) * 0.5^10 = 120/1024 = 0.1171875
|
||||
// CDF P(X<=3; n=10, p=0.5) = (1+10+45+120)/1024 = 176/1024 = 0.171875
|
||||
[InlineData(0.5, 10, 3, 0.171875)]
|
||||
// P(X<=5; n=10, p=0.5) = 638/1024 = 0.623046875 (exact)
|
||||
[InlineData(0.5, 10, 5, 0.623046875)]
|
||||
// P(X<=0; n=5, p=0.3) = (0.7)^5 = 0.16807
|
||||
[InlineData(0.3, 5, 0, 0.16807)]
|
||||
// P(X<=5; n=5, p=0.3) = 1.0 (k >= n)
|
||||
[InlineData(0.3, 5, 5, 1.0)]
|
||||
// P(X<=0; n=10, p=0.5) = 0.5^10 = 1/1024 ≈ 0.0009765625
|
||||
[InlineData(0.5, 10, 0, 0.0009765625)]
|
||||
// P(X<=10; n=10, p=0.5) = 1.0
|
||||
[InlineData(0.5, 10, 10, 1.0)]
|
||||
// P(X<=0; n=1, p=0.5) = 0.5
|
||||
[InlineData(0.5, 1, 0, 0.5)]
|
||||
// P(X<=1; n=1, p=0.5) = 1.0
|
||||
[InlineData(0.5, 1, 1, 1.0)]
|
||||
// P(X<=2; n=5, p=0.5) = (1+5+10)/32 = 16/32 = 0.5
|
||||
[InlineData(0.5, 5, 2, 0.5)]
|
||||
// P(X<=4; n=5, p=0.3) = 1 - P(X=5) = 1 - 0.3^5 = 1 - 0.00243 = 0.99757
|
||||
[InlineData(0.3, 5, 4, 0.99757)]
|
||||
public void BinomCdf_KnownValues(double p, int n, int k, double expected)
|
||||
{
|
||||
double actual = Binomdist.BinomialCdf(p, n, k);
|
||||
Assert.Equal(expected, actual, LooseTolerance);
|
||||
}
|
||||
|
||||
// ─── PMF direct known values ─────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void BinomPmf_Exact_n10_p05_k3()
|
||||
{
|
||||
// P(X=3; n=10, p=0.5) = C(10,3) / 2^10 = 120/1024 = 0.1171875
|
||||
// PMF = CDF(k) - CDF(k-1)
|
||||
double cdfK = Binomdist.BinomialCdf(0.5, 10, 3);
|
||||
double cdfKm1 = Binomdist.BinomialCdf(0.5, 10, 2);
|
||||
double pmf = cdfK - cdfKm1;
|
||||
Assert.Equal(0.1171875, pmf, Tolerance);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BinomPmf_Exact_n5_p03_k0()
|
||||
{
|
||||
// P(X=0; n=5, p=0.3) = (0.7)^5 = 0.16807
|
||||
// CDF(0) - CDF(-1) = CDF(0) = 0.16807
|
||||
double cdf = Binomdist.BinomialCdf(0.3, 5, 0);
|
||||
Assert.Equal(0.16807, cdf, Tolerance);
|
||||
}
|
||||
|
||||
// ─── Monotonicity ─────────────────────────────────────────────────────────
|
||||
|
||||
[Theory]
|
||||
[InlineData(0.3, 10)]
|
||||
[InlineData(0.5, 10)]
|
||||
[InlineData(0.7, 20)]
|
||||
[InlineData(0.1, 5)]
|
||||
public void BinomCdf_Monotonic_InK(double p, int n)
|
||||
{
|
||||
// CDF must be non-decreasing in k
|
||||
double prev = 0.0;
|
||||
for (int k = 0; k <= n; k++)
|
||||
{
|
||||
double cdf = Binomdist.BinomialCdf(p, n, k);
|
||||
Assert.True(cdf >= prev - 1e-12,
|
||||
$"CDF not monotonic at k={k}, p={p}, n={n}: got {cdf}, prev={prev}");
|
||||
prev = cdf;
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BinomCdf_MonotonicInP()
|
||||
{
|
||||
// P(X<=5; n=10, p) must be bounded [0,1] for all p
|
||||
int n = 10, k = 5;
|
||||
for (int i = 1; i <= 9; i++)
|
||||
{
|
||||
double p = i / 10.0;
|
||||
double cdf = Binomdist.BinomialCdf(p, n, k);
|
||||
Assert.True(cdf >= 0.0 && cdf <= 1.0,
|
||||
$"CDF out of bounds: {cdf} at p={p}");
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Boundary behavior ────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void BinomCdf_P_Zero_ReturnsOne()
|
||||
{
|
||||
Assert.Equal(1.0, Binomdist.BinomialCdf(0.0, 10, 0), Tolerance);
|
||||
Assert.Equal(1.0, Binomdist.BinomialCdf(0.0, 10, 10), Tolerance);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BinomCdf_P_One_KLessN_ReturnsZero()
|
||||
{
|
||||
Assert.Equal(0.0, Binomdist.BinomialCdf(1.0, 10, 5), Tolerance);
|
||||
Assert.Equal(0.0, Binomdist.BinomialCdf(1.0, 10, 9), Tolerance);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BinomCdf_P_One_KEqualN_ReturnsOne()
|
||||
{
|
||||
Assert.Equal(1.0, Binomdist.BinomialCdf(1.0, 10, 10), Tolerance);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BinomCdf_KN_ReturnsOne()
|
||||
{
|
||||
// P(X<=n; n, p) = 1 for all p in (0,1)
|
||||
Assert.Equal(1.0, Binomdist.BinomialCdf(0.3, 5, 5), Tolerance);
|
||||
Assert.Equal(1.0, Binomdist.BinomialCdf(0.5, 10, 10), Tolerance);
|
||||
Assert.Equal(1.0, Binomdist.BinomialCdf(0.9, 20, 20), Tolerance);
|
||||
}
|
||||
|
||||
// ─── Output bounds ─────────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void BinomCdf_OutputBounded_Zero_To_One()
|
||||
{
|
||||
int count = 200;
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.3, seed: 52001);
|
||||
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
|
||||
var indicator = new Binomdist(period: 20, trials: 10, threshold: 5);
|
||||
|
||||
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 → neutral CDF ─────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void BinomCdf_FlatRange_ReturnsSymmetricCdf()
|
||||
{
|
||||
// Flat range → p=0.5; for symmetric n=10, k=5: CDF = 0.623046875
|
||||
var ind = new Binomdist(20, trials: 10, threshold: 5);
|
||||
var time = DateTime.UtcNow;
|
||||
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
ind.Update(new TValue(time.AddSeconds(i), 100.0));
|
||||
}
|
||||
|
||||
Assert.Equal(0.623046875, ind.Last.Value, LooseTolerance);
|
||||
}
|
||||
|
||||
// ─── Period=1 trivial case ────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void BinomCdf_Period1_AlwaysReturnsCdfAtHalf()
|
||||
{
|
||||
// period=1: single-element window → range=0 → p=0.5 always
|
||||
var ind = new Binomdist(1, trials: 10, threshold: 5);
|
||||
var time = DateTime.UtcNow;
|
||||
|
||||
double expected = Binomdist.BinomialCdf(0.5, 10, 5);
|
||||
double[] prices = { 100.0, 50.0, 200.0, 1.0, 1000.0 };
|
||||
foreach (double p in prices)
|
||||
{
|
||||
ind.Update(new TValue(time, p));
|
||||
time = time.AddMinutes(1);
|
||||
Assert.Equal(expected, ind.Last.Value, LooseTolerance);
|
||||
}
|
||||
}
|
||||
|
||||
// ─── 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: 52002);
|
||||
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 = Binomdist.Batch(bars.Close, period: 30, trials: 15, threshold: 7);
|
||||
double[] spanResult = new double[count];
|
||||
Binomdist.Batch(rawValues, spanResult, period: 30, trials: 15, threshold: 7);
|
||||
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
Assert.Equal(tseriesResult[i].Value, spanResult[i], Tolerance);
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Large n stability ────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void BinomCdf_LargeN_Stable()
|
||||
{
|
||||
// Large n tests log-space summation's overflow avoidance
|
||||
double cdf = Binomdist.BinomialCdf(0.5, 100, 50);
|
||||
Assert.True(double.IsFinite(cdf) && cdf >= 0.0 && cdf <= 1.0,
|
||||
$"Large n CDF invalid: {cdf}");
|
||||
// n=100, k=50, p=0.5 should be near 0.54 (slightly above 0.5)
|
||||
Assert.True(cdf > 0.5 && cdf < 0.7, $"CDF={cdf} expected near 0.54");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BinomCdf_LargeDataset_Stable()
|
||||
{
|
||||
int count = 2000;
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 52003);
|
||||
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
|
||||
var indicator = new Binomdist(period: 50, trials: 20, threshold: 10);
|
||||
|
||||
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}");
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Different parameter combos all produce output in range ──────────────
|
||||
|
||||
[Theory]
|
||||
[InlineData(5, 5, 2)]
|
||||
[InlineData(14, 10, 5)]
|
||||
[InlineData(50, 20, 10)]
|
||||
[InlineData(100, 50, 25)]
|
||||
[InlineData(30, 1, 0)]
|
||||
public void BinomCdf_ParameterCombos_OutputBounded(int period, int trials, int threshold)
|
||||
{
|
||||
int count = period + 50;
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 52004 + period);
|
||||
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
|
||||
var indicator = new Binomdist(period, trials, threshold);
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Streaming convergence ────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void BinomCdf_HighPeriod_StillConverges()
|
||||
{
|
||||
int period = 200;
|
||||
var indicator = new Binomdist(period, trials: 20, threshold: 10);
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.3, seed: 52005);
|
||||
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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,355 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace QuanTAlib;
|
||||
|
||||
/// <summary>
|
||||
/// BINOMDIST: Binomial Distribution CDF
|
||||
/// Computes P(X ≤ k) for X ~ Binomial(n, p), where p is derived from the
|
||||
/// min-max normalized position of the input price within its rolling window.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Key properties:
|
||||
/// - Output always in [0, 1]
|
||||
/// - Rolling window tracks min/max for normalization; flat range returns P(X≤k|p=0.5)
|
||||
/// - p ≤ 0: returns 1.0 (all probability mass at X=0, P(X≤k)=1 for k≥0)
|
||||
/// - p ≥ 1: returns 1.0 if k≥n, else 0.0 (all mass at X=n)
|
||||
/// - Log-space computation via Lanczos log-gamma avoids factorial overflow for large n
|
||||
/// </remarks>
|
||||
[SkipLocalsInit]
|
||||
public sealed class Binomdist : AbstractBase
|
||||
{
|
||||
private readonly int _period;
|
||||
private readonly int _trials;
|
||||
private readonly int _threshold;
|
||||
private readonly RingBuffer _buffer;
|
||||
|
||||
// Lanczos g=7, 9 coefficients (Numerical Recipes 3rd Ed., Table 6.1)
|
||||
private static ReadOnlySpan<double> LanczosCoeff =>
|
||||
[
|
||||
0.99999999999980993,
|
||||
676.5203681218851,
|
||||
-1259.1392167224028,
|
||||
771.32342877765313,
|
||||
-176.61502916214059,
|
||||
12.507343278686905,
|
||||
-0.13857109526572012,
|
||||
9.9843695780195716e-6,
|
||||
1.5056327351493116e-7
|
||||
];
|
||||
|
||||
[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 Binomdist indicator.
|
||||
/// </summary>
|
||||
/// <param name="period">Lookback window for min-max normalization (default 50)</param>
|
||||
/// <param name="trials">Number of Bernoulli trials n (default 20)</param>
|
||||
/// <param name="threshold">Success threshold k — computes P(X ≤ k) (default 10)</param>
|
||||
public Binomdist(int period = 50, int trials = 20, int threshold = 10)
|
||||
{
|
||||
if (period < 1)
|
||||
{
|
||||
throw new ArgumentException("Period must be >= 1", nameof(period));
|
||||
}
|
||||
|
||||
if (trials < 1)
|
||||
{
|
||||
throw new ArgumentException("Trials must be >= 1", nameof(trials));
|
||||
}
|
||||
|
||||
if (threshold < 0)
|
||||
{
|
||||
throw new ArgumentException("Threshold must be >= 0", nameof(threshold));
|
||||
}
|
||||
|
||||
_period = period;
|
||||
_trials = trials;
|
||||
_threshold = threshold;
|
||||
_buffer = new RingBuffer(period);
|
||||
Name = $"Binomdist({period},{trials},{threshold})";
|
||||
WarmupPeriod = period;
|
||||
_state = new State(BinomCdf(0.5, trials, threshold));
|
||||
_p_state = _state;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new Binomdist indicator with source for event-based chaining.
|
||||
/// </summary>
|
||||
/// <param name="source">Source indicator for chaining</param>
|
||||
/// <param name="period">Lookback window (default 50)</param>
|
||||
/// <param name="trials">Number of Bernoulli trials n (default 20)</param>
|
||||
/// <param name="threshold">Success threshold k (default 10)</param>
|
||||
public Binomdist(ITValuePublisher source, int period = 50, int trials = 20, int threshold = 10)
|
||||
: this(period, trials, threshold)
|
||||
{
|
||||
source.Pub += HandleUpdate;
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void HandleUpdate(object? sender, in TValueEventArgs e) => Update(e.Value, e.IsNew);
|
||||
|
||||
/// <summary>
|
||||
/// Lanczos approximation of ln(Gamma(z)) for z > 0.
|
||||
/// g=7, 9 coefficients — accurate to ~15 significant digits.
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static double LnGamma(double z)
|
||||
{
|
||||
double x = z - 1.0;
|
||||
double t = x + 7.5; // g + 0.5 where g = 7
|
||||
double ser = LanczosCoeff[0];
|
||||
for (int k = 1; k <= 8; k++)
|
||||
{
|
||||
ser += LanczosCoeff[k] / (x + k);
|
||||
}
|
||||
|
||||
return 0.5 * Math.Log(2.0 * Math.PI)
|
||||
+ (x + 0.5) * Math.Log(t)
|
||||
- t
|
||||
+ Math.Log(ser);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Log of binomial coefficient: ln C(n, i) = lnGamma(n+1) - lnGamma(i+1) - lnGamma(n-i+1).
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static double LnBinom(int n, int i)
|
||||
=> LnGamma(n + 1.0) - LnGamma(i + 1.0) - LnGamma(n - i + 1.0);
|
||||
|
||||
/// <summary>
|
||||
/// Binomial CDF P(X ≤ k) for X ~ Binomial(n, p) via log-space summation.
|
||||
/// Avoids factorial overflow for large n.
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal static double BinomCdf(double p, int n, int k)
|
||||
{
|
||||
if (p <= 0.0)
|
||||
{
|
||||
return k >= 0 ? 1.0 : 0.0;
|
||||
}
|
||||
|
||||
if (p >= 1.0)
|
||||
{
|
||||
return k >= n ? 1.0 : 0.0;
|
||||
}
|
||||
|
||||
double lnP = Math.Log(p);
|
||||
double lnQ = Math.Log(1.0 - p);
|
||||
double cdf = 0.0;
|
||||
int kk = Math.Min(k, n);
|
||||
|
||||
for (int i = 0; i <= kk; i++)
|
||||
{
|
||||
double lnTerm = Math.FusedMultiplyAdd(i, lnP, Math.FusedMultiplyAdd(n - i, lnQ, LnBinom(n, i)));
|
||||
cdf += Math.Exp(lnTerm);
|
||||
}
|
||||
|
||||
return Math.Min(cdf, 1.0);
|
||||
}
|
||||
|
||||
[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 → neutral p=0.5
|
||||
double p = range > 0.0 ? (value - min) / range : 0.5;
|
||||
|
||||
result = BinomCdf(p, _trials, _threshold);
|
||||
_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 period = 50, int trials = 20, int threshold = 10)
|
||||
{
|
||||
var indicator = new Binomdist(period, trials, threshold);
|
||||
return indicator.Update(source);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Calculates Binomial 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 period = 50, int trials = 20, int threshold = 10)
|
||||
{
|
||||
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 (period < 1)
|
||||
{
|
||||
throw new ArgumentException("Period must be >= 1", nameof(period));
|
||||
}
|
||||
|
||||
if (trials < 1)
|
||||
{
|
||||
throw new ArgumentException("Trials must be >= 1", nameof(trials));
|
||||
}
|
||||
|
||||
if (threshold < 0)
|
||||
{
|
||||
throw new ArgumentException("Threshold must be >= 0", nameof(threshold));
|
||||
}
|
||||
|
||||
double lastValid = BinomCdf(0.5, trials, threshold);
|
||||
|
||||
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 p = range > 0.0 ? (val - min) / range : 0.5;
|
||||
|
||||
double result = BinomCdf(p, trials, threshold);
|
||||
lastValid = result;
|
||||
output[i] = result;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Exposes the Binomial CDF directly for testing and downstream consumers.
|
||||
/// </summary>
|
||||
public static double BinomialCdf(double p, int n, int k)
|
||||
=> BinomCdf(p, n, k);
|
||||
|
||||
public static (TSeries Results, Binomdist Indicator) Calculate(
|
||||
TSeries source, int period = 50, int trials = 20, int threshold = 10)
|
||||
{
|
||||
var indicator = new Binomdist(period, trials, threshold);
|
||||
TSeries results = indicator.Update(source);
|
||||
return (results, indicator);
|
||||
}
|
||||
|
||||
public override void Reset()
|
||||
{
|
||||
_buffer.Clear();
|
||||
_state = new State(BinomCdf(0.5, _trials, _threshold));
|
||||
_p_state = _state;
|
||||
Last = default;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user