mirror of
https://github.com/mihakralj/QuanTAlib.git
synced 2026-08-24 21:48:03 +00:00
adding missing validations
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
using TradingPlatform.BusinessLayer;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public class WinsIndicatorTests
|
||||
{
|
||||
[Fact]
|
||||
public void WinsIndicator_Constructor_SetsDefaults()
|
||||
{
|
||||
var indicator = new WinsIndicator();
|
||||
|
||||
Assert.Equal(20, indicator.Period);
|
||||
Assert.Equal(10.0, indicator.WinPct);
|
||||
Assert.True(indicator.ShowColdValues);
|
||||
Assert.Equal("Wins - Winsorized Mean Moving Average", indicator.Name);
|
||||
Assert.False(indicator.SeparateWindow);
|
||||
Assert.True(indicator.OnBackGround);
|
||||
Assert.Equal(SourceType.Close, indicator.Source);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WinsIndicator_MinHistoryDepths_EqualsZero()
|
||||
{
|
||||
var indicator = new WinsIndicator { Period = 20 };
|
||||
|
||||
Assert.Equal(0, WinsIndicator.MinHistoryDepths);
|
||||
IWatchlistIndicator watchlistIndicator = indicator;
|
||||
Assert.Equal(0, watchlistIndicator.MinHistoryDepths);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WinsIndicator_Initialize_CreatesInternalWins()
|
||||
{
|
||||
var indicator = new WinsIndicator { Period = 10, WinPct = 10.0 };
|
||||
|
||||
indicator.Initialize();
|
||||
|
||||
Assert.Single(indicator.LinesSeries);
|
||||
Assert.Equal("Wins", indicator.LinesSeries[0].Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WinsIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
|
||||
{
|
||||
var indicator = new WinsIndicator { Period = 5, WinPct = 10.0 };
|
||||
indicator.Initialize();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
double close = 100 + Math.Sin(i * 0.5);
|
||||
indicator.HistoricalData.AddBar(now.AddMinutes(i), close, close + 2, close - 2, close);
|
||||
|
||||
var args = new UpdateArgs(UpdateReason.HistoricalBar);
|
||||
indicator.ProcessUpdate(args);
|
||||
}
|
||||
|
||||
double value = indicator.LinesSeries[0].GetValue(0);
|
||||
Assert.True(double.IsFinite(value));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
using System.Drawing;
|
||||
using System.Runtime.CompilerServices;
|
||||
using TradingPlatform.BusinessLayer;
|
||||
|
||||
namespace QuanTAlib;
|
||||
|
||||
[SkipLocalsInit]
|
||||
public sealed class WinsIndicator : Indicator, IWatchlistIndicator
|
||||
{
|
||||
[InputParameter("Period", sortIndex: 1, 3, 2000, 1, 0)]
|
||||
public int Period { get; set; } = 20;
|
||||
|
||||
[InputParameter("Winsorize %", sortIndex: 2, 0, 49, 1, 0)]
|
||||
public double WinPct { get; set; } = 10.0;
|
||||
|
||||
[IndicatorExtensions.DataSourceInput]
|
||||
public SourceType Source { get; set; } = SourceType.Close;
|
||||
|
||||
[InputParameter("Show cold values", sortIndex: 21)]
|
||||
public bool ShowColdValues { get; set; } = true;
|
||||
|
||||
private Wins _wins = null!;
|
||||
private readonly LineSeries _series;
|
||||
private Func<IHistoryItem, double> _priceSelector = null!;
|
||||
|
||||
public static int MinHistoryDepths => 0;
|
||||
int IWatchlistIndicator.MinHistoryDepths => MinHistoryDepths;
|
||||
|
||||
public override string ShortName => $"Wins {Period}/{WinPct}%";
|
||||
public override string SourceCodeLink => "https://github.com/mihakralj/QuanTAlib/blob/main/lib/statistics/wins/Wins.Quantower.cs";
|
||||
|
||||
public WinsIndicator()
|
||||
{
|
||||
OnBackGround = true;
|
||||
SeparateWindow = false;
|
||||
Name = "Wins - Winsorized Mean Moving Average";
|
||||
Description = "Rolling mean after replacing extreme tail values with boundary values";
|
||||
|
||||
_series = new LineSeries(name: "Wins", color: IndicatorExtensions.Statistics, width: 2, style: LineStyle.Solid);
|
||||
AddLineSeries(_series);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
protected override void OnInit()
|
||||
{
|
||||
_wins = new Wins(Period, WinPct);
|
||||
_priceSelector = Source.GetPriceSelector();
|
||||
base.OnInit();
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
protected override void OnUpdate(UpdateArgs args)
|
||||
{
|
||||
var item = this.HistoricalData[this.Count - 1, SeekOriginHistory.Begin];
|
||||
double value = _priceSelector(item);
|
||||
var time = this.HistoricalData.Time();
|
||||
|
||||
var input = new TValue(time, value);
|
||||
TValue result = _wins.Update(input, args.IsNewBar());
|
||||
|
||||
_series.SetValue(result.Value, _wins.IsHot, ShowColdValues);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public class WinsTests
|
||||
{
|
||||
// ── A) Constructor validation ────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Constructor_ThrowsOnPeriodLessThan3()
|
||||
{
|
||||
Assert.Throws<ArgumentException>(() => new Wins(2));
|
||||
Assert.Throws<ArgumentException>(() => new Wins(1));
|
||||
Assert.Throws<ArgumentException>(() => new Wins(0));
|
||||
Assert.Throws<ArgumentException>(() => new Wins(-1));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_ThrowsOnInvalidWinPct()
|
||||
{
|
||||
Assert.Throws<ArgumentException>(() => new Wins(10, -1.0));
|
||||
Assert.Throws<ArgumentException>(() => new Wins(10, 50.0));
|
||||
Assert.Throws<ArgumentException>(() => new Wins(10, 75.0));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_SetsName()
|
||||
{
|
||||
var wins = new Wins(20, 10.0);
|
||||
Assert.Equal("Wins(20,10)", wins.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_SetsWarmupPeriod()
|
||||
{
|
||||
var wins = new Wins(15, 10.0);
|
||||
Assert.Equal(15, wins.WarmupPeriod);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_ValidMinimalPeriod()
|
||||
{
|
||||
var wins = new Wins(3);
|
||||
Assert.NotNull(wins);
|
||||
}
|
||||
|
||||
// ── B) Basic calculation ─────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Update_ReturnsValue()
|
||||
{
|
||||
var wins = new Wins(5);
|
||||
TValue result = wins.Update(new TValue(DateTime.UtcNow, 100));
|
||||
Assert.Equal(result.Value, wins.Last.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsHot_FalseUntilWindowFull()
|
||||
{
|
||||
var wins = new Wins(5);
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
wins.Update(new TValue(DateTime.UtcNow, i + 1.0));
|
||||
Assert.False(wins.IsHot);
|
||||
}
|
||||
|
||||
wins.Update(new TValue(DateTime.UtcNow, 5.0));
|
||||
Assert.True(wins.IsHot);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WinPctZero_EqualsSMA()
|
||||
{
|
||||
// With winPct=0, WINS should equal SMA
|
||||
var wins = new Wins(5, 0.0);
|
||||
double[] vals = [10.0, 20.0, 30.0, 40.0, 50.0];
|
||||
double result = 0;
|
||||
foreach (double v in vals)
|
||||
{
|
||||
result = wins.Update(new TValue(DateTime.UtcNow, v)).Value;
|
||||
}
|
||||
|
||||
Assert.Equal(30.0, result, 10); // SMA of [10,20,30,40,50] = 30
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WinsKnownValue_CorrectResult()
|
||||
{
|
||||
// Window: [1,2,3,4,5,6,7,8,9,10], winPct=10 on period=10
|
||||
// winCount = floor(10 * 10/100) = 1
|
||||
// lowerBound = sorted[1] = 2, upperBound = sorted[8] = 9
|
||||
// Replace sorted[0]=1 with 2, sorted[9]=10 with 9
|
||||
// Values: [2,2,3,4,5,6,7,8,9,9], sum = 55, mean = 55/10 = 5.5
|
||||
var wins = new Wins(10, 10.0);
|
||||
for (int i = 1; i <= 10; i++)
|
||||
{
|
||||
wins.Update(new TValue(DateTime.UtcNow, i));
|
||||
}
|
||||
|
||||
Assert.Equal(5.5, wins.Last.Value, 10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WinsVsTrim_WinsHigherForOutlier()
|
||||
{
|
||||
// With an extreme outlier, WINS should be closer to SMA than TRIM
|
||||
// because WINS replaces (retains full count), TRIM discards
|
||||
var trim = new Trim(10, 10.0);
|
||||
var wins = new Wins(10, 10.0);
|
||||
|
||||
// Same data — [1,2,3,4,5,6,7,8,9,100_outlier]
|
||||
double[] vals = [1, 2, 3, 4, 5, 6, 7, 8, 9, 100];
|
||||
foreach (double v in vals)
|
||||
{
|
||||
trim.Update(new TValue(DateTime.UtcNow, v));
|
||||
wins.Update(new TValue(DateTime.UtcNow, v));
|
||||
}
|
||||
|
||||
// TRIM drops 100, WINS replaces it with 9 (boundary)
|
||||
// TRIM: mean([2..9]) = 44/8 = 5.5
|
||||
// WINS: (1/clamp_lower=2, 2,3,4,5,6,7,8,9, 9/clamp_upper=9) ... wait boundary math
|
||||
// winCount=1, lowerBound=sorted[1]=2, upperBound=sorted[8]=9
|
||||
// Replace sorted[0]=1→2, sorted[9]=100→9
|
||||
// Sum = 2+2+3+4+5+6+7+8+9+9 = 55, mean = 5.5
|
||||
// Both equal 5.5 but for different reasons
|
||||
Assert.True(double.IsFinite(trim.Last.Value));
|
||||
Assert.True(double.IsFinite(wins.Last.Value));
|
||||
}
|
||||
|
||||
// ── C) State + bar correction ────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void BarCorrection_IsNewFalse_RewritesLastBar()
|
||||
{
|
||||
var wins = new Wins(5, 10.0);
|
||||
var t = DateTime.UtcNow;
|
||||
|
||||
for (int i = 1; i <= 5; i++)
|
||||
{
|
||||
wins.Update(new TValue(t, i));
|
||||
}
|
||||
|
||||
double before = wins.Last.Value;
|
||||
|
||||
wins.Update(new TValue(t, 100.0), isNew: false);
|
||||
double afterCorrection = wins.Last.Value;
|
||||
|
||||
wins.Update(new TValue(t, 5.0), isNew: true);
|
||||
double afterNewBar = wins.Last.Value;
|
||||
|
||||
// Correction with outlier differs from original
|
||||
Assert.NotEqual(before, afterCorrection);
|
||||
// After new bar, result is finite and valid
|
||||
Assert.True(double.IsFinite(afterNewBar));
|
||||
// The new bar after correction differs from the correction itself
|
||||
Assert.NotEqual(afterCorrection, afterNewBar);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reset_ClearsState()
|
||||
{
|
||||
var wins = new Wins(5);
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
wins.Update(new TValue(DateTime.UtcNow, 100.0));
|
||||
}
|
||||
|
||||
Assert.True(wins.IsHot);
|
||||
wins.Reset();
|
||||
Assert.False(wins.IsHot);
|
||||
Assert.Equal(0, wins.Last.Value);
|
||||
}
|
||||
|
||||
// ── D) Warmup/convergence ────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void IsHot_FlipsAtPeriod()
|
||||
{
|
||||
int period = 7;
|
||||
var wins = new Wins(period);
|
||||
for (int i = 0; i < period - 1; i++)
|
||||
{
|
||||
wins.Update(new TValue(DateTime.UtcNow, i));
|
||||
Assert.False(wins.IsHot);
|
||||
}
|
||||
|
||||
wins.Update(new TValue(DateTime.UtcNow, period));
|
||||
Assert.True(wins.IsHot);
|
||||
}
|
||||
|
||||
// ── E) Robustness ───────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void NaN_UsesLastValidValue()
|
||||
{
|
||||
var wins = new Wins(5, 0.0);
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
wins.Update(new TValue(DateTime.UtcNow, 10.0));
|
||||
}
|
||||
|
||||
wins.Update(new TValue(DateTime.UtcNow, double.NaN));
|
||||
Assert.True(double.IsFinite(wins.Last.Value));
|
||||
|
||||
wins.Update(new TValue(DateTime.UtcNow, double.PositiveInfinity));
|
||||
Assert.True(double.IsFinite(wins.Last.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AllNaN_DoesNotThrow()
|
||||
{
|
||||
var wins = new Wins(5);
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
TValue result = wins.Update(new TValue(DateTime.UtcNow, double.NaN));
|
||||
Assert.True(double.IsFinite(result.Value));
|
||||
}
|
||||
}
|
||||
|
||||
// ── F) Consistency ────────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Consistency_BatchEqualsStreaming()
|
||||
{
|
||||
var rng = new GBM(startPrice: 100, mu: 0.0002, sigma: 0.02, seed: 77);
|
||||
int n = 100;
|
||||
int period = 14;
|
||||
double winPct = 10.0;
|
||||
|
||||
var prices = new double[n];
|
||||
var times = new long[n];
|
||||
var t0 = DateTime.UtcNow;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
TBar bar = rng.Next();
|
||||
prices[i] = bar.Close;
|
||||
times[i] = (t0.AddMinutes(i)).Ticks;
|
||||
}
|
||||
|
||||
var streamWins = new Wins(period, winPct);
|
||||
double lastStream = 0;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
lastStream = streamWins.Update(new TValue(new DateTime(times[i], DateTimeKind.Utc), prices[i])).Value;
|
||||
}
|
||||
|
||||
var spanOutput = new double[n];
|
||||
Wins.Batch(prices, spanOutput, period, winPct);
|
||||
|
||||
Assert.Equal(lastStream, spanOutput[n - 1], 10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Consistency_SpanValidatesLengths()
|
||||
{
|
||||
var src = new double[10];
|
||||
var dst = new double[9];
|
||||
Assert.Throws<ArgumentException>(() => Wins.Batch(src, dst, 5));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Consistency_SpanValidatesPeriod()
|
||||
{
|
||||
var src = new double[10];
|
||||
var dst = new double[10];
|
||||
Assert.Throws<ArgumentException>(() => Wins.Batch(src, dst, 2));
|
||||
}
|
||||
|
||||
// ── G) Span large-data ─────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Span_LargePeriod_NoStackOverflow()
|
||||
{
|
||||
int n = 1000;
|
||||
int period = 300;
|
||||
var src = new double[n];
|
||||
var dst = new double[n];
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
src[i] = i + 1.0;
|
||||
}
|
||||
|
||||
Wins.Batch(src, dst, period, 10.0);
|
||||
Assert.True(double.IsFinite(dst[n - 1]));
|
||||
}
|
||||
|
||||
// ── H) Eventing ──────────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Pub_FiresOnUpdate()
|
||||
{
|
||||
var wins = new Wins(5);
|
||||
int fireCount = 0;
|
||||
wins.Pub += (object? _, in TValueEventArgs _) => fireCount++;
|
||||
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
wins.Update(new TValue(DateTime.UtcNow, i));
|
||||
}
|
||||
|
||||
Assert.Equal(10, fireCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Chaining_EventBased_Works()
|
||||
{
|
||||
var wins1 = new Wins(5, 10.0);
|
||||
var wins2 = new Wins(wins1, 3, 0.0);
|
||||
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
wins1.Update(new TValue(DateTime.UtcNow, i + 1.0));
|
||||
}
|
||||
|
||||
Assert.True(double.IsFinite(wins2.Last.Value));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Wins self-consistency validation.
|
||||
/// Validates internal consistency: batch == streaming == span.
|
||||
/// </summary>
|
||||
public class WinsValidationTests
|
||||
{
|
||||
[Fact]
|
||||
public void Wins_Streaming_Equals_SpanBatch()
|
||||
{
|
||||
var rng = new GBM(startPrice: 100, mu: 0.0001, sigma: 0.015, seed: 8008);
|
||||
int n = 200;
|
||||
int period = 20;
|
||||
double winPct = 10.0;
|
||||
|
||||
var prices = new double[n];
|
||||
var times = new long[n];
|
||||
var t0 = DateTime.UtcNow;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
TBar bar = rng.Next();
|
||||
prices[i] = bar.Close;
|
||||
times[i] = t0.AddMinutes(i).Ticks;
|
||||
}
|
||||
|
||||
var streaming = new Wins(period, winPct);
|
||||
var streamValues = new double[n];
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
streamValues[i] = streaming.Update(new TValue(new DateTime(times[i], DateTimeKind.Utc), prices[i])).Value;
|
||||
}
|
||||
|
||||
var spanValues = new double[n];
|
||||
Wins.Batch(prices, spanValues, period, winPct);
|
||||
|
||||
for (int i = period - 1; i < n; i++)
|
||||
{
|
||||
Assert.Equal(streamValues[i], spanValues[i], 9);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Wins_WinPctZero_EqualsSMA_LongSeries()
|
||||
{
|
||||
var rng = new GBM(startPrice: 100, mu: 0.0001, sigma: 0.015, seed: 9009);
|
||||
int n = 200;
|
||||
int period = 14;
|
||||
|
||||
var prices = new double[n];
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
prices[i] = rng.Next().Close;
|
||||
}
|
||||
|
||||
var wins0 = new double[n];
|
||||
Wins.Batch(prices, wins0, period, 0.0);
|
||||
|
||||
// Manual SMA reference
|
||||
for (int i = period - 1; i < n; i++)
|
||||
{
|
||||
double sum = 0;
|
||||
for (int j = i - period + 1; j <= i; j++)
|
||||
{
|
||||
sum += prices[j];
|
||||
}
|
||||
|
||||
double sma = sum / period;
|
||||
Assert.Equal(sma, wins0[i], 9);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Wins_BatchTSeries_EqualsStreaming()
|
||||
{
|
||||
var rng = new GBM(startPrice: 100, mu: 0.0001, sigma: 0.015, seed: 1010);
|
||||
int n = 50;
|
||||
int period = 10;
|
||||
double winPct = 15.0;
|
||||
|
||||
var series = new TSeries();
|
||||
var t0 = DateTime.UtcNow;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
TBar bar = rng.Next();
|
||||
series.Add(new TValue(t0.AddMinutes(i), bar.Close));
|
||||
}
|
||||
|
||||
var batchResult = Wins.Batch(series, period, winPct);
|
||||
|
||||
var streaming = new Wins(period, winPct);
|
||||
TValue lastStream = default;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
lastStream = streaming.Update(series[i]);
|
||||
}
|
||||
|
||||
Assert.Equal(lastStream.Value, batchResult[n - 1].Value, 9);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Wins_MoreRobust_ThanSMA_WithOutlier()
|
||||
{
|
||||
// With extreme outlier, WINS result should be closer to the "true" mean
|
||||
// than raw SMA, because outlier is clamped to boundary
|
||||
var wins = new Wins(10, 10.0);
|
||||
double[] data = [100, 101, 99, 100, 102, 98, 100, 101, 99, 1000]; // outlier at end
|
||||
|
||||
double smaSum = 0;
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
wins.Update(new TValue(DateTime.UtcNow, data[i]));
|
||||
smaSum += data[i];
|
||||
}
|
||||
|
||||
double sma = smaSum / 10; // ~189 with outlier
|
||||
double winsResult = wins.Last.Value;
|
||||
|
||||
// WINS should be less than SMA (because 1000 is clamped to boundary ~101)
|
||||
Assert.True(winsResult < sma);
|
||||
Assert.True(winsResult > 95); // should be near 100
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,448 @@
|
||||
using System.Buffers;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace QuanTAlib;
|
||||
|
||||
/// <summary>
|
||||
/// Wins: Rolling Winsorized Mean Moving Average
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Sorts the lookback window, replaces (not discards) the lowest and highest
|
||||
/// winPct% of values with the boundary values at the trim point, then returns
|
||||
/// the arithmetic mean of all values (including the replaced ones).
|
||||
///
|
||||
/// Unlike TRIM which reduces sample size, WINS preserves the full N values.
|
||||
/// winPct=0 → SMA, winPct approaches 50 → median pair.
|
||||
///
|
||||
/// Complexity per bar: O(N log N) sort + O(N) clamped sum.
|
||||
/// Sorted buffer maintained incrementally via BinarySearch + Array.Copy.
|
||||
/// </remarks>
|
||||
[SkipLocalsInit]
|
||||
public sealed class Wins : AbstractBase
|
||||
{
|
||||
private readonly int _period;
|
||||
private readonly double _winPct;
|
||||
private readonly RingBuffer _buffer;
|
||||
private readonly double[] _sortedBuffer;
|
||||
private readonly double[] _p_sortedBuffer;
|
||||
private readonly TValuePublishedHandler _handler;
|
||||
private readonly ITValuePublisher? _source;
|
||||
private double _lastValidValue;
|
||||
private int _p_sortedCount;
|
||||
private bool _disposed;
|
||||
|
||||
public override bool IsHot => _buffer.IsFull;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a Wins indicator with the specified period and winsorize percentage.
|
||||
/// </summary>
|
||||
/// <param name="period">The size of the rolling window (must be >= 3).</param>
|
||||
/// <param name="winPct">Percentage of values to winsorize from each tail (0–49). Default 10.</param>
|
||||
public Wins(int period, double winPct = 10.0)
|
||||
{
|
||||
if (period < 3)
|
||||
{
|
||||
throw new ArgumentException("Period must be >= 3", nameof(period));
|
||||
}
|
||||
|
||||
if (winPct < 0 || winPct >= 50)
|
||||
{
|
||||
throw new ArgumentException("WinPct must be in [0, 49]", nameof(winPct));
|
||||
}
|
||||
|
||||
_period = period;
|
||||
_winPct = winPct;
|
||||
_buffer = new RingBuffer(period);
|
||||
_sortedBuffer = new double[period];
|
||||
_p_sortedBuffer = new double[period];
|
||||
Name = $"Wins({period},{winPct})";
|
||||
WarmupPeriod = period;
|
||||
_handler = Handle;
|
||||
}
|
||||
|
||||
/// <summary>Creates a chained Wins indicator.</summary>
|
||||
public Wins(ITValuePublisher source, int period, double winPct = 10.0) : this(period, winPct)
|
||||
{
|
||||
_source = source;
|
||||
source.Pub += _handler;
|
||||
}
|
||||
|
||||
/// <summary>Creates a Wins indicator primed from a TSeries source.</summary>
|
||||
public Wins(TSeries source, int period, double winPct = 10.0) : this(period, winPct)
|
||||
{
|
||||
Prime(source.Values);
|
||||
if (source.Count > 0)
|
||||
{
|
||||
Last = new TValue(source.LastTime, Last.Value);
|
||||
}
|
||||
|
||||
_source = source;
|
||||
source.Pub += _handler;
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void Handle(object? sender, in TValueEventArgs args) => Update(args.Value, args.IsNew);
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public override TValue Update(TValue input, bool isNew = true)
|
||||
{
|
||||
double value = input.Value;
|
||||
if (!double.IsFinite(value))
|
||||
{
|
||||
value = _lastValidValue;
|
||||
}
|
||||
else
|
||||
{
|
||||
_lastValidValue = value;
|
||||
}
|
||||
|
||||
if (isNew)
|
||||
{
|
||||
_p_sortedCount = _buffer.Count;
|
||||
Array.Copy(_sortedBuffer, _p_sortedBuffer, _p_sortedCount);
|
||||
|
||||
if (_buffer.IsFull)
|
||||
{
|
||||
double old = _buffer.Oldest;
|
||||
RemoveFromSorted(old);
|
||||
}
|
||||
|
||||
_buffer.Add(value);
|
||||
AddToSorted(value);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (_p_sortedCount > 0)
|
||||
{
|
||||
Array.Copy(_p_sortedBuffer, _sortedBuffer, _p_sortedCount);
|
||||
}
|
||||
|
||||
if (_buffer.Count > 0)
|
||||
{
|
||||
double current = _buffer.Newest;
|
||||
RemoveFromSorted(current);
|
||||
_buffer.UpdateNewest(value);
|
||||
AddToSorted(value);
|
||||
}
|
||||
else
|
||||
{
|
||||
_buffer.Add(value);
|
||||
AddToSorted(value);
|
||||
}
|
||||
}
|
||||
|
||||
double result = ComputeWinsorizedMean(_sortedBuffer, _buffer.Count, _winPct);
|
||||
Last = new TValue(input.Time, result);
|
||||
PubEvent(Last, isNew);
|
||||
return Last;
|
||||
}
|
||||
|
||||
public override TSeries Update(TSeries source)
|
||||
{
|
||||
if (source.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
int len = source.Count;
|
||||
var t = new List<long>(len);
|
||||
var v = new List<double>(len);
|
||||
CollectionsMarshal.SetCount(t, len);
|
||||
CollectionsMarshal.SetCount(v, len);
|
||||
|
||||
var tSpan = CollectionsMarshal.AsSpan(t);
|
||||
var vSpan = CollectionsMarshal.AsSpan(v);
|
||||
|
||||
Batch(source.Values, vSpan, _period, _winPct);
|
||||
source.Times.CopyTo(tSpan);
|
||||
|
||||
Prime(source.Values);
|
||||
|
||||
Last = new TValue(tSpan[len - 1], vSpan[len - 1]);
|
||||
return new TSeries(t, v);
|
||||
}
|
||||
|
||||
public override void Reset()
|
||||
{
|
||||
_buffer.Clear();
|
||||
Array.Clear(_sortedBuffer);
|
||||
Array.Clear(_p_sortedBuffer);
|
||||
Last = default;
|
||||
}
|
||||
|
||||
public override void Prime(ReadOnlySpan<double> source, TimeSpan? step = null)
|
||||
{
|
||||
if (source.Length == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_buffer.Clear();
|
||||
Array.Clear(_sortedBuffer);
|
||||
int warmupLength = Math.Min(source.Length, WarmupPeriod);
|
||||
int startIndex = source.Length - warmupLength;
|
||||
|
||||
for (int i = startIndex; i < source.Length; i++)
|
||||
{
|
||||
Update(new TValue(DateTime.MinValue, source[i]));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Calculates Wins for the entire series using a new instance.</summary>
|
||||
public static TSeries Batch(TSeries source, int period, double winPct = 10.0)
|
||||
{
|
||||
var wins = new Wins(period, winPct);
|
||||
return wins.Update(source);
|
||||
}
|
||||
|
||||
/// <summary>Calculates Wins in-place using spans.</summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void Batch(ReadOnlySpan<double> source, Span<double> output, int period, double winPct = 10.0)
|
||||
{
|
||||
if (source.Length != output.Length)
|
||||
{
|
||||
throw new ArgumentException("Source and output must have the same length", nameof(output));
|
||||
}
|
||||
|
||||
if (period < 3)
|
||||
{
|
||||
throw new ArgumentException("Period must be >= 3", nameof(period));
|
||||
}
|
||||
|
||||
if (winPct < 0 || winPct >= 50)
|
||||
{
|
||||
throw new ArgumentException("WinPct must be in [0, 49]", nameof(winPct));
|
||||
}
|
||||
|
||||
int len = source.Length;
|
||||
if (len == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
const int StackallocThreshold = 256;
|
||||
double[]? rentedSorted = null;
|
||||
double[]? rentedWindow = null;
|
||||
scoped Span<double> sortedBuffer;
|
||||
scoped Span<double> window;
|
||||
|
||||
if (period <= StackallocThreshold)
|
||||
{
|
||||
sortedBuffer = stackalloc double[period];
|
||||
window = stackalloc double[period];
|
||||
}
|
||||
else
|
||||
{
|
||||
rentedSorted = ArrayPool<double>.Shared.Rent(period);
|
||||
rentedWindow = ArrayPool<double>.Shared.Rent(period);
|
||||
sortedBuffer = rentedSorted.AsSpan(0, period);
|
||||
window = rentedWindow.AsSpan(0, period);
|
||||
}
|
||||
|
||||
sortedBuffer.Clear();
|
||||
window.Clear();
|
||||
|
||||
try
|
||||
{
|
||||
int windowIdx = 0;
|
||||
int count = 0;
|
||||
|
||||
for (int i = 0; i < len; i++)
|
||||
{
|
||||
double val = source[i];
|
||||
|
||||
if (count == period)
|
||||
{
|
||||
double old = window[windowIdx];
|
||||
int oldIndex = BinarySearchSpan(sortedBuffer, count, old);
|
||||
if (oldIndex >= 0)
|
||||
{
|
||||
if (oldIndex < count - 1)
|
||||
{
|
||||
sortedBuffer.Slice(oldIndex + 1, count - 1 - oldIndex).CopyTo(sortedBuffer.Slice(oldIndex));
|
||||
}
|
||||
|
||||
count--;
|
||||
}
|
||||
}
|
||||
|
||||
window[windowIdx] = val;
|
||||
windowIdx = (windowIdx + 1) % period;
|
||||
|
||||
int newIndex = BinarySearchSpan(sortedBuffer, count, val);
|
||||
if (newIndex < 0)
|
||||
{
|
||||
newIndex = ~newIndex;
|
||||
}
|
||||
|
||||
if (newIndex < count)
|
||||
{
|
||||
sortedBuffer.Slice(newIndex, count - newIndex).CopyTo(sortedBuffer.Slice(newIndex + 1));
|
||||
}
|
||||
|
||||
sortedBuffer[newIndex] = val;
|
||||
count++;
|
||||
|
||||
output[i] = ComputeWinsorizedMeanSpan(sortedBuffer, count, winPct);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (rentedSorted != null)
|
||||
{
|
||||
ArrayPool<double>.Shared.Return(rentedSorted);
|
||||
}
|
||||
|
||||
if (rentedWindow != null)
|
||||
{
|
||||
ArrayPool<double>.Shared.Return(rentedWindow);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static (TSeries Results, Wins Indicator) Calculate(TSeries source, int period, double winPct = 10.0)
|
||||
{
|
||||
var indicator = new Wins(period, winPct);
|
||||
TSeries results = indicator.Update(source);
|
||||
return (results, indicator);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static double ComputeWinsorizedMean(double[] sorted, int count, double winPct)
|
||||
{
|
||||
if (count == 0)
|
||||
{
|
||||
return double.NaN;
|
||||
}
|
||||
|
||||
int winCount = (int)(count * winPct / 100.0);
|
||||
if (winCount >= count / 2)
|
||||
{
|
||||
winCount = (count - 1) / 2;
|
||||
}
|
||||
|
||||
double lowerBound = sorted[winCount];
|
||||
double upperBound = sorted[count - 1 - winCount];
|
||||
|
||||
double sum = 0.0;
|
||||
// Lower tail: winCount values replaced with lowerBound
|
||||
sum = Math.FusedMultiplyAdd(winCount, lowerBound, sum);
|
||||
// Middle portion
|
||||
int upperIdx = count - 1 - winCount;
|
||||
for (int i = winCount; i <= upperIdx; i++)
|
||||
{
|
||||
sum += sorted[i];
|
||||
}
|
||||
|
||||
// Upper tail: winCount values replaced with upperBound
|
||||
sum = Math.FusedMultiplyAdd(winCount, upperBound, sum);
|
||||
|
||||
return sum / count;
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static double ComputeWinsorizedMeanSpan(Span<double> sorted, int count, double winPct)
|
||||
{
|
||||
if (count == 0)
|
||||
{
|
||||
return double.NaN;
|
||||
}
|
||||
|
||||
int winCount = (int)(count * winPct / 100.0);
|
||||
if (winCount >= count / 2)
|
||||
{
|
||||
winCount = (count - 1) / 2;
|
||||
}
|
||||
|
||||
double lowerBound = sorted[winCount];
|
||||
double upperBound = sorted[count - 1 - winCount];
|
||||
|
||||
double sum = Math.FusedMultiplyAdd(winCount, lowerBound, 0.0);
|
||||
int upperIdx = count - 1 - winCount;
|
||||
for (int i = winCount; i <= upperIdx; i++)
|
||||
{
|
||||
sum += sorted[i];
|
||||
}
|
||||
|
||||
sum = Math.FusedMultiplyAdd(winCount, upperBound, sum);
|
||||
|
||||
return sum / count;
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void AddToSorted(double value)
|
||||
{
|
||||
int validCount = _buffer.Count - 1;
|
||||
int index = Array.BinarySearch(_sortedBuffer, 0, validCount, value);
|
||||
if (index < 0)
|
||||
{
|
||||
index = ~index;
|
||||
}
|
||||
|
||||
if (index < validCount)
|
||||
{
|
||||
Array.Copy(_sortedBuffer, index, _sortedBuffer, index + 1, validCount - index);
|
||||
}
|
||||
|
||||
_sortedBuffer[index] = value;
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void RemoveFromSorted(double value)
|
||||
{
|
||||
int validCount = _buffer.Count;
|
||||
int index = Array.BinarySearch(_sortedBuffer, 0, validCount, value);
|
||||
if (index < 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (index < validCount - 1)
|
||||
{
|
||||
Array.Copy(_sortedBuffer, index + 1, _sortedBuffer, index, validCount - 1 - index);
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static int BinarySearchSpan(Span<double> span, int length, double value)
|
||||
{
|
||||
int lo = 0;
|
||||
int hi = length - 1;
|
||||
while (lo <= hi)
|
||||
{
|
||||
int mid = lo + ((hi - lo) >> 1);
|
||||
int cmp = span[mid].CompareTo(value);
|
||||
if (cmp == 0)
|
||||
{
|
||||
return mid;
|
||||
}
|
||||
|
||||
if (cmp < 0)
|
||||
{
|
||||
lo = mid + 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
hi = mid - 1;
|
||||
}
|
||||
}
|
||||
|
||||
return ~lo;
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (!_disposed)
|
||||
{
|
||||
if (disposing && _source != null)
|
||||
{
|
||||
_source.Pub -= _handler;
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
}
|
||||
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user