mirror of
https://github.com/mihakralj/QuanTAlib.git
synced 2026-08-23 04:58:08 +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 KaiserIndicatorTests
|
||||
{
|
||||
[Fact]
|
||||
public void KaiserIndicator_Constructor_SetsDefaults()
|
||||
{
|
||||
var indicator = new KaiserIndicator();
|
||||
|
||||
Assert.Equal(14, indicator.Period);
|
||||
Assert.Equal(3.0, indicator.Beta);
|
||||
Assert.Equal(SourceType.Close, indicator.Source);
|
||||
Assert.True(indicator.ShowColdValues);
|
||||
Assert.Equal("KAISER - Kaiser Window Moving Average", indicator.Name);
|
||||
Assert.False(indicator.SeparateWindow);
|
||||
Assert.True(indicator.OnBackGround);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void KaiserIndicator_MinHistoryDepths_IsZero()
|
||||
{
|
||||
var indicator = new KaiserIndicator { Period = 14 };
|
||||
|
||||
Assert.Equal(0, KaiserIndicator.MinHistoryDepths);
|
||||
Assert.Equal(0, ((IWatchlistIndicator)indicator).MinHistoryDepths);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void KaiserIndicator_ShortName_IncludesPeriodAndSource()
|
||||
{
|
||||
var indicator = new KaiserIndicator { Period = 10, Beta = 5.0 };
|
||||
|
||||
Assert.Contains("KAISER", indicator.ShortName, StringComparison.Ordinal);
|
||||
Assert.Contains("10", indicator.ShortName, StringComparison.Ordinal);
|
||||
Assert.Contains("5.0", indicator.ShortName, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void KaiserIndicator_SourceCodeLink_IsValid()
|
||||
{
|
||||
var indicator = new KaiserIndicator();
|
||||
|
||||
Assert.Contains("github.com", indicator.SourceCodeLink, StringComparison.Ordinal);
|
||||
Assert.Contains("Kaiser.Quantower.cs", indicator.SourceCodeLink, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void KaiserIndicator_Initialize_CreatesInternalKaiser()
|
||||
{
|
||||
var indicator = new KaiserIndicator { Period = 14 };
|
||||
|
||||
indicator.Initialize();
|
||||
|
||||
Assert.Single(indicator.LinesSeries);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void KaiserIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
|
||||
{
|
||||
var indicator = new KaiserIndicator { 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 KaiserIndicator_ProcessUpdate_NewBar_ComputesValue()
|
||||
{
|
||||
var indicator = new KaiserIndicator { 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 KaiserIndicator_ProcessUpdate_NewTick_ProcessesWithoutError()
|
||||
{
|
||||
var indicator = new KaiserIndicator { 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 KaiserIndicator_MultipleUpdates_ProducesCorrectSequence()
|
||||
{
|
||||
var indicator = new KaiserIndicator { 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 KaiserIndicator_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 KaiserIndicator { 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 KaiserIndicator_Period_CanBeChanged()
|
||||
{
|
||||
var indicator = new KaiserIndicator { Period = 14 };
|
||||
Assert.Equal(14, indicator.Period);
|
||||
|
||||
indicator.Period = 20;
|
||||
Assert.Equal(20, indicator.Period);
|
||||
Assert.Equal(0, KaiserIndicator.MinHistoryDepths);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void KaiserIndicator_Beta_CanBeChanged()
|
||||
{
|
||||
var indicator = new KaiserIndicator { Beta = 3.0 };
|
||||
Assert.Equal(3.0, indicator.Beta);
|
||||
|
||||
indicator.Beta = 8.6;
|
||||
Assert.Equal(8.6, indicator.Beta);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
using System.Drawing;
|
||||
using System.Runtime.CompilerServices;
|
||||
using TradingPlatform.BusinessLayer;
|
||||
|
||||
namespace QuanTAlib;
|
||||
|
||||
[SkipLocalsInit]
|
||||
public sealed class KaiserIndicator : Indicator, IWatchlistIndicator
|
||||
{
|
||||
[InputParameter("Period", sortIndex: 1, 2, 2000, 1, 0)]
|
||||
public int Period { get; set; } = 14;
|
||||
|
||||
[InputParameter("Beta", sortIndex: 2, minimum: 0.0, maximum: 20.0, increment: 0.1, decimalPlaces: 1)]
|
||||
public double Beta { get; set; } = 3.0;
|
||||
|
||||
[IndicatorExtensions.DataSourceInput]
|
||||
public SourceType Source { get; set; } = SourceType.Close;
|
||||
|
||||
[InputParameter("Show cold values", sortIndex: 21)]
|
||||
public bool ShowColdValues { get; set; } = true;
|
||||
|
||||
private Kaiser _kaiser = 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 => $"KAISER {Period},{Beta:F1}:{_sourceName}";
|
||||
public override string SourceCodeLink => "https://github.com/mihakralj/QuanTAlib/blob/main/lib/trends_FIR/kaiser/Kaiser.Quantower.cs";
|
||||
|
||||
public KaiserIndicator()
|
||||
{
|
||||
OnBackGround = true;
|
||||
SeparateWindow = false;
|
||||
Name = "KAISER - Kaiser Window Moving Average";
|
||||
Description = "Kaiser Window Moving Average";
|
||||
_series = new LineSeries(name: $"KAISER {Period}", color: IndicatorExtensions.Averages, width: 2, style: LineStyle.Solid);
|
||||
AddLineSeries(_series);
|
||||
}
|
||||
|
||||
protected override void OnInit()
|
||||
{
|
||||
_priceSelector = Source.GetPriceSelector();
|
||||
_sourceName = Source.ToString();
|
||||
_kaiser = new Kaiser(Period, Beta);
|
||||
base.OnInit();
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
protected override void OnUpdate(UpdateArgs args)
|
||||
{
|
||||
bool isNew = args.IsNewBar();
|
||||
var item = HistoricalData[Count - 1, SeekOriginHistory.Begin];
|
||||
double value = _kaiser.Update(new TValue(item.TimeLeft.Ticks, _priceSelector(item)), isNew).Value;
|
||||
_series.SetValue(value, _kaiser.IsHot, ShowColdValues);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,410 @@
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public class KaiserTests
|
||||
{
|
||||
private const int DefaultPeriod = 14;
|
||||
private const double DefaultBeta = 3.0;
|
||||
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 Kaiser(period));
|
||||
Assert.Equal("period", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_NegativeBeta_Throws()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Kaiser(14, beta: -1.0));
|
||||
Assert.Equal("beta", ex.ParamName);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(2)]
|
||||
[InlineData(14)]
|
||||
[InlineData(100)]
|
||||
public void Constructor_ValidPeriod_Succeeds(int period)
|
||||
{
|
||||
var kaiser = new Kaiser(period);
|
||||
Assert.Contains(period.ToString(System.Globalization.CultureInfo.InvariantCulture), kaiser.Name, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_DefaultBeta_InName()
|
||||
{
|
||||
var kaiser = new Kaiser(14, 3.0);
|
||||
Assert.Equal("Kaiser(14,3.0)", kaiser.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_NullSource_Throws()
|
||||
{
|
||||
Assert.Throws<NullReferenceException>(() => new Kaiser(null!, DefaultPeriod));
|
||||
}
|
||||
|
||||
// ── B) Basic calculation ───────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Update_ReturnsTValue()
|
||||
{
|
||||
var kaiser = new Kaiser(DefaultPeriod);
|
||||
var result = kaiser.Update(new TValue(DateTime.UtcNow, 100.0));
|
||||
Assert.IsType<TValue>(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Last_IsAccessible()
|
||||
{
|
||||
var kaiser = new Kaiser(DefaultPeriod);
|
||||
kaiser.Update(new TValue(DateTime.UtcNow, 100.0));
|
||||
Assert.True(double.IsFinite(kaiser.Last.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Name_IsCorrect()
|
||||
{
|
||||
var kaiser = new Kaiser(14, 5.0);
|
||||
Assert.Equal("Kaiser(14,5.0)", kaiser.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Update_ReturnsFiniteValue()
|
||||
{
|
||||
var kaiser = new Kaiser(DefaultPeriod);
|
||||
foreach (var tv in _data)
|
||||
{
|
||||
var result = kaiser.Update(tv);
|
||||
Assert.True(double.IsFinite(result.Value));
|
||||
}
|
||||
}
|
||||
|
||||
// ── C) State + bar correction ──────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void IsNew_True_AdvancesState()
|
||||
{
|
||||
var kaiser = new Kaiser(5);
|
||||
var now = DateTime.UtcNow;
|
||||
kaiser.Update(new TValue(now, 10.0), isNew: true);
|
||||
kaiser.Update(new TValue(now.AddMinutes(1), 20.0), isNew: true);
|
||||
Assert.True(double.IsFinite(kaiser.Last.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsNew_False_RewritesCurrentBar()
|
||||
{
|
||||
var kaiser = new Kaiser(5, 3.0);
|
||||
var now = DateTime.UtcNow;
|
||||
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
kaiser.Update(new TValue(now.AddMinutes(i), 100.0 + i), isNew: true);
|
||||
}
|
||||
|
||||
double beforeCorrection = kaiser.Last.Value;
|
||||
kaiser.Update(new TValue(now.AddMinutes(9), 999.0), isNew: false);
|
||||
double afterCorrection = kaiser.Last.Value;
|
||||
|
||||
Assert.NotEqual(beforeCorrection, afterCorrection, Epsilon);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IterativeCorrections_Restore()
|
||||
{
|
||||
var kaiser = new Kaiser(5, 3.0);
|
||||
var now = DateTime.UtcNow;
|
||||
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
kaiser.Update(new TValue(now.AddMinutes(i), 100.0 + i), isNew: true);
|
||||
}
|
||||
|
||||
double original = kaiser.Last.Value;
|
||||
|
||||
for (int c = 0; c < 5; c++)
|
||||
{
|
||||
kaiser.Update(new TValue(now.AddMinutes(9), 200.0 + c), isNew: false);
|
||||
}
|
||||
|
||||
kaiser.Update(new TValue(now.AddMinutes(9), 109.0), isNew: false);
|
||||
Assert.Equal(original, kaiser.Last.Value, Epsilon);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reset_ClearsState()
|
||||
{
|
||||
var kaiser = new Kaiser(DefaultPeriod);
|
||||
foreach (var tv in _data)
|
||||
{
|
||||
kaiser.Update(tv);
|
||||
}
|
||||
|
||||
kaiser.Reset();
|
||||
Assert.False(kaiser.IsHot);
|
||||
}
|
||||
|
||||
// ── D) Warmup/convergence ──────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void IsHot_FlipsAtPeriod()
|
||||
{
|
||||
var kaiser = new Kaiser(5);
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
kaiser.Update(new TValue(DateTime.UtcNow, 100.0 + i));
|
||||
Assert.False(kaiser.IsHot);
|
||||
}
|
||||
kaiser.Update(new TValue(DateTime.UtcNow, 105.0));
|
||||
Assert.True(kaiser.IsHot);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WarmupPeriod_MatchesPeriod()
|
||||
{
|
||||
var kaiser = new Kaiser(10);
|
||||
Assert.Equal(10, kaiser.WarmupPeriod);
|
||||
}
|
||||
|
||||
// ── E) Robustness ──────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void NaN_UsesLastValidValue()
|
||||
{
|
||||
var kaiser = new Kaiser(5);
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
kaiser.Update(new TValue(DateTime.UtcNow, 100.0));
|
||||
}
|
||||
|
||||
kaiser.Update(new TValue(DateTime.UtcNow, double.NaN));
|
||||
Assert.True(double.IsFinite(kaiser.Last.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Infinity_UsesLastValidValue()
|
||||
{
|
||||
var kaiser = new Kaiser(5);
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
kaiser.Update(new TValue(DateTime.UtcNow, 100.0));
|
||||
}
|
||||
|
||||
kaiser.Update(new TValue(DateTime.UtcNow, double.PositiveInfinity));
|
||||
Assert.True(double.IsFinite(kaiser.Last.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BatchNaN_Safe()
|
||||
{
|
||||
var kaiser = new Kaiser(5);
|
||||
var src = MakeSeries(50);
|
||||
var result = kaiser.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;
|
||||
double beta = 3.0;
|
||||
var src = MakeSeries(100);
|
||||
|
||||
// Streaming
|
||||
var streaming = new Kaiser(period, beta);
|
||||
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 = Kaiser.Batch(src, period, beta);
|
||||
|
||||
// Span
|
||||
var spanOutput = new double[src.Count];
|
||||
Kaiser.Batch(src.Values, spanOutput, period, beta);
|
||||
|
||||
// Event-based
|
||||
var publisher = new TSeries();
|
||||
var eventKaiser = new Kaiser(publisher, period, beta);
|
||||
var eventResults = new double[src.Count];
|
||||
for (int i = 0; i < src.Count; i++)
|
||||
{
|
||||
publisher.Add(src[i], isNew: true);
|
||||
eventResults[i] = eventKaiser.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>(() => Kaiser.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>(() => Kaiser.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;
|
||||
Kaiser.Batch(src, output, 5);
|
||||
Assert.True(true);
|
||||
}
|
||||
|
||||
// ── H) Chainability ────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Pub_Fires()
|
||||
{
|
||||
var kaiser = new Kaiser(5);
|
||||
int count = 0;
|
||||
kaiser.Pub += (object? _, in TValueEventArgs _) => count++;
|
||||
kaiser.Update(new TValue(DateTime.UtcNow, 100.0));
|
||||
Assert.Equal(1, count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EventBased_Chaining()
|
||||
{
|
||||
var source = new TSeries();
|
||||
using var kaiser = new Kaiser(source, 5);
|
||||
|
||||
source.Add(new TValue(DateTime.UtcNow, 100.0), isNew: true);
|
||||
Assert.True(double.IsFinite(kaiser.Last.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Dispose_UnsubscribesFromSource()
|
||||
{
|
||||
var source = new TSeries();
|
||||
var kaiser = new Kaiser(source, 5);
|
||||
kaiser.Dispose();
|
||||
|
||||
source.Add(new TValue(DateTime.UtcNow, 100.0), isNew: true);
|
||||
Assert.Equal(default, kaiser.Last);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Dispose_Idempotent()
|
||||
{
|
||||
var kaiser = new Kaiser(5);
|
||||
kaiser.Dispose();
|
||||
kaiser.Dispose();
|
||||
Assert.True(true);
|
||||
}
|
||||
|
||||
// ── I) Kaiser-specific: beta behavior ──────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void BetaZero_ReducesToSma()
|
||||
{
|
||||
int period = 5;
|
||||
var kaiser = new Kaiser(period, beta: 0.0);
|
||||
var sma = new Sma(period);
|
||||
|
||||
var src = MakeSeries(50);
|
||||
for (int i = 0; i < src.Count; i++)
|
||||
{
|
||||
kaiser.Update(src[i]);
|
||||
sma.Update(src[i]);
|
||||
}
|
||||
|
||||
Assert.Equal(sma.Last.Value, kaiser.Last.Value, 1e-8);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HigherBeta_SmoothsMore()
|
||||
{
|
||||
var src = MakeSeries(100);
|
||||
int period = 14;
|
||||
|
||||
var kaiserLow = new Kaiser(period, beta: 1.0);
|
||||
var kaiserHigh = new Kaiser(period, beta: 8.0);
|
||||
|
||||
double sumDiffLow = 0;
|
||||
double sumDiffHigh = 0;
|
||||
|
||||
for (int i = 0; i < src.Count; i++)
|
||||
{
|
||||
double raw = src[i].Value;
|
||||
kaiserLow.Update(src[i]);
|
||||
kaiserHigh.Update(src[i]);
|
||||
|
||||
if (kaiserLow.IsHot && kaiserHigh.IsHot)
|
||||
{
|
||||
sumDiffLow += Math.Abs(raw - kaiserLow.Last.Value);
|
||||
sumDiffHigh += Math.Abs(raw - kaiserHigh.Last.Value);
|
||||
}
|
||||
}
|
||||
|
||||
Assert.True(sumDiffHigh >= sumDiffLow * 0.8);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ConstantInput_ReturnsConstant()
|
||||
{
|
||||
var kaiser = new Kaiser(7, 3.0);
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
kaiser.Update(new TValue(DateTime.UtcNow, 42.0));
|
||||
}
|
||||
Assert.Equal(42.0, kaiser.Last.Value, 1e-10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Calculate_ReturnsResultsAndIndicator()
|
||||
{
|
||||
var (results, indicator) = Kaiser.Calculate(_data, 14, 3.0);
|
||||
Assert.Equal(_data.Count, results.Count);
|
||||
Assert.True(indicator.IsHot);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Prime_SetsState()
|
||||
{
|
||||
var kaiser = new Kaiser(5, 3.0);
|
||||
var src = MakeSeries(20);
|
||||
kaiser.Prime(src.Values);
|
||||
Assert.True(kaiser.IsHot);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
using Xunit;
|
||||
|
||||
public class KaiserValidationTests
|
||||
{
|
||||
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;
|
||||
double beta = 3.0;
|
||||
|
||||
var streaming = new Kaiser(period, beta);
|
||||
var streamResults = new double[_data.Count];
|
||||
for (int i = 0; i < _data.Count; i++)
|
||||
{
|
||||
streamResults[i] = streaming.Update(_data[i]).Value;
|
||||
}
|
||||
|
||||
var batchResults = Kaiser.Batch(_data, period, beta);
|
||||
|
||||
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;
|
||||
double beta = 3.0;
|
||||
|
||||
var streaming = new Kaiser(period, beta);
|
||||
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];
|
||||
Kaiser.Batch(_data.Values, spanOutput, period, beta);
|
||||
|
||||
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 kaiser = new Kaiser(period, 3.0);
|
||||
foreach (var tv in _data)
|
||||
{
|
||||
var result = kaiser.Update(tv);
|
||||
Assert.True(double.IsFinite(result.Value));
|
||||
}
|
||||
Assert.True(kaiser.IsHot);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ConstantInput_ConvergesToConstant()
|
||||
{
|
||||
var kaiser = new Kaiser(10, 3.0);
|
||||
for (int i = 0; i < 50; i++)
|
||||
{
|
||||
kaiser.Update(new TValue(DateTime.UtcNow, 42.0));
|
||||
}
|
||||
Assert.Equal(42.0, kaiser.Last.Value, 1e-10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Calculate_ReturnsHotIndicator()
|
||||
{
|
||||
var (results, indicator) = Kaiser.Calculate(_data, 14, 3.0);
|
||||
Assert.True(indicator.IsHot);
|
||||
Assert.Equal(_data.Count, results.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BarCorrection_Consistency()
|
||||
{
|
||||
int period = 7;
|
||||
var kaiser = new Kaiser(period, 3.0);
|
||||
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
kaiser.Update(new TValue(DateTime.UtcNow, 100.0 + i), isNew: true);
|
||||
}
|
||||
|
||||
double original = kaiser.Last.Value;
|
||||
|
||||
kaiser.Update(new TValue(DateTime.UtcNow, 999.0), isNew: false);
|
||||
kaiser.Update(new TValue(DateTime.UtcNow, 119.0), isNew: false);
|
||||
|
||||
Assert.Equal(original, kaiser.Last.Value, 1e-10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SubsetStability()
|
||||
{
|
||||
int period = 10;
|
||||
double beta = 3.0;
|
||||
var src = MakeSeries(200);
|
||||
|
||||
var full = new Kaiser(period, beta);
|
||||
for (int i = 0; i < src.Count; i++)
|
||||
{
|
||||
full.Update(src[i]);
|
||||
}
|
||||
|
||||
var subset = new Kaiser(period, beta);
|
||||
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(3.0)]
|
||||
[InlineData(5.65)]
|
||||
[InlineData(8.6)]
|
||||
public void DifferentBetas_ProduceValidResults(double beta)
|
||||
{
|
||||
var kaiser = new Kaiser(14, beta);
|
||||
foreach (var tv in _data)
|
||||
{
|
||||
var result = kaiser.Update(tv);
|
||||
Assert.True(double.IsFinite(result.Value));
|
||||
}
|
||||
Assert.True(kaiser.IsHot);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,418 @@
|
||||
using System.Buffers;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace QuanTAlib;
|
||||
|
||||
/// <summary>
|
||||
/// KAISER: Kaiser Window Moving Average
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Symmetric FIR filter using the Kaiser-Bessel window function for optimal
|
||||
/// sidelobe attenuation. The beta parameter continuously controls the trade-off
|
||||
/// between main lobe width (transition band sharpness) and sidelobe attenuation.
|
||||
///
|
||||
/// Calculation: Precomputed weights via modified Bessel function I0, applied as
|
||||
/// FIR convolution over sliding window. Beta=0 gives SMA, beta≈5.65 Blackman,
|
||||
/// beta≈8.6 Hamming.
|
||||
/// </remarks>
|
||||
/// <seealso href="Kaiser.md">Detailed documentation</seealso>
|
||||
[SkipLocalsInit]
|
||||
public sealed class Kaiser : AbstractBase
|
||||
{
|
||||
private readonly int _period;
|
||||
private readonly double _beta;
|
||||
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 KAISER with specified period and beta.
|
||||
/// </summary>
|
||||
/// <param name="period">Lookback period (>= 2)</param>
|
||||
/// <param name="beta">Shape parameter controlling sidelobe attenuation (0..20, default 3.0)</param>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public Kaiser(int period = 14, double beta = 3.0)
|
||||
{
|
||||
if (period < 2)
|
||||
{
|
||||
throw new ArgumentException("Period must be at least 2", nameof(period));
|
||||
}
|
||||
if (beta < 0)
|
||||
{
|
||||
throw new ArgumentException("Beta must be non-negative", nameof(beta));
|
||||
}
|
||||
|
||||
_period = period;
|
||||
_beta = beta;
|
||||
Name = $"Kaiser({_period},{_beta:F1})";
|
||||
WarmupPeriod = _period;
|
||||
|
||||
_buffer = new RingBuffer(_period);
|
||||
_weights = new double[_period];
|
||||
|
||||
ComputeKaiserWeights(_weights, _period, _beta);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates KAISER connected to a data source for event-based updates.
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public Kaiser(ITValuePublisher source, int period = 14, double beta = 3.0) : this(period, beta)
|
||||
{
|
||||
_source = source;
|
||||
_pubHandler = Handle;
|
||||
_source.Pub += _pubHandler;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Modified Bessel function of the first kind, order 0.
|
||||
/// 25-term power series: I0(x) = sum_{m=0}^{25} [(x/2)^m / m!]^2
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static double BesselI0(double x)
|
||||
{
|
||||
double sum = 1.0;
|
||||
double term = 1.0;
|
||||
double halfX = x * 0.5;
|
||||
for (int m = 1; m <= 25; m++)
|
||||
{
|
||||
term *= halfX / m;
|
||||
sum += term * term;
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes Kaiser window weights and normalizes to sum=1.
|
||||
/// w(k) = I0(beta * sqrt(1 - t^2)) / I0(beta), where t = 2k/(N-1) - 1.
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static void ComputeKaiserWeights(Span<double> weights, int period, double beta)
|
||||
{
|
||||
double i0Beta = BesselI0(beta);
|
||||
double nm1 = period - 1;
|
||||
|
||||
double wsum = 0.0;
|
||||
for (int k = 0; k < period; k++)
|
||||
{
|
||||
double t = nm1 > 0 ? (2.0 * k / nm1) - 1.0 : 0.0;
|
||||
double argSq = 1.0 - t * t;
|
||||
double arg = argSq > 0 ? Math.Sqrt(argSq) : 0.0;
|
||||
double w = i0Beta > 0 ? BesselI0(beta * arg) / i0Beta : 1.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, _beta);
|
||||
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, double beta = 3.0)
|
||||
{
|
||||
var kaiser = new Kaiser(period, beta);
|
||||
return kaiser.Update(source);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Calculates Kaiser 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 beta = 3.0, 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);
|
||||
|
||||
ComputeKaiserWeights(weights, period, beta);
|
||||
|
||||
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, Kaiser Indicator) Calculate(TSeries source, int period = 14, double beta = 3.0)
|
||||
{
|
||||
var indicator = new Kaiser(period, beta);
|
||||
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