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 IlrsIndicatorTests
{
[Fact]
public void IlrsIndicator_Constructor_SetsDefaults()
{
var indicator = new IlrsIndicator();
Assert.Equal(14, indicator.Period);
Assert.Equal(SourceType.Close, indicator.Source);
Assert.True(indicator.ShowColdValues);
Assert.Equal("ILRS - Integral of Linear Regression Slope", indicator.Name);
Assert.False(indicator.SeparateWindow);
Assert.True(indicator.OnBackGround);
}
[Fact]
public void IlrsIndicator_MinHistoryDepths_IsZero()
{
var indicator = new IlrsIndicator { Period = 20 };
Assert.Equal(0, IlrsIndicator.MinHistoryDepths);
Assert.Equal(0, ((IWatchlistIndicator)indicator).MinHistoryDepths);
}
[Fact]
public void IlrsIndicator_ShortName_IncludesPeriodAndSource()
{
var indicator = new IlrsIndicator { Period = 15 };
Assert.Contains("ILRS", indicator.ShortName, StringComparison.Ordinal);
Assert.Contains("15", indicator.ShortName, StringComparison.Ordinal);
}
[Fact]
public void IlrsIndicator_SourceCodeLink_IsValid()
{
var indicator = new IlrsIndicator();
Assert.Contains("github.com", indicator.SourceCodeLink, StringComparison.Ordinal);
Assert.Contains("Ilrs.Quantower.cs", indicator.SourceCodeLink, StringComparison.Ordinal);
}
[Fact]
public void IlrsIndicator_Initialize_CreatesInternalIlrs()
{
var indicator = new IlrsIndicator { Period = 10 };
indicator.Initialize();
Assert.Single(indicator.LinesSeries);
}
[Fact]
public void IlrsIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
{
var indicator = new IlrsIndicator { Period = 3 };
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 IlrsIndicator_ProcessUpdate_NewBar_ComputesValue()
{
var indicator = new IlrsIndicator { Period = 3 };
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 IlrsIndicator_ProcessUpdate_NewTick_ProcessesWithoutError()
{
var indicator = new IlrsIndicator { Period = 3 };
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 IlrsIndicator_MultipleUpdates_ProducesCorrectSequence()
{
var indicator = new IlrsIndicator { Period = 3 };
indicator.Initialize();
var now = DateTime.UtcNow;
double[] closes = { 100, 102, 104, 103, 105 };
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 IlrsIndicator_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 IlrsIndicator { Period = 3, 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 IlrsIndicator_Period_CanBeChanged()
{
var indicator = new IlrsIndicator { Period = 5 };
Assert.Equal(5, indicator.Period);
indicator.Period = 20;
Assert.Equal(20, indicator.Period);
Assert.Equal(0, IlrsIndicator.MinHistoryDepths);
}
}
+56
View File
@@ -0,0 +1,56 @@
using System.Drawing;
using System.Runtime.CompilerServices;
using TradingPlatform.BusinessLayer;
namespace QuanTAlib;
[SkipLocalsInit]
public sealed class IlrsIndicator : 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 Ilrs _ilrs = 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 => $"ILRS {Period}:{_sourceName}";
public override string SourceCodeLink => "https://github.com/mihakralj/QuanTAlib/blob/main/lib/trends_FIR/ilrs/Ilrs.Quantower.cs";
public IlrsIndicator()
{
OnBackGround = true;
SeparateWindow = false;
Name = "ILRS - Integral of Linear Regression Slope";
Description = "Cumulative sum of rolling linear regression slope (Ehlers)";
_series = new LineSeries(name: $"ILRS {Period}", color: IndicatorExtensions.Averages, width: 2, style: LineStyle.Solid);
AddLineSeries(_series);
}
protected override void OnInit()
{
_priceSelector = Source.GetPriceSelector();
_sourceName = Source.ToString();
_ilrs = new Ilrs(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 = _ilrs.Update(new TValue(item.TimeLeft.Ticks, _priceSelector(item)), isNew).Value;
_series.SetValue(value, _ilrs.IsHot, ShowColdValues);
}
}
+400
View File
@@ -0,0 +1,400 @@
namespace QuanTAlib.Tests;
using Xunit;
public class IlrsTests
{
private const double Tolerance = 1e-9;
private static TSeries MakeSeries(int count = 500)
{
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.5, seed: 42);
return gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1)).Close;
}
private readonly TSeries _data = MakeSeries();
// ── A) Constructor validation ──────────────────────────────────────
[Theory]
[InlineData(1)]
[InlineData(0)]
[InlineData(-5)]
public void Constructor_InvalidPeriod_Throws(int period)
{
var ex = Assert.Throws<ArgumentException>(() => new Ilrs(period));
Assert.Equal("period", ex.ParamName);
}
[Theory]
[InlineData(2)]
[InlineData(14)]
[InlineData(100)]
public void Constructor_ValidPeriod_Succeeds(int period)
{
var ilrs = new Ilrs(period);
Assert.Equal($"Ilrs({period})", ilrs.Name);
Assert.Equal(period, ilrs.WarmupPeriod);
}
[Fact]
public void Constructor_NullSource_Throws()
{
Assert.Throws<ArgumentNullException>(() => new Ilrs(null!, 14));
}
// ── B) Basic calculation ───────────────────────────────────────────
[Fact]
public void Update_ReturnsFiniteValue()
{
var ilrs = new Ilrs(14);
var result = ilrs.Update(new TValue(DateTime.UtcNow, 100.0));
Assert.True(double.IsFinite(result.Value));
}
[Fact]
public void Update_FirstValue_EqualsInput()
{
var ilrs = new Ilrs(14);
var result = ilrs.Update(new TValue(DateTime.UtcNow, 42.0));
Assert.Equal(42.0, result.Value, Tolerance);
}
[Fact]
public void Update_ConstantInput_IntegralStaysConstant()
{
// Constant input → slope = 0 → integral stays at initial value
const int period = 5;
const double price = 100.0;
var ilrs = new Ilrs(period);
double result = 0;
for (int i = 0; i < 50; i++)
{
result = ilrs.Update(new TValue(DateTime.UtcNow, price)).Value;
}
Assert.Equal(price, result, 1e-6);
}
[Fact]
public void Update_LinearTrend_IntegralFollows()
{
// For y = x (linear trend), slope = 1, so integral grows by 1 each bar
const int period = 5;
var ilrs = new Ilrs(period);
for (int i = 0; i < 20; i++)
{
var result = ilrs.Update(new TValue(DateTime.UtcNow, (double)i));
Assert.True(double.IsFinite(result.Value));
}
// After warmup, integral should be growing
Assert.True(ilrs.Last.Value > 10);
}
[Fact]
public void Last_IsAccessible()
{
var ilrs = new Ilrs(5);
ilrs.Update(new TValue(DateTime.UtcNow, 100.0));
Assert.True(double.IsFinite(ilrs.Last.Value));
}
[Fact]
public void Name_IsCorrect()
{
var ilrs = new Ilrs(7);
Assert.Equal("Ilrs(7)", ilrs.Name);
}
// ── C) State + bar correction ──────────────────────────────────────
[Fact]
public void IsNew_True_AdvancesState()
{
var ilrs = new Ilrs(5);
ilrs.Update(new TValue(DateTime.UtcNow, 100.0), isNew: true);
ilrs.Update(new TValue(DateTime.UtcNow, 101.0), isNew: true);
var v1 = ilrs.Last.Value;
ilrs.Update(new TValue(DateTime.UtcNow, 102.0), isNew: true);
Assert.NotEqual(v1, ilrs.Last.Value);
}
[Fact]
public void IsNew_False_RewritesCurrentBar()
{
var ilrs = new Ilrs(5);
for (int i = 0; i < 8; i++)
{
ilrs.Update(new TValue(DateTime.UtcNow, 100.0 + i), isNew: true);
}
var before = ilrs.Last.Value;
ilrs.Update(new TValue(DateTime.UtcNow, 200.0), isNew: false);
Assert.NotEqual(before, ilrs.Last.Value);
}
[Fact]
public void IterativeCorrections_Restore()
{
var ilrs = new Ilrs(5);
for (int i = 0; i < 10; i++)
{
ilrs.Update(new TValue(DateTime.UtcNow, 100.0 + i), isNew: true);
}
var baseline = ilrs.Last.Value;
// Apply multiple corrections then revert
ilrs.Update(new TValue(DateTime.UtcNow, 200.0), isNew: false);
ilrs.Update(new TValue(DateTime.UtcNow, 300.0), isNew: false);
ilrs.Update(new TValue(DateTime.UtcNow, 109.0), isNew: false); // Original value
Assert.Equal(baseline, ilrs.Last.Value, 1e-6);
}
[Fact]
public void Reset_ClearsState()
{
var ilrs = new Ilrs(5);
for (int i = 0; i < 10; i++)
{
ilrs.Update(new TValue(DateTime.UtcNow, 100.0 + i));
}
ilrs.Reset();
Assert.False(ilrs.IsHot);
Assert.Equal(0, ilrs.Last.Value);
}
// ── D) Warmup/convergence ──────────────────────────────────────────
[Fact]
public void IsHot_FlipsAtPeriod()
{
const int period = 5;
var ilrs = new Ilrs(period);
for (int i = 1; i <= period; i++)
{
ilrs.Update(new TValue(DateTime.UtcNow, 100.0 + i));
if (i < period)
{
Assert.False(ilrs.IsHot, $"Should not be hot at bar {i}");
}
else
{
Assert.True(ilrs.IsHot, $"Should be hot at bar {i}");
}
}
}
[Fact]
public void WarmupPeriod_MatchesPeriod()
{
var ilrs = new Ilrs(10);
Assert.Equal(10, ilrs.WarmupPeriod);
}
// ── E) Robustness ──────────────────────────────────────────────────
[Fact]
public void NaN_UsesLastValidValue()
{
var ilrs = new Ilrs(5);
ilrs.Update(new TValue(DateTime.UtcNow, 100.0));
ilrs.Update(new TValue(DateTime.UtcNow, 101.0));
ilrs.Update(new TValue(DateTime.UtcNow, double.NaN));
Assert.True(double.IsFinite(ilrs.Last.Value));
}
[Fact]
public void Infinity_UsesLastValidValue()
{
var ilrs = new Ilrs(5);
ilrs.Update(new TValue(DateTime.UtcNow, 100.0));
ilrs.Update(new TValue(DateTime.UtcNow, double.PositiveInfinity));
Assert.True(double.IsFinite(ilrs.Last.Value));
}
[Fact]
public void BatchNaN_Safe()
{
var ilrs = new Ilrs(5);
for (int i = 0; i < 10; i++)
{
double val = i == 5 ? double.NaN : 100.0 + i;
ilrs.Update(new TValue(DateTime.UtcNow, val));
}
Assert.True(double.IsFinite(ilrs.Last.Value));
}
// ── F) Consistency (4 API modes) ───────────────────────────────────
[Fact]
public void AllModes_ProduceSameResults()
{
const int period = 7;
// Mode 1: Streaming
var ilrsStream = new Ilrs(period);
var streamResults = new double[_data.Count];
for (int i = 0; i < _data.Count; i++)
{
streamResults[i] = ilrsStream.Update(_data[i]).Value;
}
// Mode 2: Batch (TSeries)
var batchSeries = Ilrs.Batch(_data, period);
// Mode 3: Span
var spanOutput = new double[_data.Count];
Ilrs.Batch(_data.Values, spanOutput, period);
// Mode 4: Event-based
var source = new TSeries();
var ilrsEvent = new Ilrs(source, period);
var eventResults = new double[_data.Count];
for (int i = 0; i < _data.Count; i++)
{
source.Add(_data[i]);
eventResults[i] = ilrsEvent.Last.Value;
}
// Compare all modes
for (int i = 0; i < _data.Count; i++)
{
Assert.Equal(streamResults[i], batchSeries.Values[i], 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()
{
double[] src = [1, 2, 3];
double[] output = new double[2];
var ex = Assert.Throws<ArgumentException>(() => Ilrs.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>(() => Ilrs.Batch(src, output, period: 1));
Assert.Equal("period", ex.ParamName);
}
[Fact]
public void Batch_Span_EmptyInput_NoOp()
{
Ilrs.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 ilrs = new Ilrs(5);
bool fired = false;
ilrs.Pub += (object? sender, in TValueEventArgs e) => fired = true;
ilrs.Update(new TValue(DateTime.UtcNow, 100.0));
Assert.True(fired);
}
[Fact]
public void EventBased_Chaining()
{
var source = new TSeries();
var ilrs = new Ilrs(source, period: 5);
for (int i = 0; i < 10; i++)
{
source.Add(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0 + i));
}
Assert.True(ilrs.IsHot);
Assert.True(double.IsFinite(ilrs.Last.Value));
}
// ── I) Dispose ─────────────────────────────────────────────────────
[Fact]
public void Dispose_Idempotent()
{
var ilrs = new Ilrs(5);
ilrs.Dispose();
ilrs.Dispose(); // Should not throw
Assert.True(true); // no-throw is the assertion
}
[Fact]
public void Dispose_UnsubscribesFromSource()
{
var source = new TSeries();
var ilrs = new Ilrs(source, period: 5);
ilrs.Dispose();
source.Add(new TValue(DateTime.UtcNow, 999.0));
Assert.False(ilrs.IsHot);
}
// ── J) ILRS-specific: Integration behavior ────────────────────────
[Fact]
public void PositiveSlope_IntegralIncreases()
{
var ilrs = new Ilrs(5);
// Feed increasing prices
for (int i = 0; i < 10; i++)
{
ilrs.Update(new TValue(DateTime.UtcNow, 100.0 + i * 10));
}
// Integral should be well above starting value
Assert.True(ilrs.Last.Value > 100.0);
}
[Fact]
public void NegativeSlope_IntegralDecreases()
{
var ilrs = new Ilrs(5);
// Feed decreasing prices
for (int i = 0; i < 10; i++)
{
ilrs.Update(new TValue(DateTime.UtcNow, 200.0 - i * 10));
}
// Integral should be below starting value
Assert.True(ilrs.Last.Value < 200.0);
}
[Fact]
public void Calculate_ReturnsResultsAndIndicator()
{
var (results, indicator) = Ilrs.Calculate(_data, 14);
Assert.Equal(_data.Count, results.Count);
Assert.True(indicator.IsHot);
}
[Fact]
public void Prime_SetsState()
{
var ilrs = new Ilrs(5);
double[] values = [100, 101, 102, 103, 104, 105, 106, 107, 108, 109];
ilrs.Prime(values);
Assert.True(ilrs.IsHot);
Assert.True(double.IsFinite(ilrs.Last.Value));
}
}
@@ -0,0 +1,132 @@
namespace QuanTAlib.Tests;
using Xunit;
public class IlrsValidationTests
{
private const int DataCount = 5000;
private readonly TSeries _data;
public IlrsValidationTests()
{
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.3, seed: 123);
_data = gbm.Fetch(DataCount, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1)).Close;
}
[Fact]
public void Batch_Matches_Streaming()
{
const int period = 14;
var batchResult = Ilrs.Batch(_data, period);
var ilrs = new Ilrs(period);
for (int i = 0; i < _data.Count; i++)
{
ilrs.Update(_data[i]);
Assert.Equal(batchResult.Values[i], ilrs.Last.Value, 1e-6);
}
}
[Fact]
public void Span_Matches_Streaming()
{
const int period = 14;
var spanOutput = new double[_data.Count];
Ilrs.Batch(_data.Values, spanOutput, period);
var ilrs = new Ilrs(period);
for (int i = 0; i < _data.Count; i++)
{
double expected = ilrs.Update(_data[i]).Value;
Assert.Equal(expected, spanOutput[i], 1e-6);
}
}
[Theory]
[InlineData(2)]
[InlineData(7)]
[InlineData(14)]
[InlineData(50)]
public void DifferentPeriods_ProduceValidResults(int period)
{
var ilrs = new Ilrs(period);
for (int i = 0; i < _data.Count; i++)
{
var result = ilrs.Update(_data[i]);
Assert.True(double.IsFinite(result.Value), $"Non-finite at bar {i}, period {period}");
}
Assert.True(ilrs.IsHot);
}
[Fact]
public void ConstantInput_ConvergesToConstant()
{
const int period = 14;
const double price = 50.0;
var ilrs = new Ilrs(period);
for (int i = 0; i < 200; i++)
{
ilrs.Update(new TValue(DateTime.UtcNow, price));
}
Assert.Equal(price, ilrs.Last.Value, 1e-6);
}
[Fact]
public void Calculate_ReturnsHotIndicator()
{
var (results, indicator) = Ilrs.Calculate(_data, 14);
Assert.True(indicator.IsHot);
Assert.Equal(_data.Count, results.Count);
}
[Fact]
public void BarCorrection_Consistency()
{
const int period = 7;
var ilrs = new Ilrs(period);
for (int i = 0; i < 20; i++)
{
ilrs.Update(_data[i]);
}
var baseline = ilrs.Last.Value;
// Apply correction then revert
ilrs.Update(new TValue(DateTime.UtcNow, 999.0), isNew: false);
Assert.NotEqual(baseline, ilrs.Last.Value);
ilrs.Update(_data[19], isNew: false);
Assert.Equal(baseline, ilrs.Last.Value, 1e-6);
}
[Fact]
public void SubsetStability()
{
const int period = 14;
// Run on first 100 bars
var ilrs1 = new Ilrs(period);
for (int i = 0; i < 100; i++)
{
ilrs1.Update(_data[i]);
}
double val100 = ilrs1.Last.Value;
// Run on first 200 bars, check the output at bar 99 matches
var ilrs2 = new Ilrs(period);
double val100_from200 = 0;
for (int i = 0; i < 200; i++)
{
ilrs2.Update(_data[i]);
if (i == 99)
{
val100_from200 = ilrs2.Last.Value;
}
}
Assert.Equal(val100, val100_from200, 1e-9);
}
}
+416
View File
@@ -0,0 +1,416 @@
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace QuanTAlib;
/// <summary>
/// ILRS: Integral of Linear Regression Slope
/// </summary>
/// <remarks>
/// Computes the linear regression slope over a rolling window, then accumulates
/// it via discrete integration (running sum) to reconstruct a smoothed price-level
/// signal. The integration step introduces a natural momentum quality.
///
/// Algorithm: slope via O(1) incremental linreg, then ILRS += slope.
/// Initialized to first price value.
///
/// Reference: John Ehlers, "Rocket Science for Traders" (Wiley, 2001).
/// </remarks>
/// <seealso href="Ilrs.md">Detailed documentation</seealso>
[SkipLocalsInit]
public sealed class Ilrs : AbstractBase
{
private readonly int _period;
private readonly RingBuffer _buffer;
private readonly double _sumX;
private readonly double _denominator;
private readonly TValuePublishedHandler _handler;
private ITValuePublisher? _source;
private int _disposed;
[StructLayout(LayoutKind.Auto)]
private record struct State(
double SumY, double SumXY,
double Integral, double LastVal,
double LastValidValue, bool Initialized);
private State _s;
private State _ps;
private int _tickCount;
private bool _isNew;
private const int ResyncInterval = 1000;
public override bool IsHot => _buffer.IsFull;
public bool IsNew => _isNew;
/// <summary>
/// Creates ILRS with specified period.
/// </summary>
/// <param name="period">Lookback window for slope calculation (must be &gt;= 2)</param>
public Ilrs(int period = 14)
{
if (period < 2)
{
throw new ArgumentException("Period must be at least 2", nameof(period));
}
_period = period;
_buffer = new RingBuffer(period);
Name = $"Ilrs({period})";
WarmupPeriod = period;
_handler = Handle;
// Precompute constants (reversed-x convention: x=0=newest, x=n-1=oldest)
_sumX = 0.5 * period * (period - 1);
double sumX2 = (period - 1.0) * period * (2.0 * period - 1.0) / 6.0;
_denominator = period * sumX2 - _sumX * _sumX;
_s.LastValidValue = double.NaN;
}
public Ilrs(ITValuePublisher source, int period = 14) : this(period)
{
_source = source ?? throw new ArgumentNullException(nameof(source));
_source.Pub += _handler;
}
[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)
{
double val = GetValidValue(input.Value);
UpdateState(val);
_s.LastVal = val;
_ps = _s;
}
else
{
_s.LastValidValue = _ps.LastValidValue;
double val = GetValidValue(input.Value);
// Bar correction: recalculate slope with updated newest value
_s.SumY = _ps.SumY - _ps.LastVal + val;
_s.SumXY = _ps.SumXY;
_buffer.UpdateNewest(val);
_s.LastVal = val;
// Recompute slope and re-apply to previous integral
_s.Integral = _ps.Integral - ComputeSlope(_ps) + ComputeSlope(_s);
}
double result;
if (!_s.Initialized || _buffer.Count < 2)
{
result = _s.Initialized ? _s.Integral : input.Value;
}
else
{
result = _s.Integral;
}
Last = new TValue(input.Time, result);
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 entire series (integral is cumulative)
Reset();
for (int i = 0; i < len; i++)
{
Update(source[i], isNew: true, publish: false);
}
Last = new TValue(tSpan[len - 1], vSpan[len - 1]);
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))
{
_s.LastValidValue = input;
return input;
}
return _s.LastValidValue;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void UpdateState(double val)
{
if (_buffer.IsFull)
{
double oldest = _buffer.Oldest;
double prevSumY = _s.SumY;
// O(1) update for SumXY (reversed-x convention)
_s.SumXY = Math.FusedMultiplyAdd(-_period, oldest, _s.SumXY + prevSumY);
_s.SumY = _s.SumY - oldest + val;
_buffer.Add(val);
}
else
{
if (_buffer.Count > 0)
{
_s.SumXY += _s.SumY;
}
_s.SumY += val;
_buffer.Add(val);
}
// Initialize integral on first value
if (!_s.Initialized)
{
_s.Integral = val;
_s.Initialized = true;
}
else if (_buffer.Count >= 2)
{
// Integrate: ILRS += slope
_s.Integral += ComputeSlope(_s);
}
_tickCount++;
if (_buffer.IsFull && _tickCount >= ResyncInterval)
{
_tickCount = 0;
Resync();
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private double ComputeSlope(State state)
{
int n = _buffer.Count;
if (n < 2)
{
return 0;
}
double sx = _sumX;
double denom = _denominator;
if (!_buffer.IsFull)
{
double nd = n;
sx = 0.5 * nd * (nd - 1);
double sx2 = (nd - 1.0) * nd * (2.0 * nd - 1.0) / 6.0;
denom = nd * sx2 - sx * sx;
}
if (Math.Abs(denom) < 1e-10)
{
return 0;
}
// Reversed-x accumulation inverts the sign; negate to match standard orientation
return -Math.FusedMultiplyAdd(n, state.SumXY, -sx * state.SumY) / denom;
}
private void Resync()
{
_s.SumY = _buffer.Sum;
_s.SumXY = 0;
var span = _buffer.GetSpan();
for (int i = 0; i < span.Length; i++)
{
int x = span.Length - 1 - i;
_s.SumXY = Math.FusedMultiplyAdd(x, span[i], _s.SumXY);
}
}
public override void Prime(ReadOnlySpan<double> source, TimeSpan? step = null)
{
foreach (var value in source)
{
Update(new TValue(DateTime.MinValue, value));
}
}
/// <summary>
/// Calculates ILRS from a TSeries using streaming updates.
/// </summary>
public static TSeries Batch(TSeries source, int period = 14)
{
var ilrs = new Ilrs(period);
return ilrs.Update(source);
}
/// <summary>
/// Calculates ILRS in-place, writing results to pre-allocated output span.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static void Batch(ReadOnlySpan<double> source, Span<double> output, int period = 14)
{
if (source.Length != output.Length)
{
throw new ArgumentException("Source and output must have the same length", nameof(output));
}
if (period < 2)
{
throw new ArgumentException("Period must be at least 2", nameof(period));
}
int len = source.Length;
if (len == 0)
{
return;
}
const int StackAllocThreshold = 256;
Span<double> buffer = period <= StackAllocThreshold
? stackalloc double[period]
: new double[period];
double sumY = 0;
double sumXY = 0;
double lastValid = double.NaN;
double integral = double.NaN;
int bufferIndex = 0;
int count = 0;
// Precalculate constants for full period
double fullSumX = 0.5 * period * (period - 1);
double fullSumX2 = (period - 1.0) * period * (2.0 * period - 1.0) / 6.0;
double fullDenom = period * fullSumX2 - fullSumX * fullSumX;
for (int i = 0; i < len; i++)
{
double val = source[i];
if (double.IsFinite(val))
{
lastValid = val;
}
else
{
val = lastValid;
}
if (count < period)
{
// Warmup phase
buffer[count] = val;
count++;
if (count > 1)
{
sumXY += sumY;
}
sumY += val;
if (!double.IsFinite(integral))
{
integral = val;
output[i] = integral;
}
else if (count < 2)
{
output[i] = integral;
}
else
{
double n = count;
double sx = 0.5 * n * (n - 1);
double sx2 = (n - 1.0) * n * (2.0 * n - 1.0) / 6.0;
double denom = n * sx2 - sx * sx;
if (Math.Abs(denom) < 1e-10)
{
output[i] = integral;
}
else
{
double slope = -Math.FusedMultiplyAdd(n, sumXY, -sx * sumY) / denom;
integral += slope;
output[i] = integral;
}
}
if (count == period)
{
bufferIndex = 0;
}
}
else
{
// Full buffer phase — O(1) update
double oldest = buffer[bufferIndex];
double prevSumY = sumY;
sumXY = Math.FusedMultiplyAdd(-period, oldest, sumXY + prevSumY);
sumY = sumY - oldest + val;
buffer[bufferIndex] = val;
bufferIndex++;
if (bufferIndex >= period)
{
bufferIndex = 0;
}
double slope = -Math.FusedMultiplyAdd(period, sumXY, -fullSumX * sumY) / fullDenom;
integral += slope;
output[i] = integral;
}
}
}
public static (TSeries Results, Ilrs Indicator) Calculate(TSeries source, int period = 14)
{
var indicator = new Ilrs(period);
TSeries results = indicator.Update(source);
return (results, indicator);
}
public override void Reset()
{
_buffer.Clear();
_s = default;
_s.LastValidValue = double.NaN;
_ps = default;
Last = default;
_tickCount = 0;
}
protected override void Dispose(bool disposing)
{
if (Interlocked.CompareExchange(ref _disposed, 1, 0) == 0 && _source != null)
{
_source.Pub -= _handler;
_source = null;
}
base.Dispose(disposing);
}
}