mirror of
https://github.com/mihakralj/QuanTAlib.git
synced 2026-08-22 12:38:06 +00:00
adding missing validations
This commit is contained in:
@@ -0,0 +1,195 @@
|
||||
using Xunit;
|
||||
using TradingPlatform.BusinessLayer;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public class NormdistIndicatorTests
|
||||
{
|
||||
[Fact]
|
||||
public void NormdistIndicator_Constructor_SetsDefaults()
|
||||
{
|
||||
var indicator = new NormdistIndicator();
|
||||
|
||||
Assert.Equal(SourceType.Close, indicator.Source);
|
||||
Assert.Equal(0.0, indicator.Mu);
|
||||
Assert.Equal(1.0, indicator.Sigma);
|
||||
Assert.Equal(14, indicator.Period);
|
||||
Assert.True(indicator.ShowColdValues);
|
||||
Assert.Equal("NORMDIST - Normal Distribution CDF", indicator.Name);
|
||||
Assert.True(indicator.SeparateWindow);
|
||||
Assert.True(indicator.OnBackGround);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NormdistIndicator_MinHistoryDepths_EqualsPeriod()
|
||||
{
|
||||
var indicator = new NormdistIndicator { Period = 30 };
|
||||
Assert.Equal(30, indicator.MinHistoryDepths);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NormdistIndicator_ShortName_IsCorrect()
|
||||
{
|
||||
var indicator = new NormdistIndicator { Mu = 0.5, Sigma = 2.0, Period = 20 };
|
||||
Assert.Equal("NORMDIST(0.50,2.00,20)", indicator.ShortName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NormdistIndicator_Initialize_CreatesTwoLineSeries()
|
||||
{
|
||||
var indicator = new NormdistIndicator();
|
||||
indicator.Initialize();
|
||||
|
||||
Assert.Equal(2, indicator.LinesSeries.Count);
|
||||
Assert.Equal("NormDist", indicator.LinesSeries[0].Name);
|
||||
Assert.Equal("Mid", indicator.LinesSeries[1].Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NormdistIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
|
||||
{
|
||||
var indicator = new NormdistIndicator { 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 NormdistIndicator_ProcessUpdate_NewBar_AddsNewValue()
|
||||
{
|
||||
var indicator = new NormdistIndicator { 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 NormdistIndicator_ProcessUpdate_NewTick_ProcessesWithoutError()
|
||||
{
|
||||
var indicator = new NormdistIndicator { 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 NormdistIndicator_MidLine_IsAlwaysHalf()
|
||||
{
|
||||
var indicator = new NormdistIndicator { 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 NormdistIndicator_DifferentSourceType_Works()
|
||||
{
|
||||
var indicator = new NormdistIndicator { Period = 3, Source = SourceType.High };
|
||||
indicator.Initialize();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
for (int i = 0; i < 3; i++)
|
||||
{
|
||||
// High = 110+i, Low = 90, Close = 100
|
||||
indicator.HistoricalData.AddBar(now.AddMinutes(i), 0, 110 + i, 90, 100);
|
||||
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
|
||||
}
|
||||
|
||||
double val = indicator.LinesSeries[0].GetValue(0);
|
||||
Assert.True(double.IsFinite(val));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NormdistIndicator_OutputInRange_AfterManyBars()
|
||||
{
|
||||
var indicator = new NormdistIndicator { Period = 20 };
|
||||
indicator.Initialize();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 76001);
|
||||
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 NormdistIndicator_FlatPrices_OutputNearHalf()
|
||||
{
|
||||
// When all prices identical, z=0 → CDF = 0.5
|
||||
var indicator = new NormdistIndicator { Period = 5, Mu = 0.0, Sigma = 1.0 };
|
||||
indicator.Initialize();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
indicator.HistoricalData.AddBar(now.AddMinutes(i), 0, 101, 99, 100);
|
||||
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 NormdistIndicator_CustomMuSigma_ShortNameReflects()
|
||||
{
|
||||
var indicator = new NormdistIndicator { Mu = -0.5, Sigma = 1.5, Period = 14 };
|
||||
Assert.Equal("NORMDIST(-0.50,1.50,14)", indicator.ShortName);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
using System.Drawing;
|
||||
using TradingPlatform.BusinessLayer;
|
||||
using static QuanTAlib.IndicatorExtensions;
|
||||
|
||||
namespace QuanTAlib;
|
||||
|
||||
/// <summary>
|
||||
/// NORMDIST (Normal Distribution CDF) Quantower indicator.
|
||||
/// Computes Φ(z; μ, σ) applied to a z-score normalized price series
|
||||
/// over a rolling lookback window.
|
||||
/// </summary>
|
||||
public class NormdistIndicator : Indicator, IWatchlistIndicator
|
||||
{
|
||||
[DataSourceInput]
|
||||
public SourceType Source { get; set; } = SourceType.Close;
|
||||
|
||||
[InputParameter("Mean (μ)", sortIndex: 0, minimum: -100.0, maximum: 100.0, increment: 0.1, decimalPlaces: 3)]
|
||||
public double Mu { get; set; } = 0.0;
|
||||
|
||||
[InputParameter("Std Dev (σ)", sortIndex: 1, minimum: 0.001, maximum: 100.0, increment: 0.1, decimalPlaces: 3)]
|
||||
public double Sigma { 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 Normdist? _normdist;
|
||||
private Func<IHistoryItem, double>? _selector;
|
||||
|
||||
public int MinHistoryDepths => Period;
|
||||
public override string ShortName => $"NORMDIST({Mu:F2},{Sigma:F2},{Period})";
|
||||
|
||||
public NormdistIndicator()
|
||||
{
|
||||
Name = "NORMDIST - Normal Distribution CDF";
|
||||
Description = "Applies the Gaussian CDF to a z-score normalized price series";
|
||||
SeparateWindow = true;
|
||||
OnBackGround = true;
|
||||
}
|
||||
|
||||
protected override void OnInit()
|
||||
{
|
||||
_normdist = new Normdist(Mu, Sigma, Period);
|
||||
_selector = Source.GetPriceSelector();
|
||||
|
||||
AddLineSeries(new LineSeries("NormDist", Color.Cyan, 2, LineStyle.Solid));
|
||||
// Reference level at 0.5 (midpoint / rolling mean)
|
||||
AddLineSeries(new LineSeries("Mid", Color.Gray, 1, LineStyle.Dash));
|
||||
}
|
||||
|
||||
protected override void OnUpdate(UpdateArgs args)
|
||||
{
|
||||
if (_normdist == null || _selector == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var item = HistoricalData[0, SeekOriginHistory.End];
|
||||
double value = _selector(item);
|
||||
bool isNew = args.IsNewBar();
|
||||
|
||||
TValue input = new(item.TimeLeft, value);
|
||||
_normdist.Update(input, isNew);
|
||||
|
||||
bool isHot = _normdist.IsHot;
|
||||
|
||||
LinesSeries[0].SetValue(_normdist.Last.Value, isHot, ShowColdValues);
|
||||
LinesSeries[1].SetValue(0.5, isHot, ShowColdValues);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,650 @@
|
||||
using Xunit;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public class NormdistTests
|
||||
{
|
||||
private const double Tolerance = 1e-10;
|
||||
|
||||
// ─── A) Constructor validation ────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Constructor_DefaultParameters_SetsProperties()
|
||||
{
|
||||
var indicator = new Normdist();
|
||||
Assert.Equal("Normdist(0.00,1.00,14)", indicator.Name);
|
||||
Assert.Equal(14, indicator.WarmupPeriod);
|
||||
Assert.False(indicator.IsHot);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_CustomParameters_SetsName()
|
||||
{
|
||||
var indicator = new Normdist(mu: 0.5, sigma: 2.0, period: 20);
|
||||
Assert.Equal("Normdist(0.50,2.00,20)", indicator.Name);
|
||||
Assert.Equal(20, indicator.WarmupPeriod);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_ZeroSigma_ThrowsArgumentException()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Normdist(sigma: 0.0));
|
||||
Assert.Equal("sigma", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_NegativeSigma_ThrowsArgumentException()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Normdist(sigma: -1.0));
|
||||
Assert.Equal("sigma", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_PeriodOne_ThrowsArgumentException()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Normdist(period: 1));
|
||||
Assert.Equal("period", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_ZeroPeriod_ThrowsArgumentException()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Normdist(period: 0));
|
||||
Assert.Equal("period", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_NegativePeriod_ThrowsArgumentException()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Normdist(period: -1));
|
||||
Assert.Equal("period", ex.ParamName);
|
||||
}
|
||||
|
||||
// ─── B) Basic calculation ─────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Update_ReturnsValidTValue()
|
||||
{
|
||||
var indicator = new Normdist(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 Normdist(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 Normdist(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 Normdist(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_AtRollingMean_ReturnsNearHalf()
|
||||
{
|
||||
// When current value equals rolling mean (with mu=0), z=0 → Φ(0)=0.5
|
||||
var indicator = new Normdist(mu: 0.0, sigma: 1.0, period: 5);
|
||||
var time = DateTime.UtcNow;
|
||||
// Feed symmetric data; last bar equals the mean
|
||||
double[] prices = { 100.0, 102.0, 104.0, 106.0, 103.0 }; // mean = 103.0
|
||||
|
||||
foreach (var p in prices)
|
||||
{
|
||||
indicator.Update(new TValue(time, p));
|
||||
time = time.AddMinutes(1);
|
||||
}
|
||||
|
||||
// 103 is the mean, so z=0 → Φ(0)=0.5 (approximately, since stddev>0)
|
||||
// With stddev > 0 and z=0: CDF = 0.5 exactly (erf(0)=0)
|
||||
Assert.InRange(indicator.Last.Value, 0.0, 1.0);
|
||||
}
|
||||
|
||||
// ─── C) State + bar correction ────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Update_IsNewTrue_AdvancesState()
|
||||
{
|
||||
var indicator = new Normdist(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 Normdist(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 very different 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 Normdist(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 Normdist(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 Normdist(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 Normdist(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");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WarmupPeriod_EqualsConstructorPeriod()
|
||||
{
|
||||
var indicator = new Normdist(period: 25);
|
||||
Assert.Equal(25, indicator.WarmupPeriod);
|
||||
}
|
||||
|
||||
// ─── E) Robustness ────────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Update_NaN_UsesLastValidValue()
|
||||
{
|
||||
var indicator = new Normdist(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 Normdist(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 Normdist(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 Normdist(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_FlatValues_ReturnsHalf()
|
||||
{
|
||||
// When all values identical, stddev=0 → z=0 → CDF = 0.5
|
||||
var indicator = new Normdist(mu: 0.0, sigma: 1.0, period: 5);
|
||||
var time = DateTime.UtcNow;
|
||||
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
indicator.Update(new TValue(time.AddMinutes(i), 100.0));
|
||||
}
|
||||
|
||||
Assert.Equal(0.5, indicator.Last.Value, 1e-6);
|
||||
}
|
||||
|
||||
// ─── F) Consistency: batch == streaming == span == eventing ──────────────
|
||||
|
||||
[Fact]
|
||||
public void AllModes_ConsistencyCheck()
|
||||
{
|
||||
int count = 100;
|
||||
int period = 20;
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 72002);
|
||||
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
var source = bars.Close;
|
||||
|
||||
// Streaming
|
||||
var streaming = new Normdist(period: period);
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
streaming.Update(source[i]);
|
||||
}
|
||||
|
||||
// Batch (TSeries)
|
||||
var batch = Normdist.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];
|
||||
Normdist.Batch(rawValues, spanOutput, period: period);
|
||||
|
||||
// Eventing
|
||||
var eventResults = new List<double>();
|
||||
var eventSource = new TSeries();
|
||||
var eventIndicator = new Normdist(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);
|
||||
}
|
||||
|
||||
// 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: 72003);
|
||||
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
var source = bars.Close;
|
||||
|
||||
var streaming = new Normdist(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 = Normdist.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>(() =>
|
||||
Normdist.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>(() =>
|
||||
Normdist.Batch(src, dst));
|
||||
Assert.Equal("output", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Batch_Span_InvalidSigma_ThrowsArgumentException()
|
||||
{
|
||||
double[] src = { 1.0, 2.0, 3.0 };
|
||||
double[] dst = new double[3];
|
||||
var ex = Assert.Throws<ArgumentException>(() =>
|
||||
Normdist.Batch(src, dst, sigma: 0.0));
|
||||
Assert.Equal("sigma", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Batch_Span_NegativeSigma_ThrowsArgumentException()
|
||||
{
|
||||
double[] src = { 1.0, 2.0, 3.0 };
|
||||
double[] dst = new double[3];
|
||||
var ex = Assert.Throws<ArgumentException>(() =>
|
||||
Normdist.Batch(src, dst, sigma: -1.0));
|
||||
Assert.Equal("sigma", 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>(() =>
|
||||
Normdist.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];
|
||||
Normdist.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];
|
||||
Normdist.Batch(src, dst, period: 4);
|
||||
|
||||
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];
|
||||
Normdist.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];
|
||||
Normdist.Batch(src, spanOut, period: 14);
|
||||
|
||||
var streaming = new Normdist(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 Normdist(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 Normdist(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 Normdist(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: Parameter effects ───────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void DifferentSigma_ProduceDifferentResults()
|
||||
{
|
||||
int count = 60;
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 72006);
|
||||
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
|
||||
var ind1 = new Normdist(mu: 0.0, sigma: 0.5, period: 20);
|
||||
var ind2 = new Normdist(mu: 0.0, sigma: 1.0, period: 20);
|
||||
var ind3 = new Normdist(mu: 0.0, sigma: 3.0, period: 20);
|
||||
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
ind1.Update(bars.Close[i]);
|
||||
ind2.Update(bars.Close[i]);
|
||||
ind3.Update(bars.Close[i]);
|
||||
}
|
||||
|
||||
// Larger sigma compresses S-curve (output closer to 0.5)
|
||||
// All outputs still in [0,1]
|
||||
Assert.InRange(ind1.Last.Value, 0.0, 1.0);
|
||||
Assert.InRange(ind2.Last.Value, 0.0, 1.0);
|
||||
Assert.InRange(ind3.Last.Value, 0.0, 1.0);
|
||||
// Different sigma → different results
|
||||
Assert.NotEqual(ind1.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: 72007);
|
||||
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
|
||||
var (results, instance) = Normdist.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,421 @@
|
||||
using Xunit;
|
||||
using MathNet.Numerics.Distributions;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// NormdistValidationTests — validates against known mathematical properties
|
||||
/// of the Normal Distribution CDF and against MathNet.Numerics Normal.
|
||||
/// Known-value tests call Normdist.StaticCdf / NormalCdf directly (bypassing windowing)
|
||||
/// so results are exact closed-form comparisons.
|
||||
/// Tolerance 1e-4 for the 3-term A&S approximation (max error ~2.5e-5);
|
||||
/// Using 1e-4 to give headroom. MathNet cross-validation uses 1e-4.
|
||||
/// </summary>
|
||||
public class NormdistValidationTests
|
||||
{
|
||||
private const double ApproxTolerance = 1e-4; // A&S 3-term max error ~2.5e-5
|
||||
private const double LooseTolerance = 1e-3;
|
||||
|
||||
// ─── Boundary: CDF at extreme negative → 0 ───────────────────────────────
|
||||
|
||||
[Theory]
|
||||
[InlineData(0.0, 1.0)]
|
||||
[InlineData(0.5, 1.0)]
|
||||
[InlineData(0.0, 2.0)]
|
||||
public void StaticCdf_AtVeryNegativeX_ApproachesZero(double mu, double sigma)
|
||||
{
|
||||
double cdf = Normdist.StaticCdf(-100.0, mu, sigma);
|
||||
Assert.True(cdf < 1e-6, $"CDF at x=-100 should approach 0, got {cdf}");
|
||||
}
|
||||
|
||||
// ─── Boundary: CDF at extreme positive → 1 ───────────────────────────────
|
||||
|
||||
[Theory]
|
||||
[InlineData(0.0, 1.0)]
|
||||
[InlineData(0.5, 1.0)]
|
||||
[InlineData(0.0, 2.0)]
|
||||
public void StaticCdf_AtVeryPositiveX_ApproachesOne(double mu, double sigma)
|
||||
{
|
||||
double cdf = Normdist.StaticCdf(100.0, mu, sigma);
|
||||
Assert.True(cdf > 1.0 - 1e-6, $"CDF at x=100 should approach 1, got {cdf}");
|
||||
}
|
||||
|
||||
// ─── Symmetry: CDF(mu) = 0.5 ─────────────────────────────────────────────
|
||||
|
||||
[Theory]
|
||||
[InlineData(0.0, 1.0)]
|
||||
[InlineData(1.0, 1.0)]
|
||||
[InlineData(-2.5, 1.0)]
|
||||
[InlineData(0.0, 0.5)]
|
||||
[InlineData(3.0, 2.0)]
|
||||
public void StaticCdf_AtMean_IsHalf(double mu, double sigma)
|
||||
{
|
||||
double cdf = Normdist.StaticCdf(mu, mu, sigma);
|
||||
Assert.Equal(0.5, cdf, ApproxTolerance);
|
||||
}
|
||||
|
||||
// ─── Known percentiles for standard normal (μ=0, σ=1) ───────────────────
|
||||
|
||||
[Fact]
|
||||
public void StaticCdf_StandardNormal_AtPlusSigma_Is0841()
|
||||
{
|
||||
// Φ(1) ≈ 0.8413447...
|
||||
double cdf = Normdist.StaticCdf(1.0, 0.0, 1.0);
|
||||
Assert.Equal(0.8413, cdf, 3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void StaticCdf_StandardNormal_AtMinusSigma_Is0159()
|
||||
{
|
||||
// Φ(-1) ≈ 0.1586553...
|
||||
double cdf = Normdist.StaticCdf(-1.0, 0.0, 1.0);
|
||||
Assert.Equal(0.1587, cdf, 3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void StaticCdf_StandardNormal_AtPlus2Sigma_Is0977()
|
||||
{
|
||||
// Φ(2) ≈ 0.9772499...
|
||||
double cdf = Normdist.StaticCdf(2.0, 0.0, 1.0);
|
||||
Assert.Equal(0.9772, cdf, 3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void StaticCdf_StandardNormal_AtMinus2Sigma_Is0023()
|
||||
{
|
||||
// Φ(-2) ≈ 0.0227501...
|
||||
double cdf = Normdist.StaticCdf(-2.0, 0.0, 1.0);
|
||||
Assert.Equal(0.0228, cdf, 3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void StaticCdf_StandardNormal_At196_Is0975()
|
||||
{
|
||||
// Φ(1.96) ≈ 0.975 (95th percentile)
|
||||
double cdf = Normdist.StaticCdf(1.96, 0.0, 1.0);
|
||||
Assert.Equal(0.975, cdf, ApproxTolerance);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void StaticCdf_StandardNormal_At2326_Is0990()
|
||||
{
|
||||
// Φ(2.326) ≈ 0.990 (99th percentile)
|
||||
double cdf = Normdist.StaticCdf(2.326, 0.0, 1.0);
|
||||
Assert.Equal(0.990, cdf, 2);
|
||||
}
|
||||
|
||||
// ─── Complementary: Φ(x) + Φ(-x) = 1 ────────────────────────────────────
|
||||
|
||||
[Theory]
|
||||
[InlineData(0.5)]
|
||||
[InlineData(1.0)]
|
||||
[InlineData(1.5)]
|
||||
[InlineData(2.0)]
|
||||
[InlineData(0.1)]
|
||||
public void StaticCdf_Symmetry_ComplementTo1(double z)
|
||||
{
|
||||
double pos = Normdist.StaticCdf(z, 0.0, 1.0);
|
||||
double neg = Normdist.StaticCdf(-z, 0.0, 1.0);
|
||||
Assert.Equal(1.0, pos + neg, ApproxTolerance);
|
||||
}
|
||||
|
||||
// ─── MathNet.Numerics cross-validation ───────────────────────────────────
|
||||
|
||||
[Theory]
|
||||
[InlineData(0.0, 0.0, 1.0)]
|
||||
[InlineData(1.0, 0.0, 1.0)]
|
||||
[InlineData(-1.0, 0.0, 1.0)]
|
||||
[InlineData(2.0, 0.0, 1.0)]
|
||||
[InlineData(-2.0, 0.0, 1.0)]
|
||||
[InlineData(1.0, 1.0, 1.0)]
|
||||
[InlineData(0.5, 0.0, 2.0)]
|
||||
[InlineData(3.0, 2.0, 0.5)]
|
||||
[InlineData(-1.0, 0.0, 0.5)]
|
||||
[InlineData(1.96, 0.0, 1.0)]
|
||||
public void StaticCdf_VsMathNet_KnownValues(double x, double mu, double sigma)
|
||||
{
|
||||
var dist = new Normal(mu, sigma);
|
||||
double expected = dist.CumulativeDistribution(x);
|
||||
double actual = Normdist.StaticCdf(x, mu, sigma);
|
||||
Assert.Equal(expected, actual, ApproxTolerance);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0.0, 0.0, 1.0)]
|
||||
[InlineData(1.0, 0.0, 1.0)]
|
||||
[InlineData(-1.0, 0.0, 1.0)]
|
||||
[InlineData(0.5, 0.5, 1.5)]
|
||||
[InlineData(2.5, 1.0, 2.0)]
|
||||
public void NormalCdf_VsMathNet_KnownValues(double x, double mu, double sigma)
|
||||
{
|
||||
var dist = new Normal(mu, sigma);
|
||||
double expected = dist.CumulativeDistribution(x);
|
||||
double actual = Normdist.NormalCdf(x, mu, sigma);
|
||||
Assert.Equal(expected, actual, ApproxTolerance);
|
||||
}
|
||||
|
||||
// ─── Monotonicity ─────────────────────────────────────────────────────────
|
||||
|
||||
[Theory]
|
||||
[InlineData(0.0, 1.0)]
|
||||
[InlineData(1.0, 0.5)]
|
||||
[InlineData(-1.0, 2.0)]
|
||||
public void StaticCdf_MonotonicIncreasing(double mu, double sigma)
|
||||
{
|
||||
double prev = -1.0;
|
||||
|
||||
for (int i = -30; i <= 30; i++)
|
||||
{
|
||||
double x = i * 0.3;
|
||||
double cdf = Normdist.StaticCdf(x, mu, sigma);
|
||||
Assert.True(cdf >= prev - LooseTolerance,
|
||||
$"CDF not monotonic at x={x} (μ={mu}, σ={sigma}): got {cdf}, prev={prev}");
|
||||
prev = cdf;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Output bounded [0, 1] with streaming indicator ──────────────────────
|
||||
|
||||
[Fact]
|
||||
public void NormdistCdf_OutputBounded_Zero_To_One()
|
||||
{
|
||||
int count = 200;
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.3, seed: 75001);
|
||||
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
|
||||
var indicator = new Normdist(mu: 0.0, sigma: 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]");
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Flat range → CDF = 0.5 (z=0, erf(0)=0) ─────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void NormdistCdf_FlatRange_ReturnsHalf()
|
||||
{
|
||||
// When all values in window are identical: stddev=0, z=0 → Φ(0)=0.5
|
||||
var ind = new Normdist(mu: 0.0, sigma: 1.0, period: 10);
|
||||
var time = DateTime.UtcNow;
|
||||
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
ind.Update(new TValue(time.AddSeconds(i), 100.0));
|
||||
}
|
||||
|
||||
Assert.Equal(0.5, ind.Last.Value, LooseTolerance);
|
||||
}
|
||||
|
||||
// ─── z-score interpretation: above mean → > 0.5, below mean → < 0.5 ─────
|
||||
|
||||
[Fact]
|
||||
public void NormdistCdf_AboveMean_GreaterThanHalf()
|
||||
{
|
||||
// Feed data with clear trend up; last bar well above rolling mean → CDF > 0.5
|
||||
var ind = new Normdist(mu: 0.0, sigma: 1.0, period: 10);
|
||||
var time = DateTime.UtcNow;
|
||||
|
||||
// Flat base, then spike
|
||||
for (int i = 0; i < 9; i++)
|
||||
{
|
||||
ind.Update(new TValue(time.AddMinutes(i), 100.0));
|
||||
}
|
||||
ind.Update(new TValue(time.AddMinutes(9), 110.0)); // spike: well above mean/stddev
|
||||
|
||||
Assert.True(ind.Last.Value > 0.5, $"Above-mean value should give CDF > 0.5, got {ind.Last.Value}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NormdistCdf_BelowMean_LessThanHalf()
|
||||
{
|
||||
// Feed flat data, then dip → CDF < 0.5
|
||||
var ind = new Normdist(mu: 0.0, sigma: 1.0, period: 10);
|
||||
var time = DateTime.UtcNow;
|
||||
|
||||
for (int i = 0; i < 9; i++)
|
||||
{
|
||||
ind.Update(new TValue(time.AddMinutes(i), 100.0));
|
||||
}
|
||||
ind.Update(new TValue(time.AddMinutes(9), 90.0)); // dip: well below mean
|
||||
|
||||
Assert.True(ind.Last.Value < 0.5, $"Below-mean value should give CDF < 0.5, got {ind.Last.Value}");
|
||||
}
|
||||
|
||||
// ─── Erf internal correctness ─────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Erf_AtZero_IsZero()
|
||||
{
|
||||
Assert.Equal(0.0, Normdist.Erf(0.0), 1e-10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Erf_AtLargePositive_ApproachesOne()
|
||||
{
|
||||
double v = Normdist.Erf(5.0);
|
||||
Assert.True(v > 0.999, $"erf(5) should approach 1, got {v}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Erf_IsOddFunction()
|
||||
{
|
||||
// erf(-x) = -erf(x)
|
||||
double[] testX = { 0.5, 1.0, 1.5, 2.0, 3.0 };
|
||||
foreach (double x in testX)
|
||||
{
|
||||
double pos = Normdist.Erf(x);
|
||||
double neg = Normdist.Erf(-x);
|
||||
Assert.Equal(-pos, neg, ApproxTolerance);
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0.0, 0.0)] // erf(0) = 0
|
||||
[InlineData(0.5, 0.5204998778)] // known value
|
||||
[InlineData(1.0, 0.8427007929)] // known value
|
||||
[InlineData(2.0, 0.9953222650)] // known value
|
||||
public void Erf_KnownValues_WithinApproxTolerance(double x, double expected)
|
||||
{
|
||||
double actual = Normdist.Erf(x);
|
||||
Assert.Equal(expected, actual, ApproxTolerance);
|
||||
}
|
||||
|
||||
// ─── 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: 75002);
|
||||
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 = Normdist.Batch(bars.Close, period: 30);
|
||||
double[] spanResult = new double[count];
|
||||
Normdist.Batch(rawValues, spanResult, period: 30);
|
||||
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
Assert.Equal(tseriesResult[i].Value, spanResult[i], 1e-10);
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Streaming convergence ────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void NormdistCdf_HighPeriod_StillConverges()
|
||||
{
|
||||
int period = 200;
|
||||
var indicator = new Normdist(mu: 0.0, sigma: 1.0, period: period);
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.3, seed: 75003);
|
||||
var bars = gbm.Fetch(period + 50, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
|
||||
for (int i = 0; i < bars.Close.Count; i++)
|
||||
{
|
||||
indicator.Update(bars.Close[i]);
|
||||
Assert.True(double.IsFinite(indicator.Last.Value),
|
||||
$"Non-finite output at bar {i}");
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Parameter combos all within [0,1] ────────────────────────────────────
|
||||
|
||||
[Theory]
|
||||
[InlineData(0.0, 0.5, 5)]
|
||||
[InlineData(0.0, 1.0, 14)]
|
||||
[InlineData(0.5, 1.0, 10)]
|
||||
[InlineData(0.0, 2.0, 20)]
|
||||
[InlineData(-1.0, 1.0, 30)]
|
||||
public void NormdistCdf_ParameterCombos_OutputBounded(double mu, double sigma, int period)
|
||||
{
|
||||
int count = period + 50;
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 75004 + (int)(sigma * 100));
|
||||
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
|
||||
var indicator = new Normdist(mu, sigma, 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} (μ={mu}, σ={sigma}, period={period})");
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Large dataset stable ─────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void NormdistCdf_LargeDataset_Stable()
|
||||
{
|
||||
int count = 2000;
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 75005);
|
||||
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
|
||||
var indicator = new Normdist(mu: 0.0, sigma: 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}");
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Multiple points all match MathNet ───────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void StaticCdf_MultiplePoints_AllMatchMathNet()
|
||||
{
|
||||
double mu = 0.0, sigma = 1.0;
|
||||
var dist = new Normal(mu, sigma);
|
||||
|
||||
double[] testX = { -3.0, -2.0, -1.5, -1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0, 3.0 };
|
||||
|
||||
foreach (double x in testX)
|
||||
{
|
||||
double expected = dist.CumulativeDistribution(x);
|
||||
double actual = Normdist.StaticCdf(x, mu, sigma);
|
||||
Assert.Equal(expected, actual, ApproxTolerance);
|
||||
}
|
||||
}
|
||||
|
||||
// ─── NormalCdf invalid sigma returns 0.5 ──────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void NormalCdf_ZeroSigma_ReturnsHalf()
|
||||
{
|
||||
double cdf = Normdist.NormalCdf(1.0, 0.0, 0.0);
|
||||
Assert.Equal(0.5, cdf, 1e-10);
|
||||
}
|
||||
|
||||
// ─── Sigma effect: larger sigma compresses S-curve toward 0.5 ─────────────
|
||||
|
||||
[Theory]
|
||||
[InlineData(1.0, 0.0)]
|
||||
[InlineData(2.0, 0.0)]
|
||||
[InlineData(0.5, 0.0)]
|
||||
public void StaticCdf_LargerSigma_CompressesCurve(double x, double mu)
|
||||
{
|
||||
// For x > mu, larger sigma → smaller (z-mu)/sigma → CDF closer to 0.5
|
||||
double cdf1 = Normdist.StaticCdf(x, mu, 0.5);
|
||||
double cdf2 = Normdist.StaticCdf(x, mu, 1.0);
|
||||
double cdf3 = Normdist.StaticCdf(x, mu, 3.0);
|
||||
|
||||
// Larger sigma → CDF closer to 0.5 (smaller z)
|
||||
Assert.True(cdf1 >= cdf2 - LooseTolerance,
|
||||
$"σ=0.5 CDF={cdf1} should be >= σ=1.0 CDF={cdf2} for x>mu");
|
||||
Assert.True(cdf2 >= cdf3 - LooseTolerance,
|
||||
$"σ=1.0 CDF={cdf2} should be >= σ=3.0 CDF={cdf3} for x>mu");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
// NORMDIST: Normal Distribution CDF
|
||||
// Applies the Gaussian CDF Φ(z) = 0.5*(1+erf(z/√2)) to a z-score normalized
|
||||
// price series over a rolling lookback window.
|
||||
// Pipeline: Rolling mean+stddev → z-score → parameter adjustment → erf approximation → CDF.
|
||||
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace QuanTAlib;
|
||||
|
||||
/// <summary>
|
||||
/// NORMDIST: Normal Distribution CDF
|
||||
/// Computes Φ(z; μ, σ) = 0.5*(1+erf((z-μ)/(σ*√2))) applied to a z-score normalized
|
||||
/// price series over a rolling lookback window.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Key properties:
|
||||
/// - Output always in [0, 1]
|
||||
/// - Rolling window computes mean and population stddev for z-score normalization
|
||||
/// - Default μ=0, σ=1 gives standard-normal CDF of the price's z-score relative to the window
|
||||
/// - Increasing σ compresses the S-curve; shifting μ moves the midpoint away from the rolling mean
|
||||
/// - erf approximation: Abramowitz & Stegun 7.1.25 (3-term), max error ~2.5e-5
|
||||
/// - Fewer than 2 valid values in window → output 0.5 (uncertainty)
|
||||
/// - NaN/Infinity inputs use last-valid-value substitution
|
||||
/// </remarks>
|
||||
[SkipLocalsInit]
|
||||
public sealed class Normdist : AbstractBase
|
||||
{
|
||||
private readonly int _period;
|
||||
private readonly double _mu;
|
||||
private readonly double _invSigmaSqrt2; // precomputed: 1 / (sigma * sqrt(2))
|
||||
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 Normdist indicator.
|
||||
/// </summary>
|
||||
/// <param name="mu">Mean shift μ applied after z-score (default 0.0)</param>
|
||||
/// <param name="sigma">Scale σ > 0 applied after z-score (default 1.0)</param>
|
||||
/// <param name="period">Lookback window for rolling z-score normalization (default 14)</param>
|
||||
public Normdist(double mu = 0.0, double sigma = 1.0, int period = 14)
|
||||
{
|
||||
if (sigma <= 0.0)
|
||||
{
|
||||
throw new ArgumentException("Sigma must be > 0", nameof(sigma));
|
||||
}
|
||||
|
||||
if (period < 2)
|
||||
{
|
||||
throw new ArgumentException("Period must be >= 2", nameof(period));
|
||||
}
|
||||
|
||||
_mu = mu;
|
||||
_period = period;
|
||||
_invSigmaSqrt2 = 1.0 / (sigma * Math.Sqrt(2.0));
|
||||
_buffer = new RingBuffer(period);
|
||||
Name = $"Normdist({mu:F2},{sigma:F2},{period})";
|
||||
WarmupPeriod = period;
|
||||
_state = new State(0.5);
|
||||
_p_state = _state;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new Normdist indicator with source for event-based chaining.
|
||||
/// </summary>
|
||||
/// <param name="source">Source indicator for chaining</param>
|
||||
/// <param name="mu">Mean shift μ (default 0.0)</param>
|
||||
/// <param name="sigma">Scale σ > 0 (default 1.0)</param>
|
||||
/// <param name="period">Lookback window (default 14)</param>
|
||||
public Normdist(ITValuePublisher source, double mu = 0.0, double sigma = 1.0, int period = 14)
|
||||
: this(mu, sigma, period)
|
||||
{
|
||||
source.Pub += HandleUpdate;
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void HandleUpdate(object? sender, in TValueEventArgs e) => Update(e.Value, e.IsNew);
|
||||
|
||||
/// <summary>
|
||||
/// Error function approximation via Abramowitz & Stegun 7.1.25 (3-term, max error ~2.5e-5).
|
||||
/// erf(x) ≈ 1 - (a1*t + a2*t² + a3*t³)*exp(-x²), t = 1/(1 + 0.47047*|x|)
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal static double Erf(double x)
|
||||
{
|
||||
const double p = 0.47047;
|
||||
const double a1 = 0.3480242;
|
||||
const double a2 = -0.0958798;
|
||||
const double a3 = 0.7478556;
|
||||
|
||||
double ax = Math.Abs(x);
|
||||
double t = 1.0 / Math.FusedMultiplyAdd(p, ax, 1.0);
|
||||
double poly = Math.FusedMultiplyAdd(a3, t, a2);
|
||||
poly = Math.FusedMultiplyAdd(poly, t, a1);
|
||||
poly *= t;
|
||||
double val = 1.0 - poly * Math.Exp(-(ax * ax));
|
||||
return x >= 0.0 ? val : -val;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Normal Distribution CDF: Φ(x; μ, σ) = 0.5*(1 + erf((x-μ)/(σ*√2))).
|
||||
/// Returns 0.5 when σ ≤ 0.
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static double NormalCdf(double x, double mu, double sigma)
|
||||
{
|
||||
if (sigma <= 0.0)
|
||||
{
|
||||
return 0.5;
|
||||
}
|
||||
|
||||
double z = (x - mu) / (sigma * Math.Sqrt(2.0));
|
||||
return 0.5 * (1.0 + Erf(z));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pure static CDF helper — identical to <see cref="NormalCdf"/> with an explicit name
|
||||
/// for downstream consumers and validation tests.
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static double StaticCdf(double x, double mu, double sigma) => NormalCdf(x, mu, sigma);
|
||||
|
||||
/// <summary>
|
||||
/// Computes rolling mean and population standard deviation from a span of values.
|
||||
/// Returns (mean=0, stddev=0, count=0) when span is empty.
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static (double mean, double stddev, int count) RollingStats(ReadOnlySpan<double> values)
|
||||
{
|
||||
double sum = 0.0;
|
||||
double sumSq = 0.0;
|
||||
int count = 0;
|
||||
|
||||
for (int i = 0; i < values.Length; i++)
|
||||
{
|
||||
double v = values[i];
|
||||
if (double.IsFinite(v))
|
||||
{
|
||||
sum += v;
|
||||
sumSq = Math.FusedMultiplyAdd(v, v, sumSq);
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
if (count < 2)
|
||||
{
|
||||
return (0.0, 0.0, count);
|
||||
}
|
||||
|
||||
double mean = sum / count;
|
||||
double variance = sumSq / count - mean * mean;
|
||||
double stddev = variance > 0.0 ? Math.Sqrt(variance) : 0.0;
|
||||
return (mean, stddev, count);
|
||||
}
|
||||
|
||||
[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 (mean, stddev, count) = RollingStats(_buffer.GetSpan());
|
||||
|
||||
if (count < 2)
|
||||
{
|
||||
result = 0.5;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Z-score relative to rolling distribution
|
||||
double z = stddev > 0.0 ? (value - mean) / stddev : 0.0;
|
||||
|
||||
// Apply user mu/sigma shift: z_final = (z - mu) / sigma → CDF input
|
||||
double zFinal = (z - _mu) * _invSigmaSqrt2; // = (z-mu)/(sigma*sqrt(2))
|
||||
double erf = Erf(zFinal);
|
||||
result = 0.5 * (1.0 + erf);
|
||||
}
|
||||
|
||||
_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 mu = 0.0, double sigma = 1.0, int period = 14)
|
||||
{
|
||||
var indicator = new Normdist(mu, sigma, period);
|
||||
return indicator.Update(source);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Calculates Normal Distribution CDF over a span of values.
|
||||
/// Uses a sliding window z-score normalization identical to the streaming path.
|
||||
/// </summary>
|
||||
public static void Batch(
|
||||
ReadOnlySpan<double> source, Span<double> output,
|
||||
double mu = 0.0, double sigma = 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 (sigma <= 0.0)
|
||||
{
|
||||
throw new ArgumentException("Sigma must be > 0", nameof(sigma));
|
||||
}
|
||||
|
||||
if (period < 2)
|
||||
{
|
||||
throw new ArgumentException("Period must be >= 2", nameof(period));
|
||||
}
|
||||
|
||||
double invSigmaSqrt2 = 1.0 / (sigma * Math.Sqrt(2.0));
|
||||
double lastValid = 0.5;
|
||||
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
double val = source[i];
|
||||
if (!double.IsFinite(val))
|
||||
{
|
||||
output[i] = lastValid;
|
||||
continue;
|
||||
}
|
||||
|
||||
int start = Math.Max(0, i - period + 1);
|
||||
|
||||
double sum = 0.0;
|
||||
double sumSq = 0.0;
|
||||
int count = 0;
|
||||
|
||||
for (int j = start; j <= i; j++)
|
||||
{
|
||||
double v = source[j];
|
||||
if (double.IsFinite(v))
|
||||
{
|
||||
sum += v;
|
||||
sumSq = Math.FusedMultiplyAdd(v, v, sumSq);
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
double result;
|
||||
|
||||
if (count < 2)
|
||||
{
|
||||
result = 0.5;
|
||||
}
|
||||
else
|
||||
{
|
||||
double mean = sum / count;
|
||||
double variance = sumSq / count - mean * mean;
|
||||
double stddev = variance > 0.0 ? Math.Sqrt(variance) : 0.0;
|
||||
double z = stddev > 0.0 ? (val - mean) / stddev : 0.0;
|
||||
double zFinal = (z - mu) * invSigmaSqrt2;
|
||||
result = 0.5 * (1.0 + Erf(zFinal));
|
||||
}
|
||||
|
||||
lastValid = result;
|
||||
output[i] = result;
|
||||
}
|
||||
}
|
||||
|
||||
public static (TSeries Results, Normdist Indicator) Calculate(
|
||||
TSeries source, double mu = 0.0, double sigma = 1.0, int period = 14)
|
||||
{
|
||||
var indicator = new Normdist(mu, sigma, period);
|
||||
TSeries results = indicator.Update(source);
|
||||
return (results, indicator);
|
||||
}
|
||||
|
||||
public override void Reset()
|
||||
{
|
||||
_buffer.Clear();
|
||||
_state = new State(0.5);
|
||||
_p_state = _state;
|
||||
Last = default;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user