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:
Miha Kralj
2026-02-21 20:45:38 -08:00
parent 90d5638008
commit 7253f61299
199 changed files with 29577 additions and 234 deletions
@@ -0,0 +1,159 @@
using TradingPlatform.BusinessLayer;
namespace QuanTAlib.Tests;
public class ParzenIndicatorTests
{
[Fact]
public void ParzenIndicator_Constructor_SetsDefaults()
{
var indicator = new ParzenIndicator();
Assert.Equal(14, indicator.Period);
Assert.Equal(SourceType.Close, indicator.Source);
Assert.True(indicator.ShowColdValues);
Assert.Equal("PARZEN - Parzen (de la Vallée-Poussin) Window Moving Average", indicator.Name);
Assert.False(indicator.SeparateWindow);
Assert.True(indicator.OnBackGround);
}
[Fact]
public void ParzenIndicator_MinHistoryDepths_IsZero()
{
var indicator = new ParzenIndicator { Period = 14 };
Assert.Equal(0, ParzenIndicator.MinHistoryDepths);
Assert.Equal(0, ((IWatchlistIndicator)indicator).MinHistoryDepths);
}
[Fact]
public void ParzenIndicator_ShortName_IncludesPeriodAndSource()
{
var indicator = new ParzenIndicator { Period = 10 };
Assert.Contains("PARZEN", indicator.ShortName, StringComparison.Ordinal);
Assert.Contains("10", indicator.ShortName, StringComparison.Ordinal);
}
[Fact]
public void ParzenIndicator_SourceCodeLink_IsValid()
{
var indicator = new ParzenIndicator();
Assert.Contains("github.com", indicator.SourceCodeLink, StringComparison.Ordinal);
Assert.Contains("Parzen.Quantower.cs", indicator.SourceCodeLink, StringComparison.Ordinal);
}
[Fact]
public void ParzenIndicator_Initialize_CreatesInternalParzen()
{
var indicator = new ParzenIndicator { Period = 14 };
indicator.Initialize();
Assert.Single(indicator.LinesSeries);
}
[Fact]
public void ParzenIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
{
var indicator = new ParzenIndicator { 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 ParzenIndicator_ProcessUpdate_NewBar_ComputesValue()
{
var indicator = new ParzenIndicator { 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 ParzenIndicator_ProcessUpdate_NewTick_ProcessesWithoutError()
{
var indicator = new ParzenIndicator { 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 ParzenIndicator_MultipleUpdates_ProducesCorrectSequence()
{
var indicator = new ParzenIndicator { 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 ParzenIndicator_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 ParzenIndicator { 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 ParzenIndicator_Period_CanBeChanged()
{
var indicator = new ParzenIndicator { Period = 14 };
Assert.Equal(14, indicator.Period);
indicator.Period = 20;
Assert.Equal(20, indicator.Period);
Assert.Equal(0, ParzenIndicator.MinHistoryDepths);
}
}
+56
View File
@@ -0,0 +1,56 @@
using System.Drawing;
using System.Runtime.CompilerServices;
using TradingPlatform.BusinessLayer;
namespace QuanTAlib;
[SkipLocalsInit]
public sealed class ParzenIndicator : Indicator, IWatchlistIndicator
{
[InputParameter("Period", sortIndex: 1, 2, 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 Parzen _parzen = 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 => $"PARZEN {Period}:{_sourceName}";
public override string SourceCodeLink => "https://github.com/mihakralj/QuanTAlib/blob/main/lib/trends_FIR/parzen/Parzen.Quantower.cs";
public ParzenIndicator()
{
OnBackGround = true;
SeparateWindow = false;
Name = "PARZEN - Parzen (de la Vallée-Poussin) Window Moving Average";
Description = "Parzen (de la Vallée-Poussin) Window Moving Average";
_series = new LineSeries(name: $"PARZEN {Period}", color: IndicatorExtensions.Averages, width: 2, style: LineStyle.Solid);
AddLineSeries(_series);
}
protected override void OnInit()
{
_priceSelector = Source.GetPriceSelector();
_sourceName = Source.ToString();
_parzen = new Parzen(Period);
base.OnInit();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override void OnUpdate(UpdateArgs args)
{
bool isNew = args.IsNewBar();
var item = HistoricalData[Count - 1, SeekOriginHistory.Begin];
double value = _parzen.Update(new TValue(item.TimeLeft.Ticks, _priceSelector(item)), isNew).Value;
_series.SetValue(value, _parzen.IsHot, ShowColdValues);
}
}
+446
View File
@@ -0,0 +1,446 @@
namespace QuanTAlib.Tests;
public class ParzenTests
{
private const int DefaultPeriod = 14;
private const double Epsilon = 1e-10;
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();
// ── A) Constructor validation ──────────────────────────────────────
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(-5)]
public void Constructor_InvalidPeriod_Throws(int period)
{
var ex = Assert.Throws<ArgumentException>(() => new Parzen(period));
Assert.Equal("period", ex.ParamName);
}
[Theory]
[InlineData(2)]
[InlineData(14)]
[InlineData(100)]
public void Constructor_ValidPeriod_Succeeds(int period)
{
var parzen = new Parzen(period);
Assert.Contains(period.ToString(System.Globalization.CultureInfo.InvariantCulture), parzen.Name, StringComparison.Ordinal);
}
[Fact]
public void Constructor_DefaultName()
{
var parzen = new Parzen(14);
Assert.Equal("Parzen(14)", parzen.Name);
}
[Fact]
public void Constructor_NullSource_Throws()
{
Assert.Throws<NullReferenceException>(() => new Parzen(null!, DefaultPeriod));
}
// ── B) Basic calculation ───────────────────────────────────────────
[Fact]
public void Update_ReturnsTValue()
{
var parzen = new Parzen(DefaultPeriod);
var result = parzen.Update(new TValue(DateTime.UtcNow, 100.0));
Assert.IsType<TValue>(result);
}
[Fact]
public void Last_IsAccessible()
{
var parzen = new Parzen(DefaultPeriod);
parzen.Update(new TValue(DateTime.UtcNow, 100.0));
Assert.True(double.IsFinite(parzen.Last.Value));
}
[Fact]
public void Name_IsCorrect()
{
var parzen = new Parzen(20);
Assert.Equal("Parzen(20)", parzen.Name);
}
[Fact]
public void Update_ReturnsFiniteValue()
{
var parzen = new Parzen(DefaultPeriod);
foreach (var tv in _data)
{
var result = parzen.Update(tv);
Assert.True(double.IsFinite(result.Value));
}
}
// ── C) State + bar correction ──────────────────────────────────────
[Fact]
public void IsNew_True_AdvancesState()
{
var parzen = new Parzen(5);
var now = DateTime.UtcNow;
parzen.Update(new TValue(now, 10.0), isNew: true);
parzen.Update(new TValue(now.AddMinutes(1), 20.0), isNew: true);
Assert.True(double.IsFinite(parzen.Last.Value));
}
[Fact]
public void IsNew_False_DoesNotAdvanceBuffer()
{
// The Parzen window has zero weight at the boundary (|u|=1 → 2*(1-1)³=0),
// so the newest bar can have zero weight. Test that isNew=false does not
// advance the buffer by verifying state is preserved after correction.
var parzen = new Parzen(7);
var src = MakeSeries(20);
for (int i = 0; i < src.Count; i++)
{
parzen.Update(src[i], isNew: true);
}
double original = parzen.Last.Value;
// Multiple corrections should not change the final result when
// we restore the original value
parzen.Update(new TValue(src[src.Count - 1].Time, 500.0), isNew: false);
parzen.Update(new TValue(src[src.Count - 1].Time, src[src.Count - 1].Value), isNew: false);
Assert.Equal(original, parzen.Last.Value, Epsilon);
}
[Fact]
public void IterativeCorrections_Restore()
{
var parzen = new Parzen(14);
var src = MakeSeries(30);
for (int i = 0; i < src.Count; i++)
{
parzen.Update(src[i], isNew: true);
}
double original = parzen.Last.Value;
for (int c = 0; c < 5; c++)
{
parzen.Update(new TValue(src[src.Count - 1].Time, 200.0 + c), isNew: false);
}
// Restore original value
parzen.Update(new TValue(src[src.Count - 1].Time, src[src.Count - 1].Value), isNew: false);
Assert.Equal(original, parzen.Last.Value, Epsilon);
}
[Fact]
public void Reset_ClearsState()
{
var parzen = new Parzen(DefaultPeriod);
foreach (var tv in _data)
{
parzen.Update(tv);
}
parzen.Reset();
Assert.False(parzen.IsHot);
}
// ── D) Warmup/convergence ──────────────────────────────────────────
[Fact]
public void IsHot_FlipsAtPeriod()
{
var parzen = new Parzen(5);
for (int i = 0; i < 4; i++)
{
parzen.Update(new TValue(DateTime.UtcNow, 100.0 + i));
Assert.False(parzen.IsHot);
}
parzen.Update(new TValue(DateTime.UtcNow, 105.0));
Assert.True(parzen.IsHot);
}
[Fact]
public void WarmupPeriod_MatchesPeriod()
{
var parzen = new Parzen(10);
Assert.Equal(10, parzen.WarmupPeriod);
}
// ── E) Robustness ──────────────────────────────────────────────────
[Fact]
public void NaN_UsesLastValidValue()
{
var parzen = new Parzen(5);
for (int i = 0; i < 5; i++)
{
parzen.Update(new TValue(DateTime.UtcNow, 100.0));
}
parzen.Update(new TValue(DateTime.UtcNow, double.NaN));
Assert.True(double.IsFinite(parzen.Last.Value));
}
[Fact]
public void Infinity_UsesLastValidValue()
{
var parzen = new Parzen(5);
for (int i = 0; i < 5; i++)
{
parzen.Update(new TValue(DateTime.UtcNow, 100.0));
}
parzen.Update(new TValue(DateTime.UtcNow, double.PositiveInfinity));
Assert.True(double.IsFinite(parzen.Last.Value));
}
[Fact]
public void BatchNaN_Safe()
{
var parzen = new Parzen(5);
var src = MakeSeries(50);
var result = parzen.Update(src);
Assert.Equal(src.Count, result.Count);
for (int i = 0; i < result.Count; i++)
{
Assert.True(double.IsFinite(result[i].Value));
}
}
// ── F) Consistency (4-API match) ───────────────────────────────────
[Fact]
public void AllModes_ProduceSameResults()
{
int period = 10;
var src = MakeSeries(100);
// Streaming
var streaming = new Parzen(period);
var streamResults = new double[src.Count];
for (int i = 0; i < src.Count; i++)
{
streamResults[i] = streaming.Update(src[i]).Value;
}
// Batch (TSeries)
var batchResults = Parzen.Batch(src, period);
// Span
var spanOutput = new double[src.Count];
Parzen.Batch(src.Values, spanOutput, period);
// Event-based
var publisher = new TSeries();
var eventParzen = new Parzen(publisher, period);
var eventResults = new double[src.Count];
for (int i = 0; i < src.Count; i++)
{
publisher.Add(src[i], isNew: true);
eventResults[i] = eventParzen.Last.Value;
}
for (int i = 0; i < src.Count; i++)
{
Assert.Equal(streamResults[i], batchResults[i].Value, 1e-6);
Assert.Equal(streamResults[i], spanOutput[i], 1e-6);
Assert.Equal(streamResults[i], eventResults[i], 1e-6);
}
}
// ── G) Span API tests ──────────────────────────────────────────────
[Fact]
public void Batch_Span_MismatchedLengths_Throws()
{
var src = new double[10];
var output = new double[5];
var ex = Assert.Throws<ArgumentException>(() => Parzen.Batch(src, output, 5));
Assert.Equal("output", ex.ParamName);
}
[Fact]
public void Batch_Span_PeriodTooSmall_Throws()
{
var src = new double[10];
var output = new double[10];
var ex = Assert.Throws<ArgumentException>(() => Parzen.Batch(src, output, 1));
Assert.Equal("period", ex.ParamName);
}
[Fact]
public void Batch_Span_EmptyInput_NoOp()
{
var src = ReadOnlySpan<double>.Empty;
var output = Span<double>.Empty;
Parzen.Batch(src, output, 5);
Assert.True(true);
}
// ── H) Chainability ────────────────────────────────────────────────
[Fact]
public void Pub_Fires()
{
var parzen = new Parzen(5);
int count = 0;
parzen.Pub += (object? _, in TValueEventArgs e) => count++;
parzen.Update(new TValue(DateTime.UtcNow, 100.0));
Assert.Equal(1, count);
}
[Fact]
public void EventBased_Chaining()
{
var source = new TSeries();
using var parzen = new Parzen(source, 5);
source.Add(new TValue(DateTime.UtcNow, 100.0), isNew: true);
Assert.True(double.IsFinite(parzen.Last.Value));
}
[Fact]
public void Dispose_UnsubscribesFromSource()
{
var source = new TSeries();
var parzen = new Parzen(source, 5);
parzen.Dispose();
source.Add(new TValue(DateTime.UtcNow, 100.0), isNew: true);
Assert.Equal(default, parzen.Last);
}
[Fact]
public void Dispose_Idempotent()
{
var parzen = new Parzen(5);
parzen.Dispose();
parzen.Dispose();
Assert.True(true);
}
// ── I) Parzen-specific: piecewise cubic properties ─────────────────
[Fact]
public void ConstantInput_ReturnsConstant()
{
var parzen = new Parzen(7);
for (int i = 0; i < 20; i++)
{
parzen.Update(new TValue(DateTime.UtcNow, 42.0));
}
Assert.Equal(42.0, parzen.Last.Value, 1e-10);
}
[Fact]
public void Weights_AreSymmetric()
{
// Parzen window is symmetric around center
int period = 9;
var parzen1 = new Parzen(period);
var parzen2 = new Parzen(period);
// Feed ascending then descending series — symmetric weights means
// feeding [1,2,3,4,5] and [5,4,3,2,1] should give same result for center-weighted
var ascending = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var descending = new double[] { 9, 8, 7, 6, 5, 4, 3, 2, 1 };
double resultAsc = 0, resultDesc = 0;
for (int i = 0; i < period; i++)
{
resultAsc = parzen1.Update(new TValue(DateTime.UtcNow, ascending[i])).Value;
resultDesc = parzen2.Update(new TValue(DateTime.UtcNow, descending[i])).Value;
}
// Both should give 5.0 (the mean) because symmetric weights on symmetric data
Assert.Equal(resultAsc, resultDesc, 1e-10);
}
[Fact]
public void LargerPeriod_SmoothsMore()
{
var src = MakeSeries(200);
var smallPeriod = new Parzen(5);
var largePeriod = new Parzen(20);
double sumDiffSmall = 0;
double sumDiffLarge = 0;
int countSmall = 0;
int countLarge = 0;
for (int i = 0; i < src.Count; i++)
{
double raw = src[i].Value;
smallPeriod.Update(src[i]);
largePeriod.Update(src[i]);
if (smallPeriod.IsHot)
{
sumDiffSmall += Math.Abs(raw - smallPeriod.Last.Value);
countSmall++;
}
if (largePeriod.IsHot)
{
sumDiffLarge += Math.Abs(raw - largePeriod.Last.Value);
countLarge++;
}
}
double avgDiffSmall = sumDiffSmall / countSmall;
double avgDiffLarge = sumDiffLarge / countLarge;
// Larger period should smooth more (larger avg deviation from raw)
Assert.True(avgDiffLarge > avgDiffSmall);
}
[Fact]
public void AllWeights_NonNegative()
{
// Parzen window guarantees all non-negative weights (convex combination)
int period = 14;
var src = new double[period];
var output = new double[period];
for (int i = 0; i < period; i++)
{
src[i] = 100.0;
}
src[period - 1] = 200.0; // spike at newest
Parzen.Batch(src, output, period);
// Since all weights are non-negative, convex combination means output <= max(input)
// and output >= min(input)
Assert.True(output[period - 1] >= 100.0);
Assert.True(output[period - 1] <= 200.0);
}
[Fact]
public void Calculate_ReturnsResultsAndIndicator()
{
var (results, indicator) = Parzen.Calculate(_data, 14);
Assert.Equal(_data.Count, results.Count);
Assert.True(indicator.IsHot);
}
[Fact]
public void Prime_SetsState()
{
var parzen = new Parzen(5);
var src = MakeSeries(20);
parzen.Prime(src.Values);
Assert.True(parzen.IsHot);
}
}
@@ -0,0 +1,148 @@
namespace QuanTAlib.Tests;
using Xunit;
public class ParzenValidationTests
{
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 = 14;
var streaming = new Parzen(period);
var streamResults = new double[_data.Count];
for (int i = 0; i < _data.Count; i++)
{
streamResults[i] = streaming.Update(_data[i]).Value;
}
var batchResults = Parzen.Batch(_data, period);
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 = 14;
var streaming = new Parzen(period);
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];
Parzen.Batch(_data.Values, spanOutput, period);
for (int i = 0; i < _data.Count; i++)
{
Assert.Equal(streamResults[i], spanOutput[i], 1e-9);
}
}
[Theory]
[InlineData(2)]
[InlineData(7)]
[InlineData(14)]
[InlineData(50)]
public void DifferentPeriods_ProduceValidResults(int period)
{
var parzen = new Parzen(period);
foreach (var tv in _data)
{
var result = parzen.Update(tv);
Assert.True(double.IsFinite(result.Value));
}
Assert.True(parzen.IsHot);
}
[Fact]
public void ConstantInput_ConvergesToConstant()
{
var parzen = new Parzen(10);
for (int i = 0; i < 50; i++)
{
parzen.Update(new TValue(DateTime.UtcNow, 42.0));
}
Assert.Equal(42.0, parzen.Last.Value, 1e-10);
}
[Fact]
public void Calculate_ReturnsHotIndicator()
{
var (results, indicator) = Parzen.Calculate(_data, 14);
Assert.True(indicator.IsHot);
Assert.Equal(_data.Count, results.Count);
}
[Fact]
public void BarCorrection_Consistency()
{
int period = 7;
var parzen = new Parzen(period);
for (int i = 0; i < 20; i++)
{
parzen.Update(new TValue(DateTime.UtcNow, 100.0 + i), isNew: true);
}
double original = parzen.Last.Value;
parzen.Update(new TValue(DateTime.UtcNow, 999.0), isNew: false);
parzen.Update(new TValue(DateTime.UtcNow, 119.0), isNew: false);
Assert.Equal(original, parzen.Last.Value, 1e-10);
}
[Fact]
public void SubsetStability()
{
int period = 10;
var src = MakeSeries(200);
var full = new Parzen(period);
for (int i = 0; i < src.Count; i++)
{
full.Update(src[i]);
}
var subset = new Parzen(period);
for (int i = 0; i < src.Count; i++)
{
subset.Update(src[i]);
}
Assert.Equal(full.Last.Value, subset.Last.Value, 1e-10);
}
[Fact]
public void OddAndEvenPeriods_BothWork()
{
var oddParzen = new Parzen(7);
var evenParzen = new Parzen(8);
foreach (var tv in _data)
{
var oddResult = oddParzen.Update(tv);
var evenResult = evenParzen.Update(tv);
Assert.True(double.IsFinite(oddResult.Value));
Assert.True(double.IsFinite(evenResult.Value));
}
Assert.True(oddParzen.IsHot);
Assert.True(evenParzen.IsHot);
}
}
+408
View File
@@ -0,0 +1,408 @@
using System.Buffers;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace QuanTAlib;
/// <summary>
/// PARZEN: Parzen (de la Vallée-Poussin) Window Moving Average
/// </summary>
/// <remarks>
/// Symmetric FIR filter using the Parzen piecewise cubic window function.
/// The Parzen window is the self-convolution of two Bartlett (triangular) windows
/// at half-length, yielding continuous first and second derivatives and -24 dB/octave
/// sidelobe rolloff. All weights are non-negative.
///
/// Calculation: Precomputed piecewise cubic weights, applied as FIR convolution
/// over sliding window. O(period) per bar.
/// </remarks>
/// <seealso href="Parzen.md">Detailed documentation</seealso>
[SkipLocalsInit]
public sealed class Parzen : AbstractBase
{
private readonly int _period;
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 PARZEN with specified period.
/// </summary>
/// <param name="period">Lookback period (>= 2)</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Parzen(int period = 14)
{
if (period < 2)
{
throw new ArgumentException("Period must be at least 2", nameof(period));
}
_period = period;
Name = $"Parzen({_period.ToString(System.Globalization.CultureInfo.InvariantCulture)})";
WarmupPeriod = _period;
_buffer = new RingBuffer(_period);
_weights = new double[_period];
ComputeParzenWeights(_weights, _period);
}
/// <summary>
/// Creates PARZEN connected to a data source for event-based updates.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Parzen(ITValuePublisher source, int period = 14) : this(period)
{
_source = source;
_pubHandler = Handle;
_source.Pub += _pubHandler;
}
/// <summary>
/// Computes Parzen (de la Vallée-Poussin) window weights and normalizes to sum=1.
/// Inner region (|u| &lt;= 0.5): w = 1 - 6u² + 6|u|³
/// Outer region (0.5 &lt; |u| &lt;= 1.0): w = 2(1 - |u|)³
/// All weights are non-negative.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void ComputeParzenWeights(Span<double> weights, int period)
{
double halfN = (period - 1) * 0.5;
double wsum = 0.0;
for (int k = 0; k < period; k++)
{
double u = halfN > 0 ? (k - halfN) / halfN : 0.0;
double absU = Math.Abs(u);
double w;
if (absU <= 0.5)
{
// Inner region: cubic spline
w = Math.FusedMultiplyAdd(6.0, absU * absU * absU, 1.0 - 6.0 * absU * absU);
}
else if (absU <= 1.0)
{
// Outer region: cubic taper to zero
double t = 1.0 - absU;
w = 2.0 * t * t * t;
}
else
{
w = 0.0;
}
weights[k] = w;
wsum += w;
}
if (Math.Abs(wsum) > double.Epsilon)
{
double inv = 1.0 / wsum;
for (int k = 0; k < period; k++)
{
weights[k] *= 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
{
_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);
_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);
source.Times.CopyTo(tSpan);
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));
}
}
public static TSeries Batch(TSeries source, int period = 14)
{
var parzen = new Parzen(period);
return parzen.Update(source);
}
/// <summary>
/// Calculates Parzen Window MA over a span of values.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Batch(ReadOnlySpan<double> source, Span<double> output, int period = 14, double nanValue = double.NaN)
{
if (period < 2)
{
throw new ArgumentException("Period must be at least 2", nameof(period));
}
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;
double[]? weightsRented = period > StackallocThreshold ? ArrayPool<double>.Shared.Rent(period) : null;
Span<double> weights = period <= StackallocThreshold
? stackalloc double[period]
: weightsRented!.AsSpan(0, period);
double[]? ringRented = period > StackallocThreshold ? ArrayPool<double>.Shared.Rent(period) : null;
Span<double> ring = period <= StackallocThreshold
? stackalloc double[period]
: ringRented!.AsSpan(0, period);
double[]? cleanRented = len > StackallocThreshold ? ArrayPool<double>.Shared.Rent(len) : null;
Span<double> clean = len <= StackallocThreshold
? stackalloc double[len]
: cleanRented!.AsSpan(0, len);
ComputeParzenWeights(weights, period);
try
{
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;
}
}
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)
{
output[i] = val;
continue;
}
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);
}
}
}
public static (TSeries Results, Parzen Indicator) Calculate(TSeries source, int period = 14)
{
var indicator = new Parzen(period);
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);
}
}