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
+159
View File
@@ -0,0 +1,159 @@
using TradingPlatform.BusinessLayer;
namespace QuanTAlib.Tests;
public class HendIndicatorTests
{
[Fact]
public void HendIndicator_Constructor_SetsDefaults()
{
var indicator = new HendIndicator();
Assert.Equal(7, indicator.Period);
Assert.Equal(SourceType.Close, indicator.Source);
Assert.True(indicator.ShowColdValues);
Assert.Equal("HEND - Henderson Moving Average", indicator.Name);
Assert.False(indicator.SeparateWindow);
Assert.True(indicator.OnBackGround);
}
[Fact]
public void HendIndicator_MinHistoryDepths_IsZero()
{
var indicator = new HendIndicator { Period = 13 };
Assert.Equal(0, HendIndicator.MinHistoryDepths);
Assert.Equal(0, ((IWatchlistIndicator)indicator).MinHistoryDepths);
}
[Fact]
public void HendIndicator_ShortName_IncludesPeriodAndSource()
{
var indicator = new HendIndicator { Period = 9 };
Assert.Contains("HEND", indicator.ShortName, StringComparison.Ordinal);
Assert.Contains("9", indicator.ShortName, StringComparison.Ordinal);
}
[Fact]
public void HendIndicator_SourceCodeLink_IsValid()
{
var indicator = new HendIndicator();
Assert.Contains("github.com", indicator.SourceCodeLink, StringComparison.Ordinal);
Assert.Contains("Hend.Quantower.cs", indicator.SourceCodeLink, StringComparison.Ordinal);
}
[Fact]
public void HendIndicator_Initialize_CreatesInternalHend()
{
var indicator = new HendIndicator { Period = 7 };
indicator.Initialize();
Assert.Single(indicator.LinesSeries);
}
[Fact]
public void HendIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
{
var indicator = new HendIndicator { 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 HendIndicator_ProcessUpdate_NewBar_ComputesValue()
{
var indicator = new HendIndicator { 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 HendIndicator_ProcessUpdate_NewTick_ProcessesWithoutError()
{
var indicator = new HendIndicator { 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 HendIndicator_MultipleUpdates_ProducesCorrectSequence()
{
var indicator = new HendIndicator { 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 HendIndicator_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 HendIndicator { 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 HendIndicator_Period_CanBeChanged()
{
var indicator = new HendIndicator { Period = 7 };
Assert.Equal(7, indicator.Period);
indicator.Period = 13;
Assert.Equal(13, indicator.Period);
Assert.Equal(0, HendIndicator.MinHistoryDepths);
}
}
+56
View File
@@ -0,0 +1,56 @@
using System.Drawing;
using System.Runtime.CompilerServices;
using TradingPlatform.BusinessLayer;
namespace QuanTAlib;
[SkipLocalsInit]
public sealed class HendIndicator : Indicator, IWatchlistIndicator
{
[InputParameter("Period", sortIndex: 1, 5, 2000, 2, 0)]
public int Period { get; set; } = 7;
[IndicatorExtensions.DataSourceInput]
public SourceType Source { get; set; } = SourceType.Close;
[InputParameter("Show cold values", sortIndex: 21)]
public bool ShowColdValues { get; set; } = true;
private Hend _hend = 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 => $"HEND {Period}:{_sourceName}";
public override string SourceCodeLink => "https://github.com/mihakralj/QuanTAlib/blob/main/lib/trends_FIR/hend/Hend.Quantower.cs";
public HendIndicator()
{
OnBackGround = true;
SeparateWindow = false;
Name = "HEND - Henderson Moving Average";
Description = "Henderson Moving Average";
_series = new LineSeries(name: $"HEND {Period}", color: IndicatorExtensions.Averages, width: 2, style: LineStyle.Solid);
AddLineSeries(_series);
}
protected override void OnInit()
{
_priceSelector = Source.GetPriceSelector();
_sourceName = Source.ToString();
_hend = new Hend(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 = _hend.Update(new TValue(item.TimeLeft.Ticks, _priceSelector(item)), isNew).Value;
_series.SetValue(value, _hend.IsHot, ShowColdValues);
}
}
+461
View File
@@ -0,0 +1,461 @@
using Xunit;
namespace QuanTAlib.Tests;
public class HendTests
{
private const int DefaultPeriod = 7;
private const double Epsilon = 1e-10;
// ── A) Constructor validation ──────────────────────────────────────
[Fact]
public void Constructor_PeriodTooSmall_Throws()
{
var ex = Assert.Throws<ArgumentException>(() => new Hend(period: 3));
Assert.Equal("period", ex.ParamName);
}
[Fact]
public void Constructor_ValidPeriod_SetsName()
{
var hend = new Hend(period: 7);
Assert.Equal("Hend(7)", hend.Name);
}
[Fact]
public void Constructor_EvenPeriod_AdjustedToOdd()
{
var hend = new Hend(period: 8);
Assert.Equal("Hend(9)", hend.Name);
}
[Fact]
public void Constructor_MinPeriod5_Works()
{
var hend = new Hend(period: 5);
Assert.Equal("Hend(5)", hend.Name);
}
// ── B) Basic calculation ───────────────────────────────────────────
[Fact]
public void Update_ReturnsTValue()
{
var hend = new Hend(DefaultPeriod);
var result = hend.Update(new TValue(DateTime.UtcNow, 100.0));
Assert.IsType<TValue>(result);
}
[Fact]
public void Last_IsAccessible()
{
var hend = new Hend(DefaultPeriod);
hend.Update(new TValue(DateTime.UtcNow, 50.0));
Assert.Equal(50.0, hend.Last.Value, Epsilon);
}
[Fact]
public void ConstantInput_ReturnsConstant()
{
var hend = new Hend(5);
const double c = 42.0;
for (int i = 0; i < 20; i++)
{
hend.Update(new TValue(DateTime.UtcNow.AddSeconds(i), c));
}
Assert.Equal(c, hend.Last.Value, 1e-9);
}
[Fact]
public void LinearTrend_PreservedExactly()
{
// Henderson preserves up to cubic polynomials at the CENTER of the window.
// For period=5, half=2, the output at bar N represents polynomial at index N-2.
const int period = 5;
int half = (period - 1) / 2;
var hend = new Hend(period);
int total = 20;
double lastResult = double.NaN;
for (int i = 0; i < total; i++)
{
double val = 10.0 + 3.0 * i;
var result = hend.Update(new TValue(DateTime.UtcNow.AddSeconds(i), val));
lastResult = result.Value;
}
// Centered filter: output at bar N = polynomial value at bar N - half
int centerIdx = total - 1 - half;
double expected = 10.0 + 3.0 * centerIdx;
Assert.Equal(expected, lastResult, 1e-6);
}
[Fact]
public void QuadraticTrend_PreservedExactly()
{
const int period = 5;
int half = (period - 1) / 2;
var hend = new Hend(period);
int total = 20;
double lastResult = double.NaN;
for (int i = 0; i < total; i++)
{
double val = 5.0 + 2.0 * i + 0.5 * i * i;
var result = hend.Update(new TValue(DateTime.UtcNow.AddSeconds(i), val));
lastResult = result.Value;
}
int centerIdx = total - 1 - half;
double expected = 5.0 + 2.0 * centerIdx + 0.5 * centerIdx * centerIdx;
Assert.Equal(expected, lastResult, 1e-4);
}
[Fact]
public void CubicTrend_PreservedExactly()
{
const int period = 5;
int half = (period - 1) / 2;
var hend = new Hend(period);
int total = 20;
double lastResult = double.NaN;
for (int i = 0; i < total; i++)
{
double val = 1.0 + 0.5 * i + 0.1 * i * i + 0.01 * i * i * i;
var result = hend.Update(new TValue(DateTime.UtcNow.AddSeconds(i), val));
lastResult = result.Value;
}
int centerIdx = total - 1 - half;
double expected = 1.0 + 0.5 * centerIdx + 0.1 * centerIdx * centerIdx + 0.01 * centerIdx * centerIdx * centerIdx;
Assert.Equal(expected, lastResult, 1e-2);
}
// ── C) State + bar correction ──────────────────────────────────────
[Fact]
public void IsNew_True_AdvancesState()
{
var hend = new Hend(5);
for (int i = 0; i < 10; i++)
{
hend.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100 + i), isNew: true);
}
Assert.True(hend.IsHot);
}
[Fact]
public void IsNew_False_Rewrites()
{
var hend = new Hend(5);
for (int i = 0; i < 6; i++)
{
hend.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0), isNew: true);
}
var before = hend.Last.Value;
// Bar correction with different value
hend.Update(new TValue(DateTime.UtcNow.AddSeconds(5), 200.0), isNew: false);
var corrected = hend.Last.Value;
// Should be different since one value changed
Assert.NotEqual(before, corrected);
}
[Fact]
public void IterativeCorrections_Restore()
{
var hend = new Hend(5);
for (int i = 0; i < 10; i++)
{
hend.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 50.0 + i), isNew: true);
}
var snapshot = hend.Last.Value;
// Multiple corrections, then re-send same value
hend.Update(new TValue(DateTime.UtcNow.AddSeconds(10), 999.0), isNew: false);
hend.Update(new TValue(DateTime.UtcNow.AddSeconds(10), 888.0), isNew: false);
hend.Update(new TValue(DateTime.UtcNow.AddSeconds(10), 50.0 + 9), isNew: false);
// Last correction with original value should restore
Assert.Equal(snapshot, hend.Last.Value, 1e-10);
}
[Fact]
public void Reset_ClearsState()
{
var hend = new Hend(5);
for (int i = 0; i < 10; i++)
{
hend.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0));
}
Assert.True(hend.IsHot);
hend.Reset();
Assert.False(hend.IsHot);
Assert.Equal(default, hend.Last);
}
// ── D) Warmup / convergence ────────────────────────────────────────
[Fact]
public void IsHot_FlipsWhenBufferFull()
{
var hend = new Hend(5);
for (int i = 0; i < 4; i++)
{
hend.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0));
Assert.False(hend.IsHot);
}
hend.Update(new TValue(DateTime.UtcNow.AddSeconds(4), 100.0));
Assert.True(hend.IsHot);
}
[Fact]
public void WarmupPeriod_EqualsUserPeriod()
{
var hend = new Hend(7);
Assert.Equal(7, hend.WarmupPeriod);
}
// ── E) Robustness ──────────────────────────────────────────────────
[Fact]
public void NaN_SubstitutesLastValid()
{
var hend = new Hend(5);
for (int i = 0; i < 6; i++)
{
hend.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0));
}
// Send NaN - should substitute last valid
hend.Update(new TValue(DateTime.UtcNow.AddSeconds(6), double.NaN));
Assert.True(double.IsFinite(hend.Last.Value));
}
[Fact]
public void Infinity_SubstitutesLastValid()
{
var hend = new Hend(5);
for (int i = 0; i < 6; i++)
{
hend.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0));
}
hend.Update(new TValue(DateTime.UtcNow.AddSeconds(6), double.PositiveInfinity));
Assert.True(double.IsFinite(hend.Last.Value));
}
[Fact]
public void BatchNaN_Safe()
{
double[] src = [1, 2, double.NaN, 4, 5, 6, 7, 8, 9, 10];
double[] output = new double[src.Length];
Hend.Batch(src, output, period: 5);
for (int i = 0; i < output.Length; i++)
{
Assert.True(double.IsFinite(output[i]), $"output[{i}] is not finite");
}
}
// ── F) Consistency ─────────────────────────────────────────────────
[Fact]
public void Batch_MatchesStreaming()
{
const int len = 50;
var source = new TSeries();
var gbm = new GBM(startPrice: 100, seed: 42);
for (int i = 0; i < len; i++)
{
var bar = gbm.Next();
source.Add(bar.C);
}
// Streaming
var hend = new Hend(DefaultPeriod);
var streaming = new double[len];
for (int i = 0; i < len; i++)
{
var result = hend.Update(source[i]);
streaming[i] = result.Value;
}
// Batch TSeries
var batchResult = Hend.Batch(source, DefaultPeriod);
for (int i = 0; i < len; i++)
{
Assert.Equal(streaming[i], batchResult[i].Value, 1e-10);
}
}
[Fact]
public void Span_MatchesStreaming()
{
const int len = 50;
var source = new TSeries();
var gbm = new GBM(startPrice: 100, seed: 42);
for (int i = 0; i < len; i++)
{
var bar = gbm.Next();
source.Add(bar.C);
}
// Streaming
var hend = new Hend(DefaultPeriod);
var streaming = new double[len];
for (int i = 0; i < len; i++)
{
var result = hend.Update(source[i]);
streaming[i] = result.Value;
}
// Span
double[] spanOutput = new double[len];
Hend.Batch(source.Values, spanOutput, DefaultPeriod);
for (int i = 0; i < len; i++)
{
Assert.Equal(streaming[i], spanOutput[i], 1e-10);
}
}
// ── G) Span API tests ──────────────────────────────────────────────
[Fact]
public void Batch_Span_MismatchedLengths_Throws()
{
double[] src = [1, 2, 3, 4, 5];
double[] output = new double[3];
var ex = Assert.Throws<ArgumentException>(() => Hend.Batch(src, output, period: 5));
Assert.Equal("output", ex.ParamName);
}
[Fact]
public void Batch_Span_PeriodTooSmall_Throws()
{
double[] src = [1, 2, 3];
double[] output = new double[3];
var ex = Assert.Throws<ArgumentException>(() => Hend.Batch(src, output, period: 3));
Assert.Equal("period", ex.ParamName);
}
[Fact]
public void Batch_Span_EmptyInput_NoOp()
{
Hend.Batch(ReadOnlySpan<double>.Empty, Span<double>.Empty, period: 5);
Assert.True(true); // no-throw is the assertion
}
// ── H) Chainability ────────────────────────────────────────────────
[Fact]
public void Pub_Fires()
{
var hend = new Hend(5);
bool fired = false;
hend.Pub += (object? sender, in TValueEventArgs e) => fired = true;
hend.Update(new TValue(DateTime.UtcNow, 100.0));
Assert.True(fired);
}
[Fact]
public void EventBased_Chaining()
{
var source = new TSeries();
var hend = new Hend(source, period: 5);
for (int i = 0; i < 10; i++)
{
source.Add(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0 + i));
}
Assert.True(hend.IsHot);
Assert.True(double.IsFinite(hend.Last.Value));
}
// ── I) Dispose ─────────────────────────────────────────────────────
[Fact]
public void Dispose_Idempotent()
{
var hend = new Hend(5);
hend.Dispose();
hend.Dispose(); // Should not throw
Assert.True(true); // no-throw is the assertion
}
[Fact]
public void Dispose_UnsubscribesFromSource()
{
var source = new TSeries();
var hend = new Hend(source, period: 5);
hend.Dispose();
// Adding to source after dispose should not affect hend
source.Add(new TValue(DateTime.UtcNow, 999.0));
Assert.False(hend.IsHot);
}
// ── J) Henderson-specific: Wolfram-verified H5 weights ─────────────
[Fact]
public void H5_ConstInput_ReturnsConstant()
{
// Wolfram-verified: H5 weights = {-21/286, 42/143, 80/143, 42/143, -21/286}
// For constant input, sum of weights * constant = constant (weights sum to 1)
var hend = new Hend(5);
const double c = 100.0;
for (int i = 0; i < 5; i++)
{
hend.Update(new TValue(DateTime.UtcNow.AddSeconds(i), c));
}
Assert.Equal(c, hend.Last.Value, 1e-10);
}
[Fact]
public void H5_NegativeEdgeWeights_BandpassProperty()
{
// Henderson has negative weights at edges — verify filter can output
// values outside the min-max range of inputs (bandpass property)
var hend = new Hend(5);
// Step function: 0,0,100,0,0 — negative edge weights will push result outside [0,100]
double[] vals = [0, 0, 100, 0, 0];
TValue result = default;
for (int i = 0; i < 5; i++)
{
result = hend.Update(new TValue(DateTime.UtcNow.AddSeconds(i), vals[i]));
}
// Henderson H5 center weight = 80/143 ≈ 0.5594
// Expected: 0*w0 + 0*w1 + 100*w2 + 0*w3 + 0*w4 = 100 * 80/143 ≈ 55.944
double expected = 100.0 * 80.0 / 143.0;
Assert.Equal(expected, result.Value, 1e-6);
}
[Fact]
public void H5_Symmetric_Weights()
{
// Henderson weights are symmetric: w(k) = w(-k)
// Reversing the input order of a symmetric window should give same center value
var hend1 = new Hend(5);
var hend2 = new Hend(5);
double[] forward = [10, 20, 30, 40, 50];
double[] reverse = [50, 40, 30, 20, 10];
TValue r1 = default, r2 = default;
for (int i = 0; i < 5; i++)
{
r1 = hend1.Update(new TValue(DateTime.UtcNow.AddSeconds(i), forward[i]));
r2 = hend2.Update(new TValue(DateTime.UtcNow.AddSeconds(i), reverse[i]));
}
// For linear input, Henderson preserves the polynomial, so both
// should give 30 (the center value of the linear trend)
// forward: 10+20+30+40+50, reverse: 50+40+30+20+10
// With symmetric weights applied, sum(w*forward) + sum(w*reverse) = 2*30*sum(w) = 60
Assert.Equal(60.0, r1.Value + r2.Value, 1e-6);
}
}
@@ -0,0 +1,160 @@
using Xunit;
using Xunit.Abstractions;
namespace QuanTAlib.Tests;
public class HendValidationTests(ITestOutputHelper output)
{
private readonly ValidationTestData _testData = new();
private readonly ITestOutputHelper _output = output;
private const int DefaultPeriod = 7;
// ── Batch vs Streaming consistency ──────────────────────────────────
[Fact]
public void BatchVsStreaming_Match()
{
var source = new TSeries();
var gbm = new GBM(startPrice: 100, seed: 42);
const int count = 100;
for (int i = 0; i < count; i++)
{
var bar = gbm.Next();
source.Add(bar.C);
}
// Streaming
var hend = new Hend(DefaultPeriod);
var streaming = new double[count];
for (int i = 0; i < count; i++)
{
streaming[i] = hend.Update(source[i]).Value;
}
// Batch
var batchResult = Hend.Batch(source, DefaultPeriod);
for (int i = 0; i < count; i++)
{
Assert.Equal(streaming[i], batchResult[i].Value, 1e-10);
}
}
// ── Span vs Streaming consistency ──────────────────────────────────
[Fact]
public void SpanVsStreaming_Match()
{
var source = new TSeries();
var gbm = new GBM(startPrice: 100, seed: 42);
const int count = 100;
for (int i = 0; i < count; i++)
{
var bar = gbm.Next();
source.Add(bar.C);
}
// Streaming
var hend = new Hend(DefaultPeriod);
var streaming = new double[count];
for (int i = 0; i < count; i++)
{
streaming[i] = hend.Update(source[i]).Value;
}
// Span
double[] spanOutput = new double[count];
Hend.Batch(source.Values, spanOutput, DefaultPeriod);
for (int i = 0; i < count; i++)
{
Assert.Equal(streaming[i], spanOutput[i], 1e-10);
}
}
// ── Polynomial exact-fit validation ────────────────────────────────
[Fact]
public void LinearPolynomial_ExactFit()
{
// Henderson preserves linear trends at the CENTER of the window.
// For period=7, half=3, output at bar N = polynomial at bar N-3.
int half = (DefaultPeriod - 1) / 2;
var hend = new Hend(DefaultPeriod);
const int total = 50;
const double a = 5.0, b = 3.0;
for (int i = 0; i < total; i++)
{
double val = a + b * i;
hend.Update(new TValue(DateTime.UtcNow.AddSeconds(i), val));
}
int centerIdx = total - 1 - half;
double expected = a + b * centerIdx;
_output.WriteLine($"Linear: expected={expected}, actual={hend.Last.Value}");
Assert.Equal(expected, hend.Last.Value, 1e-6);
}
[Fact]
public void QuadraticPolynomial_ExactFit()
{
int half = (DefaultPeriod - 1) / 2;
var hend = new Hend(DefaultPeriod);
const int total = 50;
const double a = 2.0, b = 1.5, c = 0.3;
for (int i = 0; i < total; i++)
{
double val = a + b * i + c * i * i;
hend.Update(new TValue(DateTime.UtcNow.AddSeconds(i), val));
}
int centerIdx = total - 1 - half;
double expected = a + b * centerIdx + c * centerIdx * centerIdx;
_output.WriteLine($"Quadratic: expected={expected}, actual={hend.Last.Value}");
Assert.Equal(expected, hend.Last.Value, 0.1);
}
[Fact]
public void CubicPolynomial_ExactFit()
{
int half = (DefaultPeriod - 1) / 2;
var hend = new Hend(DefaultPeriod);
const int total = 50;
const double a = 1.0, b = 0.5, c = 0.1, d = 0.005;
for (int i = 0; i < total; i++)
{
double val = a + b * i + c * i * i + d * i * i * i;
hend.Update(new TValue(DateTime.UtcNow.AddSeconds(i), val));
}
int centerIdx = total - 1 - half;
double expected = a + b * centerIdx + c * centerIdx * centerIdx + d * centerIdx * centerIdx * centerIdx;
_output.WriteLine($"Cubic: expected={expected}, actual={hend.Last.Value}");
Assert.Equal(expected, hend.Last.Value, 1.0);
}
// ── Calculate returns hot indicator ─────────────────────────────────
[Fact]
public void Calculate_ReturnsHotIndicator()
{
var source = new TSeries();
var gbm = new GBM(startPrice: 100, seed: 42);
for (int i = 0; i < 50; i++)
{
var bar = gbm.Next();
source.Add(bar.C);
}
var (results, indicator) = Hend.Calculate(source, DefaultPeriod);
Assert.True(indicator.IsHot);
Assert.Equal(50, results.Count);
}
}
+426
View File
@@ -0,0 +1,426 @@
using System.Buffers;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace QuanTAlib;
/// <summary>
/// HEND: Henderson Moving Average
/// </summary>
/// <remarks>
/// Symmetric FIR filter from the X-11 seasonal adjustment framework that
/// preserves cubic polynomial trends without distortion. Weights are derived
/// from the closed-form Henderson formula and can be negative at edges.
///
/// Calculation: Precomputed weights via Henderson (1916) closed-form formula,
/// applied as FIR convolution over sliding window. Period must be odd >= 5.
/// </remarks>
/// <seealso href="Hend.md">Detailed documentation</seealso>
[SkipLocalsInit]
public sealed class Hend : 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 HEND with specified period.
/// </summary>
/// <param name="period">Lookback period (must be odd, >= 5)</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Hend(int period = 7)
{
if (period < 5)
{
throw new ArgumentException("Period must be at least 5", nameof(period));
}
// Ensure period is odd
_period = period % 2 == 0 ? period + 1 : period;
Name = $"Hend({_period})";
WarmupPeriod = _period;
_buffer = new RingBuffer(_period);
_weights = new double[_period];
ComputeHendersonWeights(_weights, _period);
}
/// <summary>
/// Creates HEND connected to a data source for event-based updates.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Hend(ITValuePublisher source, int period = 7) : this(period)
{
_source = source;
_pubHandler = Handle;
_source.Pub += _pubHandler;
}
/// <summary>
/// Computes Henderson filter weights using the closed-form formula.
/// w(k) = 315 * [(n-1)²-k²][(n²-k²)][(n+1)²-k²][3n²-16-11k²]
/// / {8n(n²-1)(4n²-1)(4n²-9)(4n²-25)}
/// where n = (period+3)/2, k ranges from -(period-1)/2 to (period-1)/2.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void ComputeHendersonWeights(Span<double> weights, int period)
{
int half = (period - 1) / 2;
double n = (period + 3) * 0.5;
double n2 = n * n;
double nm1_2 = (n - 1) * (n - 1);
double np1_2 = (n + 1) * (n + 1);
double denom = 8.0 * n * (n2 - 1) * (4 * n2 - 1) * (4 * n2 - 9) * (4 * n2 - 25);
double wsum = 0.0;
for (int i = 0; i < period; i++)
{
int k = i - half;
double k2 = (double)(k * k);
double w = 315.0 * (nm1_2 - k2) * (n2 - k2) * (np1_2 - k2) * (3 * n2 - 16 - 11 * k2) / denom;
weights[i] = w;
wsum += w;
}
// Normalize to sum=1.0 (handles floating-point drift)
if (Math.Abs(wsum) > double.Epsilon)
{
double inv = 1.0 / wsum;
for (int i = 0; i < period; i++)
{
weights[i] *= inv;
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override TValue Update(TValue input, bool isNew = true)
{
_isNew = isNew;
return Update(input, isNew, publish: true);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private TValue Update(TValue input, bool isNew, bool publish)
{
if (isNew)
{
_p_lastValidValue = _lastValidValue;
}
else
{
_lastValidValue = _p_lastValidValue;
}
double val = GetValidValue(input.Value);
if (!double.IsFinite(val))
{
Last = new TValue(input.Time, double.NaN);
if (publish) { PubEvent(Last, isNew); }
return Last;
}
if (isNew)
{
_lastValidValue = val;
_buffer.Add(val);
int count = _buffer.Count;
double result;
if (count < _period)
{
// During warmup, return raw value (matching Pine behavior)
result = val;
}
else
{
// Full window: apply Henderson FIR convolution via DotProduct
result = ConvolveFull(_buffer, _weights);
}
Last = new TValue(input.Time, result);
if (publish) { PubEvent(Last, isNew); }
return Last;
}
else
{
// Bar correction: snapshot, compute, restore
_buffer.Snapshot();
double prevLast = _lastValidValue;
double prevPLast = _p_lastValidValue;
_lastValidValue = val;
_buffer.UpdateNewest(val);
int count = _buffer.Count;
double result;
if (count < _period)
{
result = val;
}
else
{
result = ConvolveFull(_buffer, _weights);
}
Last = new TValue(input.Time, result);
// Restore buffer and state
_buffer.Restore();
_lastValidValue = prevLast;
_p_lastValidValue = prevPLast;
if (publish) { PubEvent(Last, isNew); }
return Last;
}
}
public override TSeries Update(TSeries source)
{
if (source.Count == 0)
{
return new TSeries([], []);
}
int len = source.Count;
var t = new List<long>(len);
var v = new List<double>(len);
CollectionsMarshal.SetCount(t, len);
CollectionsMarshal.SetCount(v, len);
var tSpan = CollectionsMarshal.AsSpan(t);
var vSpan = CollectionsMarshal.AsSpan(v);
Batch(source.Values, vSpan, _period);
source.Times.CopyTo(tSpan);
// Restore state by replaying last period bars
Reset();
int startIndex = Math.Max(0, len - _period);
for (int i = startIndex; i < len; i++)
{
Update(source[i], isNew: true, publish: false);
}
return new TSeries(t, v);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void Handle(object? sender, in TValueEventArgs e) => Update(e.Value, e.IsNew);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private double GetValidValue(double input)
{
if (double.IsFinite(input))
{
return input;
}
return double.IsFinite(_lastValidValue) ? _lastValidValue : double.NaN;
}
/// <summary>
/// FIR convolution using SIMD DotProduct over circular buffer.
/// Weight[0] corresponds to oldest bar, Weight[period-1] to newest.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static double ConvolveFull(RingBuffer buffer, double[] weights)
{
ReadOnlySpan<double> internalBuf = buffer.InternalBuffer;
int head = buffer.StartIndex;
int period = buffer.Capacity;
int part1Len = period - head;
double sum1 = internalBuf.Slice(head, part1Len).DotProduct(weights.AsSpan(0, part1Len));
double sum2 = internalBuf[..head].DotProduct(weights.AsSpan(part1Len));
return sum1 + sum2;
}
public override void Prime(ReadOnlySpan<double> source, TimeSpan? step = null)
{
foreach (var value in source)
{
Update(new TValue(DateTime.MinValue, value));
}
}
/// <summary>
/// Calculates HEND from a TSeries using streaming updates.
/// </summary>
public static TSeries Batch(TSeries source, int period = 7)
{
var hend = new Hend(period);
return hend.Update(source);
}
/// <summary>
/// Calculates Henderson Moving Average over a span of values.
/// </summary>
/// <param name="source">Input values</param>
/// <param name="output">Output buffer (must be same length as source)</param>
/// <param name="period">Period for weight calculation (must be odd, >= 5)</param>
/// <param name="nanValue">Value to use for NaN substitution (default: NaN)</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Batch(ReadOnlySpan<double> source, Span<double> output, int period = 7, double nanValue = double.NaN)
{
if (period < 5)
{
throw new ArgumentException("Period must be at least 5", 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 usePeriod = period % 2 == 0 ? period + 1 : period;
int len = source.Length;
const int StackallocThreshold = 256;
// Allocate weights
double[]? weightsRented = usePeriod > StackallocThreshold ? ArrayPool<double>.Shared.Rent(usePeriod) : null;
Span<double> weights = usePeriod <= StackallocThreshold
? stackalloc double[usePeriod]
: weightsRented!.AsSpan(0, usePeriod);
// Allocate ring buffer
double[]? ringRented = usePeriod > StackallocThreshold ? ArrayPool<double>.Shared.Rent(usePeriod) : null;
Span<double> ring = usePeriod <= StackallocThreshold
? stackalloc double[usePeriod]
: ringRented!.AsSpan(0, usePeriod);
// Allocate NaN-corrected values array
double[]? cleanRented = len > StackallocThreshold ? ArrayPool<double>.Shared.Rent(len) : null;
Span<double> clean = len <= StackallocThreshold
? stackalloc double[len]
: cleanRented!.AsSpan(0, len);
ComputeHendersonWeights(weights, usePeriod);
try
{
// Build NaN-corrected values array
double lastValid = nanValue;
for (int i = 0; i < len; i++)
{
double val = source[i];
if (double.IsFinite(val))
{
lastValid = val;
clean[i] = val;
}
else if (double.IsFinite(lastValid))
{
clean[i] = lastValid;
}
else
{
clean[i] = double.NaN;
}
}
// Apply Henderson FIR convolution
int ringIdx = 0;
int count = 0;
for (int i = 0; i < len; i++)
{
double val = clean[i];
ring[ringIdx] = val;
ringIdx++;
if (ringIdx >= usePeriod)
{
ringIdx = 0;
}
if (count < usePeriod)
{
count++;
}
if (count < usePeriod)
{
// Warmup: return raw value
output[i] = val;
continue;
}
// Full window: DotProduct convolution over circular buffer
// ringIdx points to next-write = oldest entry
int part1Len = usePeriod - ringIdx;
ReadOnlySpan<double> ringRo = ring;
double sum = ringRo.Slice(ringIdx, part1Len).DotProduct(weights.Slice(0, part1Len))
+ ringRo[..ringIdx].DotProduct(weights.Slice(part1Len));
output[i] = sum;
}
}
finally
{
if (weightsRented != null)
{
ArrayPool<double>.Shared.Return(weightsRented);
}
if (ringRented != null)
{
ArrayPool<double>.Shared.Return(ringRented);
}
if (cleanRented != null)
{
ArrayPool<double>.Shared.Return(cleanRented);
}
}
}
/// <summary>
/// Creates a HEND indicator and calculates results from source.
/// </summary>
public static (TSeries Results, Hend Indicator) Calculate(TSeries source, int period = 7)
{
var indicator = new Hend(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);
}
}