mirror of
https://github.com/mihakralj/QuanTAlib.git
synced 2026-08-19 11:08:05 +00:00
adding missing validations
This commit is contained in:
@@ -0,0 +1,193 @@
|
||||
using TradingPlatform.BusinessLayer;
|
||||
using QuanTAlib;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public sealed class PolyfitIndicatorTests
|
||||
{
|
||||
// ── 1. Constructor defaults ───────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Constructor_DefaultValues()
|
||||
{
|
||||
var ind = new PolyfitIndicator();
|
||||
Assert.Equal(20, ind.Period);
|
||||
Assert.Equal(2, ind.Degree);
|
||||
Assert.True(ind.ShowColdValues);
|
||||
Assert.Equal("Polyfit - Polynomial Fitting", ind.Name);
|
||||
Assert.False(ind.SeparateWindow);
|
||||
Assert.True(ind.OnBackGround);
|
||||
Assert.Equal(SourceType.Close, ind.Source);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_ShortName_IncludesPeriodDegree()
|
||||
{
|
||||
var ind = new PolyfitIndicator { Period = 10, Degree = 3 };
|
||||
Assert.Equal("Polyfit 10,3", ind.ShortName);
|
||||
}
|
||||
|
||||
// ── 2. MinHistoryDepths ───────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void MinHistoryDepths_IsZero()
|
||||
{
|
||||
Assert.Equal(0, PolyfitIndicator.MinHistoryDepths);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MinHistoryDepths_InterfaceImplementation()
|
||||
{
|
||||
IWatchlistIndicator ind = new PolyfitIndicator();
|
||||
Assert.Equal(0, ind.MinHistoryDepths);
|
||||
}
|
||||
|
||||
// ── 3. Initialize creates internal indicator and line series ──────────────
|
||||
|
||||
[Fact]
|
||||
public void Initialize_CreatesLineSeries()
|
||||
{
|
||||
var ind = new PolyfitIndicator { Period = 10 };
|
||||
ind.Initialize();
|
||||
|
||||
Assert.Single(ind.LinesSeries);
|
||||
Assert.Equal("Polyfit", ind.LinesSeries[0].Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Initialize_CustomPeriodDegree()
|
||||
{
|
||||
var ind = new PolyfitIndicator { Period = 8, Degree = 3 };
|
||||
ind.Initialize();
|
||||
Assert.Equal("Polyfit 8,3", ind.ShortName);
|
||||
}
|
||||
|
||||
// ── 4. ProcessUpdate — historical data ────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void ProcessUpdate_HistoricalBars_ProducesFiniteValues()
|
||||
{
|
||||
var ind = new PolyfitIndicator { Period = 5, Degree = 2 };
|
||||
ind.Initialize();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
ind.HistoricalData.AddBar(now.AddMinutes(i), 100 + i, 110 + i, 90 + i, 105 + i);
|
||||
var args = new UpdateArgs(UpdateReason.HistoricalBar);
|
||||
ind.ProcessUpdate(args);
|
||||
}
|
||||
|
||||
double val = ind.LinesSeries[0].GetValue(0);
|
||||
Assert.True(double.IsFinite(val));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ProcessUpdate_NewBar_UpdatesValue()
|
||||
{
|
||||
var ind = new PolyfitIndicator { Period = 5, Degree = 2 };
|
||||
ind.Initialize();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
// Fill warmup with historical bars
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
ind.HistoricalData.AddBar(now.AddMinutes(i), 100 + i, 110 + i, 90 + i, 105 + i);
|
||||
ind.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
|
||||
}
|
||||
|
||||
double val1 = ind.LinesSeries[0].GetValue(0);
|
||||
|
||||
// Add one more new bar
|
||||
ind.HistoricalData.AddBar(now.AddMinutes(5), 110, 120, 100, 115);
|
||||
ind.ProcessUpdate(new UpdateArgs(UpdateReason.NewBar));
|
||||
double val2 = ind.LinesSeries[0].GetValue(0);
|
||||
|
||||
Assert.True(double.IsFinite(val1));
|
||||
Assert.True(double.IsFinite(val2));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ProcessUpdate_SameBarUpdate_ProducesFiniteValue()
|
||||
{
|
||||
var ind = new PolyfitIndicator { Period = 5, Degree = 2 };
|
||||
ind.Initialize();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
ind.HistoricalData.AddBar(now.AddMinutes(i), 100 + i, 110 + i, 90 + i, 105 + i);
|
||||
ind.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
|
||||
}
|
||||
|
||||
// Non-new bar update (bar correction)
|
||||
ind.HistoricalData.AddBar(now.AddMinutes(4), 108, 118, 98, 112);
|
||||
ind.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
|
||||
double val = ind.LinesSeries[0].GetValue(0);
|
||||
|
||||
Assert.True(double.IsFinite(val));
|
||||
}
|
||||
|
||||
// ── 5. Different source types ─────────────────────────────────────────────
|
||||
|
||||
[Theory]
|
||||
[InlineData(SourceType.Close)]
|
||||
[InlineData(SourceType.Open)]
|
||||
[InlineData(SourceType.High)]
|
||||
[InlineData(SourceType.Low)]
|
||||
[InlineData(SourceType.HL2)]
|
||||
public void DifferentSourceTypes_ProducesFiniteValues(SourceType sourceType)
|
||||
{
|
||||
var ind = new PolyfitIndicator { Period = 5, Degree = 2, Source = sourceType };
|
||||
ind.Initialize();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
ind.HistoricalData.AddBar(now.AddMinutes(i), 100 + i, 110 + i, 90 + i, 105 + i);
|
||||
ind.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
|
||||
}
|
||||
|
||||
double val = ind.LinesSeries[0].GetValue(0);
|
||||
Assert.True(double.IsFinite(val));
|
||||
}
|
||||
|
||||
// ── 6. Different degree variants ─────────────────────────────────────────
|
||||
|
||||
[Theory]
|
||||
[InlineData(1)]
|
||||
[InlineData(2)]
|
||||
[InlineData(3)]
|
||||
public void DifferentDegrees_ProducesFiniteValues(int degree)
|
||||
{
|
||||
var ind = new PolyfitIndicator { Period = 10, Degree = degree };
|
||||
ind.Initialize();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
ind.HistoricalData.AddBar(now.AddMinutes(i), 100 + i, 110 + i, 90 + i, 105 + i);
|
||||
ind.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
|
||||
}
|
||||
|
||||
double val = ind.LinesSeries[0].GetValue(0);
|
||||
Assert.True(double.IsFinite(val));
|
||||
Assert.True(val > 0, "Expected positive overlay value");
|
||||
}
|
||||
|
||||
// ── 7. SeparateWindow and SourceCodeLink ──────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void SeparateWindow_IsFalse_Overlay()
|
||||
{
|
||||
var ind = new PolyfitIndicator();
|
||||
Assert.False(ind.SeparateWindow);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SourceCodeLink_ContainsPolyfit()
|
||||
{
|
||||
var ind = new PolyfitIndicator();
|
||||
Assert.Contains("Polyfit", ind.SourceCodeLink, StringComparison.Ordinal);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
using System.Drawing;
|
||||
using System.Runtime.CompilerServices;
|
||||
using TradingPlatform.BusinessLayer;
|
||||
|
||||
namespace QuanTAlib;
|
||||
|
||||
[SkipLocalsInit]
|
||||
public sealed class PolyfitIndicator : Indicator, IWatchlistIndicator
|
||||
{
|
||||
[InputParameter("Period", sortIndex: 1, 2, 2000, 1, 0)]
|
||||
public int Period { get; set; } = 20;
|
||||
|
||||
[InputParameter("Degree", sortIndex: 2, 1, 6, 1, 0)]
|
||||
public int Degree { get; set; } = 2;
|
||||
|
||||
[IndicatorExtensions.DataSourceInput]
|
||||
public SourceType Source { get; set; } = SourceType.Close;
|
||||
|
||||
[InputParameter("Show cold values", sortIndex: 21)]
|
||||
public bool ShowColdValues { get; set; } = true;
|
||||
|
||||
private Polyfit _polyfit = null!;
|
||||
private readonly LineSeries _series;
|
||||
private Func<IHistoryItem, double> _priceSelector = null!;
|
||||
|
||||
public static int MinHistoryDepths => 0;
|
||||
int IWatchlistIndicator.MinHistoryDepths => MinHistoryDepths;
|
||||
|
||||
public override string ShortName => $"Polyfit {Period},{Degree}";
|
||||
public override string SourceCodeLink => "https://github.com/mihakralj/QuanTAlib/blob/main/lib/statistics/polyfit/Polyfit.Quantower.cs";
|
||||
|
||||
public PolyfitIndicator()
|
||||
{
|
||||
OnBackGround = true;
|
||||
SeparateWindow = false;
|
||||
Name = "Polyfit - Polynomial Fitting";
|
||||
Description = "Rolling polynomial regression of configurable degree; returns fitted value at current bar";
|
||||
|
||||
_series = new LineSeries(name: "Polyfit", color: IndicatorExtensions.Statistics, width: 2, style: LineStyle.Solid);
|
||||
AddLineSeries(_series);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
protected override void OnInit()
|
||||
{
|
||||
_polyfit = new Polyfit(Period, Degree);
|
||||
_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 = _polyfit.Update(input, args.IsNewBar());
|
||||
|
||||
_series.SetValue(result.Value, _polyfit.IsHot, ShowColdValues);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,504 @@
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public class PolyfitTests
|
||||
{
|
||||
// ── A) Constructor validation ─────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Constructor_DefaultParams_SetsName()
|
||||
{
|
||||
var p = new Polyfit(20);
|
||||
Assert.Equal("Polyfit(20,2)", p.Name);
|
||||
Assert.Equal(20, p.WarmupPeriod);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_ExplicitDegree_SetsName()
|
||||
{
|
||||
var p = new Polyfit(10, 3);
|
||||
Assert.Equal("Polyfit(10,3)", p.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_PeriodLessThan2_Throws()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Polyfit(1));
|
||||
Assert.Equal("period", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_PeriodZero_Throws()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Polyfit(0));
|
||||
Assert.Equal("period", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_DegreeZero_Throws()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Polyfit(10, 0));
|
||||
Assert.Equal("degree", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_DegreeClampedToPeriodMinus1()
|
||||
{
|
||||
// degree=10 with period=5 → clamped to 4
|
||||
var p = new Polyfit(5, 10);
|
||||
Assert.Equal("Polyfit(5,4)", p.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_ChainingSubscribes()
|
||||
{
|
||||
var src = new Sma(3);
|
||||
var p = new Polyfit(src, 5, 2);
|
||||
Assert.Equal("Polyfit(5,2)", p.Name);
|
||||
}
|
||||
|
||||
// ── B) Basic calculation ──────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void BasicCalc_ReturnsFiniteAfterWarmup()
|
||||
{
|
||||
var p = new Polyfit(5, 2);
|
||||
var gbm = new GBM(100, 0.05, 0.2, seed: 1);
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
var bar = gbm.Next();
|
||||
p.Update(new TValue(bar.Time, bar.Close));
|
||||
}
|
||||
Assert.True(p.IsHot);
|
||||
Assert.True(double.IsFinite(p.Last.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BasicCalc_LinearInput_Degree1_MatchesLinearTrend()
|
||||
{
|
||||
// For perfectly linear data y=i with period=5, degree=1,
|
||||
// the linear fit should reproduce the last value y=4 (value at i=4).
|
||||
var p = new Polyfit(5, 1);
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
p.Update(new TValue(DateTime.UtcNow.AddSeconds(i), (double)i));
|
||||
}
|
||||
// Linear regression: slope=1, passes through points 0..4
|
||||
// P(1.0 normalized) = y at x=1.0 = 4.0
|
||||
Assert.Equal(4.0, p.Last.Value, 1e-9);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BasicCalc_ConstantInput_ReturnsConstant()
|
||||
{
|
||||
var p = new Polyfit(5, 2);
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
p.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 42.0));
|
||||
}
|
||||
Assert.Equal(42.0, p.Last.Value, 1e-9);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BasicCalc_NotHotBeforeWarmup()
|
||||
{
|
||||
var p = new Polyfit(5, 2);
|
||||
Assert.False(p.IsHot);
|
||||
p.Update(new TValue(DateTime.UtcNow, 10.0));
|
||||
Assert.False(p.IsHot);
|
||||
}
|
||||
|
||||
// ── C) State + bar correction (isNew) ────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void IsNewTrue_AdvancesBuffer()
|
||||
{
|
||||
var p = new Polyfit(5, 2);
|
||||
var gbm = new GBM(100, 0.05, 0.2, seed: 2);
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
var bar = gbm.Next();
|
||||
p.Update(new TValue(bar.Time, bar.Close));
|
||||
}
|
||||
double v1 = p.Last.Value;
|
||||
|
||||
// Adding a new bar with extreme value changes the result
|
||||
p.Update(new TValue(DateTime.UtcNow.AddSeconds(5), 200.0));
|
||||
double v2 = p.Last.Value;
|
||||
Assert.NotEqual(v1, v2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsNewFalse_CorrectsBars_RestoresExactly()
|
||||
{
|
||||
var p = new Polyfit(5, 2);
|
||||
double[] vals = [10.0, 20.0, 30.0, 40.0, 50.0];
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
p.Update(new TValue(DateTime.UtcNow.AddSeconds(i), vals[i]));
|
||||
}
|
||||
double original = p.Last.Value;
|
||||
|
||||
// Overwrite current bar with different value
|
||||
p.Update(new TValue(DateTime.UtcNow.AddSeconds(4), 9999.0), isNew: false);
|
||||
Assert.NotEqual(original, p.Last.Value);
|
||||
|
||||
// Restore — must exactly match original
|
||||
p.Update(new TValue(DateTime.UtcNow.AddSeconds(4), vals[4]), isNew: false);
|
||||
Assert.Equal(original, p.Last.Value, 1e-9);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IterativeCorrections_FinalMatchesOriginal()
|
||||
{
|
||||
var p = new Polyfit(5, 2);
|
||||
double[] vals = [10, 20, 30, 40, 50];
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
p.Update(new TValue(DateTime.UtcNow.AddSeconds(i), vals[i]));
|
||||
}
|
||||
double original = p.Last.Value;
|
||||
|
||||
for (int iter = 0; iter < 5; iter++)
|
||||
{
|
||||
p.Update(new TValue(DateTime.UtcNow.AddSeconds(4), 999.0), isNew: false);
|
||||
p.Update(new TValue(DateTime.UtcNow.AddSeconds(4), 50.0), isNew: false);
|
||||
}
|
||||
Assert.Equal(original, p.Last.Value, 1e-9);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reset_ClearsAllState()
|
||||
{
|
||||
var p = new Polyfit(5, 2);
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
p.Update(new TValue(DateTime.UtcNow.AddSeconds(i), (double)(i + 1) * 10));
|
||||
}
|
||||
Assert.True(p.IsHot);
|
||||
|
||||
p.Reset();
|
||||
Assert.False(p.IsHot);
|
||||
Assert.Equal(default, p.Last);
|
||||
}
|
||||
|
||||
// ── D) Warmup / convergence ───────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void IsHot_FlipsAtPeriod()
|
||||
{
|
||||
var p = new Polyfit(4, 2);
|
||||
for (int i = 0; i < 3; i++)
|
||||
{
|
||||
p.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 10.0));
|
||||
Assert.False(p.IsHot);
|
||||
}
|
||||
p.Update(new TValue(DateTime.UtcNow.AddSeconds(3), 10.0));
|
||||
Assert.True(p.IsHot);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WarmupPeriod_MatchesConstructorPeriod()
|
||||
{
|
||||
var p = new Polyfit(12, 3);
|
||||
Assert.Equal(12, p.WarmupPeriod);
|
||||
}
|
||||
|
||||
// ── E) Robustness: NaN / Infinity ─────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void NaN_SubstitutesLastValid()
|
||||
{
|
||||
var p = new Polyfit(5, 2);
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
p.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 10.0 + i));
|
||||
}
|
||||
p.Update(new TValue(DateTime.UtcNow.AddSeconds(4), double.NaN));
|
||||
Assert.True(double.IsFinite(p.Last.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Infinity_SubstitutesLastValid()
|
||||
{
|
||||
var p = new Polyfit(5, 2);
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
p.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 10.0));
|
||||
}
|
||||
p.Update(new TValue(DateTime.UtcNow.AddSeconds(4), double.PositiveInfinity));
|
||||
Assert.True(double.IsFinite(p.Last.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BatchNaN_Safe()
|
||||
{
|
||||
double[] src = [10, 20, double.NaN, 30, 40, double.NaN, 50];
|
||||
double[] dst = new double[src.Length];
|
||||
Polyfit.Batch(src, dst, period: 5, degree: 2);
|
||||
// All outputs should be finite (NaN substituted by last valid)
|
||||
for (int i = 0; i < src.Length; i++)
|
||||
{
|
||||
Assert.True(double.IsFinite(dst[i]) || dst[i] == 0);
|
||||
}
|
||||
}
|
||||
|
||||
// ── F) Consistency: batch == streaming == span == eventing ───────────────
|
||||
|
||||
[Fact]
|
||||
public void AllModes_Consistent()
|
||||
{
|
||||
int period = 7;
|
||||
int degree = 2;
|
||||
int dataLen = 40;
|
||||
var gbm = new GBM(100, 0.05, 0.2, seed: 99);
|
||||
var series = new TSeries();
|
||||
for (int i = 0; i < dataLen; i++)
|
||||
{
|
||||
var bar = gbm.Next();
|
||||
series.Add(new TValue(bar.Time, bar.Close));
|
||||
}
|
||||
|
||||
// 1. Batch (TSeries)
|
||||
var batchResult = Polyfit.Batch(series, period, degree);
|
||||
|
||||
// 2. Streaming (separate GBM reset to same seed)
|
||||
var streaming = new Polyfit(period, degree);
|
||||
for (int i = 0; i < dataLen; i++)
|
||||
{
|
||||
streaming.Update(series[i]);
|
||||
}
|
||||
|
||||
// 3. Span
|
||||
double[] spanOut = new double[dataLen];
|
||||
Polyfit.Batch(series.Values, spanOut.AsSpan(), period, degree);
|
||||
|
||||
// Compare batch vs span for all hot values
|
||||
for (int i = period - 1; i < dataLen; i++)
|
||||
{
|
||||
Assert.Equal(batchResult[i].Value, spanOut[i], 1e-9);
|
||||
}
|
||||
|
||||
// Final value: streaming == batch
|
||||
Assert.Equal(batchResult[dataLen - 1].Value, streaming.Last.Value, 1e-9);
|
||||
}
|
||||
|
||||
// ── G) Span API ───────────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void SpanAPI_WrongLength_Throws()
|
||||
{
|
||||
double[] src = [1, 2, 3, 4, 5];
|
||||
double[] dst = new double[4];
|
||||
var ex = Assert.Throws<ArgumentException>(() =>
|
||||
Polyfit.Batch(src.AsSpan(), dst.AsSpan(), period: 3, degree: 2));
|
||||
Assert.Equal("output", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SpanAPI_PeriodLessThan2_Throws()
|
||||
{
|
||||
double[] src = [1, 2, 3];
|
||||
double[] dst = new double[3];
|
||||
var ex = Assert.Throws<ArgumentException>(() =>
|
||||
Polyfit.Batch(src.AsSpan(), dst.AsSpan(), period: 1, degree: 2));
|
||||
Assert.Equal("period", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SpanAPI_DegreeLessThan1_Throws()
|
||||
{
|
||||
double[] src = [1, 2, 3];
|
||||
double[] dst = new double[3];
|
||||
var ex = Assert.Throws<ArgumentException>(() =>
|
||||
Polyfit.Batch(src.AsSpan(), dst.AsSpan(), period: 3, degree: 0));
|
||||
Assert.Equal("degree", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SpanAPI_LargeData_NoStackOverflow()
|
||||
{
|
||||
int n = 2000;
|
||||
double[] src = new double[n];
|
||||
var gbm = new GBM(100, 0.05, 0.2, seed: 7);
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
src[i] = gbm.Next().Close;
|
||||
}
|
||||
double[] dst = new double[n];
|
||||
// period=300 > StackallocThreshold(256) → uses ArrayPool path
|
||||
Polyfit.Batch(src.AsSpan(), dst.AsSpan(), period: 300, degree: 2);
|
||||
Assert.True(double.IsFinite(dst[n - 1]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SpanAPI_MatchesTSeries()
|
||||
{
|
||||
int period = 6;
|
||||
int degree = 2;
|
||||
var gbm = new GBM(100, 0.05, 0.2, seed: 55);
|
||||
var series = new TSeries();
|
||||
for (int i = 0; i < 30; i++)
|
||||
{
|
||||
var bar = gbm.Next();
|
||||
series.Add(new TValue(bar.Time, bar.Close));
|
||||
}
|
||||
|
||||
var batchResult = Polyfit.Batch(series, period, degree);
|
||||
double[] spanOut = new double[30];
|
||||
Polyfit.Batch(series.Values, spanOut.AsSpan(), period, degree);
|
||||
|
||||
for (int i = period - 1; i < 30; i++)
|
||||
{
|
||||
Assert.Equal(batchResult[i].Value, spanOut[i], 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
// ── H) Chainability ───────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void EventFires_OnUpdate()
|
||||
{
|
||||
var p = new Polyfit(3, 1);
|
||||
int eventCount = 0;
|
||||
p.Pub += (_, in args) => eventCount++;
|
||||
for (int i = 0; i < 3; i++)
|
||||
{
|
||||
p.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 10.0));
|
||||
}
|
||||
Assert.Equal(3, eventCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Chaining_WorksCorrectly()
|
||||
{
|
||||
var sma = new Sma(3);
|
||||
var poly = new Polyfit(sma, 5, 2);
|
||||
Assert.False(poly.IsHot);
|
||||
for (int i = 0; i < 7; i++)
|
||||
{
|
||||
sma.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 10.0 + i));
|
||||
}
|
||||
Assert.True(poly.IsHot);
|
||||
}
|
||||
|
||||
// ── I) Degree=1 matches LSMA / linear regression ─────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Degree1_MatchesLinearRegression()
|
||||
{
|
||||
int period = 5;
|
||||
var poly = new Polyfit(period, 1);
|
||||
var lsma = new Lsma(period);
|
||||
|
||||
var gbm = new GBM(100, 0.05, 0.2, seed: 42);
|
||||
for (int i = 0; i < 30; i++)
|
||||
{
|
||||
var bar = gbm.Next();
|
||||
var tv = new TValue(bar.Time, bar.Close);
|
||||
poly.Update(tv);
|
||||
lsma.Update(tv);
|
||||
}
|
||||
// Degree=1 polynomial fit == linear regression endpoint
|
||||
Assert.Equal(lsma.Last.Value, poly.Last.Value, 1e-6);
|
||||
}
|
||||
|
||||
// ── J) Quadratic captures curvature ──────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Degree2_QuadraticData_MatchesExact()
|
||||
{
|
||||
// Data: y_i = (i/(n-1))^2 for i=0..n-1, n=5
|
||||
// Quadratic fit should be exact → P(1.0) = 1.0^2 = 1.0
|
||||
var p = new Polyfit(5, 2);
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
double xi = i / 4.0;
|
||||
p.Update(new TValue(DateTime.UtcNow.AddSeconds(i), xi * xi));
|
||||
}
|
||||
Assert.Equal(1.0, p.Last.Value, 1e-9);
|
||||
}
|
||||
|
||||
// ── K) Prime() – stateful priming ─────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Prime_SetsState()
|
||||
{
|
||||
var p = new Polyfit(5, 2);
|
||||
double[] primeData = [10.0, 20.0, 30.0, 40.0, 50.0];
|
||||
p.Prime(primeData);
|
||||
Assert.True(p.IsHot);
|
||||
Assert.True(double.IsFinite(p.Last.Value));
|
||||
}
|
||||
|
||||
// ── L) Calculate static method ────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Calculate_StaticMethod_ReturnsBoth()
|
||||
{
|
||||
var gbm = new GBM(100, 0.05, 0.2, seed: 7);
|
||||
var series = new TSeries();
|
||||
for (int i = 0; i < 25; i++)
|
||||
{
|
||||
var bar = gbm.Next();
|
||||
series.Add(new TValue(bar.Time, bar.Close));
|
||||
}
|
||||
var (results, indicator) = Polyfit.Calculate(series, period: 10, degree: 2);
|
||||
Assert.NotNull(results);
|
||||
Assert.NotNull(indicator);
|
||||
Assert.Equal(25, results.Count);
|
||||
Assert.True(indicator.IsHot);
|
||||
}
|
||||
|
||||
// ── M) Various degrees ────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Degree3_Cubic_ReturnsFinite()
|
||||
{
|
||||
var p = new Polyfit(10, 3);
|
||||
var gbm = new GBM(100, 0.05, 0.2, seed: 101);
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
p.Update(new TValue(DateTime.UtcNow.AddSeconds(i), gbm.Next().Close));
|
||||
}
|
||||
Assert.True(p.IsHot);
|
||||
Assert.True(double.IsFinite(p.Last.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Degree6_MaxDegree_ReturnsFinite()
|
||||
{
|
||||
var p = new Polyfit(10, 6);
|
||||
var gbm = new GBM(100, 0.05, 0.2, seed: 202);
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
p.Update(new TValue(DateTime.UtcNow.AddSeconds(i), gbm.Next().Close));
|
||||
}
|
||||
Assert.True(p.IsHot);
|
||||
Assert.True(double.IsFinite(p.Last.Value));
|
||||
}
|
||||
|
||||
// ── N) Update(TSeries) round-trip ────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void UpdateTSeries_MatchesBatch()
|
||||
{
|
||||
int period = 8;
|
||||
int degree = 2;
|
||||
var gbm = new GBM(100, 0.05, 0.2, seed: 77);
|
||||
var series = new TSeries();
|
||||
for (int i = 0; i < 30; i++)
|
||||
{
|
||||
var bar = gbm.Next();
|
||||
series.Add(new TValue(bar.Time, bar.Close));
|
||||
}
|
||||
|
||||
var p = new Polyfit(period, degree);
|
||||
var result = p.Update(series);
|
||||
var batchResult = Polyfit.Batch(series, period, degree);
|
||||
|
||||
for (int i = 0; i < 30; i++)
|
||||
{
|
||||
Assert.Equal(batchResult[i].Value, result[i].Value, 1e-9);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Validation tests for Polyfit against manual OLS computations and mathematical identities.
|
||||
/// No external library (Skender/TA-Lib/Tulip/Ooples) implements polynomial regression of
|
||||
/// variable degree, so validation is against closed-form solutions and known identities.
|
||||
/// </summary>
|
||||
public class PolyfitValidationTests
|
||||
{
|
||||
// ── 1. Streaming vs Batch vs Span consistency ─────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Streaming_Batch_Span_Consistent()
|
||||
{
|
||||
int period = 10;
|
||||
int degree = 2;
|
||||
int dataLen = 50;
|
||||
var gbm = new GBM(100, 0.05, 0.2, seed: 42);
|
||||
var series = new TSeries();
|
||||
for (int i = 0; i < dataLen; i++)
|
||||
{
|
||||
var bar = gbm.Next();
|
||||
series.Add(new TValue(bar.Time, bar.Close));
|
||||
}
|
||||
|
||||
// Streaming
|
||||
var streaming = new Polyfit(period, degree);
|
||||
double[] streamVals = new double[dataLen];
|
||||
for (int i = 0; i < dataLen; i++)
|
||||
{
|
||||
streaming.Update(series[i]);
|
||||
streamVals[i] = streaming.Last.Value;
|
||||
}
|
||||
|
||||
// Batch TSeries
|
||||
var batchResult = Polyfit.Batch(series, period, degree);
|
||||
|
||||
// Span
|
||||
double[] spanOut = new double[dataLen];
|
||||
Polyfit.Batch(series.Values, spanOut.AsSpan(), period, degree);
|
||||
|
||||
// All modes must agree at every hot position
|
||||
for (int i = period - 1; i < dataLen; i++)
|
||||
{
|
||||
Assert.Equal(streamVals[i], batchResult[i].Value, 1e-9);
|
||||
Assert.Equal(streamVals[i], spanOut[i], 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
// ── 2. Known values: degree=1 matches closed-form linear regression ────────
|
||||
|
||||
[Fact]
|
||||
public void Degree1_KnownValues_MatchOlsLinearRegression()
|
||||
{
|
||||
// For y = [1,2,3,4,5] with x_norm = [0, 0.25, 0.5, 0.75, 1.0]:
|
||||
// Linear fit: b1=(n*Σxy-Σx*Σy)/(n*Σx²-Σx²), b0=Ȳ-b1*x̄
|
||||
// P(1.0) for y=1..5 → value at the endpoint = 5 (perfect linear fit)
|
||||
var p = new Polyfit(5, 1);
|
||||
for (int i = 1; i <= 5; i++)
|
||||
{
|
||||
p.Update(new TValue(DateTime.UtcNow.AddSeconds(i), (double)i));
|
||||
}
|
||||
Assert.Equal(5.0, p.Last.Value, 1e-9);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Degree1_ReverseLinear_MatchesEndpoint()
|
||||
{
|
||||
// y = 5,4,3,2,1 → P(1.0) = 1.0 (last value)
|
||||
var p = new Polyfit(5, 1);
|
||||
for (int i = 5; i >= 1; i--)
|
||||
{
|
||||
p.Update(new TValue(DateTime.UtcNow.AddSeconds(5 - i), (double)i));
|
||||
}
|
||||
Assert.Equal(1.0, p.Last.Value, 1e-9);
|
||||
}
|
||||
|
||||
// ── 3. Degree=2 exact quadratic recovery ──────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Degree2_ExactQuadratic_RecoverCoefficients()
|
||||
{
|
||||
// y = 3 + 2*x + x^2 with x_norm in [0,1] over 5 points
|
||||
// P(1) = 3 + 2 + 1 = 6
|
||||
int n = 5;
|
||||
var p = new Polyfit(n, 2);
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
double x = i / (double)(n - 1);
|
||||
double y = Math.FusedMultiplyAdd(x, x, Math.FusedMultiplyAdd(2.0, x, 3.0));
|
||||
p.Update(new TValue(DateTime.UtcNow.AddSeconds(i), y));
|
||||
}
|
||||
Assert.Equal(6.0, p.Last.Value, 1e-9);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Degree2_PureQuadratic_RecoverEndpoint()
|
||||
{
|
||||
// y = x^2, n=11, x in [0,1] step 0.1 → P(1.0) = 1.0
|
||||
int n = 11;
|
||||
var p = new Polyfit(n, 2);
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
double x = i / (double)(n - 1);
|
||||
p.Update(new TValue(DateTime.UtcNow.AddSeconds(i), x * x));
|
||||
}
|
||||
Assert.Equal(1.0, p.Last.Value, 1e-9);
|
||||
}
|
||||
|
||||
// ── 4. Degree=3 exact cubic recovery ──────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Degree3_ExactCubic_RecoverEndpoint()
|
||||
{
|
||||
// y = x^3 with x_norm in [0,1], n=10 → P(1.0) = 1.0
|
||||
int n = 10;
|
||||
var p = new Polyfit(n, 3);
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
double x = i / (double)(n - 1);
|
||||
p.Update(new TValue(DateTime.UtcNow.AddSeconds(i), x * x * x));
|
||||
}
|
||||
Assert.Equal(1.0, p.Last.Value, 1e-9);
|
||||
}
|
||||
|
||||
// ── 5. Constant data trivially correct for all degrees ────────────────────
|
||||
|
||||
[Theory]
|
||||
[InlineData(1)]
|
||||
[InlineData(2)]
|
||||
[InlineData(3)]
|
||||
[InlineData(4)]
|
||||
public void ConstantData_AllDegrees_ReturnsConstant(int degree)
|
||||
{
|
||||
var p = new Polyfit(10, degree);
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
p.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0));
|
||||
}
|
||||
Assert.Equal(100.0, p.Last.Value, 1e-9);
|
||||
}
|
||||
|
||||
// ── 6. Degree=1 matches Lsma (offset=0) exactly ───────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Degree1_MatchesLsma_MultiBar()
|
||||
{
|
||||
int period = 10;
|
||||
var poly = new Polyfit(period, 1);
|
||||
var lsma = new Lsma(period);
|
||||
|
||||
var gbm = new GBM(100, 0.05, 0.2, seed: 123);
|
||||
for (int i = 0; i < 50; i++)
|
||||
{
|
||||
var bar = gbm.Next();
|
||||
var tv = new TValue(bar.Time, bar.Close);
|
||||
poly.Update(tv);
|
||||
lsma.Update(tv);
|
||||
|
||||
if (poly.IsHot)
|
||||
{
|
||||
// Polyfit(degree=1) == LSMA(offset=0): both are the lin-reg endpoint
|
||||
Assert.Equal(lsma.Last.Value, poly.Last.Value, 1e-6);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── 7. Higher degree fits better for polynomial data ──────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Degree2_FitsBetterThanDegree1_ForQuadraticSignal()
|
||||
{
|
||||
// Quadratic signal: degree=2 should recover the endpoint more accurately
|
||||
int n = 20;
|
||||
var series = new TSeries();
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
double x = i / (double)(n - 1);
|
||||
double y = x * x;
|
||||
series.Add(new TValue(DateTime.UtcNow.AddSeconds(i), y));
|
||||
}
|
||||
|
||||
var poly1 = new Polyfit(n, 1);
|
||||
var poly2 = new Polyfit(n, 2);
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
poly1.Update(series[i]);
|
||||
poly2.Update(series[i]);
|
||||
}
|
||||
|
||||
// Degree=2 should exactly reproduce y=1.0 for pure quadratic
|
||||
Assert.Equal(1.0, poly2.Last.Value, 1e-9);
|
||||
|
||||
// Degree=1 approximates but can't exactly match a quadratic
|
||||
double err1 = Math.Abs(poly1.Last.Value - 1.0);
|
||||
double err2 = Math.Abs(poly2.Last.Value - 1.0);
|
||||
Assert.True(err2 <= err1 + 1e-12);
|
||||
}
|
||||
|
||||
// ── 8. Rolling window correctness ─────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void RollingWindow_StreamingMatchesBatchAtEachBar()
|
||||
{
|
||||
int period = 6;
|
||||
int degree = 2;
|
||||
var gbm = new GBM(100, 0.05, 0.2, seed: 321);
|
||||
double[] allData = new double[25];
|
||||
DateTime[] allTimes = new DateTime[25];
|
||||
for (int i = 0; i < 25; i++)
|
||||
{
|
||||
var bar = gbm.Next();
|
||||
allData[i] = bar.Close;
|
||||
allTimes[i] = DateTime.UtcNow.AddSeconds(i);
|
||||
}
|
||||
|
||||
var streaming = new Polyfit(period, degree);
|
||||
for (int i = 0; i < 25; i++)
|
||||
{
|
||||
streaming.Update(new TValue(allTimes[i], allData[i]));
|
||||
|
||||
// At each bar, manually compute polyfit over the window ending at bar i
|
||||
int windowStart = Math.Max(0, i - period + 1);
|
||||
int windowLen = i - windowStart + 1;
|
||||
double[] window = allData[windowStart..(i + 1)];
|
||||
|
||||
double manualResult = Polyfit.ComputePolyfit(window, Math.Min(degree, windowLen - 1));
|
||||
Assert.Equal(manualResult, streaming.Last.Value, 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
// ── 9. Multiple periods with GBM data ─────────────────────────────────────
|
||||
|
||||
[Theory]
|
||||
[InlineData(5, 1)]
|
||||
[InlineData(10, 2)]
|
||||
[InlineData(20, 3)]
|
||||
[InlineData(14, 2)]
|
||||
public void GBMData_AllFinite(int period, int degree)
|
||||
{
|
||||
var gbm = new GBM(100, 0.05, 0.2, seed: period * 10 + degree);
|
||||
var p = new Polyfit(period, degree);
|
||||
for (int i = 0; i < 100; i++)
|
||||
{
|
||||
var bar = gbm.Next();
|
||||
p.Update(new TValue(bar.Time, bar.Close));
|
||||
if (p.IsHot)
|
||||
{
|
||||
Assert.True(double.IsFinite(p.Last.Value),
|
||||
$"Got non-finite at i={i}: {p.Last.Value}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── 10. Batch TSeries vs streaming at last value ───────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void BatchFinalValue_MatchesStreamingFinalValue()
|
||||
{
|
||||
int period = 8;
|
||||
int degree = 2;
|
||||
var gbm = new GBM(100, 0.05, 0.2, seed: 999);
|
||||
var series = new TSeries();
|
||||
var streaming = new Polyfit(period, degree);
|
||||
|
||||
for (int i = 0; i < 40; i++)
|
||||
{
|
||||
var bar = gbm.Next();
|
||||
var tv = new TValue(bar.Time, bar.Close);
|
||||
series.Add(tv);
|
||||
streaming.Update(tv);
|
||||
}
|
||||
|
||||
var batchResult = Polyfit.Batch(series, period, degree);
|
||||
Assert.Equal(batchResult[39].Value, streaming.Last.Value, 1e-9);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,460 @@
|
||||
using System.Buffers;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace QuanTAlib;
|
||||
|
||||
/// <summary>
|
||||
/// Polyfit: Polynomial Fit (Regression) Moving Average
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Fits a degree-m polynomial y = a0 + a1*t + ... + am*t^m to the most recent
|
||||
/// N bars via least squares normal equations, where t is normalized to [0,1]
|
||||
/// (t=0 oldest bar, t=1 newest bar). Returns the fitted value at t=1.
|
||||
///
|
||||
/// Calculation: Accumulate (2m+1) power sums + (m+1) cross-products in O(N*m),
|
||||
/// solve (m+1)×(m+1) normal equations via Gaussian elimination with partial
|
||||
/// pivoting in O(m³). Degree is clamped to period-1. Min period = degree+1.
|
||||
///
|
||||
/// With degree=1 the result is identical to LSMA (linear regression endpoint).
|
||||
/// </remarks>
|
||||
/// <seealso href="Polyfit.md">Detailed documentation</seealso>
|
||||
[SkipLocalsInit]
|
||||
public sealed class Polyfit : AbstractBase
|
||||
{
|
||||
private readonly int _period;
|
||||
private readonly int _degree;
|
||||
private readonly RingBuffer _buffer;
|
||||
private readonly TValuePublishedHandler _handler;
|
||||
private ITValuePublisher? _source;
|
||||
private int _disposed;
|
||||
|
||||
[StructLayout(LayoutKind.Auto)]
|
||||
private record struct State(double LastVal, double LastValidValue);
|
||||
private State _state;
|
||||
private State _p_state;
|
||||
|
||||
private bool _isNew;
|
||||
|
||||
public int Degree => _degree;
|
||||
public override bool IsHot => _buffer.IsFull;
|
||||
public bool IsNew => _isNew;
|
||||
|
||||
/// <summary>
|
||||
/// Creates Polyfit with specified period and polynomial degree.
|
||||
/// </summary>
|
||||
/// <param name="period">Lookback window size (must be >= 2)</param>
|
||||
/// <param name="degree">Polynomial degree 1–6 (clamped to period-1)</param>
|
||||
public Polyfit(int period, int degree = 2)
|
||||
{
|
||||
if (period < 2)
|
||||
{
|
||||
throw new ArgumentException("Period must be at least 2", nameof(period));
|
||||
}
|
||||
if (degree < 1)
|
||||
{
|
||||
throw new ArgumentException("Degree must be at least 1", nameof(degree));
|
||||
}
|
||||
|
||||
_period = period;
|
||||
_degree = Math.Min(degree, period - 1);
|
||||
_buffer = new RingBuffer(period);
|
||||
Name = $"Polyfit({period},{_degree})";
|
||||
WarmupPeriod = period;
|
||||
_handler = Handle;
|
||||
_state.LastValidValue = double.NaN;
|
||||
}
|
||||
|
||||
public Polyfit(ITValuePublisher source, int period, int degree = 2) : this(period, degree)
|
||||
{
|
||||
_source = source ?? throw new ArgumentNullException(nameof(source));
|
||||
_source.Pub += _handler;
|
||||
}
|
||||
|
||||
private void Handle(object? sender, in TValueEventArgs e) => Update(e.Value, e.IsNew);
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private double GetValidValue(double input)
|
||||
{
|
||||
if (double.IsFinite(input))
|
||||
{
|
||||
_state.LastValidValue = input;
|
||||
return input;
|
||||
}
|
||||
return _state.LastValidValue;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Solves the (m+1)×(m+1) normal equation system for polynomial regression of degree m.
|
||||
/// t-convention: data[0]=oldest (t=0/(n-1)), data[n-1]=newest (t=1).
|
||||
/// Returns the fitted value at t=1.0 (newest bar).
|
||||
/// </summary>
|
||||
/// <param name="data">Values oldest-first (data[0] = oldest, data[n-1] = newest)</param>
|
||||
/// <param name="count">Number of valid values in data</param>
|
||||
/// <param name="degree">Polynomial degree</param>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static double SolvePoly(ReadOnlySpan<double> data, int count, int degree)
|
||||
{
|
||||
int m = degree;
|
||||
int sz = m + 1;
|
||||
|
||||
// Power sums and cross products accumulate with normalized t ∈ [0, 1].
|
||||
// Max degree=6 → sz=7, matrix=7*8=56 doubles + powSums=13 + crossSums=7 — all stackalloc safe.
|
||||
Span<double> powSums = stackalloc double[2 * m + 1];
|
||||
Span<double> crossSums = stackalloc double[sz];
|
||||
Span<double> aug = stackalloc double[sz * (sz + 1)]; // augmented matrix row-major
|
||||
|
||||
powSums.Clear();
|
||||
crossSums.Clear();
|
||||
aug.Clear();
|
||||
|
||||
double tScale = count > 1 ? 1.0 / (count - 1) : 0.0;
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
double v = data[i];
|
||||
double t = i * tScale; // t=0 for oldest (i=0), t=1 for newest (i=count-1)
|
||||
double tk = 1.0;
|
||||
for (int k = 0; k <= 2 * m; k++)
|
||||
{
|
||||
powSums[k] += tk;
|
||||
tk *= t;
|
||||
}
|
||||
tk = 1.0;
|
||||
for (int k = 0; k <= m; k++)
|
||||
{
|
||||
crossSums[k] = Math.FusedMultiplyAdd(tk, v, crossSums[k]);
|
||||
tk *= t;
|
||||
}
|
||||
}
|
||||
|
||||
// Build augmented matrix: G[row,col] = powSums[row+col], rhs[row] = crossSums[row]
|
||||
int stride = sz + 1;
|
||||
for (int row = 0; row < sz; row++)
|
||||
{
|
||||
for (int col = 0; col < sz; col++)
|
||||
{
|
||||
aug[row * stride + col] = powSums[row + col];
|
||||
}
|
||||
aug[row * stride + sz] = crossSums[row];
|
||||
}
|
||||
|
||||
// Gaussian elimination with partial pivoting
|
||||
for (int col = 0; col < sz; col++)
|
||||
{
|
||||
int pivotRow = col;
|
||||
double pivotMax = Math.Abs(aug[col * stride + col]);
|
||||
for (int row = col + 1; row < sz; row++)
|
||||
{
|
||||
double absVal = Math.Abs(aug[row * stride + col]);
|
||||
if (absVal > pivotMax)
|
||||
{
|
||||
pivotMax = absVal;
|
||||
pivotRow = row;
|
||||
}
|
||||
}
|
||||
|
||||
if (pivotMax < 1e-12)
|
||||
{
|
||||
return double.NaN; // Singular — caller substitutes raw price
|
||||
}
|
||||
|
||||
if (pivotRow != col)
|
||||
{
|
||||
int colOff = col * stride;
|
||||
int pivOff = pivotRow * stride;
|
||||
for (int k = col; k <= sz; k++)
|
||||
{
|
||||
(aug[colOff + k], aug[pivOff + k]) = (aug[pivOff + k], aug[colOff + k]);
|
||||
}
|
||||
}
|
||||
|
||||
double diag = aug[col * stride + col];
|
||||
for (int row = col + 1; row < sz; row++)
|
||||
{
|
||||
double factor = aug[row * stride + col] / diag;
|
||||
for (int k = col; k <= sz; k++)
|
||||
{
|
||||
aug[row * stride + k] = Math.FusedMultiplyAdd(-factor, aug[col * stride + k], aug[row * stride + k]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Back-substitution → coefficients a[0..m]
|
||||
Span<double> a = stackalloc double[sz];
|
||||
for (int row = sz - 1; row >= 0; row--)
|
||||
{
|
||||
double val = aug[row * stride + sz];
|
||||
for (int k = row + 1; k < sz; k++)
|
||||
{
|
||||
val = Math.FusedMultiplyAdd(-aug[row * stride + k], a[k], val);
|
||||
}
|
||||
a[row] = val / aug[row * stride + row];
|
||||
}
|
||||
|
||||
// Evaluate polynomial at t=1: P(1) = a0 + a1 + a2 + ... + am
|
||||
double result = 0.0;
|
||||
for (int k = 0; k < sz; k++)
|
||||
{
|
||||
result += a[k];
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Public entry point for the validation tests: accepts oldest-first data,
|
||||
/// returns the polynomial fit evaluated at t=1 (the newest bar endpoint).
|
||||
/// </summary>
|
||||
public static double ComputePolyfit(ReadOnlySpan<double> data, int degree)
|
||||
{
|
||||
if (data.Length < 1)
|
||||
{
|
||||
return double.NaN;
|
||||
}
|
||||
int m = Math.Min(degree, data.Length - 1);
|
||||
if (m < 1)
|
||||
{
|
||||
return data[^1];
|
||||
}
|
||||
return SolvePoly(data, data.Length, m);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public override TValue Update(TValue input, bool isNew = true)
|
||||
{
|
||||
_isNew = isNew;
|
||||
if (isNew)
|
||||
{
|
||||
_p_state = _state;
|
||||
double val = GetValidValue(input.Value);
|
||||
_buffer.Add(val);
|
||||
_state.LastVal = val;
|
||||
}
|
||||
else
|
||||
{
|
||||
_state.LastValidValue = _p_state.LastValidValue;
|
||||
double val = GetValidValue(input.Value);
|
||||
_buffer.UpdateNewest(val);
|
||||
_state.LastVal = val;
|
||||
}
|
||||
|
||||
double result;
|
||||
int count = _buffer.Count;
|
||||
int minPoints = _degree + 1;
|
||||
if (count < minPoints)
|
||||
{
|
||||
result = _buffer.Newest;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Get buffer in chronological oldest-first order for SolvePoly
|
||||
const int StackAllocThreshold = 256;
|
||||
double[]? rented = count > StackAllocThreshold ? ArrayPool<double>.Shared.Rent(count) : null;
|
||||
Span<double> data = rented != null
|
||||
? rented.AsSpan(0, count)
|
||||
: stackalloc double[count];
|
||||
|
||||
try
|
||||
{
|
||||
// RingBuffer.GetSpan() returns oldest-first — matches SolvePoly t=0..1 convention
|
||||
_buffer.GetSpan().CopyTo(data);
|
||||
|
||||
double solved = SolvePoly(data, count, _degree);
|
||||
result = double.IsFinite(solved) ? solved : _buffer.Newest;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (rented != null)
|
||||
{
|
||||
ArrayPool<double>.Shared.Return(rented);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Last = new TValue(input.Time, result);
|
||||
PubEvent(Last, isNew);
|
||||
return Last;
|
||||
}
|
||||
|
||||
public override TSeries Update(TSeries source)
|
||||
{
|
||||
if (source.Count == 0)
|
||||
{
|
||||
return new TSeries([], []);
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
double initialLastValid = _state.LastValidValue;
|
||||
Batch(source.Values, vSpan, _period, _degree, initialLastValid);
|
||||
source.Times.CopyTo(tSpan);
|
||||
|
||||
// Restore streaming state by replaying last 'period' bars
|
||||
int windowSize = Math.Min(len, _period);
|
||||
int startIndex = len - windowSize;
|
||||
|
||||
Reset();
|
||||
|
||||
if (startIndex > 0)
|
||||
{
|
||||
for (int i = startIndex - 1; i >= 0; i--)
|
||||
{
|
||||
if (double.IsFinite(source.Values[i]))
|
||||
{
|
||||
_state.LastValidValue = source.Values[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
_state.LastValidValue = initialLastValid;
|
||||
}
|
||||
|
||||
for (int i = startIndex; i < len; i++)
|
||||
{
|
||||
double val = GetValidValue(source.Values[i]);
|
||||
_buffer.Add(val);
|
||||
_state.LastVal = val;
|
||||
}
|
||||
_p_state = _state;
|
||||
|
||||
Last = new TValue(tSpan[len - 1], vSpan[len - 1]);
|
||||
return new TSeries(t, v);
|
||||
}
|
||||
|
||||
public override void Prime(ReadOnlySpan<double> source, TimeSpan? step = null)
|
||||
{
|
||||
foreach (var value in source)
|
||||
{
|
||||
Update(new TValue(DateTime.MinValue, value));
|
||||
}
|
||||
}
|
||||
|
||||
public static TSeries Batch(TSeries source, int period, int degree = 2)
|
||||
{
|
||||
var pf = new Polyfit(period, degree);
|
||||
return pf.Update(source);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Calculates Polyfit in-place, writing results to pre-allocated output span.
|
||||
/// Zero-allocation method for maximum performance. Data oldest-first.
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void Batch(ReadOnlySpan<double> source, Span<double> output, int period, int degree = 2, double initialLastValid = double.NaN)
|
||||
{
|
||||
if (source.Length != output.Length)
|
||||
{
|
||||
throw new ArgumentException("Source and output must have the same length", nameof(output));
|
||||
}
|
||||
if (period < 2)
|
||||
{
|
||||
throw new ArgumentException("Period must be at least 2", nameof(period));
|
||||
}
|
||||
if (degree < 1)
|
||||
{
|
||||
throw new ArgumentException("Degree must be at least 1", nameof(degree));
|
||||
}
|
||||
|
||||
int m = Math.Min(degree, period - 1);
|
||||
int len = source.Length;
|
||||
if (len == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
const int StackAllocThreshold = 256;
|
||||
|
||||
double[]? rentedClean = len > StackAllocThreshold ? ArrayPool<double>.Shared.Rent(len) : null;
|
||||
Span<double> clean = rentedClean != null
|
||||
? rentedClean.AsSpan(0, len)
|
||||
: stackalloc double[len];
|
||||
|
||||
double[]? rentedData = period > StackAllocThreshold ? ArrayPool<double>.Shared.Rent(period) : null;
|
||||
Span<double> dataBuffer = rentedData != null
|
||||
? rentedData.AsSpan(0, period)
|
||||
: stackalloc double[period];
|
||||
|
||||
try
|
||||
{
|
||||
// Build NaN-corrected array (oldest-first matches source order)
|
||||
double lastValid = initialLastValid;
|
||||
for (int i = 0; i < len; i++)
|
||||
{
|
||||
double val = source[i];
|
||||
if (double.IsFinite(val))
|
||||
{
|
||||
lastValid = val;
|
||||
clean[i] = val;
|
||||
}
|
||||
else
|
||||
{
|
||||
clean[i] = double.IsFinite(lastValid) ? lastValid : 0.0;
|
||||
}
|
||||
}
|
||||
|
||||
int minPoints = m + 1;
|
||||
for (int i = 0; i < len; i++)
|
||||
{
|
||||
int n = Math.Min(i + 1, period);
|
||||
if (n < minPoints)
|
||||
{
|
||||
output[i] = clean[i];
|
||||
}
|
||||
else
|
||||
{
|
||||
// Window is clean[i-n+1..i] already oldest-first
|
||||
Span<double> data = dataBuffer[..n];
|
||||
clean.Slice(i - n + 1, n).CopyTo(data);
|
||||
|
||||
double solved = SolvePoly(data, n, m);
|
||||
output[i] = double.IsFinite(solved) ? solved : clean[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (rentedClean != null)
|
||||
{
|
||||
ArrayPool<double>.Shared.Return(rentedClean);
|
||||
}
|
||||
if (rentedData != null)
|
||||
{
|
||||
ArrayPool<double>.Shared.Return(rentedData);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static (TSeries Results, Polyfit Indicator) Calculate(TSeries source, int period, int degree = 2)
|
||||
{
|
||||
var indicator = new Polyfit(period, degree);
|
||||
TSeries results = indicator.Update(source);
|
||||
return (results, indicator);
|
||||
}
|
||||
|
||||
public override void Reset()
|
||||
{
|
||||
_buffer.Clear();
|
||||
_state = default;
|
||||
_state.LastValidValue = double.NaN;
|
||||
_p_state = default;
|
||||
Last = default;
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (Interlocked.CompareExchange(ref _disposed, 1, 0) == 0 && _source != null)
|
||||
{
|
||||
_source.Pub -= _handler;
|
||||
_source = null;
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
using TradingPlatform.BusinessLayer;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public class TrimIndicatorTests
|
||||
{
|
||||
[Fact]
|
||||
public void TrimIndicator_Constructor_SetsDefaults()
|
||||
{
|
||||
var indicator = new TrimIndicator();
|
||||
|
||||
Assert.Equal(20, indicator.Period);
|
||||
Assert.Equal(10.0, indicator.TrimPct);
|
||||
Assert.True(indicator.ShowColdValues);
|
||||
Assert.Equal("Trim - Trimmed Mean Moving Average", indicator.Name);
|
||||
Assert.False(indicator.SeparateWindow);
|
||||
Assert.True(indicator.OnBackGround);
|
||||
Assert.Equal(SourceType.Close, indicator.Source);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TrimIndicator_MinHistoryDepths_EqualsZero()
|
||||
{
|
||||
var indicator = new TrimIndicator { Period = 20 };
|
||||
|
||||
Assert.Equal(0, TrimIndicator.MinHistoryDepths);
|
||||
IWatchlistIndicator watchlistIndicator = indicator;
|
||||
Assert.Equal(0, watchlistIndicator.MinHistoryDepths);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TrimIndicator_Initialize_CreatesInternalTrim()
|
||||
{
|
||||
var indicator = new TrimIndicator { Period = 10, TrimPct = 10.0 };
|
||||
|
||||
indicator.Initialize();
|
||||
|
||||
Assert.Single(indicator.LinesSeries);
|
||||
Assert.Equal("Trim", indicator.LinesSeries[0].Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TrimIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
|
||||
{
|
||||
var indicator = new TrimIndicator { Period = 5, TrimPct = 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 TrimIndicator : Indicator, IWatchlistIndicator
|
||||
{
|
||||
[InputParameter("Period", sortIndex: 1, 3, 2000, 1, 0)]
|
||||
public int Period { get; set; } = 20;
|
||||
|
||||
[InputParameter("Trim %", sortIndex: 2, 0, 49, 1, 0)]
|
||||
public double TrimPct { 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 Trim _trim = null!;
|
||||
private readonly LineSeries _series;
|
||||
private Func<IHistoryItem, double> _priceSelector = null!;
|
||||
|
||||
public static int MinHistoryDepths => 0;
|
||||
int IWatchlistIndicator.MinHistoryDepths => MinHistoryDepths;
|
||||
|
||||
public override string ShortName => $"Trim {Period}/{TrimPct}%";
|
||||
public override string SourceCodeLink => "https://github.com/mihakralj/QuanTAlib/blob/main/lib/statistics/trim/Trim.Quantower.cs";
|
||||
|
||||
public TrimIndicator()
|
||||
{
|
||||
OnBackGround = true;
|
||||
SeparateWindow = false;
|
||||
Name = "Trim - Trimmed Mean Moving Average";
|
||||
Description = "Rolling mean after discarding extreme values from each tail";
|
||||
|
||||
_series = new LineSeries(name: "Trim", color: IndicatorExtensions.Statistics, width: 2, style: LineStyle.Solid);
|
||||
AddLineSeries(_series);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
protected override void OnInit()
|
||||
{
|
||||
_trim = new Trim(Period, TrimPct);
|
||||
_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 = _trim.Update(input, args.IsNewBar());
|
||||
|
||||
_series.SetValue(result.Value, _trim.IsHot, ShowColdValues);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public class TrimTests
|
||||
{
|
||||
// ── A) Constructor validation ────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Constructor_ThrowsOnPeriodLessThan3()
|
||||
{
|
||||
Assert.Throws<ArgumentException>(() => new Trim(2));
|
||||
Assert.Throws<ArgumentException>(() => new Trim(1));
|
||||
Assert.Throws<ArgumentException>(() => new Trim(0));
|
||||
Assert.Throws<ArgumentException>(() => new Trim(-1));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_ThrowsOnInvalidTrimPct()
|
||||
{
|
||||
Assert.Throws<ArgumentException>(() => new Trim(10, -1.0));
|
||||
Assert.Throws<ArgumentException>(() => new Trim(10, 50.0));
|
||||
Assert.Throws<ArgumentException>(() => new Trim(10, 75.0));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_SetsName()
|
||||
{
|
||||
var trim = new Trim(20, 10.0);
|
||||
Assert.Equal("Trim(20,10)", trim.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_SetsWarmupPeriod()
|
||||
{
|
||||
var trim = new Trim(15, 10.0);
|
||||
Assert.Equal(15, trim.WarmupPeriod);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_ValidMinimalPeriod()
|
||||
{
|
||||
var trim = new Trim(3);
|
||||
Assert.NotNull(trim);
|
||||
}
|
||||
|
||||
// ── B) Basic calculation ─────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Update_ReturnsValue()
|
||||
{
|
||||
var trim = new Trim(5);
|
||||
TValue result = trim.Update(new TValue(DateTime.UtcNow, 100));
|
||||
Assert.Equal(result.Value, trim.Last.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsHot_FalseUntilWindowFull()
|
||||
{
|
||||
var trim = new Trim(5);
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
trim.Update(new TValue(DateTime.UtcNow, i + 1.0));
|
||||
Assert.False(trim.IsHot);
|
||||
}
|
||||
|
||||
trim.Update(new TValue(DateTime.UtcNow, 5.0));
|
||||
Assert.True(trim.IsHot);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TrimPctZero_EqualsSMA()
|
||||
{
|
||||
// With trimPct=0, TRIM should equal SMA
|
||||
var trim = new Trim(5, 0.0);
|
||||
double[] vals = [10.0, 20.0, 30.0, 40.0, 50.0];
|
||||
double result = 0;
|
||||
foreach (double v in vals)
|
||||
{
|
||||
result = trim.Update(new TValue(DateTime.UtcNow, v)).Value;
|
||||
}
|
||||
|
||||
Assert.Equal(30.0, result, 10); // SMA of [10,20,30,40,50] = 30
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TrimKnownValue_CorrectResult()
|
||||
{
|
||||
// Window: [1,2,3,4,5,6,7,8,9,10], trimPct=10 on period=10
|
||||
// trimCount = floor(10 * 10/100) = 1
|
||||
// keepCount = 10 - 2 = 8
|
||||
// mean([2,3,4,5,6,7,8,9]) = 44/8 = 5.5
|
||||
var trim = new Trim(10, 10.0);
|
||||
for (int i = 1; i <= 10; i++)
|
||||
{
|
||||
trim.Update(new TValue(DateTime.UtcNow, i));
|
||||
}
|
||||
|
||||
Assert.Equal(5.5, trim.Last.Value, 10);
|
||||
}
|
||||
|
||||
// ── C) State + bar correction ────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void BarCorrection_IsNewFalse_RewritesLastBar()
|
||||
{
|
||||
var trim = new Trim(5, 10.0);
|
||||
var t = DateTime.UtcNow;
|
||||
|
||||
// Fill window with [1,2,3,4,5]
|
||||
for (int i = 1; i <= 5; i++)
|
||||
{
|
||||
trim.Update(new TValue(t, i));
|
||||
}
|
||||
|
||||
double before = trim.Last.Value; // TRIM([1,2,3,4,5], 10%) — trimCount=0, SMA=3.0
|
||||
|
||||
// Bar correction: replace last value (5) with 100 (an outlier)
|
||||
trim.Update(new TValue(t, 100.0), isNew: false);
|
||||
double afterCorrection = trim.Last.Value;
|
||||
|
||||
// Next bar (isNew=true) with value=5: window slides to [2,3,4,5,5] from corrected state
|
||||
// (isNew=false set last bar to 5.0 before this new bar arrives)
|
||||
trim.Update(new TValue(t, 5.0), isNew: true);
|
||||
double afterNewBar = trim.Last.Value;
|
||||
|
||||
// Correction with outlier should differ from original
|
||||
Assert.NotEqual(before, afterCorrection);
|
||||
// After new bar, result is finite and valid
|
||||
Assert.True(double.IsFinite(afterNewBar));
|
||||
// The new bar result differs from original (window shifted, different values)
|
||||
Assert.NotEqual(afterCorrection, afterNewBar);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reset_ClearsState()
|
||||
{
|
||||
var trim = new Trim(5);
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
trim.Update(new TValue(DateTime.UtcNow, 100.0));
|
||||
}
|
||||
|
||||
Assert.True(trim.IsHot);
|
||||
trim.Reset();
|
||||
Assert.False(trim.IsHot);
|
||||
Assert.Equal(0, trim.Last.Value);
|
||||
}
|
||||
|
||||
// ── D) Warmup/convergence ────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void IsHot_FlipsAtPeriod()
|
||||
{
|
||||
int period = 7;
|
||||
var trim = new Trim(period);
|
||||
for (int i = 0; i < period - 1; i++)
|
||||
{
|
||||
trim.Update(new TValue(DateTime.UtcNow, i));
|
||||
Assert.False(trim.IsHot);
|
||||
}
|
||||
|
||||
trim.Update(new TValue(DateTime.UtcNow, period));
|
||||
Assert.True(trim.IsHot);
|
||||
}
|
||||
|
||||
// ── E) Robustness (NaN/Infinity) ─────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void NaN_UsesLastValidValue()
|
||||
{
|
||||
var trim = new Trim(5, 0.0); // trimPct=0 means SMA for easy verification
|
||||
for (int i = 1; i <= 5; i++)
|
||||
{
|
||||
trim.Update(new TValue(DateTime.UtcNow, 10.0));
|
||||
}
|
||||
|
||||
_ = trim.Last.Value; // should be 10 – value not compared directly
|
||||
|
||||
// Feed NaN — should use last valid (10)
|
||||
trim.Update(new TValue(DateTime.UtcNow, double.NaN));
|
||||
Assert.True(double.IsFinite(trim.Last.Value));
|
||||
|
||||
// Feed Infinity — should use last valid
|
||||
trim.Update(new TValue(DateTime.UtcNow, double.PositiveInfinity));
|
||||
Assert.True(double.IsFinite(trim.Last.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AllNaN_DoesNotThrow()
|
||||
{
|
||||
var trim = new Trim(5);
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
TValue result = trim.Update(new TValue(DateTime.UtcNow, double.NaN));
|
||||
Assert.True(double.IsFinite(result.Value));
|
||||
}
|
||||
}
|
||||
|
||||
// ── F) Consistency (batch == streaming == span == eventing) ─────────────
|
||||
|
||||
[Fact]
|
||||
public void Consistency_BatchEqualsStreaming()
|
||||
{
|
||||
var rng = new GBM(startPrice: 100, mu: 0.0002, sigma: 0.02, seed: 42);
|
||||
int n = 100;
|
||||
int period = 14;
|
||||
double trimPct = 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;
|
||||
}
|
||||
|
||||
// Streaming
|
||||
var streamTrim = new Trim(period, trimPct);
|
||||
double lastStream = 0;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
lastStream = streamTrim.Update(new TValue(new DateTime(times[i], DateTimeKind.Utc), prices[i])).Value;
|
||||
}
|
||||
|
||||
// Batch via Span
|
||||
var spanOutput = new double[n];
|
||||
Trim.Batch(prices, spanOutput, period, trimPct);
|
||||
|
||||
Assert.Equal(lastStream, spanOutput[n - 1], 10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Consistency_SpanValidatesLengths()
|
||||
{
|
||||
var src = new double[10];
|
||||
var dst = new double[9]; // wrong length
|
||||
Assert.Throws<ArgumentException>(() => Trim.Batch(src, dst, 5));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Consistency_SpanValidatesPeriod()
|
||||
{
|
||||
var src = new double[10];
|
||||
var dst = new double[10];
|
||||
Assert.Throws<ArgumentException>(() => Trim.Batch(src, dst, 2));
|
||||
}
|
||||
|
||||
// ── G) Span API large-data (stackalloc threshold) ─────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Span_LargePeriod_NoStackOverflow()
|
||||
{
|
||||
int n = 1000;
|
||||
int period = 300; // > 256 stackalloc threshold → ArrayPool path
|
||||
var src = new double[n];
|
||||
var dst = new double[n];
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
src[i] = i + 1.0;
|
||||
}
|
||||
|
||||
// Must not throw
|
||||
Trim.Batch(src, dst, period, 10.0);
|
||||
Assert.True(double.IsFinite(dst[n - 1]));
|
||||
}
|
||||
|
||||
// ── H) Chainability / eventing ───────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Pub_FiresOnUpdate()
|
||||
{
|
||||
var trim = new Trim(5);
|
||||
int fireCount = 0;
|
||||
trim.Pub += (object? _, in TValueEventArgs _) => fireCount++;
|
||||
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
trim.Update(new TValue(DateTime.UtcNow, i));
|
||||
}
|
||||
|
||||
Assert.Equal(10, fireCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Chaining_EventBased_Works()
|
||||
{
|
||||
var trim1 = new Trim(5, 10.0);
|
||||
var trim2 = new Trim(trim1, 3, 0.0);
|
||||
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
trim1.Update(new TValue(DateTime.UtcNow, i + 1.0));
|
||||
}
|
||||
|
||||
Assert.True(double.IsFinite(trim2.Last.Value));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Trim self-consistency validation.
|
||||
/// No external library has a built-in trimmed mean moving average,
|
||||
/// so we validate internal consistency: batch == streaming == span.
|
||||
/// </summary>
|
||||
public class TrimValidationTests
|
||||
{
|
||||
private const double Tolerance = 1e-10;
|
||||
|
||||
[Fact]
|
||||
public void Trim_Streaming_Equals_SpanBatch()
|
||||
{
|
||||
var rng = new GBM(startPrice: 100, mu: 0.0001, sigma: 0.015, seed: 1001);
|
||||
int n = 200;
|
||||
int period = 20;
|
||||
double trimPct = 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;
|
||||
}
|
||||
|
||||
// Streaming
|
||||
var streaming = new Trim(period, trimPct);
|
||||
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;
|
||||
}
|
||||
|
||||
// Span batch
|
||||
var spanValues = new double[n];
|
||||
Trim.Batch(prices, spanValues, period, trimPct);
|
||||
|
||||
for (int i = period - 1; i < n; i++)
|
||||
{
|
||||
Assert.Equal(streamValues[i], spanValues[i], 9);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Trim_TrimPctZero_EqualsSMA_LongSeries()
|
||||
{
|
||||
var rng = new GBM(startPrice: 100, mu: 0.0001, sigma: 0.015, seed: 2002);
|
||||
int n = 200;
|
||||
int period = 14;
|
||||
|
||||
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 smaRef = new double[n];
|
||||
var trimOut = new double[n];
|
||||
|
||||
// Manual SMA using span for reference (trimZero is redundant — Batch is the span path)
|
||||
Trim.Batch(prices, trimOut, period, 0.0);
|
||||
|
||||
// Manual reference: SMA with period
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
int start = Math.Max(0, i - period + 1);
|
||||
double sum = 0;
|
||||
int cnt = 0;
|
||||
for (int j = start; j <= i; j++)
|
||||
{
|
||||
sum += prices[j];
|
||||
cnt++;
|
||||
}
|
||||
|
||||
smaRef[i] = sum / cnt;
|
||||
}
|
||||
|
||||
// After warmup, both should match
|
||||
for (int i = period - 1; i < n; i++)
|
||||
{
|
||||
Assert.Equal(smaRef[i], trimOut[i], 9);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Trim_BatchTSeries_EqualsStreaming()
|
||||
{
|
||||
var rng = new GBM(startPrice: 100, mu: 0.0001, sigma: 0.015, seed: 3003);
|
||||
int n = 50;
|
||||
int period = 10;
|
||||
double trimPct = 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 = Trim.Batch(series, period, trimPct);
|
||||
|
||||
var streaming = new Trim(period, trimPct);
|
||||
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 Trim_HighTrimPct_ApproachesMedian()
|
||||
{
|
||||
// With trimPct=49 on period=10, trimCount=4, keepCount=2 (middle 2 values)
|
||||
var trim = new Trim(10, 49.0);
|
||||
double[] vals = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
|
||||
foreach (double v in vals)
|
||||
{
|
||||
trim.Update(new TValue(DateTime.UtcNow, v));
|
||||
}
|
||||
|
||||
// keepCount = 10 - 2*4 = 2, trimCount=4
|
||||
// middle 2 values of sorted [1..10] = [5,6], mean = 5.5
|
||||
Assert.Equal(5.5, trim.Last.Value, 10);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,437 @@
|
||||
using System.Buffers;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace QuanTAlib;
|
||||
|
||||
/// <summary>
|
||||
/// Trim: Rolling Trimmed Mean Moving Average
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Sorts the lookback window, discards the lowest and highest trimPct% of values,
|
||||
/// and returns the arithmetic mean of the remaining middle portion.
|
||||
/// trimPct=0 → SMA, trimPct approaches 50 → Median.
|
||||
///
|
||||
/// Complexity per bar: O(N log N) sort + O(N) sum — unavoidable for exact order statistics.
|
||||
/// Sorted buffer maintained incrementally via BinarySearch + Array.Copy to avoid full re-sort.
|
||||
/// </remarks>
|
||||
[SkipLocalsInit]
|
||||
public sealed class Trim : AbstractBase
|
||||
{
|
||||
private readonly int _period;
|
||||
private readonly double _trimPct;
|
||||
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 Trim indicator with the specified period and trim percentage.
|
||||
/// </summary>
|
||||
/// <param name="period">The size of the rolling window (must be >= 3).</param>
|
||||
/// <param name="trimPct">Percentage of values to trim from each tail (0–49). Default 10.</param>
|
||||
public Trim(int period, double trimPct = 10.0)
|
||||
{
|
||||
if (period < 3)
|
||||
{
|
||||
throw new ArgumentException("Period must be >= 3", nameof(period));
|
||||
}
|
||||
|
||||
if (trimPct < 0 || trimPct >= 50)
|
||||
{
|
||||
throw new ArgumentException("TrimPct must be in [0, 49]", nameof(trimPct));
|
||||
}
|
||||
|
||||
_period = period;
|
||||
_trimPct = trimPct;
|
||||
_buffer = new RingBuffer(period);
|
||||
_sortedBuffer = new double[period];
|
||||
_p_sortedBuffer = new double[period];
|
||||
Name = $"Trim({period},{trimPct})";
|
||||
WarmupPeriod = period;
|
||||
_handler = Handle;
|
||||
}
|
||||
|
||||
/// <summary>Creates a chained Trim indicator.</summary>
|
||||
public Trim(ITValuePublisher source, int period, double trimPct = 10.0) : this(period, trimPct)
|
||||
{
|
||||
_source = source;
|
||||
source.Pub += _handler;
|
||||
}
|
||||
|
||||
/// <summary>Creates a Trim indicator primed from a TSeries source.</summary>
|
||||
public Trim(TSeries source, int period, double trimPct = 10.0) : this(period, trimPct)
|
||||
{
|
||||
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 = ComputeTrimmedMean(_sortedBuffer, _buffer.Count, _trimPct);
|
||||
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, _trimPct);
|
||||
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 Trim for the entire series using a new instance.</summary>
|
||||
public static TSeries Batch(TSeries source, int period, double trimPct = 10.0)
|
||||
{
|
||||
var trim = new Trim(period, trimPct);
|
||||
return trim.Update(source);
|
||||
}
|
||||
|
||||
/// <summary>Calculates Trim in-place using spans.</summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void Batch(ReadOnlySpan<double> source, Span<double> output, int period, double trimPct = 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 (trimPct < 0 || trimPct >= 50)
|
||||
{
|
||||
throw new ArgumentException("TrimPct must be in [0, 49]", nameof(trimPct));
|
||||
}
|
||||
|
||||
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] = ComputeTrimmedMeanSpan(sortedBuffer, count, trimPct);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (rentedSorted != null)
|
||||
{
|
||||
ArrayPool<double>.Shared.Return(rentedSorted);
|
||||
}
|
||||
|
||||
if (rentedWindow != null)
|
||||
{
|
||||
ArrayPool<double>.Shared.Return(rentedWindow);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static (TSeries Results, Trim Indicator) Calculate(TSeries source, int period, double trimPct = 10.0)
|
||||
{
|
||||
var indicator = new Trim(period, trimPct);
|
||||
TSeries results = indicator.Update(source);
|
||||
return (results, indicator);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static double ComputeTrimmedMean(double[] sorted, int count, double trimPct)
|
||||
{
|
||||
if (count == 0)
|
||||
{
|
||||
return double.NaN;
|
||||
}
|
||||
|
||||
int trimCount = (int)(count * trimPct / 100.0);
|
||||
int keepCount = count - 2 * trimCount;
|
||||
|
||||
if (keepCount < 1)
|
||||
{
|
||||
keepCount = 1;
|
||||
trimCount = (count - 1) / 2;
|
||||
}
|
||||
|
||||
double sum = 0.0;
|
||||
int end = trimCount + keepCount;
|
||||
for (int i = trimCount; i < end; i++)
|
||||
{
|
||||
sum += sorted[i];
|
||||
}
|
||||
|
||||
return sum / keepCount;
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static double ComputeTrimmedMeanSpan(Span<double> sorted, int count, double trimPct)
|
||||
{
|
||||
if (count == 0)
|
||||
{
|
||||
return double.NaN;
|
||||
}
|
||||
|
||||
int trimCount = (int)(count * trimPct / 100.0);
|
||||
int keepCount = count - 2 * trimCount;
|
||||
|
||||
if (keepCount < 1)
|
||||
{
|
||||
keepCount = 1;
|
||||
trimCount = (count - 1) / 2;
|
||||
}
|
||||
|
||||
double sum = 0.0;
|
||||
int end = trimCount + keepCount;
|
||||
for (int i = trimCount; i < end; i++)
|
||||
{
|
||||
sum += sorted[i];
|
||||
}
|
||||
|
||||
return sum / keepCount;
|
||||
}
|
||||
|
||||
[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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using TradingPlatform.BusinessLayer;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public class WavgIndicatorTests
|
||||
{
|
||||
[Fact]
|
||||
public void WavgIndicator_Constructor_SetsDefaults()
|
||||
{
|
||||
var indicator = new WavgIndicator();
|
||||
|
||||
Assert.Equal(14, indicator.Period);
|
||||
Assert.True(indicator.ShowColdValues);
|
||||
Assert.Equal("Wavg - Linearly Weighted Average", indicator.Name);
|
||||
Assert.False(indicator.SeparateWindow);
|
||||
Assert.True(indicator.OnBackGround);
|
||||
Assert.Equal(SourceType.Close, indicator.Source);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WavgIndicator_MinHistoryDepths_EqualsZero()
|
||||
{
|
||||
var indicator = new WavgIndicator { Period = 14 };
|
||||
|
||||
Assert.Equal(0, WavgIndicator.MinHistoryDepths);
|
||||
IWatchlistIndicator watchlistIndicator = indicator;
|
||||
Assert.Equal(0, watchlistIndicator.MinHistoryDepths);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WavgIndicator_Initialize_CreatesInternalWavg()
|
||||
{
|
||||
var indicator = new WavgIndicator { Period = 10 };
|
||||
|
||||
indicator.Initialize();
|
||||
|
||||
Assert.Single(indicator.LinesSeries);
|
||||
Assert.Equal("Wavg", indicator.LinesSeries[0].Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WavgIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
|
||||
{
|
||||
var indicator = new WavgIndicator { Period = 5 };
|
||||
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,60 @@
|
||||
using System.Drawing;
|
||||
using System.Runtime.CompilerServices;
|
||||
using TradingPlatform.BusinessLayer;
|
||||
|
||||
namespace QuanTAlib;
|
||||
|
||||
[SkipLocalsInit]
|
||||
public sealed class WavgIndicator : Indicator, IWatchlistIndicator
|
||||
{
|
||||
[InputParameter("Period", sortIndex: 1, 1, 2000, 1, 0)]
|
||||
public int Period { get; set; } = 14;
|
||||
|
||||
[IndicatorExtensions.DataSourceInput]
|
||||
public SourceType Source { get; set; } = SourceType.Close;
|
||||
|
||||
[InputParameter("Show cold values", sortIndex: 21)]
|
||||
public bool ShowColdValues { get; set; } = true;
|
||||
|
||||
private Wavg _wavg = null!;
|
||||
private readonly LineSeries _series;
|
||||
private Func<IHistoryItem, double> _priceSelector = null!;
|
||||
|
||||
public static int MinHistoryDepths => 0;
|
||||
int IWatchlistIndicator.MinHistoryDepths => MinHistoryDepths;
|
||||
|
||||
public override string ShortName => $"Wavg {Period}";
|
||||
public override string SourceCodeLink => "https://github.com/mihakralj/QuanTAlib/blob/main/lib/statistics/wavg/Wavg.Quantower.cs";
|
||||
|
||||
public WavgIndicator()
|
||||
{
|
||||
OnBackGround = true;
|
||||
SeparateWindow = false;
|
||||
Name = "Wavg - Linearly Weighted Average";
|
||||
Description = "Rolling linearly-weighted average (identical to WMA) categorized as statistics";
|
||||
|
||||
_series = new LineSeries(name: "Wavg", color: IndicatorExtensions.Statistics, width: 2, style: LineStyle.Solid);
|
||||
AddLineSeries(_series);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
protected override void OnInit()
|
||||
{
|
||||
_wavg = new Wavg(Period);
|
||||
_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 = _wavg.Update(input, args.IsNewBar());
|
||||
|
||||
_series.SetValue(result.Value, _wavg.IsHot, ShowColdValues);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public class WavgTests
|
||||
{
|
||||
// ── A) Constructor validation ────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Constructor_ThrowsOnZeroPeriod()
|
||||
{
|
||||
Assert.Throws<ArgumentException>(() => new Wavg(0));
|
||||
Assert.Throws<ArgumentException>(() => new Wavg(-1));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_SetsName()
|
||||
{
|
||||
var wavg = new Wavg(14);
|
||||
Assert.Equal("Wavg(14)", wavg.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_SetsWarmupPeriod()
|
||||
{
|
||||
var wavg = new Wavg(20);
|
||||
Assert.Equal(20, wavg.WarmupPeriod);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_ValidPeriod1()
|
||||
{
|
||||
var wavg = new Wavg(1);
|
||||
Assert.NotNull(wavg);
|
||||
}
|
||||
|
||||
// ── B) Basic calculation ─────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Update_ReturnsValue()
|
||||
{
|
||||
var wavg = new Wavg(5);
|
||||
TValue result = wavg.Update(new TValue(DateTime.UtcNow, 100));
|
||||
Assert.Equal(result.Value, wavg.Last.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsHot_FalseUntilWindowFull()
|
||||
{
|
||||
var wavg = new Wavg(5);
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
wavg.Update(new TValue(DateTime.UtcNow, i + 1.0));
|
||||
Assert.False(wavg.IsHot);
|
||||
}
|
||||
|
||||
wavg.Update(new TValue(DateTime.UtcNow, 5.0));
|
||||
Assert.True(wavg.IsHot);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SingleValue_ReturnsThatValue()
|
||||
{
|
||||
var wavg = new Wavg(5);
|
||||
TValue result = wavg.Update(new TValue(DateTime.UtcNow, 42.0));
|
||||
Assert.Equal(42.0, result.Value, 10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void KnownValue_CorrectWeightedAverage()
|
||||
{
|
||||
// period=4, values=[1,2,3,4] (oldest→newest)
|
||||
// weights = [1,2,3,4], denom = 4*5/2 = 10
|
||||
// WAVG = (1*1 + 2*2 + 3*3 + 4*4) / 10 = (1+4+9+16)/10 = 30/10 = 3.0
|
||||
var wavg = new Wavg(4);
|
||||
wavg.Update(new TValue(DateTime.UtcNow, 1.0));
|
||||
wavg.Update(new TValue(DateTime.UtcNow, 2.0));
|
||||
wavg.Update(new TValue(DateTime.UtcNow, 3.0));
|
||||
TValue result = wavg.Update(new TValue(DateTime.UtcNow, 4.0));
|
||||
|
||||
Assert.Equal(3.0, result.Value, 10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AllSameValues_ReturnsValue()
|
||||
{
|
||||
// All weights × same value / sum_weights = value
|
||||
var wavg = new Wavg(10);
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
wavg.Update(new TValue(DateTime.UtcNow, 5.0));
|
||||
}
|
||||
|
||||
Assert.Equal(5.0, wavg.Last.Value, 10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SlidingWindow_DropsOldest()
|
||||
{
|
||||
// Fill with [1,2,3,4,5], then slide in 6
|
||||
// After sliding: window=[2,3,4,5,6]
|
||||
// WAVG = (1*2 + 2*3 + 3*4 + 4*5 + 5*6)/15 = (2+6+12+20+30)/15 = 70/15
|
||||
var wavg = new Wavg(5);
|
||||
for (int i = 1; i <= 5; i++)
|
||||
{
|
||||
wavg.Update(new TValue(DateTime.UtcNow, i));
|
||||
}
|
||||
|
||||
TValue result = wavg.Update(new TValue(DateTime.UtcNow, 6.0));
|
||||
Assert.Equal(70.0 / 15.0, result.Value, 10);
|
||||
}
|
||||
|
||||
// ── C) State + bar correction ────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void BarCorrection_IsNewFalse_RewritesLastBar()
|
||||
{
|
||||
var wavg = new Wavg(4);
|
||||
var t = DateTime.UtcNow;
|
||||
|
||||
wavg.Update(new TValue(t, 1.0));
|
||||
wavg.Update(new TValue(t, 2.0));
|
||||
wavg.Update(new TValue(t, 3.0));
|
||||
wavg.Update(new TValue(t, 4.0));
|
||||
|
||||
double before = wavg.Last.Value; // WAVG([1,2,3,4]) = (1+4+9+16)/10 = 3.0
|
||||
|
||||
// Correct last bar to different value
|
||||
wavg.Update(new TValue(t, 10.0), isNew: false);
|
||||
double corrected = wavg.Last.Value;
|
||||
Assert.NotEqual(before, corrected); // correction changes result ✓
|
||||
|
||||
// Next new bar with value=4: window slides from corrected state [1,2,3,10] to [2,3,10,4]
|
||||
// WAVG([2,3,10,4]) = (1*2+2*3+3*10+4*4)/10 = (2+6+30+16)/10 = 54/10 = 5.4
|
||||
wavg.Update(new TValue(t, 4.0), isNew: true);
|
||||
Assert.True(double.IsFinite(wavg.Last.Value)); // finite result
|
||||
Assert.NotEqual(corrected, wavg.Last.Value); // new bar shifts the result
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reset_ClearsState()
|
||||
{
|
||||
var wavg = new Wavg(5);
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
wavg.Update(new TValue(DateTime.UtcNow, 100.0));
|
||||
}
|
||||
|
||||
Assert.True(wavg.IsHot);
|
||||
wavg.Reset();
|
||||
Assert.False(wavg.IsHot);
|
||||
Assert.Equal(0, wavg.Last.Value);
|
||||
}
|
||||
|
||||
// ── D) Warmup/convergence ────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void IsHot_FlipsAtPeriod()
|
||||
{
|
||||
int period = 8;
|
||||
var wavg = new Wavg(period);
|
||||
for (int i = 0; i < period - 1; i++)
|
||||
{
|
||||
wavg.Update(new TValue(DateTime.UtcNow, i));
|
||||
Assert.False(wavg.IsHot);
|
||||
}
|
||||
|
||||
wavg.Update(new TValue(DateTime.UtcNow, period));
|
||||
Assert.True(wavg.IsHot);
|
||||
}
|
||||
|
||||
// ── E) Robustness ───────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void NaN_UsesLastValidValue()
|
||||
{
|
||||
var wavg = new Wavg(5);
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
wavg.Update(new TValue(DateTime.UtcNow, 10.0));
|
||||
}
|
||||
|
||||
wavg.Update(new TValue(DateTime.UtcNow, double.NaN));
|
||||
Assert.True(double.IsFinite(wavg.Last.Value));
|
||||
|
||||
wavg.Update(new TValue(DateTime.UtcNow, double.PositiveInfinity));
|
||||
Assert.True(double.IsFinite(wavg.Last.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AllNaN_DoesNotThrow()
|
||||
{
|
||||
var wavg = new Wavg(5);
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
TValue result = wavg.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: 99);
|
||||
int n = 100;
|
||||
int period = 14;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
// Streaming
|
||||
var streamWavg = new Wavg(period);
|
||||
double lastStream = 0;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
lastStream = streamWavg.Update(new TValue(new DateTime(times[i], DateTimeKind.Utc), prices[i])).Value;
|
||||
}
|
||||
|
||||
// Span batch
|
||||
var spanOutput = new double[n];
|
||||
Wavg.Batch(prices, spanOutput, period);
|
||||
|
||||
Assert.Equal(lastStream, spanOutput[n - 1], 6);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Consistency_SpanValidatesLengths()
|
||||
{
|
||||
var src = new double[10];
|
||||
var dst = new double[9];
|
||||
Assert.Throws<ArgumentException>(() => Wavg.Batch(src, dst, 5));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Consistency_SpanValidatesPeriod()
|
||||
{
|
||||
var src = new double[10];
|
||||
var dst = new double[10];
|
||||
Assert.Throws<ArgumentException>(() => Wavg.Batch(src, dst, 0));
|
||||
}
|
||||
|
||||
// ── G) Eventing ──────────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Pub_FiresOnUpdate()
|
||||
{
|
||||
var wavg = new Wavg(5);
|
||||
int fireCount = 0;
|
||||
wavg.Pub += (object? _, in TValueEventArgs _) => fireCount++;
|
||||
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
wavg.Update(new TValue(DateTime.UtcNow, i));
|
||||
}
|
||||
|
||||
Assert.Equal(10, fireCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Chaining_EventBased_Works()
|
||||
{
|
||||
var wavg1 = new Wavg(5);
|
||||
var wavg2 = new Wavg(wavg1, 3);
|
||||
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
wavg1.Update(new TValue(DateTime.UtcNow, i + 1.0));
|
||||
}
|
||||
|
||||
Assert.True(double.IsFinite(wavg2.Last.Value));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Wavg self-consistency validation.
|
||||
/// Validates against manual WMA computation and cross-mode consistency.
|
||||
/// </summary>
|
||||
public class WavgValidationTests
|
||||
{
|
||||
[Fact]
|
||||
public void Wavg_Streaming_Equals_SpanBatch()
|
||||
{
|
||||
var rng = new GBM(startPrice: 100, mu: 0.0001, sigma: 0.015, seed: 5005);
|
||||
int n = 200;
|
||||
int period = 14;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
// Streaming
|
||||
var streaming = new Wavg(period);
|
||||
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;
|
||||
}
|
||||
|
||||
// Span batch
|
||||
var spanValues = new double[n];
|
||||
Wavg.Batch(prices, spanValues, period);
|
||||
|
||||
for (int i = period - 1; i < n; i++)
|
||||
{
|
||||
Assert.Equal(streamValues[i], spanValues[i], 6);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Wavg_ManualWMA_Matches_KnownPeriod()
|
||||
{
|
||||
// Verify against hand-computed WMA
|
||||
// Values [10, 20, 30], period=3
|
||||
// weights [1,2,3], denom=6
|
||||
// WMA = (1*10 + 2*20 + 3*30)/6 = (10+40+90)/6 = 140/6 ≈ 23.333
|
||||
var wavg = new Wavg(3);
|
||||
wavg.Update(new TValue(DateTime.UtcNow, 10.0));
|
||||
wavg.Update(new TValue(DateTime.UtcNow, 20.0));
|
||||
TValue result = wavg.Update(new TValue(DateTime.UtcNow, 30.0));
|
||||
|
||||
Assert.Equal(140.0 / 6.0, result.Value, 10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Wavg_BatchTSeries_EqualsStreaming()
|
||||
{
|
||||
var rng = new GBM(startPrice: 100, mu: 0.0001, sigma: 0.015, seed: 6006);
|
||||
int n = 50;
|
||||
int period = 10;
|
||||
|
||||
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 = Wavg.Batch(series, period);
|
||||
|
||||
var streaming = new Wavg(period);
|
||||
TValue lastStream = default;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
lastStream = streaming.Update(series[i]);
|
||||
}
|
||||
|
||||
Assert.Equal(lastStream.Value, batchResult[n - 1].Value, 6);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Wavg_Period1_EqualsInput()
|
||||
{
|
||||
// With period=1, weight=1, denom=1 → result = input
|
||||
var wavg = new Wavg(1);
|
||||
var rng = new GBM(startPrice: 100, mu: 0.0001, sigma: 0.015, seed: 7007);
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
double price = rng.Next().Close;
|
||||
TValue result = wavg.Update(new TValue(DateTime.UtcNow, price));
|
||||
Assert.Equal(price, result.Value, 10);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Wavg_RecentValueHasHigherWeight()
|
||||
{
|
||||
// WAVG should be closer to recent values than SMA
|
||||
// Ascending series: WAVG > SMA
|
||||
var wavg = new Wavg(5);
|
||||
// Fill with ascending values
|
||||
for (int i = 1; i <= 5; i++)
|
||||
{
|
||||
wavg.Update(new TValue(DateTime.UtcNow, i * 10.0));
|
||||
}
|
||||
|
||||
// SMA = (10+20+30+40+50)/5 = 30
|
||||
// WAVG = (1*10+2*20+3*30+4*40+5*50)/(1+2+3+4+5) = (10+40+90+160+250)/15 = 550/15 ≈ 36.67
|
||||
Assert.True(wavg.Last.Value > 30.0); // WAVG > SMA for ascending
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace QuanTAlib;
|
||||
|
||||
/// <summary>
|
||||
/// Wavg: Rolling Linearly-Weighted Average
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Assigns linearly increasing weights to the lookback window:
|
||||
/// weight_i = i + 1 for i = 0 (oldest) to count-1 (newest)
|
||||
/// WAVG = Σ(weight_i × value_i) / Σ(weight_i)
|
||||
/// Σ(weight_i) = count × (count + 1) / 2
|
||||
///
|
||||
/// O(1) incremental update uses two recurrences:
|
||||
///
|
||||
/// WARMUP (count growing 1 → period):
|
||||
/// W_new = W_old + count_new × v_new (no subtraction; existing positions unchanged)
|
||||
/// S_new = S_old + v_new
|
||||
///
|
||||
/// STEADY STATE (window full, oldest departs):
|
||||
/// W_new = W_old - S_old + period × v_new (shift all weights down, evict oldest, add new)
|
||||
/// S_new = S_old - oldest + v_new
|
||||
///
|
||||
/// Mathematically identical to WMA.
|
||||
/// </remarks>
|
||||
[SkipLocalsInit]
|
||||
public sealed class Wavg : AbstractBase
|
||||
{
|
||||
private readonly int _period;
|
||||
private readonly RingBuffer _buffer;
|
||||
private readonly TValuePublishedHandler _handler;
|
||||
private readonly ITValuePublisher? _source;
|
||||
|
||||
// O(1) running state
|
||||
private double _weightedSum;
|
||||
private double _runningSum;
|
||||
private int _count;
|
||||
private double _lastValidValue;
|
||||
|
||||
// Previous-state snapshot for isNew=false rollback
|
||||
private double _p_weightedSum;
|
||||
private double _p_runningSum;
|
||||
private int _p_count;
|
||||
|
||||
private bool _disposed;
|
||||
|
||||
public override bool IsHot => _buffer.IsFull;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a Wavg indicator with the specified period.
|
||||
/// </summary>
|
||||
/// <param name="period">The size of the rolling window (must be > 0).</param>
|
||||
public Wavg(int period)
|
||||
{
|
||||
if (period <= 0)
|
||||
{
|
||||
throw new ArgumentException("Period must be greater than 0", nameof(period));
|
||||
}
|
||||
|
||||
_period = period;
|
||||
_buffer = new RingBuffer(period);
|
||||
Name = $"Wavg({period})";
|
||||
WarmupPeriod = period;
|
||||
_handler = Handle;
|
||||
}
|
||||
|
||||
/// <summary>Creates a chained Wavg indicator.</summary>
|
||||
public Wavg(ITValuePublisher source, int period) : this(period)
|
||||
{
|
||||
_source = source;
|
||||
source.Pub += _handler;
|
||||
}
|
||||
|
||||
/// <summary>Creates a Wavg indicator primed from a TSeries source.</summary>
|
||||
public Wavg(TSeries source, int period) : this(period)
|
||||
{
|
||||
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)
|
||||
{
|
||||
// Save state for potential rollback
|
||||
_p_weightedSum = _weightedSum;
|
||||
_p_runningSum = _runningSum;
|
||||
_p_count = _count;
|
||||
|
||||
if (_buffer.IsFull)
|
||||
{
|
||||
// STEADY STATE: oldest departs
|
||||
// Shift all weights down by 1 (each existing element's weight decreases by 1,
|
||||
// so δW = -S_old). Then evict oldest from S. Then add new at weight = period.
|
||||
_weightedSum -= _runningSum; // shift: δW = -S_old (oldest contribution zeroes out)
|
||||
_runningSum -= _buffer.Oldest; // evict oldest from unweighted sum
|
||||
_runningSum += value;
|
||||
_weightedSum += _count * value; // add new at weight = period (= _count, fixed when full)
|
||||
}
|
||||
else
|
||||
{
|
||||
// WARMUP: no eviction, existing positions unchanged, new element appended at weight = count+1
|
||||
_count++;
|
||||
_runningSum += value;
|
||||
_weightedSum += _count * value;
|
||||
}
|
||||
|
||||
_buffer.Add(value);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Bar correction: restore previous state, then replace newest in buffer and recompute
|
||||
// O(period) recompute — only triggered on bar corrections, not the hot path
|
||||
_weightedSum = _p_weightedSum;
|
||||
_runningSum = _p_runningSum;
|
||||
_count = _p_count;
|
||||
|
||||
// Undo the last Add of the old newest value (before the prior isNew=true step)
|
||||
double oldNewest = _buffer.Newest;
|
||||
|
||||
if (_count == _period)
|
||||
{
|
||||
// The prior step was steady-state: undo it, then redo with new value
|
||||
// Undo: W = W_p, S = S_p (already restored from _p_)
|
||||
// Redo steady-state with different new value:
|
||||
_weightedSum -= _runningSum;
|
||||
_runningSum -= _buffer.Oldest;
|
||||
_runningSum += value;
|
||||
_weightedSum += _count * value;
|
||||
}
|
||||
else
|
||||
{
|
||||
// The prior step was warmup: undo newest contribution, sub in corrected value
|
||||
// _count was already incremented in the prior isNew=true step, so _p_count = _count-1
|
||||
// After restoring _count = _p_count, reapply the warmup step with new value
|
||||
_count++;
|
||||
_runningSum -= oldNewest;
|
||||
_runningSum += value;
|
||||
_weightedSum -= _count * oldNewest;
|
||||
_weightedSum += _count * value;
|
||||
}
|
||||
|
||||
// Note: buffer is NOT rolled back on isNew=false — UpdateNewest replaces in-place
|
||||
_buffer.UpdateNewest(value);
|
||||
}
|
||||
|
||||
double denom = _count * (_count + 1.0) / 2.0;
|
||||
double result = denom > 0.0 ? _weightedSum / denom : value;
|
||||
|
||||
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);
|
||||
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();
|
||||
_weightedSum = 0;
|
||||
_runningSum = 0;
|
||||
_count = 0;
|
||||
_p_weightedSum = 0;
|
||||
_p_runningSum = 0;
|
||||
_p_count = 0;
|
||||
Last = default;
|
||||
}
|
||||
|
||||
public override void Prime(ReadOnlySpan<double> source, TimeSpan? step = null)
|
||||
{
|
||||
if (source.Length == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_buffer.Clear();
|
||||
_weightedSum = 0;
|
||||
_runningSum = 0;
|
||||
_count = 0;
|
||||
|
||||
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 Wavg for the entire series using a new instance.</summary>
|
||||
public static TSeries Batch(TSeries source, int period)
|
||||
{
|
||||
var wavg = new Wavg(period);
|
||||
return wavg.Update(source);
|
||||
}
|
||||
|
||||
/// <summary>Calculates Wavg in-place using spans. O(n) total, O(1) per bar.</summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void Batch(ReadOnlySpan<double> source, Span<double> output, int period)
|
||||
{
|
||||
if (source.Length != output.Length)
|
||||
{
|
||||
throw new ArgumentException("Source and output must have the same length", nameof(output));
|
||||
}
|
||||
|
||||
if (period <= 0)
|
||||
{
|
||||
throw new ArgumentException("Period must be greater than 0", nameof(period));
|
||||
}
|
||||
|
||||
int len = source.Length;
|
||||
if (len == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Circular buffer for oldest-value eviction
|
||||
double[] buf = new double[period];
|
||||
int head = 0;
|
||||
double weightedSum = 0.0;
|
||||
double runningSum = 0.0;
|
||||
int count = 0;
|
||||
|
||||
for (int i = 0; i < len; i++)
|
||||
{
|
||||
double v = source[i];
|
||||
|
||||
if (count < period)
|
||||
{
|
||||
// WARMUP: append, existing weights unchanged
|
||||
count++;
|
||||
runningSum += v;
|
||||
weightedSum += count * v;
|
||||
}
|
||||
else
|
||||
{
|
||||
// STEADY STATE: shift all weights down, evict oldest, add new at weight=period
|
||||
double oldest = buf[head];
|
||||
weightedSum -= runningSum; // shift: each existing weight -1
|
||||
runningSum -= oldest; // evict oldest
|
||||
runningSum += v;
|
||||
weightedSum += count * v; // add new at weight=period (=count, fixed)
|
||||
}
|
||||
|
||||
buf[head] = v;
|
||||
head = (head + 1) % period;
|
||||
|
||||
double denom = count * (count + 1.0) / 2.0;
|
||||
output[i] = denom > 0.0 ? weightedSum / denom : v;
|
||||
}
|
||||
}
|
||||
|
||||
public static (TSeries Results, Wavg Indicator) Calculate(TSeries source, int period)
|
||||
{
|
||||
var indicator = new Wavg(period);
|
||||
TSeries results = indicator.Update(source);
|
||||
return (results, indicator);
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (!_disposed)
|
||||
{
|
||||
if (disposing && _source != null)
|
||||
{
|
||||
_source.Pub -= _handler;
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
}
|
||||
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
}
|
||||
@@ -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