mirror of
https://github.com/mihakralj/QuanTAlib.git
synced 2026-08-22 12:38:06 +00:00
adding missing validations
This commit is contained in:
@@ -0,0 +1,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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user