adding missing validations

This commit is contained in:
Miha Kralj
2026-02-26 09:59:44 -08:00
parent 467a8c1cef
commit 9ab37c1200
231 changed files with 60015 additions and 302 deletions
@@ -0,0 +1,195 @@
using Xunit;
using TradingPlatform.BusinessLayer;
namespace QuanTAlib.Tests;
public class WeibulldistIndicatorTests
{
[Fact]
public void WeibulldistIndicator_Constructor_SetsDefaults()
{
var indicator = new WeibulldistIndicator();
Assert.Equal(SourceType.Close, indicator.Source);
Assert.Equal(1.5, indicator.K);
Assert.Equal(1.0, indicator.Lambda);
Assert.Equal(14, indicator.Period);
Assert.True(indicator.ShowColdValues);
Assert.Equal("WEIBULLDIST - Weibull Distribution CDF", indicator.Name);
Assert.True(indicator.SeparateWindow);
Assert.True(indicator.OnBackGround);
}
[Fact]
public void WeibulldistIndicator_MinHistoryDepths_EqualsPeriod()
{
var indicator = new WeibulldistIndicator { Period = 30 };
Assert.Equal(30, indicator.MinHistoryDepths);
}
[Fact]
public void WeibulldistIndicator_ShortName_IsCorrect()
{
var indicator = new WeibulldistIndicator { K = 2.0, Lambda = 0.5, Period = 20 };
Assert.Equal("WEIBULLDIST(2.00,0.50,20)", indicator.ShortName);
}
[Fact]
public void WeibulldistIndicator_Initialize_CreatesTwoLineSeries()
{
var indicator = new WeibulldistIndicator();
indicator.Initialize();
Assert.Equal(2, indicator.LinesSeries.Count);
Assert.Equal("WeibullDist", indicator.LinesSeries[0].Name);
Assert.Equal("Mid", indicator.LinesSeries[1].Name);
}
[Fact]
public void WeibulldistIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
{
var indicator = new WeibulldistIndicator { 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 5 bars (= period), 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 WeibulldistIndicator_ProcessUpdate_NewBar_AddsNewValue()
{
var indicator = new WeibulldistIndicator { 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 WeibulldistIndicator_ProcessUpdate_NewTick_ProcessesWithoutError()
{
var indicator = new WeibulldistIndicator { 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 WeibulldistIndicator_MidLine_IsAlwaysHalf()
{
var indicator = new WeibulldistIndicator { 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 WeibulldistIndicator_DifferentSourceType_Works()
{
var indicator = new WeibulldistIndicator { Period = 3, Source = SourceType.High };
indicator.Initialize();
var now = DateTime.UtcNow;
for (int i = 0; i < 3; i++)
{
// High = 110+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 WeibulldistIndicator_OutputInRange_AfterManyBars()
{
var indicator = new WeibulldistIndicator { Period = 20 };
indicator.Initialize();
var now = DateTime.UtcNow;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 74001);
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 WeibulldistIndicator_HighK_OutputFinite()
{
// With k=5.0, S-curve shape; CDF stays low until near scale
var indicator = new WeibulldistIndicator { Period = 5, K = 5.0, Lambda = 1.0 };
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 WeibulldistIndicator_CustomParams_ShortNameReflects()
{
var indicator = new WeibulldistIndicator { K = 3.6, Lambda = 2.0, Period = 30 };
Assert.Equal("WEIBULLDIST(3.60,2.00,30)", indicator.ShortName);
}
}
@@ -0,0 +1,72 @@
using System.Drawing;
using TradingPlatform.BusinessLayer;
using static QuanTAlib.IndicatorExtensions;
namespace QuanTAlib;
/// <summary>
/// WEIBULLDIST (Weibull Distribution CDF) Quantower indicator.
/// Computes F(x; k, λ) = 1 - exp(-(x/λ)^k) applied to a min-max normalized
/// price series over a rolling lookback window.
/// </summary>
public class WeibulldistIndicator : Indicator, IWatchlistIndicator
{
[DataSourceInput]
public SourceType Source { get; set; } = SourceType.Close;
[InputParameter("Shape (k)", sortIndex: 0, minimum: 0.001, maximum: 100.0, increment: 0.1, decimalPlaces: 3)]
public double K { get; set; } = 1.5;
[InputParameter("Scale (λ)", sortIndex: 1, minimum: 0.001, maximum: 100.0, increment: 0.1, decimalPlaces: 3)]
public double Lambda { get; set; } = 1.0;
[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 Weibulldist? _weibulldist;
private Func<IHistoryItem, double>? _selector;
public int MinHistoryDepths => Period;
public override string ShortName => $"WEIBULLDIST({K:F2},{Lambda:F2},{Period})";
public WeibulldistIndicator()
{
Name = "WEIBULLDIST - Weibull Distribution CDF";
Description = "Applies the Weibull CDF to a min-max normalized price series";
SeparateWindow = true;
OnBackGround = true;
}
protected override void OnInit()
{
_weibulldist = new Weibulldist(K, Lambda, Period);
_selector = Source.GetPriceSelector();
AddLineSeries(new LineSeries("WeibullDist", 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 (_weibulldist == null || _selector == null)
{
return;
}
var item = HistoricalData[0, SeekOriginHistory.End];
double value = _selector(item);
bool isNew = args.IsNewBar();
TValue input = new(item.TimeLeft, value);
_weibulldist.Update(input, isNew);
bool isHot = _weibulldist.IsHot;
LinesSeries[0].SetValue(_weibulldist.Last.Value, isHot, ShowColdValues);
LinesSeries[1].SetValue(0.5, isHot, ShowColdValues);
}
}
@@ -0,0 +1,689 @@
using Xunit;
namespace QuanTAlib.Tests;
public class WeibulldistTests
{
private const double Tolerance = 1e-10;
// ─── A) Constructor validation ────────────────────────────────────────────
[Fact]
public void Constructor_DefaultParameters_SetsProperties()
{
var indicator = new Weibulldist();
Assert.Equal("Weibulldist(1.50,1.00,14)", indicator.Name);
Assert.Equal(14, indicator.WarmupPeriod);
Assert.False(indicator.IsHot);
}
[Fact]
public void Constructor_CustomParameters_SetsName()
{
var indicator = new Weibulldist(k: 2.0, lambda: 0.5, period: 20);
Assert.Equal("Weibulldist(2.00,0.50,20)", indicator.Name);
Assert.Equal(20, indicator.WarmupPeriod);
}
[Fact]
public void Constructor_ZeroK_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentException>(() => new Weibulldist(k: 0.0));
Assert.Equal("k", ex.ParamName);
}
[Fact]
public void Constructor_NegativeK_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentException>(() => new Weibulldist(k: -1.0));
Assert.Equal("k", ex.ParamName);
}
[Fact]
public void Constructor_ZeroLambda_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentException>(() => new Weibulldist(lambda: 0.0));
Assert.Equal("lambda", ex.ParamName);
}
[Fact]
public void Constructor_NegativeLambda_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentException>(() => new Weibulldist(lambda: -1.0));
Assert.Equal("lambda", ex.ParamName);
}
[Fact]
public void Constructor_PeriodOne_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentException>(() => new Weibulldist(period: 1));
Assert.Equal("period", ex.ParamName);
}
[Fact]
public void Constructor_PeriodZero_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentException>(() => new Weibulldist(period: 0));
Assert.Equal("period", ex.ParamName);
}
[Fact]
public void Constructor_NegativePeriod_ThrowsArgumentException()
{
var ex = Assert.Throws<ArgumentException>(() => new Weibulldist(period: -1));
Assert.Equal("period", ex.ParamName);
}
// ─── B) Basic calculation ─────────────────────────────────────────────────
[Fact]
public void Update_ReturnsValidTValue()
{
var indicator = new Weibulldist(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 Weibulldist(k: 1.5, lambda: 1.0, 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 Weibulldist(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 Weibulldist(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_ReturnsNearOne()
{
// When current value equals window max, x=1.0 → high CDF value
var indicator = new Weibulldist(k: 2.0, lambda: 1.0, period: 5);
var time = DateTime.UtcNow;
double[] prices = { 100.0, 102.0, 98.0, 101.0, 110.0 }; // 110 is max
foreach (var p in prices)
{
indicator.Update(new TValue(time, p));
time = time.AddMinutes(1);
}
// CDF(1.0, k=2, λ=1) = 1 - exp(-1) ≈ 0.6321
Assert.True(indicator.Last.Value > 0.5, $"Expected > 0.5 but got {indicator.Last.Value}");
}
[Fact]
public void Update_AtMinOfWindow_ReturnsZero()
{
// When current value equals window min, x=0.0 → CDF(0, k, λ) = 0
var indicator = new Weibulldist(k: 2.0, lambda: 1.0, period: 5);
var time = DateTime.UtcNow;
double[] prices = { 110.0, 102.0, 98.0, 101.0, 90.0 }; // 90 is min
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 Weibulldist(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 Weibulldist(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
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: 72001);
var bars = gbm.Fetch(20, time.Ticks, TimeSpan.FromMinutes(1));
// Streaming without corrections
var straight = new Weibulldist(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 Weibulldist(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 Weibulldist(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 Weibulldist(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 Weibulldist(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 Weibulldist(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 Weibulldist(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 Weibulldist(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_ReturnsCdfAtHalf()
{
// When all values in window are identical, range=0 → x=0.5
var indicator = new Weibulldist(k: 2.0, lambda: 1.0, period: 5);
var time = DateTime.UtcNow;
for (int i = 0; i < 10; i++)
{
indicator.Update(new TValue(time.AddMinutes(i), 100.0));
}
// CDF(0.5/1.0, k=2, λ=1) = 1 - exp(-0.5^2) = 1 - exp(-0.25)
double expected = 1.0 - Math.Exp(-Math.Pow(0.5, 2.0));
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: 72002);
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
var source = bars.Close;
// Streaming
var streaming = new Weibulldist(period: period);
for (int i = 0; i < source.Count; i++)
{
streaming.Update(source[i]);
}
// Batch (TSeries)
var batch = Weibulldist.Batch(source, 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];
Weibulldist.Batch(rawValues, spanOutput, period: period);
// Eventing
var eventResults = new List<double>();
var eventSource = new TSeries();
var eventIndicator = new Weibulldist(eventSource, 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);
}
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: 72003);
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
var source = bars.Close;
var streaming = new Weibulldist(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 = Weibulldist.Batch(source, 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>(() =>
Weibulldist.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>(() =>
Weibulldist.Batch(src, dst));
Assert.Equal("output", ex.ParamName);
}
[Fact]
public void Batch_Span_InvalidK_ThrowsArgumentException()
{
double[] src = { 1.0, 2.0, 3.0 };
double[] dst = new double[3];
var ex = Assert.Throws<ArgumentException>(() =>
Weibulldist.Batch(src, dst, k: 0.0));
Assert.Equal("k", ex.ParamName);
}
[Fact]
public void Batch_Span_NegativeK_ThrowsArgumentException()
{
double[] src = { 1.0, 2.0, 3.0 };
double[] dst = new double[3];
var ex = Assert.Throws<ArgumentException>(() =>
Weibulldist.Batch(src, dst, k: -0.5));
Assert.Equal("k", ex.ParamName);
}
[Fact]
public void Batch_Span_InvalidLambda_ThrowsArgumentException()
{
double[] src = { 1.0, 2.0, 3.0 };
double[] dst = new double[3];
var ex = Assert.Throws<ArgumentException>(() =>
Weibulldist.Batch(src, dst, lambda: 0.0));
Assert.Equal("lambda", ex.ParamName);
}
[Fact]
public void Batch_Span_NegativeLambda_ThrowsArgumentException()
{
double[] src = { 1.0, 2.0, 3.0 };
double[] dst = new double[3];
var ex = Assert.Throws<ArgumentException>(() =>
Weibulldist.Batch(src, dst, lambda: -1.0));
Assert.Equal("lambda", 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>(() =>
Weibulldist.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: 72004);
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];
Weibulldist.Batch(src, dst, 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];
Weibulldist.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];
Weibulldist.Batch(src, dst, 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: 72005);
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];
Weibulldist.Batch(src, spanOut, period: 14);
var streaming = new Weibulldist(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 Weibulldist(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 Weibulldist(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 Weibulldist(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: Shape/scale parameter effects ───────────────────────────
[Fact]
public void DifferentShapes_ProduceDifferentResults()
{
// Verify at a non-boundary interior point (x=0.4, lambda=1.0) that different k values
// produce provably distinct CDF outputs — no GBM needed for this mathematical property
const double x = 0.4;
const double lambda = 1.0;
double cdf05 = Weibulldist.StaticCdf(x, k: 0.5, lambda: lambda); // concave, fast rise
double cdf15 = Weibulldist.StaticCdf(x, k: 1.5, lambda: lambda); // intermediate
double cdf50 = Weibulldist.StaticCdf(x, k: 5.0, lambda: lambda); // sigmoidal, slow rise
// All in [0,1]
Assert.InRange(cdf05, 0.0, 1.0);
Assert.InRange(cdf15, 0.0, 1.0);
Assert.InRange(cdf50, 0.0, 1.0);
// k=0.5 (concave) > k=1.5 > k=5.0 (sigmoidal) at x=0.4 < lambda: strict ordering
Assert.True(cdf05 > cdf15 + 1e-6, $"k=0.5 ({cdf05:G10}) should exceed k=1.5 ({cdf15:G10}) at x={x}");
Assert.True(cdf15 > cdf50 + 1e-6, $"k=1.5 ({cdf15:G10}) should exceed k=5.0 ({cdf50:G10}) at x={x}");
}
[Fact]
public void Calculate_StaticMethod_ReturnsTuple()
{
int count = 50;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 72007);
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
var (results, instance) = Weibulldist.Calculate(bars.Close, period: 20);
Assert.Equal(count, results.Count);
Assert.True(instance.IsHot);
Assert.Equal(results[^1].Value, instance.Last.Value, Tolerance);
}
}
@@ -0,0 +1,355 @@
using Xunit;
using MathNet.Numerics.Distributions;
namespace QuanTAlib.Tests;
/// <summary>
/// WeibulldistValidationTests — validates against known mathematical properties
/// of the Weibull CDF and cross-validates with MathNet.Numerics.Distributions.Weibull.
/// StaticCdf tests call Weibulldist.StaticCdf directly (bypassing windowing)
/// so results are exact closed-form comparisons.
/// </summary>
public class WeibulldistValidationTests
{
private const double Tolerance = 1e-9;
private const double LooseTolerance = 1e-6;
// ─── Known-value tests via StaticCdf static method ───────────────────────
// F(x; k, λ) = 1 - exp(-(x/λ)^k), closed-form.
[Theory]
[InlineData(0.0, 1.5, 1.0, 0.0)] // F(0; k, λ) = 0 always
[InlineData(1.0, 1.0, 1.0, 0.6321205588285578)] // k=1: exponential, F(1;1,1) = 1-1/e
[InlineData(1.0, 2.0, 1.0, 0.6321205588285578)] // F(λ; k, λ) = 1-1/e for any k (x=λ=1)
[InlineData(1.0, 1.5, 1.0, 0.6321205588285578)] // F(λ; k, λ) = 1-1/e (x=λ=1)
[InlineData(1.0, 3.0, 1.0, 0.6321205588285578)] // F(λ; k, λ) = 1-1/e (x=λ=1)
[InlineData(2.0, 2.0, 2.0, 0.6321205588285578)] // F(λ=2; k=2, λ=2) = 1-1/e
[InlineData(0.5, 1.0, 1.0, 0.3934693402873666)] // k=1: F(0.5;1,1)=1-exp(-0.5)
[InlineData(1.0, 2.0, 2.0, 0.2211992169285951)] // F(1;2,2)=1-exp(-0.25)
[InlineData(2.0, 1.0, 1.0, 0.8646647167633873)] // k=1: F(2;1,1)=1-exp(-2)
public void StaticCdf_KnownValues(double x, double k, double lambda, double expected)
{
double actual = Weibulldist.StaticCdf(x, k, lambda);
Assert.Equal(expected, actual, LooseTolerance);
}
// ─── Boundary conditions ─────────────────────────────────────────────────
[Theory]
[InlineData(1.5, 1.0)]
[InlineData(2.0, 2.0)]
[InlineData(5.0, 0.5)]
[InlineData(0.5, 3.0)]
public void StaticCdf_AtZero_IsAlwaysZero(double k, double lambda)
{
Assert.Equal(0.0, Weibulldist.StaticCdf(0.0, k, lambda), Tolerance);
}
[Theory]
[InlineData(1.5, 1.0)]
[InlineData(2.0, 0.5)]
[InlineData(0.5, 2.0)]
public void StaticCdf_AtNegative_IsAlwaysZero(double k, double lambda)
{
Assert.Equal(0.0, Weibulldist.StaticCdf(-1.0, k, lambda), Tolerance);
Assert.Equal(0.0, Weibulldist.StaticCdf(-100.0, k, lambda), Tolerance);
}
[Theory]
[InlineData(1.5, 1.0)]
[InlineData(2.0, 2.0)]
[InlineData(0.5, 0.5)]
public void StaticCdf_AtLargeX_ApproachesOne(double k, double lambda)
{
double cdf = Weibulldist.StaticCdf(1000.0, k, lambda);
Assert.Equal(1.0, cdf, LooseTolerance);
}
// ─── Characteristic life property: F(λ; k, λ) = 1 - 1/e for any k ───────
[Theory]
[InlineData(0.5, 0.5)]
[InlineData(1.0, 1.0)]
[InlineData(1.5, 1.0)]
[InlineData(2.0, 2.0)]
[InlineData(3.6, 0.5)]
[InlineData(5.0, 3.0)]
public void StaticCdf_AtCharacteristicLife_Is1MinusInvE(double k, double lambda)
{
// CDF(lambda, k, lambda) = 1 - exp(-(lambda/lambda)^k) = 1 - exp(-1) for any k
double expected = 1.0 - Math.Exp(-1.0); // ≈ 0.6321205588285578
double actual = Weibulldist.StaticCdf(lambda, k, lambda);
Assert.Equal(expected, actual, LooseTolerance);
}
// ─── k=1 reduces to Exponential distribution ─────────────────────────────
[Theory]
[InlineData(0.5, 1.0)]
[InlineData(1.0, 1.0)]
[InlineData(2.0, 2.0)]
[InlineData(0.3, 0.5)]
public void StaticCdf_KEquals1_MatchesExponential(double x, double lambda)
{
// Weibull(k=1, λ) = Exponential(rate=1/λ)
double weibull = Weibulldist.StaticCdf(x, 1.0, lambda);
double exponential = 1.0 - Math.Exp(-x / lambda);
Assert.Equal(exponential, weibull, Tolerance);
}
// ─── Monotonicity ────────────────────────────────────────────────────────
[Theory]
[InlineData(0.5)]
[InlineData(1.0)]
[InlineData(2.0)]
[InlineData(5.0)]
public void StaticCdf_MonotonicIncreasing(double k)
{
double lambda = 1.0;
double prev = -1.0;
for (int i = 0; i <= 30; i++)
{
double x = i * 0.1;
double cdf = Weibulldist.StaticCdf(x, k, lambda);
Assert.True(cdf >= prev - LooseTolerance,
$"CDF not monotonic at x={x}, k={k}: got {cdf}, prev={prev}");
prev = cdf;
}
}
// ─── MathNet cross-validation ─────────────────────────────────────────────
[Theory]
[InlineData(0.5, 1.5, 1.0)]
[InlineData(1.0, 1.0, 1.0)]
[InlineData(1.0, 2.0, 1.0)]
[InlineData(0.5, 2.0, 0.5)]
[InlineData(2.0, 0.5, 2.0)]
[InlineData(1.5, 3.0, 1.5)]
[InlineData(3.0, 1.5, 2.0)]
[InlineData(0.1, 5.0, 1.0)]
[InlineData(0.9, 2.0, 1.0)]
[InlineData(2.5, 1.5, 2.0)]
public void StaticCdf_MatchesMathNet(double x, double k, double lambda)
{
// MathNet Weibull(shape, scale) = Weibull(k, lambda) — same parameterization
var dist = new Weibull(k, lambda);
double expected = dist.CumulativeDistribution(x);
double actual = Weibulldist.StaticCdf(x, k, lambda);
Assert.Equal(expected, actual, Tolerance);
}
[Fact]
public void StaticCdf_MathNet_ExtensiveComparison()
{
double[] kValues = { 0.5, 1.0, 1.5, 2.0, 3.6, 5.0 };
double[] lambdaValues = { 0.5, 1.0, 2.0 };
double[] xValues = { 0.0, 0.1, 0.5, 1.0, 1.5, 2.0, 5.0, 10.0 };
foreach (double k in kValues)
{
foreach (double lambda in lambdaValues)
{
var dist = new Weibull(k, lambda);
foreach (double x in xValues)
{
double expected = dist.CumulativeDistribution(x);
double actual = Weibulldist.StaticCdf(x, k, lambda);
// MathNet uses internal Taylor approximations; tolerance 1e-8 covers its rounding
Assert.Equal(expected, actual, LooseTolerance);
}
}
}
}
// ─── Flat range → F(0.5; k, λ) ───────────────────────────────────────────
[Theory]
[InlineData(1.5, 1.0)]
[InlineData(2.0, 0.5)]
[InlineData(1.0, 1.0)]
[InlineData(3.0, 2.0)]
public void WeibulldistCdf_FlatRange_ReturnsCdfAtHalf(double k, double lambda)
{
var ind = new Weibulldist(k, lambda, 20);
var time = DateTime.UtcNow;
for (int i = 0; i < 20; i++)
{
ind.Update(new TValue(time.AddSeconds(i), 100.0));
}
// Streaming normalizes to [0,1] then multiplies by invLambda before pow
// Equivalent: 1 - exp(-(0.5 * (1/lambda))^k)
double expectedDirect = 1.0 - Math.Exp(-Math.Pow(0.5 * (1.0 / lambda), k));
Assert.Equal(expectedDirect, ind.Last.Value, LooseTolerance);
}
// ─── Output bounded [0, 1] ────────────────────────────────────────────────
[Fact]
public void WeibulldistCdf_OutputBounded_Zero_To_One()
{
int count = 200;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.3, seed: 73001);
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
var indicator = new Weibulldist(k: 1.5, lambda: 1.0, 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]");
}
}
// ─── 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: 73002);
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 = Weibulldist.Batch(bars.Close, period: 30);
double[] spanResult = new double[count];
Weibulldist.Batch(rawValues, spanResult, period: 30);
for (int i = 0; i < count; i++)
{
Assert.Equal(tseriesResult[i].Value, spanResult[i], Tolerance);
}
}
// ─── Streaming convergence ────────────────────────────────────────────────
[Fact]
public void WeibulldistCdf_HighPeriod_StillConverges()
{
int period = 200;
var indicator = new Weibulldist(k: 2.0, lambda: 1.0, period: period);
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.3, seed: 73003);
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}");
}
}
[Fact]
public void WeibulldistCdf_ExtremePrices_StillInRange()
{
var indicator = new Weibulldist(k: 1.5, lambda: 1.0, 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}");
}
}
// ─── Parameter combos all produce output in range ─────────────────────────
[Theory]
[InlineData(5, 0.5, 1.0)]
[InlineData(14, 1.5, 1.0)]
[InlineData(50, 2.0, 0.5)]
[InlineData(20, 3.6, 2.0)]
[InlineData(30, 5.0, 1.0)]
public void WeibulldistCdf_ParameterCombos_OutputBounded(int period, double k, double lambda)
{
int count = period + 50;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 73004 + period);
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
var indicator = new Weibulldist(k, lambda, 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} (k={k}, lambda={lambda}, period={period})");
}
}
// ─── Large dataset: stable ────────────────────────────────────────────────
[Fact]
public void WeibulldistCdf_LargeDataset_Stable()
{
int count = 2000;
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 73005);
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
var indicator = new Weibulldist(k: 1.5, lambda: 1.0, 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}");
}
}
// ─── Survival function: F(x) + S(x) = 1 ─────────────────────────────────
[Fact]
public void StaticCdf_PlusSurvival_IsOne()
{
double[] kValues = { 0.5, 1.0, 2.0, 5.0 };
double[] lambdaValues = { 0.5, 1.0, 2.0 };
double[] xs = { 0.1, 0.5, 1.0, 2.0 };
foreach (double k in kValues)
{
foreach (double lambda in lambdaValues)
{
foreach (double x in xs)
{
double cdf = Weibulldist.StaticCdf(x, k, lambda);
double survival = Math.Exp(-Math.Pow(x / lambda, k));
Assert.Equal(1.0, cdf + survival, LooseTolerance);
}
}
}
}
// ─── Streaming vs MathNet cross-validation ────────────────────────────────
[Fact]
public void WeibulldistCdf_StreamingOutput_MatchesMathNetOnKnownData()
{
// Feed known values so streaming result is predictable via MathNet
// Period=3, strictly ascending: first 3 bars warm up, then check bar 3
var indicator = new Weibulldist(k: 2.0, lambda: 1.0, period: 3);
var time = DateTime.UtcNow;
// Values: 100, 102, 104 → x = (104-100)/(104-100) = 1.0
indicator.Update(new TValue(time, 100.0));
indicator.Update(new TValue(time.AddMinutes(1), 102.0));
indicator.Update(new TValue(time.AddMinutes(2), 104.0));
// After 3 bars: window = [100,102,104], min=100, max=104, range=4
// Current (104-100)/4 = 1.0 → x=1.0, CDF(1/1.0, k=2) = 1-exp(-1)
double expected = 1.0 - Math.Exp(-Math.Pow(1.0, 2.0)); // = 1 - exp(-1) ≈ 0.6321
Assert.Equal(expected, indicator.Last.Value, LooseTolerance);
}
}
+301
View File
@@ -0,0 +1,301 @@
// WEIBULLDIST: Weibull Distribution CDF
// Applies F(x; k, λ) = 1 - exp(-(x/λ)^k) to a min-max normalized price series
// over a rolling lookback window.
// Pipeline: MinMax normalization → closed-form CDF evaluation (one pow + one exp).
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace QuanTAlib;
/// <summary>
/// WEIBULLDIST: Weibull Distribution CDF
/// Computes F(x; k, λ) = 1 - exp(-(x/λ)^k) applied to a min-max normalized
/// price series over a rolling lookback window.
/// </summary>
/// <remarks>
/// Key properties:
/// - Output always in [0, 1]
/// - Rolling window tracks min/max for normalization; flat range returns F(0.5; k, λ)
/// - k (shape) controls CDF curvature: k&lt;1 concave, k=1 exponential, k=2 Rayleigh, k&gt;3 S-curve
/// - λ (scale) controls rise speed: larger λ → slower rise, smaller λ → faster saturation
/// - CDF at x=λ equals 1 - e^(-1) ≈ 0.6321 for any k (characteristic life property)
/// - Two operations: one Math.Pow + one Math.Exp — no special functions required
/// - NaN/Infinity inputs use last-valid-value substitution
/// </remarks>
[SkipLocalsInit]
public sealed class Weibulldist : AbstractBase
{
private readonly int _period;
private readonly double _k;
private readonly double _invLambda; // precomputed: 1 / lambda
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 Weibulldist indicator.
/// </summary>
/// <param name="k">Shape parameter k &gt; 0 (default 1.5)</param>
/// <param name="lambda">Scale parameter λ &gt; 0 (default 1.0)</param>
/// <param name="period">Lookback window for min-max normalization (default 14)</param>
public Weibulldist(double k = 1.5, double lambda = 1.0, int period = 14)
{
if (k <= 0.0)
{
throw new ArgumentException("Shape k must be > 0", nameof(k));
}
if (lambda <= 0.0)
{
throw new ArgumentException("Scale lambda must be > 0", nameof(lambda));
}
if (period < 2)
{
throw new ArgumentException("Period must be >= 2", nameof(period));
}
_k = k;
_invLambda = 1.0 / lambda;
_period = period;
_buffer = new RingBuffer(period);
Name = $"Weibulldist({k:F2},{lambda:F2},{period})";
WarmupPeriod = period;
_state = new State(0.0);
_p_state = _state;
}
/// <summary>
/// Initializes a new Weibulldist indicator with source for event-based chaining.
/// </summary>
/// <param name="source">Source indicator for chaining</param>
/// <param name="k">Shape parameter k &gt; 0 (default 1.5)</param>
/// <param name="lambda">Scale parameter λ &gt; 0 (default 1.0)</param>
/// <param name="period">Lookback window (default 14)</param>
public Weibulldist(ITValuePublisher source, double k = 1.5, double lambda = 1.0, int period = 14)
: this(k, lambda, period)
{
source.Pub += HandleUpdate;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void HandleUpdate(object? sender, in TValueEventArgs e) => Update(e.Value, e.IsNew);
/// <summary>
/// Weibull CDF: F(x; k, λ) = 1 - exp(-(x/λ)^k) for x &gt; 0, else 0.
/// Closed-form; requires one Math.Pow + one Math.Exp call.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static double StaticCdf(double x, double k, double lambda)
{
if (x <= 0.0)
{
return 0.0;
}
return 1.0 - Math.Exp(-Math.Pow(x / lambda, k));
}
[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 to avoid degenerate output
double x = range > 0.0 ? (value - min) / range : 0.5;
// x ∈ [0,1]; apply Weibull CDF directly (λ scales within [0,1] domain)
result = 1.0 - Math.Exp(-Math.Pow(x * _invLambda, _k));
_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, double k = 1.5, double lambda = 1.0, int period = 14)
{
var indicator = new Weibulldist(k, lambda, period);
return indicator.Update(source);
}
/// <summary>
/// Calculates Weibull 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,
double k = 1.5, double lambda = 1.0, 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 (k <= 0.0)
{
throw new ArgumentException("Shape k must be > 0", nameof(k));
}
if (lambda <= 0.0)
{
throw new ArgumentException("Scale lambda must be > 0", nameof(lambda));
}
if (period < 2)
{
throw new ArgumentException("Period must be >= 2", nameof(period));
}
double invLambda = 1.0 / lambda;
double lastValid = 0.0;
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 x = range > 0.0 ? (val - min) / range : 0.5;
double result = 1.0 - Math.Exp(-Math.Pow(x * invLambda, k));
lastValid = result;
output[i] = result;
}
}
public static (TSeries Results, Weibulldist Indicator) Calculate(
TSeries source, double k = 1.5, double lambda = 1.0, int period = 14)
{
var indicator = new Weibulldist(k, lambda, period);
TSeries results = indicator.Update(source);
return (results, indicator);
}
public override void Reset()
{
_buffer.Clear();
_state = new State(0.0);
_p_state = _state;
Last = default;
}
}