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 QrmaIndicatorTests
{
[Fact]
public void QrmaIndicator_Constructor_SetsDefaults()
{
var indicator = new QrmaIndicator();
Assert.Equal(14, indicator.Period);
Assert.Equal(SourceType.Close, indicator.Source);
Assert.True(indicator.ShowColdValues);
Assert.Equal("QRMA - Quadratic Regression Moving Average", indicator.Name);
Assert.False(indicator.SeparateWindow);
Assert.True(indicator.OnBackGround);
}
[Fact]
public void QrmaIndicator_MinHistoryDepths_IsZero()
{
var indicator = new QrmaIndicator { Period = 20 };
Assert.Equal(0, QrmaIndicator.MinHistoryDepths);
Assert.Equal(0, ((IWatchlistIndicator)indicator).MinHistoryDepths);
}
[Fact]
public void QrmaIndicator_ShortName_IncludesPeriodAndSource()
{
var indicator = new QrmaIndicator { Period = 15 };
Assert.Contains("QRMA", indicator.ShortName, StringComparison.Ordinal);
Assert.Contains("15", indicator.ShortName, StringComparison.Ordinal);
}
[Fact]
public void QrmaIndicator_SourceCodeLink_IsValid()
{
var indicator = new QrmaIndicator();
Assert.Contains("github.com", indicator.SourceCodeLink, StringComparison.Ordinal);
Assert.Contains("Qrma.Quantower.cs", indicator.SourceCodeLink, StringComparison.Ordinal);
}
[Fact]
public void QrmaIndicator_Initialize_CreatesInternalQrma()
{
var indicator = new QrmaIndicator { Period = 10 };
indicator.Initialize();
Assert.Single(indicator.LinesSeries);
}
[Fact]
public void QrmaIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
{
var indicator = new QrmaIndicator { 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 QrmaIndicator_ProcessUpdate_NewBar_ComputesValue()
{
var indicator = new QrmaIndicator { 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 QrmaIndicator_ProcessUpdate_NewTick_ProcessesWithoutError()
{
var indicator = new QrmaIndicator { 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 QrmaIndicator_MultipleUpdates_ProducesCorrectSequence()
{
var indicator = new QrmaIndicator { 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 QrmaIndicator_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 QrmaIndicator { 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 QrmaIndicator_Period_CanBeChanged()
{
var indicator = new QrmaIndicator { Period = 5 };
Assert.Equal(5, indicator.Period);
indicator.Period = 20;
Assert.Equal(20, indicator.Period);
Assert.Equal(0, QrmaIndicator.MinHistoryDepths);
}
}
+56
View File
@@ -0,0 +1,56 @@
using System.Drawing;
using System.Runtime.CompilerServices;
using TradingPlatform.BusinessLayer;
namespace QuanTAlib;
[SkipLocalsInit]
public sealed class QrmaIndicator : Indicator, IWatchlistIndicator
{
[InputParameter("Period", sortIndex: 1, 3, 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 Qrma _qrma = 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 => $"QRMA {Period}:{_sourceName}";
public override string SourceCodeLink => "https://github.com/mihakralj/QuanTAlib/blob/main/lib/trends_FIR/qrma/Qrma.Quantower.cs";
public QrmaIndicator()
{
OnBackGround = true;
SeparateWindow = false;
Name = "QRMA - Quadratic Regression Moving Average";
Description = "Quadratic Regression Moving Average";
_series = new LineSeries(name: $"QRMA {Period}", color: IndicatorExtensions.Averages, width: 2, style: LineStyle.Solid);
AddLineSeries(_series);
}
protected override void OnInit()
{
_priceSelector = Source.GetPriceSelector();
_sourceName = Source.ToString();
_qrma = new Qrma(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 = _qrma.Update(new TValue(item.TimeLeft.Ticks, _priceSelector(item)), isNew).Value;
_series.SetValue(value, _qrma.IsHot, ShowColdValues);
}
}
+459
View File
@@ -0,0 +1,459 @@
namespace QuanTAlib.Tests;
public class QrmaTests
{
[Fact]
public void Constructor_InvalidPeriod_ThrowsArgumentException()
{
Assert.Throws<ArgumentException>(() => new Qrma(0));
Assert.Throws<ArgumentException>(() => new Qrma(-1));
Assert.Throws<ArgumentException>(() => new Qrma(2)); // Minimum is 3
}
[Fact]
public void Constructor_ValidParameters_SetsProperties()
{
var qrma = new Qrma(14);
Assert.Equal("Qrma(14)", qrma.Name);
Assert.False(qrma.IsHot);
}
[Fact]
public void Update_SingleValue_ReturnsSameValue()
{
var qrma = new Qrma(14);
var result = qrma.Update(new TValue(DateTime.UtcNow, 100));
Assert.Equal(100, result.Value);
}
[Fact]
public void Update_LinearTrend_ReturnsExactValue()
{
// For a perfect linear trend y = x, quadratic regression should also return x
// (higher-order coefficient c becomes zero)
const int period = 10;
var qrma = new Qrma(period);
for (int i = 0; i < period * 2; i++)
{
var result = qrma.Update(new TValue(DateTime.UtcNow, i));
if (i >= period) // After warmup
{
Assert.Equal(i, result.Value, 1e-6);
}
}
}
[Fact]
public void Update_QuadraticTrend_ReturnsExactValue()
{
// For y = x², quadratic regression should fit exactly
const int period = 10;
var qrma = new Qrma(period);
for (int i = 0; i < period * 2; i++)
{
double y = (double)i * i;
var result = qrma.Update(new TValue(DateTime.UtcNow, y));
if (i >= period)
{
Assert.Equal(y, result.Value, 1e-4);
}
}
}
[Fact]
public void Update_ConstantValue_ReturnsSameValue()
{
const int period = 10;
var qrma = new Qrma(period);
const double value = 123.45;
for (int i = 0; i < period * 2; i++)
{
var result = qrma.Update(new TValue(DateTime.UtcNow, value));
Assert.Equal(value, result.Value, 1e-9);
}
}
[Fact]
public void Update_BarCorrection_UpdatesCorrectly()
{
var qrma = new Qrma(5);
// Fill buffer
for (int i = 0; i < 5; i++)
{
qrma.Update(new TValue(DateTime.UtcNow, i));
}
// New bar
var result1 = qrma.Update(new TValue(DateTime.UtcNow, 10));
// Update same bar with different value
var result2 = qrma.Update(new TValue(DateTime.UtcNow, 20), isNew: false);
Assert.NotEqual(result1.Value, result2.Value);
// Verify internal state by adding next bar
var result3 = qrma.Update(new TValue(DateTime.UtcNow, 30));
Assert.True(double.IsFinite(result3.Value));
}
[Fact]
public void Update_IterativeCorrection_RestoresState()
{
var qrma = new Qrma(5);
// Build up state
for (int i = 0; i < 10; i++)
{
qrma.Update(new TValue(DateTime.UtcNow, i * 10.0));
}
// New bar
var resultNew = qrma.Update(new TValue(DateTime.UtcNow, 100));
// Multiple corrections on the same bar
qrma.Update(new TValue(DateTime.UtcNow, 105), isNew: false);
qrma.Update(new TValue(DateTime.UtcNow, 110), isNew: false);
var resultFinal = qrma.Update(new TValue(DateTime.UtcNow, 100), isNew: false);
// Correcting back to original value should give same result
Assert.Equal(resultNew.Value, resultFinal.Value, 1e-9);
}
[Fact]
public void Update_NaN_HandlesGracefully()
{
var qrma = new Qrma(5);
for (int i = 1; i <= 5; i++)
{
qrma.Update(new TValue(DateTime.UtcNow, i));
}
// NaN should be replaced with last valid value
var result = qrma.Update(new TValue(DateTime.UtcNow, double.NaN));
Assert.True(double.IsFinite(result.Value));
}
[Fact]
public void Update_Infinity_HandlesGracefully()
{
var qrma = new Qrma(5);
for (int i = 1; i <= 5; i++)
{
qrma.Update(new TValue(DateTime.UtcNow, i));
}
var result = qrma.Update(new TValue(DateTime.UtcNow, double.PositiveInfinity));
Assert.True(double.IsFinite(result.Value));
}
[Fact]
public void Update_BatchNaN_Safe()
{
var qrma = new Qrma(5);
qrma.Update(new TValue(DateTime.UtcNow, 10));
// Several NaN values
for (int i = 0; i < 5; i++)
{
var result = qrma.Update(new TValue(DateTime.UtcNow, double.NaN));
Assert.True(double.IsFinite(result.Value));
}
}
[Fact]
public void Calculate_StaticMethod_MatchesObjectInstance()
{
const int period = 10;
const int count = 100;
var source = new TSeries();
var gbm = new GBM(startPrice: 100, seed: 42);
for (int i = 0; i < count; i++)
{
var bar = gbm.Next();
source.Add(bar.C);
}
var qrma = new Qrma(period);
var series1 = qrma.Update(source);
var series2 = Qrma.Batch(source, period);
Assert.Equal(series1.Count, series2.Count);
for (int i = 0; i < count; i++)
{
Assert.Equal(series1[i].Value, series2[i].Value, 1e-9);
}
}
[Fact]
public void Calculate_Span_MatchesSeries()
{
const int period = 10;
const int count = 100;
var values = new double[count];
var output = new double[count];
var gbm = new GBM(startPrice: 100, seed: 42);
for (int i = 0; i < count; i++)
{
var bar = gbm.Next();
values[i] = bar.Close;
}
Qrma.Batch(values, output, period);
var qrma = new Qrma(period);
for (int i = 0; i < count; i++)
{
var result = qrma.Update(new TValue(DateTime.UtcNow, values[i]));
Assert.Equal(result.Value, output[i], 1e-9);
}
}
[Fact]
public void Span_InvalidLength_ThrowsArgumentException()
{
var source = new double[10];
var output = new double[5]; // Mismatched length
var ex = Assert.Throws<ArgumentException>(() => Qrma.Batch(source, output, 3));
Assert.Equal("output", ex.ParamName);
}
[Fact]
public void Span_InvalidPeriod_ThrowsArgumentException()
{
var source = new double[10];
var output = new double[10];
var ex = Assert.Throws<ArgumentException>(() => Qrma.Batch(source, output, 2));
Assert.Equal("period", ex.ParamName);
}
[Fact]
public void Span_LargeData_DoesNotStackOverflow()
{
const int period = 20;
const int count = 5000;
var values = new double[count];
var output = new double[count];
var gbm = new GBM(startPrice: 100, seed: 42);
for (int i = 0; i < count; i++)
{
values[i] = gbm.Next().Close;
}
// Should not throw
Qrma.Batch(values, output, period);
// All post-warmup values should be finite
for (int i = period; i < count; i++)
{
Assert.True(double.IsFinite(output[i]), $"Output at index {i} is not finite");
}
}
[Fact]
public void Span_NaN_HandledCorrectly()
{
const int period = 5;
var source = new double[] { 1, 2, 3, double.NaN, 5, 6, 7, 8, 9, 10 };
var output = new double[source.Length];
Qrma.Batch(source, output, period);
for (int i = 0; i < source.Length; i++)
{
Assert.True(double.IsFinite(output[i]), $"Output at index {i} is not finite");
}
}
[Fact]
public void Reset_ClearsState()
{
var qrma = new Qrma(5);
for (int i = 0; i < 10; i++)
{
qrma.Update(new TValue(DateTime.UtcNow, i));
}
Assert.True(qrma.IsHot);
qrma.Reset();
Assert.False(qrma.IsHot);
Assert.Equal(0, qrma.Last.Value);
var result = qrma.Update(new TValue(DateTime.UtcNow, 100));
Assert.Equal(100, result.Value);
}
[Fact]
public void IsHot_BecomesTrueWhenBufferFull()
{
const int period = 5;
var qrma = new Qrma(period);
for (int i = 0; i < period; i++)
{
Assert.False(qrma.IsHot);
qrma.Update(new TValue(DateTime.UtcNow, i));
}
Assert.True(qrma.IsHot);
}
[Fact]
public void Chainability_Works()
{
var source = new TSeries();
var qrma = new Qrma(source, 5);
source.Add(new TValue(DateTime.UtcNow, 100));
Assert.Equal(100, qrma.Last.Value);
}
[Fact]
public void Dispose_UnsubscribesFromSource()
{
var source = new TSeries();
var qrma = new Qrma(source, 5);
source.Add(new TValue(DateTime.UtcNow, 100));
Assert.Equal(100, qrma.Last.Value);
qrma.Dispose();
source.Add(new TValue(DateTime.UtcNow, 200));
Assert.Equal(100, qrma.Last.Value); // Should remain at previous value
}
[Fact]
public void Dispose_IsIdempotent()
{
var source = new TSeries();
var qrma = new Qrma(source, 5);
source.Add(new TValue(DateTime.UtcNow, 100));
#pragma warning disable S3966
qrma.Dispose();
qrma.Dispose();
#pragma warning restore S3966
source.Add(new TValue(DateTime.UtcNow, 200));
Assert.Equal(100, qrma.Last.Value);
}
[Fact]
public async System.Threading.Tasks.Task Dispose_IsThreadSafe()
{
var source = new TSeries();
var qrma = new Qrma(source, 5);
source.Add(new TValue(DateTime.UtcNow, 100));
var tasks = new System.Threading.Tasks.Task[10];
for (int i = 0; i < tasks.Length; i++)
{
tasks[i] = System.Threading.Tasks.Task.Run(() => qrma.Dispose());
}
await System.Threading.Tasks.Task.WhenAll(tasks);
source.Add(new TValue(DateTime.UtcNow, 200));
Assert.Equal(100, qrma.Last.Value);
}
[Fact]
public void Dispose_WithoutSource_DoesNotThrow()
{
var qrma = new Qrma(5);
#pragma warning disable S3966
qrma.Dispose();
qrma.Dispose();
#pragma warning restore S3966
Assert.False(qrma.IsHot);
}
[Fact]
public void Constructor_NullSource_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => new Qrma(null!, 5));
}
[Fact]
public void MinPeriod_Three_Works()
{
// QRMA minimum period is 3 (3 unknowns for quadratic)
var qrma = new Qrma(3);
qrma.Update(new TValue(DateTime.UtcNow, 1));
qrma.Update(new TValue(DateTime.UtcNow, 4));
var result = qrma.Update(new TValue(DateTime.UtcNow, 9));
// y = x² with x={0,1,2} → at x=2 → 4
// But input values are {1,4,9} which is y=(x+1)² → endpoint at x=2: a+2b+4c
Assert.True(double.IsFinite(result.Value));
Assert.True(qrma.IsHot);
}
[Fact]
public void AllModes_ProduceConsistentResults()
{
const int period = 10;
const int count = 50;
var gbm = new GBM(startPrice: 100, seed: 42);
var source = new TSeries();
var values = new double[count];
for (int i = 0; i < count; i++)
{
var bar = gbm.Next();
source.Add(bar.C);
values[i] = bar.Close;
}
// Mode 1: Streaming
var streaming = new Qrma(period);
var streamingResults = new double[count];
for (int i = 0; i < count; i++)
{
streamingResults[i] = streaming.Update(source[i]).Value;
}
// Mode 2: Batch TSeries
var batchResults = Qrma.Batch(source, period);
// Mode 3: Span
var spanOutput = new double[count];
Qrma.Batch(values, spanOutput, period);
// Mode 4: Event-based
var eventSource = new TSeries();
var eventQrma = new Qrma(eventSource, period);
var eventResults = new double[count];
for (int i = 0; i < count; i++)
{
eventSource.Add(source[i]);
eventResults[i] = eventQrma.Last.Value;
}
// All four modes should match
for (int i = 0; i < count; i++)
{
Assert.Equal(streamingResults[i], batchResults[i].Value, 1e-9);
Assert.Equal(streamingResults[i], spanOutput[i], 1e-9);
Assert.Equal(streamingResults[i], eventResults[i], 1e-9);
}
}
}
@@ -0,0 +1,140 @@
using Xunit.Abstractions;
namespace QuanTAlib.Tests;
public class QrmaValidationTests
{
private readonly ValidationTestData _testData;
private readonly ITestOutputHelper _output;
public QrmaValidationTests(ITestOutputHelper output)
{
_output = output;
_testData = new ValidationTestData();
}
[Fact]
public void Validate_Batch_Vs_Streaming()
{
int[] periods = { 5, 10, 14, 20, 50 };
foreach (var period in periods)
{
// Calculate QuanTAlib QRMA (batch TSeries)
var qrma = new global::QuanTAlib.Qrma(period);
var batchResult = qrma.Update(_testData.Data);
// Calculate QuanTAlib QRMA (streaming)
var qrmaStreaming = new global::QuanTAlib.Qrma(period);
var streamingResults = new List<double>();
foreach (var item in _testData.Data)
{
streamingResults.Add(qrmaStreaming.Update(item).Value);
}
// Compare all records
Assert.Equal(batchResult.Count, streamingResults.Count);
for (int i = 0; i < batchResult.Count; i++)
{
Assert.Equal(batchResult[i].Value, streamingResults[i], 1e-9);
}
}
_output.WriteLine("QRMA Batch(TSeries) vs Streaming validated successfully");
}
[Fact]
public void Validate_Span_Vs_Streaming()
{
int[] periods = { 5, 10, 14, 20, 50 };
foreach (var period in periods)
{
// Calculate QuanTAlib QRMA (Span API)
double[] qOutput = new double[_testData.RawData.Length];
global::QuanTAlib.Qrma.Batch(_testData.RawData.Span, qOutput.AsSpan(), period);
// Calculate QuanTAlib QRMA (streaming)
var qrmaStreaming = new global::QuanTAlib.Qrma(period);
var streamingResults = new List<double>();
foreach (var item in _testData.Data)
{
streamingResults.Add(qrmaStreaming.Update(item).Value);
}
// Compare all records
for (int i = 0; i < qOutput.Length; i++)
{
Assert.Equal(streamingResults[i], qOutput[i], 1e-9);
}
}
_output.WriteLine("QRMA Span vs Streaming validated successfully");
}
[Fact]
public void Validate_Calculate_ReturnsHotIndicator()
{
int[] periods = { 5, 10, 14, 20 };
foreach (var period in periods)
{
var (results, indicator) = global::QuanTAlib.Qrma.Calculate(_testData.Data, period);
Assert.True(indicator.IsHot);
Assert.Equal(results.Count, _testData.Data.Count);
Assert.True(double.IsFinite(indicator.Last.Value));
// The hot indicator should continue to produce valid results
var nextResult = indicator.Update(new TValue(DateTime.UtcNow, 100.0));
Assert.True(double.IsFinite(nextResult.Value));
}
_output.WriteLine("QRMA Calculate returns hot indicator validated successfully");
}
[Fact]
public void Validate_LinearData_ExactFit()
{
// For linear data y = 2x + 5, quadratic regression should fit exactly
const int period = 14;
const int count = 100;
var values = new double[count];
var output = new double[count];
for (int i = 0; i < count; i++)
{
values[i] = 2.0 * i + 5.0;
}
global::QuanTAlib.Qrma.Batch(values, output, period);
// After warmup, should match perfectly (linear is subset of quadratic)
for (int i = period; i < count; i++)
{
Assert.Equal(values[i], output[i], 1e-6);
}
_output.WriteLine("QRMA linear data exact fit validated successfully");
}
[Fact]
public void Validate_QuadraticData_ExactFit()
{
// For quadratic data y = 0.5x² + x + 3, quadratic regression should fit exactly
const int period = 14;
const int count = 100;
var values = new double[count];
var output = new double[count];
for (int i = 0; i < count; i++)
{
values[i] = 0.5 * i * i + i + 3.0;
}
global::QuanTAlib.Qrma.Batch(values, output, period);
// After warmup, should match well (quadratic model fits quadratic data exactly)
for (int i = period; i < count; i++)
{
Assert.Equal(values[i], output[i], 1e-3);
}
_output.WriteLine("QRMA quadratic data exact fit validated successfully");
}
}
+397
View File
@@ -0,0 +1,397 @@
using System.Buffers;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace QuanTAlib;
/// <summary>
/// QRMA: Quadratic Regression Moving Average
/// </summary>
/// <remarks>
/// Fits a degree-2 polynomial y = a + b*x + c*x² to the most recent N bars via
/// ordinary least squares, returns the fitted endpoint value at x = N-1 (newest bar).
///
/// Calculation: Accumulate Faulhaber power sums S0..S4 + 3 cross-products in O(N),
/// solve 3×3 normal equations via Cramer's rule in O(1).
/// X-indexing: x = 0 oldest, x = N-1 newest; evaluate at x = N-1.
/// </remarks>
/// <seealso href="Qrma.md">Detailed documentation</seealso>
[SkipLocalsInit]
public sealed class Qrma : AbstractBase
{
private readonly int _period;
private readonly RingBuffer _buffer;
private readonly TValuePublishedHandler _handler;
private ITValuePublisher? _source;
private int _disposed;
[StructLayout(LayoutKind.Auto)]
private record struct State(double LastVal, double LastValidValue);
private State _state;
private State _p_state;
private bool _isNew;
public override bool IsHot => _buffer.IsFull;
public bool IsNew => _isNew;
/// <summary>
/// Creates QRMA with specified period.
/// </summary>
/// <param name="period">Lookback period (must be >= 3 for quadratic regression)</param>
public Qrma(int period)
{
if (period < 3)
{
throw new ArgumentException("Period must be at least 3 for quadratic regression", nameof(period));
}
_period = period;
_buffer = new RingBuffer(period);
Name = $"Qrma({period})";
WarmupPeriod = period;
_handler = Handle;
_state.LastValidValue = double.NaN;
}
public Qrma(ITValuePublisher source, int period) : this(period)
{
_source = source ?? throw new ArgumentNullException(nameof(source));
_source.Pub += _handler;
}
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))
{
_state.LastValidValue = input;
return input;
}
return _state.LastValidValue;
}
/// <summary>
/// Solves the 3×3 normal equation system for quadratic polynomial regression
/// using Cramer's rule. Data is oldest-first: data[0] = oldest, data[N-1] = newest.
/// Returns the fitted value at x = N-1 (newest bar endpoint).
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static double SolveQuadratic(ReadOnlySpan<double> data, int count)
{
// N = count; x goes 0..N-1 (oldest=0, newest=N-1)
double n = count;
// Faulhaber closed-form power sums (O(1))
double s1 = n * (n - 1.0) * 0.5; // Σx
double s2 = n * (n - 1.0) * (2.0 * n - 1.0) / 6.0; // Σx²
double s3 = s1 * s1; // Σx³ = [N(N-1)/2]²
double s4 = n * (n - 1.0) * (2.0 * n - 1.0) * Math.FusedMultiplyAdd(3.0 * n, n - 1.0, -1.0) / 30.0; // Σx⁴
// Cross-products in O(N)
double r0 = 0, r1 = 0, r2 = 0;
for (int i = 0; i < count; i++)
{
double v = data[i];
double x = (double)i;
double x2 = x * x;
r0 += v; // Σy
r1 = Math.FusedMultiplyAdd(x, v, r1); // Σxy
r2 = Math.FusedMultiplyAdd(x2, v, r2); // Σx²y
}
// 3×3 normal equations:
// [ N S1 S2 ] [a] [r0]
// [ S1 S2 S3 ] [b] = [r1]
// [ S2 S3 S4 ] [c] [r2]
// Cramer's rule: det of coefficient matrix
double det = Math.FusedMultiplyAdd(n, s2 * s4 - s3 * s3,
Math.FusedMultiplyAdd(-s1, s1 * s4 - s3 * s2,
s2 * (s1 * s3 - s2 * s2)));
if (Math.Abs(det) < 1e-20)
{
return double.NaN; // Singular — caller substitutes raw price
}
double invDet = 1.0 / det;
// det_a: replace column 0 with [r0, r1, r2]
double detA = Math.FusedMultiplyAdd(r0, s2 * s4 - s3 * s3,
Math.FusedMultiplyAdd(-s1, r1 * s4 - r2 * s3,
s2 * (r1 * s3 - r2 * s2)));
// det_b: replace column 1 with [r0, r1, r2]
double detB = Math.FusedMultiplyAdd(n, r1 * s4 - r2 * s3,
Math.FusedMultiplyAdd(-r0, s1 * s4 - s3 * s2,
s2 * (s1 * r2 - s2 * r1)));
// det_c: replace column 2 with [r0, r1, r2]
double detC = Math.FusedMultiplyAdd(n, s2 * r2 - s3 * r1,
Math.FusedMultiplyAdd(-s1, s1 * r2 - s2 * r1,
r0 * (s1 * s3 - s2 * s2)));
double a = detA * invDet;
double b = detB * invDet;
double c = detC * invDet;
// Evaluate at x = N-1 (newest bar endpoint)
double xEval = n - 1.0;
return Math.FusedMultiplyAdd(c, xEval * xEval, Math.FusedMultiplyAdd(b, xEval, a));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override TValue Update(TValue input, bool isNew = true)
{
_isNew = isNew;
if (isNew)
{
_p_state = _state;
double val = GetValidValue(input.Value);
_buffer.Add(val);
_state.LastVal = val;
}
else
{
_state.LastValidValue = _p_state.LastValidValue;
double val = GetValidValue(input.Value);
_buffer.UpdateNewest(val);
_state.LastVal = val;
}
double result;
int count = _buffer.Count;
if (count < 3)
{
// Not enough points for quadratic regression — return current value
result = _buffer.Newest;
}
else
{
// Get buffer data in chronological order (oldest=index 0, newest=last)
// SolveQuadratic expects oldest-first: data[0]=oldest, data[N-1]=newest
const int StackAllocThreshold = 256;
double[]? rented = count > StackAllocThreshold ? ArrayPool<double>.Shared.Rent(count) : null;
Span<double> data = rented != null
? rented.AsSpan(0, count)
: stackalloc double[count];
try
{
// Copy buffer in chronological order (oldest first) — direct from RingBuffer
var span = _buffer.GetSpan();
span[..count].CopyTo(data);
double solved = SolveQuadratic(data, count);
result = double.IsFinite(solved) ? solved : _buffer.Newest;
}
finally
{
if (rented != null)
{
ArrayPool<double>.Shared.Return(rented);
}
}
}
Last = new TValue(input.Time, result);
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);
double initialLastValid = _state.LastValidValue;
Batch(source.Values, vSpan, _period, initialLastValid);
source.Times.CopyTo(tSpan);
// Restore state by replaying last 'period' bars
int windowSize = Math.Min(len, _period);
int startIndex = len - windowSize;
Reset();
if (startIndex > 0)
{
for (int i = startIndex - 1; i >= 0; i--)
{
if (double.IsFinite(source.Values[i]))
{
_state.LastValidValue = source.Values[i];
break;
}
}
}
else
{
_state.LastValidValue = initialLastValid;
}
for (int i = startIndex; i < len; i++)
{
double val = GetValidValue(source.Values[i]);
_buffer.Add(val);
_state.LastVal = val;
}
_p_state = _state;
Last = new TValue(tSpan[len - 1], vSpan[len - 1]);
return new TSeries(t, v);
}
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)
{
var qrma = new Qrma(period);
return qrma.Update(source);
}
/// <summary>
/// Calculates QRMA in-place, writing results to pre-allocated output span.
/// Zero-allocation method for maximum performance.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Batch(ReadOnlySpan<double> source, Span<double> output, int period, double initialLastValid = double.NaN)
{
if (source.Length != output.Length)
{
throw new ArgumentException("Source and output must have the same length", nameof(output));
}
if (period < 3)
{
throw new ArgumentException("Period must be at least 3 for quadratic regression", nameof(period));
}
int len = source.Length;
if (len == 0)
{
return;
}
const int StackAllocThreshold = 256;
// Pre-process: build a NaN-corrected copy of source so we can index it directly
double[]? rentedClean = len > StackAllocThreshold ? ArrayPool<double>.Shared.Rent(len) : null;
Span<double> clean = rentedClean != null
? rentedClean.AsSpan(0, len)
: stackalloc double[len];
double[]? rentedData = period > StackAllocThreshold ? ArrayPool<double>.Shared.Rent(period) : null;
Span<double> dataBuffer = rentedData != null
? rentedData.AsSpan(0, period)
: stackalloc double[period];
try
{
double lastValid = initialLastValid;
// Build NaN-corrected array
for (int i = 0; i < len; i++)
{
double val = source[i];
if (double.IsFinite(val))
{
lastValid = val;
clean[i] = val;
}
else
{
clean[i] = lastValid;
}
}
// For each bar, solve quadratic regression over the window
for (int i = 0; i < len; i++)
{
int n = Math.Min(i + 1, period);
if (n < 3)
{
output[i] = clean[i];
}
else
{
// Build oldest-first data for SolveQuadratic
// data[0]=oldest (bar i-n+1), data[n-1]=newest (bar i)
Span<double> data = dataBuffer[..n];
for (int j = 0; j < n; j++)
{
data[j] = clean[i - n + 1 + j];
}
double solved = SolveQuadratic(data, n);
output[i] = double.IsFinite(solved) ? solved : clean[i];
}
}
}
finally
{
if (rentedClean != null)
{
ArrayPool<double>.Shared.Return(rentedClean);
}
if (rentedData != null)
{
ArrayPool<double>.Shared.Return(rentedData);
}
}
}
public static (TSeries Results, Qrma Indicator) Calculate(TSeries source, int period)
{
var indicator = new Qrma(period);
TSeries results = indicator.Update(source);
return (results, indicator);
}
/// <summary>
/// Resets the QRMA state.
/// </summary>
public override void Reset()
{
_buffer.Clear();
_state = default;
_state.LastValidValue = double.NaN;
_p_state = default;
Last = default;
}
/// <summary>
/// Disposes the Qrma instance, unsubscribing from the source publisher if subscribed.
/// This method is idempotent and thread-safe.
/// </summary>
protected override void Dispose(bool disposing)
{
if (Interlocked.CompareExchange(ref _disposed, 1, 0) == 0 && _source != null)
{
_source.Pub -= _handler;
_source = null;
}
base.Dispose(disposing);
}
}