mirror of
https://github.com/mihakralj/QuanTAlib.git
synced 2026-08-25 13:58:04 +00:00
Add TRAMA implementation and comprehensive tests
- Implemented the TRAMA (Trend Regularity Adaptive Moving Average) class with adaptive EMA logic. - Added unit tests for TRAMA functionality, including constructor validation, basic calculations, state management, and robustness checks. - Created validation tests to ensure consistency across different modes of operation (streaming, batch, and static calculations). - Enhanced documentation for TRAMA, including performance profiles and quality metrics. - Updated workspace configuration by removing unnecessary folder references.
This commit is contained in:
@@ -0,0 +1,171 @@
|
||||
using TradingPlatform.BusinessLayer;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public class TukeyWIndicatorTests
|
||||
{
|
||||
[Fact]
|
||||
public void TukeyWIndicator_Constructor_SetsDefaults()
|
||||
{
|
||||
var indicator = new TukeyWIndicator();
|
||||
|
||||
Assert.Equal(20, indicator.Period);
|
||||
Assert.Equal(0.5, indicator.Alpha);
|
||||
Assert.Equal(SourceType.Close, indicator.Source);
|
||||
Assert.True(indicator.ShowColdValues);
|
||||
Assert.Equal("TUKEY_W - Tukey (Tapered Cosine) Window Moving Average", indicator.Name);
|
||||
Assert.False(indicator.SeparateWindow);
|
||||
Assert.True(indicator.OnBackGround);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TukeyWIndicator_MinHistoryDepths_IsZero()
|
||||
{
|
||||
var indicator = new TukeyWIndicator { Period = 20 };
|
||||
|
||||
Assert.Equal(0, TukeyWIndicator.MinHistoryDepths);
|
||||
Assert.Equal(0, ((IWatchlistIndicator)indicator).MinHistoryDepths);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TukeyWIndicator_ShortName_IncludesPeriodAndSource()
|
||||
{
|
||||
var indicator = new TukeyWIndicator { Period = 10, Alpha = 0.75 };
|
||||
|
||||
Assert.Contains("TUKEY_W", indicator.ShortName, StringComparison.Ordinal);
|
||||
Assert.Contains("10", indicator.ShortName, StringComparison.Ordinal);
|
||||
Assert.Contains("0.75", indicator.ShortName, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TukeyWIndicator_SourceCodeLink_IsValid()
|
||||
{
|
||||
var indicator = new TukeyWIndicator();
|
||||
|
||||
Assert.Contains("github.com", indicator.SourceCodeLink, StringComparison.Ordinal);
|
||||
Assert.Contains("Tukey_w.Quantower.cs", indicator.SourceCodeLink, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TukeyWIndicator_Initialize_CreatesInternalTukeyW()
|
||||
{
|
||||
var indicator = new TukeyWIndicator { Period = 20 };
|
||||
|
||||
indicator.Initialize();
|
||||
|
||||
Assert.Single(indicator.LinesSeries);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TukeyWIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
|
||||
{
|
||||
var indicator = new TukeyWIndicator { Period = 5 };
|
||||
indicator.Initialize();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
indicator.HistoricalData.AddBar(now, 100, 105, 95, 102);
|
||||
|
||||
var args = new UpdateArgs(UpdateReason.HistoricalBar);
|
||||
indicator.ProcessUpdate(args);
|
||||
|
||||
Assert.Equal(1, indicator.LinesSeries[0].Count);
|
||||
Assert.True(double.IsFinite(indicator.LinesSeries[0].GetValue(0)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TukeyWIndicator_ProcessUpdate_NewBar_ComputesValue()
|
||||
{
|
||||
var indicator = new TukeyWIndicator { Period = 5 };
|
||||
indicator.Initialize();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
indicator.HistoricalData.AddBar(now, 100, 105, 95, 102);
|
||||
indicator.HistoricalData.AddBar(now.AddMinutes(1), 102, 108, 100, 106);
|
||||
|
||||
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
|
||||
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.NewBar));
|
||||
|
||||
Assert.Equal(2, indicator.LinesSeries[0].Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TukeyWIndicator_ProcessUpdate_NewTick_ProcessesWithoutError()
|
||||
{
|
||||
var indicator = new TukeyWIndicator { Period = 5 };
|
||||
indicator.Initialize();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
indicator.HistoricalData.AddBar(now, 100, 105, 95, 102);
|
||||
|
||||
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
|
||||
double firstValue = indicator.LinesSeries[0].GetValue(0);
|
||||
|
||||
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.NewTick));
|
||||
double secondValue = indicator.LinesSeries[0].GetValue(0);
|
||||
|
||||
Assert.True(double.IsFinite(firstValue));
|
||||
Assert.True(double.IsFinite(secondValue));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TukeyWIndicator_MultipleUpdates_ProducesCorrectSequence()
|
||||
{
|
||||
var indicator = new TukeyWIndicator { Period = 5 };
|
||||
indicator.Initialize();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
double[] closes = { 100, 102, 104, 103, 105, 107, 106 };
|
||||
|
||||
foreach (var close in closes)
|
||||
{
|
||||
indicator.HistoricalData.AddBar(now, close, close + 2, close - 2, close);
|
||||
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
|
||||
now = now.AddMinutes(1);
|
||||
}
|
||||
|
||||
for (int i = 0; i < closes.Length; i++)
|
||||
{
|
||||
Assert.True(double.IsFinite(indicator.LinesSeries[0].GetValue(closes.Length - 1 - i)));
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TukeyWIndicator_DifferentSourceTypes_Work()
|
||||
{
|
||||
var sources = new[] { SourceType.Open, SourceType.High, SourceType.Low, SourceType.Close, SourceType.HL2, SourceType.HLC3 };
|
||||
|
||||
foreach (var source in sources)
|
||||
{
|
||||
var indicator = new TukeyWIndicator { Period = 5, Source = source };
|
||||
indicator.Initialize();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
indicator.HistoricalData.AddBar(now, 100, 110, 90, 105);
|
||||
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
|
||||
|
||||
Assert.True(double.IsFinite(indicator.LinesSeries[0].GetValue(0)),
|
||||
$"Source {source} should produce finite value");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TukeyWIndicator_Period_CanBeChanged()
|
||||
{
|
||||
var indicator = new TukeyWIndicator { Period = 20 };
|
||||
Assert.Equal(20, indicator.Period);
|
||||
|
||||
indicator.Period = 30;
|
||||
Assert.Equal(30, indicator.Period);
|
||||
Assert.Equal(0, TukeyWIndicator.MinHistoryDepths);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TukeyWIndicator_Alpha_CanBeChanged()
|
||||
{
|
||||
var indicator = new TukeyWIndicator { Alpha = 0.5 };
|
||||
Assert.Equal(0.5, indicator.Alpha);
|
||||
|
||||
indicator.Alpha = 0.75;
|
||||
Assert.Equal(0.75, indicator.Alpha);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
using System.Drawing;
|
||||
using System.Runtime.CompilerServices;
|
||||
using TradingPlatform.BusinessLayer;
|
||||
|
||||
namespace QuanTAlib;
|
||||
|
||||
[SkipLocalsInit]
|
||||
public sealed class TukeyWIndicator : Indicator, IWatchlistIndicator
|
||||
{
|
||||
[InputParameter("Period", sortIndex: 1, 2, 2000, 1, 0)]
|
||||
public int Period { get; set; } = 20;
|
||||
|
||||
[InputParameter("Alpha", sortIndex: 2, minimum: 0.0, maximum: 1.0, increment: 0.05, decimalPlaces: 2)]
|
||||
public double Alpha { get; set; } = 0.5;
|
||||
|
||||
[IndicatorExtensions.DataSourceInput]
|
||||
public SourceType Source { get; set; } = SourceType.Close;
|
||||
|
||||
[InputParameter("Show cold values", sortIndex: 21)]
|
||||
public bool ShowColdValues { get; set; } = true;
|
||||
|
||||
private Tukey_w _tukey = null!;
|
||||
private readonly LineSeries _series;
|
||||
private string _sourceName = null!;
|
||||
private Func<IHistoryItem, double> _priceSelector = null!;
|
||||
|
||||
public static int MinHistoryDepths => 0;
|
||||
int IWatchlistIndicator.MinHistoryDepths => MinHistoryDepths;
|
||||
|
||||
public override string ShortName => $"TUKEY_W {Period},{Alpha:F2}:{_sourceName}";
|
||||
public override string SourceCodeLink => "https://github.com/mihakralj/QuanTAlib/blob/main/lib/trends_FIR/tukey_w/Tukey_w.Quantower.cs";
|
||||
|
||||
public TukeyWIndicator()
|
||||
{
|
||||
OnBackGround = true;
|
||||
SeparateWindow = false;
|
||||
Name = "TUKEY_W - Tukey (Tapered Cosine) Window Moving Average";
|
||||
Description = "Tukey (Tapered Cosine) Window Moving Average";
|
||||
_series = new LineSeries(name: $"TUKEY_W {Period}", color: IndicatorExtensions.Averages, width: 2, style: LineStyle.Solid);
|
||||
AddLineSeries(_series);
|
||||
}
|
||||
|
||||
protected override void OnInit()
|
||||
{
|
||||
_priceSelector = Source.GetPriceSelector();
|
||||
_sourceName = Source.ToString();
|
||||
_tukey = new Tukey_w(Period, Alpha);
|
||||
base.OnInit();
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
protected override void OnUpdate(UpdateArgs args)
|
||||
{
|
||||
bool isNew = args.IsNewBar();
|
||||
var item = HistoricalData[Count - 1, SeekOriginHistory.Begin];
|
||||
double value = _tukey.Update(new TValue(item.TimeLeft.Ticks, _priceSelector(item)), isNew).Value;
|
||||
_series.SetValue(value, _tukey.IsHot, ShowColdValues);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,464 @@
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public class Tukey_wTests
|
||||
{
|
||||
private static TSeries MakeSeries(int count = 500)
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100, seed: 42);
|
||||
var series = new TSeries();
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
series.Add(gbm.Next());
|
||||
}
|
||||
return series;
|
||||
}
|
||||
|
||||
// === A) Constructor validation ===
|
||||
|
||||
[Fact]
|
||||
public void Constructor_DefaultPeriod_Is20()
|
||||
{
|
||||
var tw = new Tukey_w();
|
||||
Assert.Equal("Tukey_w(20,0.50)", tw.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_CustomPeriodAndAlpha()
|
||||
{
|
||||
var tw = new Tukey_w(period: 10, alpha: 0.3);
|
||||
Assert.Equal("Tukey_w(10,0.30)", tw.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_Period2_IsValid()
|
||||
{
|
||||
var tw = new Tukey_w(period: 2);
|
||||
Assert.Equal("Tukey_w(2,0.50)", tw.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_PeriodBelow2_Throws()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Tukey_w(period: 1));
|
||||
Assert.Equal("period", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_NegativePeriod_Throws()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Tukey_w(period: -5));
|
||||
Assert.Equal("period", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_AlphaBelowZero_Throws()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Tukey_w(period: 10, alpha: -0.1));
|
||||
Assert.Equal("alpha", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_AlphaAboveOne_Throws()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Tukey_w(period: 10, alpha: 1.1));
|
||||
Assert.Equal("alpha", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_AlphaZero_IsValid()
|
||||
{
|
||||
var tw = new Tukey_w(period: 5, alpha: 0.0);
|
||||
Assert.Contains("0.00", tw.Name, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_AlphaOne_IsValid()
|
||||
{
|
||||
var tw = new Tukey_w(period: 5, alpha: 1.0);
|
||||
Assert.Contains("1.00", tw.Name, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_SetsWarmupPeriod()
|
||||
{
|
||||
var tw = new Tukey_w(period: 8);
|
||||
Assert.Equal(8, tw.WarmupPeriod);
|
||||
}
|
||||
|
||||
// === B) Basic calculation ===
|
||||
|
||||
[Fact]
|
||||
public void Update_ReturnsTValue()
|
||||
{
|
||||
var tw = new Tukey_w(period: 4);
|
||||
var result = tw.Update(new TValue(DateTime.UtcNow, 100.0));
|
||||
Assert.True(double.IsFinite(result.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Update_ConstantInput_ReturnsConstant()
|
||||
{
|
||||
var tw = new Tukey_w(period: 5, alpha: 0.5);
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
tw.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 42.0));
|
||||
}
|
||||
Assert.Equal(42.0, tw.Last.Value, 1e-10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Update_Alpha0_EquivalentToSMA()
|
||||
{
|
||||
// alpha=0 → rectangular window → SMA
|
||||
int period = 5;
|
||||
var tw = new Tukey_w(period: period, alpha: 0.0);
|
||||
double[] vals = { 10, 20, 30, 40, 50 };
|
||||
for (int i = 0; i < vals.Length; i++)
|
||||
{
|
||||
tw.Update(new TValue(DateTime.UtcNow.AddSeconds(i), vals[i]));
|
||||
}
|
||||
// SMA(5) = (10+20+30+40+50)/5 = 30
|
||||
Assert.Equal(30.0, tw.Last.Value, 1e-10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Update_Alpha0_LargerSeries_MatchesSMA()
|
||||
{
|
||||
var src = MakeSeries(100);
|
||||
int period = 10;
|
||||
|
||||
var tw = Tukey_w.Batch(src, period, alpha: 0.0);
|
||||
var sma = Sma.Batch(src, period);
|
||||
|
||||
// After warmup, should match SMA exactly
|
||||
for (int i = period - 1; i < src.Count; i++)
|
||||
{
|
||||
Assert.Equal(sma[i].Value, tw[i].Value, 1e-10);
|
||||
}
|
||||
}
|
||||
|
||||
// === C) State + bar correction ===
|
||||
|
||||
[Fact]
|
||||
public void Update_IsNew_True_AdvancesState()
|
||||
{
|
||||
var tw = new Tukey_w(period: 4);
|
||||
tw.Update(new TValue(DateTime.UtcNow, 100.0), isNew: true);
|
||||
tw.Update(new TValue(DateTime.UtcNow.AddSeconds(1), 110.0), isNew: true);
|
||||
var r1 = tw.Last;
|
||||
tw.Update(new TValue(DateTime.UtcNow.AddSeconds(2), 120.0), isNew: true);
|
||||
Assert.NotEqual(r1.Value, tw.Last.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Update_IsNew_False_Rewrites()
|
||||
{
|
||||
var tw = new Tukey_w(period: 4, alpha: 0.5);
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
tw.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0 + i), isNew: true);
|
||||
}
|
||||
var afterNew = tw.Last;
|
||||
|
||||
tw.Update(new TValue(DateTime.UtcNow.AddSeconds(4), 104.0), isNew: false);
|
||||
Assert.Equal(afterNew.Value, tw.Last.Value, 1e-10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reset_ClearsState()
|
||||
{
|
||||
var tw = new Tukey_w(period: 4);
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
tw.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0 + i));
|
||||
}
|
||||
Assert.True(tw.IsHot);
|
||||
|
||||
tw.Reset();
|
||||
Assert.False(tw.IsHot);
|
||||
Assert.Equal(default, tw.Last);
|
||||
}
|
||||
|
||||
// === D) Warmup/convergence ===
|
||||
|
||||
[Fact]
|
||||
public void IsHot_FlipsAtPeriod()
|
||||
{
|
||||
var tw = new Tukey_w(period: 5);
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
tw.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0 + i));
|
||||
Assert.False(tw.IsHot);
|
||||
}
|
||||
tw.Update(new TValue(DateTime.UtcNow.AddSeconds(4), 104.0));
|
||||
Assert.True(tw.IsHot);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DuringWarmup_ReturnsRawValue()
|
||||
{
|
||||
var tw = new Tukey_w(period: 5);
|
||||
var result = tw.Update(new TValue(DateTime.UtcNow, 42.0));
|
||||
Assert.Equal(42.0, result.Value, 1e-10);
|
||||
}
|
||||
|
||||
// === E) Robustness ===
|
||||
|
||||
[Fact]
|
||||
public void Update_NaN_UsesLastValid()
|
||||
{
|
||||
var tw = new Tukey_w(period: 4);
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
tw.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0));
|
||||
}
|
||||
|
||||
tw.Update(new TValue(DateTime.UtcNow.AddSeconds(5), double.NaN));
|
||||
Assert.True(double.IsFinite(tw.Last.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Update_Infinity_UsesLastValid()
|
||||
{
|
||||
var tw = new Tukey_w(period: 4);
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
tw.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0));
|
||||
}
|
||||
|
||||
tw.Update(new TValue(DateTime.UtcNow.AddSeconds(5), double.PositiveInfinity));
|
||||
Assert.True(double.IsFinite(tw.Last.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Update_FirstValueNaN_ReturnsNaN()
|
||||
{
|
||||
var tw = new Tukey_w(period: 4);
|
||||
var result = tw.Update(new TValue(DateTime.UtcNow, double.NaN));
|
||||
Assert.True(double.IsNaN(result.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Batch_BatchNaN_Safe()
|
||||
{
|
||||
double[] source = { 10, 20, double.NaN, 40, 50, 60 };
|
||||
double[] output = new double[source.Length];
|
||||
Tukey_w.Batch(source, output, period: 3, alpha: 0.5);
|
||||
|
||||
for (int i = 0; i < output.Length; i++)
|
||||
{
|
||||
Assert.True(double.IsFinite(output[i]), $"output[{i}] should be finite");
|
||||
}
|
||||
}
|
||||
|
||||
// === F) Consistency (4 modes match) ===
|
||||
|
||||
[Fact]
|
||||
public void AllModes_ProduceSameResults()
|
||||
{
|
||||
var src = MakeSeries(100);
|
||||
int period = 6;
|
||||
double alpha = 0.4;
|
||||
|
||||
// Mode 1: Streaming
|
||||
var streaming = new Tukey_w(period, alpha);
|
||||
var streamResults = new List<double>();
|
||||
for (int i = 0; i < src.Count; i++)
|
||||
{
|
||||
streamResults.Add(streaming.Update(src[i]).Value);
|
||||
}
|
||||
|
||||
// Mode 2: Batch TSeries
|
||||
var batchResults = Tukey_w.Batch(src, period, alpha);
|
||||
|
||||
// Mode 3: Span API
|
||||
var spanOutput = new double[src.Count];
|
||||
Tukey_w.Batch(src.Values, spanOutput, period, alpha);
|
||||
|
||||
// Mode 4: Event-based
|
||||
var publisher = new TSeries();
|
||||
var eventResults = new List<double>();
|
||||
var eventTw = new Tukey_w(publisher, period, alpha);
|
||||
eventTw.Pub += (object? sender, in TValueEventArgs e) => eventResults.Add(e.Value.Value);
|
||||
for (int i = 0; i < src.Count; i++)
|
||||
{
|
||||
publisher.Add(src[i]);
|
||||
}
|
||||
|
||||
Assert.Equal(src.Count, batchResults.Count);
|
||||
Assert.Equal(src.Count, eventResults.Count);
|
||||
|
||||
for (int i = 0; i < src.Count; i++)
|
||||
{
|
||||
double s = streamResults[i];
|
||||
double b = batchResults[i].Value;
|
||||
double sp = spanOutput[i];
|
||||
double ev = eventResults[i];
|
||||
|
||||
if (double.IsNaN(s))
|
||||
{
|
||||
Assert.True(double.IsNaN(b));
|
||||
Assert.True(double.IsNaN(sp));
|
||||
Assert.True(double.IsNaN(ev));
|
||||
}
|
||||
else
|
||||
{
|
||||
Assert.Equal(s, b, 1e-10);
|
||||
Assert.Equal(s, sp, 1e-10);
|
||||
Assert.Equal(s, ev, 1e-10);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// === G) Span API tests ===
|
||||
|
||||
[Fact]
|
||||
public void Batch_Span_MismatchedLengths_Throws()
|
||||
{
|
||||
double[] source = { 1, 2, 3 };
|
||||
double[] output = new double[2];
|
||||
|
||||
var ex = Assert.Throws<ArgumentException>(() => Tukey_w.Batch(source, output, period: 2));
|
||||
Assert.Equal("output", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Batch_Span_PeriodBelow2_Throws()
|
||||
{
|
||||
double[] source = { 1, 2, 3 };
|
||||
double[] output = new double[3];
|
||||
|
||||
var ex = Assert.Throws<ArgumentException>(() => Tukey_w.Batch(source, output, period: 1));
|
||||
Assert.Equal("period", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Batch_Span_AlphaOutOfRange_Throws()
|
||||
{
|
||||
double[] source = { 1, 2, 3 };
|
||||
double[] output = new double[3];
|
||||
|
||||
Assert.Throws<ArgumentException>(() => Tukey_w.Batch(source, output, period: 2, alpha: -0.1));
|
||||
Assert.Throws<ArgumentException>(() => Tukey_w.Batch(source, output, period: 2, alpha: 1.5));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Batch_Span_EmptyInput_NoOutput()
|
||||
{
|
||||
Tukey_w.Batch(ReadOnlySpan<double>.Empty, Span<double>.Empty, period: 4);
|
||||
Assert.True(true);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Batch_Span_LargeData_NoStackOverflow()
|
||||
{
|
||||
int count = 10_000;
|
||||
double[] source = new double[count];
|
||||
double[] output = new double[count];
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
source[i] = 100.0 + (i % 50);
|
||||
}
|
||||
|
||||
Tukey_w.Batch(source, output, period: 20, alpha: 0.5);
|
||||
Assert.True(double.IsFinite(output[^1]));
|
||||
}
|
||||
|
||||
// === H) Chainability ===
|
||||
|
||||
[Fact]
|
||||
public void Pub_FiresOnUpdate()
|
||||
{
|
||||
var tw = new Tukey_w(period: 4);
|
||||
int pubCount = 0;
|
||||
tw.Pub += (object? sender, in TValueEventArgs e) => pubCount++;
|
||||
|
||||
tw.Update(new TValue(DateTime.UtcNow, 100.0));
|
||||
Assert.Equal(1, pubCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EventBased_Chaining_Works()
|
||||
{
|
||||
var publisher = new TSeries();
|
||||
var tw = new Tukey_w(publisher, period: 4, alpha: 0.5);
|
||||
int resultCount = 0;
|
||||
tw.Pub += (object? sender, in TValueEventArgs e) => resultCount++;
|
||||
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
publisher.Add(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0 + i));
|
||||
}
|
||||
Assert.Equal(10, resultCount);
|
||||
}
|
||||
|
||||
// === Additional ===
|
||||
|
||||
[Fact]
|
||||
public void Calculate_ReturnsResultsAndIndicator()
|
||||
{
|
||||
var src = MakeSeries(50);
|
||||
var (results, indicator) = Tukey_w.Calculate(src, period: 5, alpha: 0.5);
|
||||
|
||||
Assert.Equal(50, results.Count);
|
||||
Assert.True(indicator.IsHot);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Dispose_UnsubscribesFromSource()
|
||||
{
|
||||
var publisher = new TSeries();
|
||||
var tw = new Tukey_w(publisher, period: 4);
|
||||
int pubCount = 0;
|
||||
tw.Pub += (object? sender, in TValueEventArgs e) => pubCount++;
|
||||
|
||||
publisher.Add(new TValue(DateTime.UtcNow, 100.0));
|
||||
Assert.Equal(1, pubCount);
|
||||
|
||||
tw.Dispose();
|
||||
|
||||
publisher.Add(new TValue(DateTime.UtcNow.AddSeconds(1), 200.0));
|
||||
Assert.Equal(1, pubCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Prime_SetsStateFromSpan()
|
||||
{
|
||||
var tw = new Tukey_w(period: 4);
|
||||
double[] data = { 10, 20, 30, 40, 50 };
|
||||
tw.Prime(data);
|
||||
|
||||
Assert.True(tw.IsHot);
|
||||
Assert.True(double.IsFinite(tw.Last.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Output_BoundedByInputRange()
|
||||
{
|
||||
// All weights non-negative: output bounded by min/max input
|
||||
var tw = new Tukey_w(period: 5, alpha: 0.5);
|
||||
double[] vals = { 10, 20, 30, 40, 50 };
|
||||
for (int i = 0; i < vals.Length; i++)
|
||||
{
|
||||
tw.Update(new TValue(DateTime.UtcNow.AddSeconds(i), vals[i]));
|
||||
}
|
||||
Assert.InRange(tw.Last.Value, 10.0, 50.0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Update_TSeries_EmptySource_ReturnsEmpty()
|
||||
{
|
||||
var tw = new Tukey_w(period: 4);
|
||||
var result = tw.Update(new TSeries());
|
||||
Assert.Empty(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Update_TSeries_ProducesCorrectLength()
|
||||
{
|
||||
var src = MakeSeries(100);
|
||||
var tw = new Tukey_w(period: 5);
|
||||
var result = tw.Update(src);
|
||||
Assert.Equal(100, result.Count);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
using Xunit;
|
||||
|
||||
public class TukeyWValidationTests
|
||||
{
|
||||
private static TSeries MakeSeries(int count = 500)
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 42);
|
||||
return gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1)).Close;
|
||||
}
|
||||
|
||||
private readonly TSeries _data = MakeSeries();
|
||||
|
||||
[Fact]
|
||||
public void Batch_Matches_Streaming()
|
||||
{
|
||||
int period = 20;
|
||||
double alpha = 0.5;
|
||||
|
||||
var streaming = new Tukey_w(period, alpha);
|
||||
var streamResults = new double[_data.Count];
|
||||
for (int i = 0; i < _data.Count; i++)
|
||||
{
|
||||
streamResults[i] = streaming.Update(_data[i]).Value;
|
||||
}
|
||||
|
||||
var batchResults = Tukey_w.Batch(_data, period, alpha);
|
||||
|
||||
for (int i = 0; i < _data.Count; i++)
|
||||
{
|
||||
Assert.Equal(streamResults[i], batchResults[i].Value, 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Span_Matches_Streaming()
|
||||
{
|
||||
int period = 20;
|
||||
double alpha = 0.5;
|
||||
|
||||
var streaming = new Tukey_w(period, alpha);
|
||||
var streamResults = new double[_data.Count];
|
||||
for (int i = 0; i < _data.Count; i++)
|
||||
{
|
||||
streamResults[i] = streaming.Update(_data[i]).Value;
|
||||
}
|
||||
|
||||
var spanOutput = new double[_data.Count];
|
||||
Tukey_w.Batch(_data.Values, spanOutput, period, alpha);
|
||||
|
||||
for (int i = 0; i < _data.Count; i++)
|
||||
{
|
||||
Assert.Equal(streamResults[i], spanOutput[i], 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(2)]
|
||||
[InlineData(7)]
|
||||
[InlineData(20)]
|
||||
[InlineData(50)]
|
||||
public void DifferentPeriods_ProduceValidResults(int period)
|
||||
{
|
||||
var tukey = new Tukey_w(period, 0.5);
|
||||
foreach (var tv in _data)
|
||||
{
|
||||
var result = tukey.Update(tv);
|
||||
Assert.True(double.IsFinite(result.Value));
|
||||
}
|
||||
Assert.True(tukey.IsHot);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ConstantInput_ConvergesToConstant()
|
||||
{
|
||||
var tukey = new Tukey_w(10, 0.5);
|
||||
for (int i = 0; i < 50; i++)
|
||||
{
|
||||
tukey.Update(new TValue(DateTime.UtcNow, 42.0));
|
||||
}
|
||||
Assert.Equal(42.0, tukey.Last.Value, 1e-10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Calculate_ReturnsHotIndicator()
|
||||
{
|
||||
var (results, indicator) = Tukey_w.Calculate(_data, 20, 0.5);
|
||||
Assert.True(indicator.IsHot);
|
||||
Assert.Equal(_data.Count, results.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BarCorrection_Consistency()
|
||||
{
|
||||
int period = 7;
|
||||
var tukey = new Tukey_w(period, 0.5);
|
||||
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
tukey.Update(new TValue(DateTime.UtcNow, 100.0 + i), isNew: true);
|
||||
}
|
||||
|
||||
double original = tukey.Last.Value;
|
||||
|
||||
tukey.Update(new TValue(DateTime.UtcNow, 999.0), isNew: false);
|
||||
tukey.Update(new TValue(DateTime.UtcNow, 119.0), isNew: false);
|
||||
|
||||
Assert.Equal(original, tukey.Last.Value, 1e-10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SubsetStability()
|
||||
{
|
||||
int period = 10;
|
||||
double alpha = 0.5;
|
||||
var src = MakeSeries(200);
|
||||
|
||||
var full = new Tukey_w(period, alpha);
|
||||
for (int i = 0; i < src.Count; i++)
|
||||
{
|
||||
full.Update(src[i]);
|
||||
}
|
||||
|
||||
var subset = new Tukey_w(period, alpha);
|
||||
for (int i = 0; i < src.Count; i++)
|
||||
{
|
||||
subset.Update(src[i]);
|
||||
}
|
||||
|
||||
Assert.Equal(full.Last.Value, subset.Last.Value, 1e-10);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0.0)]
|
||||
[InlineData(0.25)]
|
||||
[InlineData(0.5)]
|
||||
[InlineData(0.75)]
|
||||
[InlineData(1.0)]
|
||||
public void DifferentAlphas_ProduceValidResults(double alpha)
|
||||
{
|
||||
var tukey = new Tukey_w(20, alpha);
|
||||
foreach (var tv in _data)
|
||||
{
|
||||
var result = tukey.Update(tv);
|
||||
Assert.True(double.IsFinite(result.Value));
|
||||
}
|
||||
Assert.True(tukey.IsHot);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Alpha0_MatchesSma()
|
||||
{
|
||||
int period = 10;
|
||||
var tukey = new Tukey_w(period, 0.0);
|
||||
var sma = new Sma(period);
|
||||
|
||||
foreach (var tv in _data)
|
||||
{
|
||||
tukey.Update(tv);
|
||||
sma.Update(tv);
|
||||
}
|
||||
|
||||
Assert.Equal(sma.Last.Value, tukey.Last.Value, 1e-10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DifferentAlphas_ProduceDifferentResults()
|
||||
{
|
||||
int period = 20;
|
||||
var tukey025 = new Tukey_w(period, 0.25);
|
||||
var tukey075 = new Tukey_w(period, 0.75);
|
||||
|
||||
foreach (var tv in _data)
|
||||
{
|
||||
tukey025.Update(tv);
|
||||
tukey075.Update(tv);
|
||||
}
|
||||
|
||||
Assert.NotEqual(tukey025.Last.Value, tukey075.Last.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Weights_AreSymmetric()
|
||||
{
|
||||
int period = 11;
|
||||
double alpha = 0.5;
|
||||
var tukey1 = new Tukey_w(period, alpha);
|
||||
|
||||
// Feed ascending then verify symmetry by checking constant input
|
||||
for (int i = 0; i < 50; i++)
|
||||
{
|
||||
tukey1.Update(new TValue(DateTime.UtcNow, 50.0));
|
||||
}
|
||||
Assert.Equal(50.0, tukey1.Last.Value, 1e-10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Output_BoundedByInput()
|
||||
{
|
||||
int period = 10;
|
||||
var tukey = new Tukey_w(period, 0.5);
|
||||
|
||||
for (int i = 0; i < _data.Count; i++)
|
||||
{
|
||||
tukey.Update(_data[i]);
|
||||
if (i >= period - 1)
|
||||
{
|
||||
// Track recent window min/max
|
||||
double wMin = double.MaxValue;
|
||||
double wMax = double.MinValue;
|
||||
int start = Math.Max(0, i - period + 1);
|
||||
for (int j = start; j <= i; j++)
|
||||
{
|
||||
double v = _data[j].Value;
|
||||
if (v < wMin)
|
||||
{
|
||||
wMin = v;
|
||||
}
|
||||
if (v > wMax)
|
||||
{
|
||||
wMax = v;
|
||||
}
|
||||
}
|
||||
Assert.InRange(tukey.Last.Value, wMin - 1e-10, wMax + 1e-10);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PineScript_Equivalence_Alpha05()
|
||||
{
|
||||
// Verify the piecewise Tukey window with known values
|
||||
// period=5, alpha=0.5: N=4, aN=2
|
||||
// i=0: i < aN/2=1 → w = 0.5*(1-cos(2π*0/2)) = 0.5*(1-1) = 0
|
||||
// i=1: i >= aN/2=1 and i <= N-aN/2=3 → w = 1.0
|
||||
// i=2: flat → w = 1.0
|
||||
// i=3: flat → w = 1.0
|
||||
// i=4: i > N-aN/2=3 → w = 0.5*(1-cos(2π*(4-4)/2)) = 0.5*(1-1) = 0
|
||||
// weights = [0, 1, 1, 1, 0] normalized = [0, 1/3, 1/3, 1/3, 0]
|
||||
// So for constant input 10.0, result should be 10.0
|
||||
var tukey = new Tukey_w(5, 0.5);
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
tukey.Update(new TValue(DateTime.UtcNow, 10.0));
|
||||
}
|
||||
Assert.Equal(10.0, tukey.Last.Value, 1e-10);
|
||||
|
||||
// For values [1,2,3,4,5] with weights [0,1/3,1/3,1/3,0]:
|
||||
// result = (0*1 + 1/3*2 + 1/3*3 + 1/3*4 + 0*5) = (2+3+4)/3 = 3.0
|
||||
var tukey2 = new Tukey_w(5, 0.5);
|
||||
for (int i = 1; i <= 5; i++)
|
||||
{
|
||||
tukey2.Update(new TValue(DateTime.UtcNow, i));
|
||||
}
|
||||
Assert.Equal(3.0, tukey2.Last.Value, 1e-10);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,442 @@
|
||||
using System.Buffers;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace QuanTAlib;
|
||||
|
||||
/// <summary>
|
||||
/// TUKEY_W: Tukey (Tapered Cosine) Window Moving Average
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// FIR filter using the Tukey (tapered cosine) window as weights.
|
||||
/// Parameter alpha controls the taper fraction:
|
||||
/// alpha=0 → rectangular window (SMA)
|
||||
/// alpha=1 → Hann window (full cosine taper)
|
||||
/// alpha=0.5 → half tapered, half flat (default)
|
||||
///
|
||||
/// Default period=20, alpha=0.5, min period=2.
|
||||
/// </remarks>
|
||||
/// <seealso href="Tukey_w.md">Detailed documentation</seealso>
|
||||
[SkipLocalsInit]
|
||||
#pragma warning disable S101 // S101 - Indicator name 'Tukey_w' matches file/PineScript convention with underscore variant suffix
|
||||
public sealed class Tukey_w : AbstractBase
|
||||
#pragma warning restore S101
|
||||
{
|
||||
private readonly int _period;
|
||||
private readonly double _alpha;
|
||||
private readonly double[] _weights;
|
||||
private readonly RingBuffer _buffer;
|
||||
private readonly ITValuePublisher? _source;
|
||||
private readonly TValuePublishedHandler? _pubHandler;
|
||||
private bool _isNew = true;
|
||||
private bool _disposed;
|
||||
private double _lastValidValue = double.NaN;
|
||||
private double _p_lastValidValue = double.NaN;
|
||||
|
||||
public bool IsNew => _isNew;
|
||||
public override bool IsHot => _buffer.IsFull;
|
||||
|
||||
/// <summary>
|
||||
/// Creates TUKEY_W with specified period and alpha.
|
||||
/// </summary>
|
||||
/// <param name="period">Lookback period (must be >= 2)</param>
|
||||
/// <param name="alpha">Taper fraction: 0=SMA, 1=Hann (must be in [0,1])</param>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public Tukey_w(int period = 20, double alpha = 0.5)
|
||||
{
|
||||
if (period < 2)
|
||||
{
|
||||
throw new ArgumentException("Period must be at least 2", nameof(period));
|
||||
}
|
||||
if (alpha < 0.0 || alpha > 1.0)
|
||||
{
|
||||
throw new ArgumentException("Alpha must be between 0.0 and 1.0", nameof(alpha));
|
||||
}
|
||||
|
||||
_period = period;
|
||||
_alpha = alpha;
|
||||
Name = $"Tukey_w({_period},{_alpha:F2})";
|
||||
WarmupPeriod = _period;
|
||||
|
||||
_buffer = new RingBuffer(_period);
|
||||
_weights = new double[_period];
|
||||
|
||||
ComputeTukeyWeights(_weights, _period, _alpha);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates TUKEY_W connected to a data source for event-based updates.
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public Tukey_w(ITValuePublisher source, int period = 20, double alpha = 0.5) : this(period, alpha)
|
||||
{
|
||||
_source = source;
|
||||
_pubHandler = Handle;
|
||||
_source.Pub += _pubHandler;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes Tukey (tapered cosine) window weights.
|
||||
/// Left taper: w(n) = 0.5*(1 - cos(2π*n / (alpha*(N-1))))
|
||||
/// Flat center: w(n) = 1.0
|
||||
/// Right taper: w(n) = 0.5*(1 - cos(2π*(N-1-n) / (alpha*(N-1))))
|
||||
/// Normalized to sum=1.0.
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static void ComputeTukeyWeights(Span<double> weights, int period, double alpha)
|
||||
{
|
||||
int N = period - 1;
|
||||
double aN = alpha * N;
|
||||
double wsum = 0.0;
|
||||
|
||||
for (int i = 0; i < period; i++)
|
||||
{
|
||||
double w = 1.0;
|
||||
if (aN > 0.0)
|
||||
{
|
||||
if (i < aN * 0.5)
|
||||
{
|
||||
w = 0.5 * (1.0 - Math.Cos(2.0 * Math.PI * i / aN));
|
||||
}
|
||||
else if (i > N - aN * 0.5)
|
||||
{
|
||||
w = 0.5 * (1.0 - Math.Cos(2.0 * Math.PI * (N - i) / aN));
|
||||
}
|
||||
}
|
||||
weights[i] = w;
|
||||
wsum += w;
|
||||
}
|
||||
|
||||
// Normalize to sum=1.0
|
||||
if (wsum > double.Epsilon)
|
||||
{
|
||||
double inv = 1.0 / wsum;
|
||||
for (int i = 0; i < period; i++)
|
||||
{
|
||||
weights[i] *= inv;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public override TValue Update(TValue input, bool isNew = true)
|
||||
{
|
||||
_isNew = isNew;
|
||||
return Update(input, isNew, publish: true);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private TValue Update(TValue input, bool isNew, bool publish)
|
||||
{
|
||||
if (isNew)
|
||||
{
|
||||
_p_lastValidValue = _lastValidValue;
|
||||
}
|
||||
else
|
||||
{
|
||||
_lastValidValue = _p_lastValidValue;
|
||||
}
|
||||
|
||||
double val = GetValidValue(input.Value);
|
||||
|
||||
if (!double.IsFinite(val))
|
||||
{
|
||||
Last = new TValue(input.Time, double.NaN);
|
||||
if (publish) { PubEvent(Last, isNew); }
|
||||
return Last;
|
||||
}
|
||||
|
||||
if (isNew)
|
||||
{
|
||||
_lastValidValue = val;
|
||||
_buffer.Add(val);
|
||||
|
||||
int count = _buffer.Count;
|
||||
double result;
|
||||
|
||||
if (count < _period)
|
||||
{
|
||||
result = val;
|
||||
}
|
||||
else
|
||||
{
|
||||
result = ConvolveFull(_buffer, _weights);
|
||||
}
|
||||
|
||||
Last = new TValue(input.Time, result);
|
||||
if (publish) { PubEvent(Last, isNew); }
|
||||
return Last;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Bar correction: snapshot, compute, restore
|
||||
_buffer.Snapshot();
|
||||
double prevLast = _lastValidValue;
|
||||
double prevPLast = _p_lastValidValue;
|
||||
|
||||
_lastValidValue = val;
|
||||
_buffer.UpdateNewest(val);
|
||||
|
||||
int count = _buffer.Count;
|
||||
double result;
|
||||
|
||||
if (count < _period)
|
||||
{
|
||||
result = val;
|
||||
}
|
||||
else
|
||||
{
|
||||
result = ConvolveFull(_buffer, _weights);
|
||||
}
|
||||
|
||||
Last = new TValue(input.Time, result);
|
||||
|
||||
// Restore buffer and state
|
||||
_buffer.Restore();
|
||||
_lastValidValue = prevLast;
|
||||
_p_lastValidValue = prevPLast;
|
||||
|
||||
if (publish) { 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);
|
||||
|
||||
Batch(source.Values, vSpan, _period, _alpha);
|
||||
source.Times.CopyTo(tSpan);
|
||||
|
||||
// Restore state by replaying last period bars
|
||||
Reset();
|
||||
int startIndex = Math.Max(0, len - _period);
|
||||
for (int i = startIndex; i < len; i++)
|
||||
{
|
||||
Update(source[i], isNew: true, publish: false);
|
||||
}
|
||||
|
||||
return new TSeries(t, v);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
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))
|
||||
{
|
||||
return input;
|
||||
}
|
||||
return double.IsFinite(_lastValidValue) ? _lastValidValue : double.NaN;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// FIR convolution using SIMD DotProduct over circular buffer.
|
||||
/// Weight[0] corresponds to oldest bar, Weight[period-1] to newest.
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static double ConvolveFull(RingBuffer buffer, double[] weights)
|
||||
{
|
||||
ReadOnlySpan<double> internalBuf = buffer.InternalBuffer;
|
||||
int head = buffer.StartIndex;
|
||||
int period = buffer.Capacity;
|
||||
|
||||
int part1Len = period - head;
|
||||
double sum1 = internalBuf.Slice(head, part1Len).DotProduct(weights.AsSpan(0, part1Len));
|
||||
double sum2 = internalBuf[..head].DotProduct(weights.AsSpan(part1Len));
|
||||
|
||||
return sum1 + sum2;
|
||||
}
|
||||
|
||||
public override void Prime(ReadOnlySpan<double> source, TimeSpan? step = null)
|
||||
{
|
||||
foreach (var value in source)
|
||||
{
|
||||
Update(new TValue(DateTime.MinValue, value));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Calculates TUKEY_W from a TSeries using streaming updates.
|
||||
/// </summary>
|
||||
public static TSeries Batch(TSeries source, int period = 20, double alpha = 0.5)
|
||||
{
|
||||
var tukey = new Tukey_w(period, alpha);
|
||||
return tukey.Update(source);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Calculates Tukey Window Moving Average over a span of values.
|
||||
/// </summary>
|
||||
/// <param name="source">Input values</param>
|
||||
/// <param name="output">Output buffer (must be same length as source)</param>
|
||||
/// <param name="period">Period for weight calculation (must be >= 2)</param>
|
||||
/// <param name="alpha">Taper fraction: 0=SMA, 1=Hann (must be in [0,1])</param>
|
||||
/// <param name="nanValue">Value to use for NaN substitution (default: NaN)</param>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void Batch(ReadOnlySpan<double> source, Span<double> output, int period = 20, double alpha = 0.5, double nanValue = double.NaN)
|
||||
{
|
||||
if (period < 2)
|
||||
{
|
||||
throw new ArgumentException("Period must be at least 2", nameof(period));
|
||||
}
|
||||
if (alpha < 0.0 || alpha > 1.0)
|
||||
{
|
||||
throw new ArgumentException("Alpha must be between 0.0 and 1.0", nameof(alpha));
|
||||
}
|
||||
|
||||
if (source.Length != output.Length)
|
||||
{
|
||||
throw new ArgumentException("Source and output must have the same length", nameof(output));
|
||||
}
|
||||
|
||||
if (source.Length == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int len = source.Length;
|
||||
|
||||
const int StackallocThreshold = 256;
|
||||
|
||||
// Allocate weights
|
||||
double[]? weightsRented = period > StackallocThreshold ? ArrayPool<double>.Shared.Rent(period) : null;
|
||||
Span<double> weights = period <= StackallocThreshold
|
||||
? stackalloc double[period]
|
||||
: weightsRented!.AsSpan(0, period);
|
||||
|
||||
// Allocate ring buffer
|
||||
double[]? ringRented = period > StackallocThreshold ? ArrayPool<double>.Shared.Rent(period) : null;
|
||||
Span<double> ring = period <= StackallocThreshold
|
||||
? stackalloc double[period]
|
||||
: ringRented!.AsSpan(0, period);
|
||||
|
||||
// Allocate NaN-corrected values array
|
||||
double[]? cleanRented = len > StackallocThreshold ? ArrayPool<double>.Shared.Rent(len) : null;
|
||||
Span<double> clean = len <= StackallocThreshold
|
||||
? stackalloc double[len]
|
||||
: cleanRented!.AsSpan(0, len);
|
||||
|
||||
ComputeTukeyWeights(weights, period, alpha);
|
||||
|
||||
try
|
||||
{
|
||||
// Build NaN-corrected values array
|
||||
double lastValid = nanValue;
|
||||
for (int i = 0; i < len; i++)
|
||||
{
|
||||
double val = source[i];
|
||||
if (double.IsFinite(val))
|
||||
{
|
||||
lastValid = val;
|
||||
clean[i] = val;
|
||||
}
|
||||
else if (double.IsFinite(lastValid))
|
||||
{
|
||||
clean[i] = lastValid;
|
||||
}
|
||||
else
|
||||
{
|
||||
clean[i] = double.NaN;
|
||||
}
|
||||
}
|
||||
|
||||
// Apply Tukey FIR convolution
|
||||
int ringIdx = 0;
|
||||
int count = 0;
|
||||
|
||||
for (int i = 0; i < len; i++)
|
||||
{
|
||||
double val = clean[i];
|
||||
|
||||
ring[ringIdx] = val;
|
||||
ringIdx++;
|
||||
if (ringIdx >= period)
|
||||
{
|
||||
ringIdx = 0;
|
||||
}
|
||||
|
||||
if (count < period)
|
||||
{
|
||||
count++;
|
||||
}
|
||||
|
||||
if (count < period)
|
||||
{
|
||||
// Warmup: return raw value
|
||||
output[i] = val;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Full window: DotProduct convolution over circular buffer
|
||||
int part1Len = period - ringIdx;
|
||||
|
||||
ReadOnlySpan<double> ringRo = ring;
|
||||
double sum = ringRo.Slice(ringIdx, part1Len).DotProduct(weights.Slice(0, part1Len))
|
||||
+ ringRo[..ringIdx].DotProduct(weights.Slice(part1Len));
|
||||
|
||||
output[i] = sum;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (weightsRented != null)
|
||||
{
|
||||
ArrayPool<double>.Shared.Return(weightsRented);
|
||||
}
|
||||
if (ringRented != null)
|
||||
{
|
||||
ArrayPool<double>.Shared.Return(ringRented);
|
||||
}
|
||||
if (cleanRented != null)
|
||||
{
|
||||
ArrayPool<double>.Shared.Return(cleanRented);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a TUKEY_W indicator and calculates results from source.
|
||||
/// </summary>
|
||||
public static (TSeries Results, Tukey_w Indicator) Calculate(TSeries source, int period = 20, double alpha = 0.5)
|
||||
{
|
||||
var indicator = new Tukey_w(period, alpha);
|
||||
TSeries results = indicator.Update(source);
|
||||
return (results, indicator);
|
||||
}
|
||||
|
||||
public override void Reset()
|
||||
{
|
||||
_buffer.Clear();
|
||||
_lastValidValue = double.NaN;
|
||||
_p_lastValidValue = double.NaN;
|
||||
Last = default;
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (!_disposed)
|
||||
{
|
||||
if (disposing && _source != null && _pubHandler != null)
|
||||
{
|
||||
_source.Pub -= _pubHandler;
|
||||
}
|
||||
_disposed = true;
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user