mirror of
https://github.com/mihakralj/QuanTAlib.git
synced 2026-08-22 20:48: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,159 @@
|
||||
using TradingPlatform.BusinessLayer;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public class LanczosIndicatorTests
|
||||
{
|
||||
[Fact]
|
||||
public void LanczosIndicator_Constructor_SetsDefaults()
|
||||
{
|
||||
var indicator = new LanczosIndicator();
|
||||
|
||||
Assert.Equal(14, indicator.Period);
|
||||
Assert.Equal(SourceType.Close, indicator.Source);
|
||||
Assert.True(indicator.ShowColdValues);
|
||||
Assert.Equal("LANCZOS - Lanczos (Sinc) Window Moving Average", indicator.Name);
|
||||
Assert.False(indicator.SeparateWindow);
|
||||
Assert.True(indicator.OnBackGround);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LanczosIndicator_MinHistoryDepths_IsZero()
|
||||
{
|
||||
var indicator = new LanczosIndicator { Period = 14 };
|
||||
|
||||
Assert.Equal(0, LanczosIndicator.MinHistoryDepths);
|
||||
Assert.Equal(0, ((IWatchlistIndicator)indicator).MinHistoryDepths);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LanczosIndicator_ShortName_IncludesPeriodAndSource()
|
||||
{
|
||||
var indicator = new LanczosIndicator { Period = 10 };
|
||||
|
||||
Assert.Contains("LANCZOS", indicator.ShortName, StringComparison.Ordinal);
|
||||
Assert.Contains("10", indicator.ShortName, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LanczosIndicator_SourceCodeLink_IsValid()
|
||||
{
|
||||
var indicator = new LanczosIndicator();
|
||||
|
||||
Assert.Contains("github.com", indicator.SourceCodeLink, StringComparison.Ordinal);
|
||||
Assert.Contains("Lanczos.Quantower.cs", indicator.SourceCodeLink, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LanczosIndicator_Initialize_CreatesInternalLanczos()
|
||||
{
|
||||
var indicator = new LanczosIndicator { Period = 14 };
|
||||
|
||||
indicator.Initialize();
|
||||
|
||||
Assert.Single(indicator.LinesSeries);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LanczosIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
|
||||
{
|
||||
var indicator = new LanczosIndicator { 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 LanczosIndicator_ProcessUpdate_NewBar_ComputesValue()
|
||||
{
|
||||
var indicator = new LanczosIndicator { 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 LanczosIndicator_ProcessUpdate_NewTick_ProcessesWithoutError()
|
||||
{
|
||||
var indicator = new LanczosIndicator { 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 LanczosIndicator_MultipleUpdates_ProducesCorrectSequence()
|
||||
{
|
||||
var indicator = new LanczosIndicator { 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 LanczosIndicator_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 LanczosIndicator { 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 LanczosIndicator_Period_CanBeChanged()
|
||||
{
|
||||
var indicator = new LanczosIndicator { Period = 14 };
|
||||
Assert.Equal(14, indicator.Period);
|
||||
|
||||
indicator.Period = 20;
|
||||
Assert.Equal(20, indicator.Period);
|
||||
Assert.Equal(0, LanczosIndicator.MinHistoryDepths);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
using System.Drawing;
|
||||
using System.Runtime.CompilerServices;
|
||||
using TradingPlatform.BusinessLayer;
|
||||
|
||||
namespace QuanTAlib;
|
||||
|
||||
[SkipLocalsInit]
|
||||
public sealed class LanczosIndicator : 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 Lanczos _lanczos = 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 => $"LANCZOS {Period}:{_sourceName}";
|
||||
public override string SourceCodeLink => "https://github.com/mihakralj/QuanTAlib/blob/main/lib/trends_FIR/lanczos/Lanczos.Quantower.cs";
|
||||
|
||||
public LanczosIndicator()
|
||||
{
|
||||
OnBackGround = true;
|
||||
SeparateWindow = false;
|
||||
Name = "LANCZOS - Lanczos (Sinc) Window Moving Average";
|
||||
Description = "Lanczos (Sinc) Window Moving Average";
|
||||
_series = new LineSeries(name: $"LANCZOS {Period}", color: IndicatorExtensions.Averages, width: 2, style: LineStyle.Solid);
|
||||
AddLineSeries(_series);
|
||||
}
|
||||
|
||||
protected override void OnInit()
|
||||
{
|
||||
_priceSelector = Source.GetPriceSelector();
|
||||
_sourceName = Source.ToString();
|
||||
_lanczos = new Lanczos(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 = _lanczos.Update(new TValue(item.TimeLeft.Ticks, _priceSelector(item)), isNew).Value;
|
||||
_series.SetValue(value, _lanczos.IsHot, ShowColdValues);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,420 @@
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public class LanczosTests
|
||||
{
|
||||
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 Lanczos(period));
|
||||
Assert.Equal("period", ex.ParamName);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(2)]
|
||||
[InlineData(14)]
|
||||
[InlineData(100)]
|
||||
public void Constructor_ValidPeriod_Succeeds(int period)
|
||||
{
|
||||
var lanczos = new Lanczos(period);
|
||||
Assert.Contains(period.ToString(System.Globalization.CultureInfo.InvariantCulture), lanczos.Name, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_DefaultName()
|
||||
{
|
||||
var lanczos = new Lanczos(14);
|
||||
Assert.Equal("Lanczos(14)", lanczos.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_NullSource_Throws()
|
||||
{
|
||||
Assert.Throws<NullReferenceException>(() => new Lanczos(null!, DefaultPeriod));
|
||||
}
|
||||
|
||||
// ── B) Basic calculation ───────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Update_ReturnsTValue()
|
||||
{
|
||||
var lanczos = new Lanczos(DefaultPeriod);
|
||||
var result = lanczos.Update(new TValue(DateTime.UtcNow, 100.0));
|
||||
Assert.IsType<TValue>(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Last_IsAccessible()
|
||||
{
|
||||
var lanczos = new Lanczos(DefaultPeriod);
|
||||
lanczos.Update(new TValue(DateTime.UtcNow, 100.0));
|
||||
Assert.True(double.IsFinite(lanczos.Last.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Name_IsCorrect()
|
||||
{
|
||||
var lanczos = new Lanczos(20);
|
||||
Assert.Equal("Lanczos(20)", lanczos.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Update_ReturnsFiniteValue()
|
||||
{
|
||||
var lanczos = new Lanczos(DefaultPeriod);
|
||||
foreach (var tv in _data)
|
||||
{
|
||||
var result = lanczos.Update(tv);
|
||||
Assert.True(double.IsFinite(result.Value));
|
||||
}
|
||||
}
|
||||
|
||||
// ── C) State + bar correction ──────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void IsNew_True_AdvancesState()
|
||||
{
|
||||
var lanczos = new Lanczos(5);
|
||||
var now = DateTime.UtcNow;
|
||||
lanczos.Update(new TValue(now, 10.0), isNew: true);
|
||||
lanczos.Update(new TValue(now.AddMinutes(1), 20.0), isNew: true);
|
||||
Assert.True(double.IsFinite(lanczos.Last.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsNew_False_DoesNotAdvanceBuffer()
|
||||
{
|
||||
// The Lanczos sinc window has zero weight at the newest bar position
|
||||
// (since sinc(1)=0 at k=period-1), so we test that isNew=false does not
|
||||
// advance the buffer by verifying state is preserved after correction.
|
||||
var lanczos = new Lanczos(7);
|
||||
var src = MakeSeries(20);
|
||||
|
||||
for (int i = 0; i < src.Count; i++)
|
||||
{
|
||||
lanczos.Update(src[i], isNew: true);
|
||||
}
|
||||
|
||||
double original = lanczos.Last.Value;
|
||||
|
||||
// Multiple corrections should not change the final result when
|
||||
// we restore the original value
|
||||
lanczos.Update(new TValue(src[src.Count - 1].Time, 500.0), isNew: false);
|
||||
lanczos.Update(new TValue(src[src.Count - 1].Time, src[src.Count - 1].Value), isNew: false);
|
||||
|
||||
Assert.Equal(original, lanczos.Last.Value, Epsilon);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IterativeCorrections_Restore()
|
||||
{
|
||||
var lanczos = new Lanczos(14);
|
||||
var src = MakeSeries(30);
|
||||
|
||||
for (int i = 0; i < src.Count; i++)
|
||||
{
|
||||
lanczos.Update(src[i], isNew: true);
|
||||
}
|
||||
|
||||
double original = lanczos.Last.Value;
|
||||
|
||||
for (int c = 0; c < 5; c++)
|
||||
{
|
||||
lanczos.Update(new TValue(src[src.Count - 1].Time, 200.0 + c), isNew: false);
|
||||
}
|
||||
|
||||
// Restore original value
|
||||
lanczos.Update(new TValue(src[src.Count - 1].Time, src[src.Count - 1].Value), isNew: false);
|
||||
Assert.Equal(original, lanczos.Last.Value, Epsilon);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reset_ClearsState()
|
||||
{
|
||||
var lanczos = new Lanczos(DefaultPeriod);
|
||||
foreach (var tv in _data)
|
||||
{
|
||||
lanczos.Update(tv);
|
||||
}
|
||||
|
||||
lanczos.Reset();
|
||||
Assert.False(lanczos.IsHot);
|
||||
}
|
||||
|
||||
// ── D) Warmup/convergence ──────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void IsHot_FlipsAtPeriod()
|
||||
{
|
||||
var lanczos = new Lanczos(5);
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
lanczos.Update(new TValue(DateTime.UtcNow, 100.0 + i));
|
||||
Assert.False(lanczos.IsHot);
|
||||
}
|
||||
lanczos.Update(new TValue(DateTime.UtcNow, 105.0));
|
||||
Assert.True(lanczos.IsHot);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WarmupPeriod_MatchesPeriod()
|
||||
{
|
||||
var lanczos = new Lanczos(10);
|
||||
Assert.Equal(10, lanczos.WarmupPeriod);
|
||||
}
|
||||
|
||||
// ── E) Robustness ──────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void NaN_UsesLastValidValue()
|
||||
{
|
||||
var lanczos = new Lanczos(5);
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
lanczos.Update(new TValue(DateTime.UtcNow, 100.0));
|
||||
}
|
||||
|
||||
lanczos.Update(new TValue(DateTime.UtcNow, double.NaN));
|
||||
Assert.True(double.IsFinite(lanczos.Last.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Infinity_UsesLastValidValue()
|
||||
{
|
||||
var lanczos = new Lanczos(5);
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
lanczos.Update(new TValue(DateTime.UtcNow, 100.0));
|
||||
}
|
||||
|
||||
lanczos.Update(new TValue(DateTime.UtcNow, double.PositiveInfinity));
|
||||
Assert.True(double.IsFinite(lanczos.Last.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BatchNaN_Safe()
|
||||
{
|
||||
var lanczos = new Lanczos(5);
|
||||
var src = MakeSeries(50);
|
||||
var result = lanczos.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 Lanczos(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 = Lanczos.Batch(src, period);
|
||||
|
||||
// Span
|
||||
var spanOutput = new double[src.Count];
|
||||
Lanczos.Batch(src.Values, spanOutput, period);
|
||||
|
||||
// Event-based
|
||||
var publisher = new TSeries();
|
||||
var eventLanczos = new Lanczos(publisher, period);
|
||||
var eventResults = new double[src.Count];
|
||||
for (int i = 0; i < src.Count; i++)
|
||||
{
|
||||
publisher.Add(src[i], isNew: true);
|
||||
eventResults[i] = eventLanczos.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>(() => Lanczos.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>(() => Lanczos.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;
|
||||
Lanczos.Batch(src, output, 5);
|
||||
Assert.True(true);
|
||||
}
|
||||
|
||||
// ── H) Chainability ────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Pub_Fires()
|
||||
{
|
||||
var lanczos = new Lanczos(5);
|
||||
int count = 0;
|
||||
lanczos.Pub += (object? _, in TValueEventArgs e) => count++;
|
||||
lanczos.Update(new TValue(DateTime.UtcNow, 100.0));
|
||||
Assert.Equal(1, count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EventBased_Chaining()
|
||||
{
|
||||
var source = new TSeries();
|
||||
using var lanczos = new Lanczos(source, 5);
|
||||
|
||||
source.Add(new TValue(DateTime.UtcNow, 100.0), isNew: true);
|
||||
Assert.True(double.IsFinite(lanczos.Last.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Dispose_UnsubscribesFromSource()
|
||||
{
|
||||
var source = new TSeries();
|
||||
var lanczos = new Lanczos(source, 5);
|
||||
lanczos.Dispose();
|
||||
|
||||
source.Add(new TValue(DateTime.UtcNow, 100.0), isNew: true);
|
||||
Assert.Equal(default, lanczos.Last);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Dispose_Idempotent()
|
||||
{
|
||||
var lanczos = new Lanczos(5);
|
||||
lanczos.Dispose();
|
||||
lanczos.Dispose();
|
||||
Assert.True(true);
|
||||
}
|
||||
|
||||
// ── I) Lanczos-specific: sinc properties ───────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void ConstantInput_ReturnsConstant()
|
||||
{
|
||||
var lanczos = new Lanczos(7);
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
lanczos.Update(new TValue(DateTime.UtcNow, 42.0));
|
||||
}
|
||||
Assert.Equal(42.0, lanczos.Last.Value, 1e-10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Period2_ReducesToSma()
|
||||
{
|
||||
// For period=2: k=0 -> x = -1, k=1 -> x = 1
|
||||
// sinc(-1) = sinc(1) = 0, both weights zero -> normalization makes them equal -> SMA(2)
|
||||
int period = 2;
|
||||
var lanczos = new Lanczos(period);
|
||||
var sma = new Sma(period);
|
||||
|
||||
var src = MakeSeries(50);
|
||||
for (int i = 0; i < src.Count; i++)
|
||||
{
|
||||
lanczos.Update(src[i]);
|
||||
sma.Update(src[i]);
|
||||
}
|
||||
|
||||
Assert.Equal(sma.Last.Value, lanczos.Last.Value, 1e-8);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LargerPeriod_SmoothsMore()
|
||||
{
|
||||
var src = MakeSeries(200);
|
||||
|
||||
var smallPeriod = new Lanczos(5);
|
||||
var largePeriod = new Lanczos(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 Calculate_ReturnsResultsAndIndicator()
|
||||
{
|
||||
var (results, indicator) = Lanczos.Calculate(_data, 14);
|
||||
Assert.Equal(_data.Count, results.Count);
|
||||
Assert.True(indicator.IsHot);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Prime_SetsState()
|
||||
{
|
||||
var lanczos = new Lanczos(5);
|
||||
var src = MakeSeries(20);
|
||||
lanczos.Prime(src.Values);
|
||||
Assert.True(lanczos.IsHot);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
using Xunit;
|
||||
|
||||
public class LanczosValidationTests
|
||||
{
|
||||
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 Lanczos(period);
|
||||
var streamResults = new double[_data.Count];
|
||||
for (int i = 0; i < _data.Count; i++)
|
||||
{
|
||||
streamResults[i] = streaming.Update(_data[i]).Value;
|
||||
}
|
||||
|
||||
var batchResults = Lanczos.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 Lanczos(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];
|
||||
Lanczos.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 lanczos = new Lanczos(period);
|
||||
foreach (var tv in _data)
|
||||
{
|
||||
var result = lanczos.Update(tv);
|
||||
Assert.True(double.IsFinite(result.Value));
|
||||
}
|
||||
Assert.True(lanczos.IsHot);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ConstantInput_ConvergesToConstant()
|
||||
{
|
||||
var lanczos = new Lanczos(10);
|
||||
for (int i = 0; i < 50; i++)
|
||||
{
|
||||
lanczos.Update(new TValue(DateTime.UtcNow, 42.0));
|
||||
}
|
||||
Assert.Equal(42.0, lanczos.Last.Value, 1e-10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Calculate_ReturnsHotIndicator()
|
||||
{
|
||||
var (results, indicator) = Lanczos.Calculate(_data, 14);
|
||||
Assert.True(indicator.IsHot);
|
||||
Assert.Equal(_data.Count, results.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BarCorrection_Consistency()
|
||||
{
|
||||
int period = 7;
|
||||
var lanczos = new Lanczos(period);
|
||||
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
lanczos.Update(new TValue(DateTime.UtcNow, 100.0 + i), isNew: true);
|
||||
}
|
||||
|
||||
double original = lanczos.Last.Value;
|
||||
|
||||
lanczos.Update(new TValue(DateTime.UtcNow, 999.0), isNew: false);
|
||||
lanczos.Update(new TValue(DateTime.UtcNow, 119.0), isNew: false);
|
||||
|
||||
Assert.Equal(original, lanczos.Last.Value, 1e-10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SubsetStability()
|
||||
{
|
||||
int period = 10;
|
||||
var src = MakeSeries(200);
|
||||
|
||||
var full = new Lanczos(period);
|
||||
for (int i = 0; i < src.Count; i++)
|
||||
{
|
||||
full.Update(src[i]);
|
||||
}
|
||||
|
||||
var subset = new Lanczos(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 oddLanczos = new Lanczos(7);
|
||||
var evenLanczos = new Lanczos(8);
|
||||
|
||||
foreach (var tv in _data)
|
||||
{
|
||||
var oddResult = oddLanczos.Update(tv);
|
||||
var evenResult = evenLanczos.Update(tv);
|
||||
Assert.True(double.IsFinite(oddResult.Value));
|
||||
Assert.True(double.IsFinite(evenResult.Value));
|
||||
}
|
||||
|
||||
Assert.True(oddLanczos.IsHot);
|
||||
Assert.True(evenLanczos.IsHot);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,400 @@
|
||||
using System.Buffers;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace QuanTAlib;
|
||||
|
||||
/// <summary>
|
||||
/// LANCZOS: Lanczos (Sinc) Window Moving Average
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Symmetric FIR filter using the normalized sinc function as the window shape.
|
||||
/// The sinc function is the impulse response of the ideal brick-wall low-pass filter;
|
||||
/// windowing it to finite length trades sharp cutoff for practical realizability.
|
||||
///
|
||||
/// Calculation: Precomputed weights via sinc(2k/(N-1) - 1), applied as FIR
|
||||
/// convolution over sliding window. Negative sidelobes are preserved for
|
||||
/// frequency-domain fidelity.
|
||||
/// </remarks>
|
||||
/// <seealso href="Lanczos.md">Detailed documentation</seealso>
|
||||
[SkipLocalsInit]
|
||||
public sealed class Lanczos : 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 LANCZOS with specified period.
|
||||
/// </summary>
|
||||
/// <param name="period">Lookback period (>= 2)</param>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public Lanczos(int period = 14)
|
||||
{
|
||||
if (period < 2)
|
||||
{
|
||||
throw new ArgumentException("Period must be at least 2", nameof(period));
|
||||
}
|
||||
|
||||
_period = period;
|
||||
Name = $"Lanczos({_period.ToString(System.Globalization.CultureInfo.InvariantCulture)})";
|
||||
WarmupPeriod = _period;
|
||||
|
||||
_buffer = new RingBuffer(_period);
|
||||
_weights = new double[_period];
|
||||
|
||||
ComputeLanczosWeights(_weights, _period);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates LANCZOS connected to a data source for event-based updates.
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public Lanczos(ITValuePublisher source, int period = 14) : this(period)
|
||||
{
|
||||
_source = source;
|
||||
_pubHandler = Handle;
|
||||
_source.Pub += _pubHandler;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes Lanczos (sinc) window weights and normalizes to sum=1.
|
||||
/// w(k) = sinc(2k/(N-1) - 1), where sinc(x) = sin(pi*x)/(pi*x), sinc(0) = 1.
|
||||
/// Negative sidelobes are preserved for frequency-domain fidelity.
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static void ComputeLanczosWeights(Span<double> weights, int period)
|
||||
{
|
||||
double nm1 = period - 1;
|
||||
|
||||
double wsum = 0.0;
|
||||
for (int k = 0; k < period; k++)
|
||||
{
|
||||
double x = nm1 > 0 ? (2.0 * k / nm1) - 1.0 : 0.0;
|
||||
double w;
|
||||
if (Math.Abs(x) < 1e-10)
|
||||
{
|
||||
w = 1.0;
|
||||
}
|
||||
else
|
||||
{
|
||||
double piX = Math.PI * x;
|
||||
w = Math.Sin(piX) / piX;
|
||||
}
|
||||
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 lanczos = new Lanczos(period);
|
||||
return lanczos.Update(source);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Calculates Lanczos 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);
|
||||
|
||||
ComputeLanczosWeights(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, Lanczos Indicator) Calculate(TSeries source, int period = 14)
|
||||
{
|
||||
var indicator = new Lanczos(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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user