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 CrmaIndicatorTests
{
[Fact]
public void CrmaIndicator_Constructor_SetsDefaults()
{
var indicator = new CrmaIndicator();
Assert.Equal(14, indicator.Period);
Assert.Equal(SourceType.Close, indicator.Source);
Assert.True(indicator.ShowColdValues);
Assert.Equal("CRMA - Cubic Regression Moving Average", indicator.Name);
Assert.False(indicator.SeparateWindow);
Assert.True(indicator.OnBackGround);
}
[Fact]
public void CrmaIndicator_MinHistoryDepths_IsZero()
{
var indicator = new CrmaIndicator { Period = 20 };
Assert.Equal(0, CrmaIndicator.MinHistoryDepths);
Assert.Equal(0, ((IWatchlistIndicator)indicator).MinHistoryDepths);
}
[Fact]
public void CrmaIndicator_ShortName_IncludesPeriodAndSource()
{
var indicator = new CrmaIndicator { Period = 15 };
Assert.Contains("CRMA", indicator.ShortName, StringComparison.Ordinal);
Assert.Contains("15", indicator.ShortName, StringComparison.Ordinal);
}
[Fact]
public void CrmaIndicator_SourceCodeLink_IsValid()
{
var indicator = new CrmaIndicator();
Assert.Contains("github.com", indicator.SourceCodeLink, StringComparison.Ordinal);
Assert.Contains("Crma.Quantower.cs", indicator.SourceCodeLink, StringComparison.Ordinal);
}
[Fact]
public void CrmaIndicator_Initialize_CreatesInternalCrma()
{
var indicator = new CrmaIndicator { Period = 10 };
indicator.Initialize();
Assert.Single(indicator.LinesSeries);
}
[Fact]
public void CrmaIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
{
var indicator = new CrmaIndicator { Period = 4 };
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 CrmaIndicator_ProcessUpdate_NewBar_ComputesValue()
{
var indicator = new CrmaIndicator { Period = 4 };
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 CrmaIndicator_ProcessUpdate_NewTick_ProcessesWithoutError()
{
var indicator = new CrmaIndicator { Period = 4 };
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 CrmaIndicator_MultipleUpdates_ProducesCorrectSequence()
{
var indicator = new CrmaIndicator { Period = 4 };
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 CrmaIndicator_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 CrmaIndicator { Period = 4, 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 CrmaIndicator_Period_CanBeChanged()
{
var indicator = new CrmaIndicator { Period = 5 };
Assert.Equal(5, indicator.Period);
indicator.Period = 20;
Assert.Equal(20, indicator.Period);
Assert.Equal(0, CrmaIndicator.MinHistoryDepths);
}
}
+56
View File
@@ -0,0 +1,56 @@
using System.Drawing;
using System.Runtime.CompilerServices;
using TradingPlatform.BusinessLayer;
namespace QuanTAlib;
[SkipLocalsInit]
public sealed class CrmaIndicator : Indicator, IWatchlistIndicator
{
[InputParameter("Period", sortIndex: 1, 4, 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 Crma _crma = 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 => $"CRMA {Period}:{_sourceName}";
public override string SourceCodeLink => "https://github.com/mihakralj/QuanTAlib/blob/main/lib/trends_FIR/crma/Crma.Quantower.cs";
public CrmaIndicator()
{
OnBackGround = true;
SeparateWindow = false;
Name = "CRMA - Cubic Regression Moving Average";
Description = "Cubic Regression Moving Average";
_series = new LineSeries(name: $"CRMA {Period}", color: IndicatorExtensions.Averages, width: 2, style: LineStyle.Solid);
AddLineSeries(_series);
}
protected override void OnInit()
{
_priceSelector = Source.GetPriceSelector();
_sourceName = Source.ToString();
_crma = new Crma(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 = _crma.Update(new TValue(item.TimeLeft.Ticks, _priceSelector(item)), isNew).Value;
_series.SetValue(value, _crma.IsHot, ShowColdValues);
}
}
+461
View File
@@ -0,0 +1,461 @@
namespace QuanTAlib.Tests;
public class CrmaTests
{
[Fact]
public void Constructor_InvalidPeriod_ThrowsArgumentException()
{
Assert.Throws<ArgumentException>(() => new Crma(0));
Assert.Throws<ArgumentException>(() => new Crma(-1));
Assert.Throws<ArgumentException>(() => new Crma(3)); // Minimum is 4
}
[Fact]
public void Constructor_ValidParameters_SetsProperties()
{
var crma = new Crma(14);
Assert.Equal("Crma(14)", crma.Name);
Assert.False(crma.IsHot);
}
[Fact]
public void Update_SingleValue_ReturnsSameValue()
{
var crma = new Crma(14);
var result = crma.Update(new TValue(DateTime.UtcNow, 100));
Assert.Equal(100, result.Value);
}
[Fact]
public void Update_LinearTrend_ReturnsExactValue()
{
// For a perfect linear trend y = x, cubic regression should also return x
// (higher-order coefficients become zero)
const int period = 10;
var crma = new Crma(period);
for (int i = 0; i < period * 2; i++)
{
var result = crma.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², cubic regression should fit exactly
const int period = 10;
var crma = new Crma(period);
for (int i = 0; i < period * 2; i++)
{
double y = (double)i * i;
var result = crma.Update(new TValue(DateTime.UtcNow, y));
if (i >= period)
{
Assert.Equal(y, result.Value, 1e-4);
}
}
}
[Fact]
public void Update_CubicTrend_ReturnsExactValue()
{
// For y = x³, cubic regression should fit exactly
const int period = 10;
var crma = new Crma(period);
for (int i = 0; i < period * 2; i++)
{
double y = (double)i * i * i;
var result = crma.Update(new TValue(DateTime.UtcNow, y));
if (i >= period)
{
Assert.Equal(y, result.Value, 1e-1);
}
}
}
[Fact]
public void Update_ConstantValue_ReturnsSameValue()
{
const int period = 10;
var crma = new Crma(period);
const double value = 123.45;
for (int i = 0; i < period * 2; i++)
{
var result = crma.Update(new TValue(DateTime.UtcNow, value));
Assert.Equal(value, result.Value, 1e-9);
}
}
[Fact]
public void Update_BarCorrection_UpdatesCorrectly()
{
var crma = new Crma(5);
// Fill buffer
for (int i = 0; i < 5; i++)
{
crma.Update(new TValue(DateTime.UtcNow, i));
}
// New bar
var result1 = crma.Update(new TValue(DateTime.UtcNow, 10));
// Update same bar with different value
var result2 = crma.Update(new TValue(DateTime.UtcNow, 20), isNew: false);
Assert.NotEqual(result1.Value, result2.Value);
// Verify internal state by adding next bar
var result3 = crma.Update(new TValue(DateTime.UtcNow, 30));
Assert.True(double.IsFinite(result3.Value));
}
[Fact]
public void Update_IterativeCorrection_RestoresState()
{
var crma = new Crma(5);
// Build up state
for (int i = 0; i < 10; i++)
{
crma.Update(new TValue(DateTime.UtcNow, i * 10.0));
}
// New bar
var resultNew = crma.Update(new TValue(DateTime.UtcNow, 100));
// Multiple corrections on the same bar
crma.Update(new TValue(DateTime.UtcNow, 105), isNew: false);
crma.Update(new TValue(DateTime.UtcNow, 110), isNew: false);
var resultFinal = crma.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 crma = new Crma(5);
for (int i = 1; i <= 5; i++)
{
crma.Update(new TValue(DateTime.UtcNow, i));
}
// NaN should be replaced with last valid value
var result = crma.Update(new TValue(DateTime.UtcNow, double.NaN));
Assert.True(double.IsFinite(result.Value));
}
[Fact]
public void Update_Infinity_HandlesGracefully()
{
var crma = new Crma(5);
for (int i = 1; i <= 5; i++)
{
crma.Update(new TValue(DateTime.UtcNow, i));
}
var result = crma.Update(new TValue(DateTime.UtcNow, double.PositiveInfinity));
Assert.True(double.IsFinite(result.Value));
}
[Fact]
public void Update_BatchNaN_Safe()
{
var crma = new Crma(5);
crma.Update(new TValue(DateTime.UtcNow, 10));
// Several NaN values
for (int i = 0; i < 5; i++)
{
var result = crma.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 crma = new Crma(period);
var series1 = crma.Update(source);
var series2 = Crma.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;
}
Crma.Batch(values, output, period);
var crma = new Crma(period);
for (int i = 0; i < count; i++)
{
var result = crma.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>(() => Crma.Batch(source, output, 4));
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>(() => Crma.Batch(source, output, 3));
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
Crma.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];
Crma.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 crma = new Crma(5);
for (int i = 0; i < 10; i++)
{
crma.Update(new TValue(DateTime.UtcNow, i));
}
Assert.True(crma.IsHot);
crma.Reset();
Assert.False(crma.IsHot);
Assert.Equal(0, crma.Last.Value);
var result = crma.Update(new TValue(DateTime.UtcNow, 100));
Assert.Equal(100, result.Value);
}
[Fact]
public void IsHot_BecomesTrueWhenBufferFull()
{
const int period = 5;
var crma = new Crma(period);
for (int i = 0; i < period; i++)
{
Assert.False(crma.IsHot);
crma.Update(new TValue(DateTime.UtcNow, i));
}
Assert.True(crma.IsHot);
}
[Fact]
public void Chainability_Works()
{
var source = new TSeries();
var crma = new Crma(source, 5);
source.Add(new TValue(DateTime.UtcNow, 100));
Assert.Equal(100, crma.Last.Value);
}
[Fact]
public void Dispose_UnsubscribesFromSource()
{
var source = new TSeries();
var crma = new Crma(source, 5);
source.Add(new TValue(DateTime.UtcNow, 100));
Assert.Equal(100, crma.Last.Value);
crma.Dispose();
source.Add(new TValue(DateTime.UtcNow, 200));
Assert.Equal(100, crma.Last.Value); // Should remain at previous value
}
[Fact]
public void Dispose_IsIdempotent()
{
var source = new TSeries();
var crma = new Crma(source, 5);
source.Add(new TValue(DateTime.UtcNow, 100));
#pragma warning disable S3966
crma.Dispose();
crma.Dispose();
#pragma warning restore S3966
source.Add(new TValue(DateTime.UtcNow, 200));
Assert.Equal(100, crma.Last.Value);
}
[Fact]
public async System.Threading.Tasks.Task Dispose_IsThreadSafe()
{
var source = new TSeries();
var crma = new Crma(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(() => crma.Dispose());
}
await System.Threading.Tasks.Task.WhenAll(tasks);
source.Add(new TValue(DateTime.UtcNow, 200));
Assert.Equal(100, crma.Last.Value);
}
[Fact]
public void Dispose_WithoutSource_DoesNotThrow()
{
var crma = new Crma(5);
#pragma warning disable S3966
crma.Dispose();
crma.Dispose();
#pragma warning restore S3966
Assert.False(crma.IsHot);
}
[Fact]
public void Constructor_NullSource_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => new Crma(null!, 5));
}
[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 Crma(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 = Crma.Batch(source, period);
// Mode 3: Span
var spanOutput = new double[count];
Crma.Batch(values, spanOutput, period);
// Mode 4: Event-based
var eventSource = new TSeries();
var eventCrma = new Crma(eventSource, period);
var eventResults = new double[count];
for (int i = 0; i < count; i++)
{
eventSource.Add(source[i]);
eventResults[i] = eventCrma.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,167 @@
using Xunit.Abstractions;
namespace QuanTAlib.Tests;
public class CrmaValidationTests
{
private readonly ValidationTestData _testData;
private readonly ITestOutputHelper _output;
public CrmaValidationTests(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 CRMA (batch TSeries)
var crma = new global::QuanTAlib.Crma(period);
var batchResult = crma.Update(_testData.Data);
// Calculate QuanTAlib CRMA (streaming)
var crmaStreaming = new global::QuanTAlib.Crma(period);
var streamingResults = new List<double>();
foreach (var item in _testData.Data)
{
streamingResults.Add(crmaStreaming.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("CRMA 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 CRMA (Span API)
double[] qOutput = new double[_testData.RawData.Length];
global::QuanTAlib.Crma.Batch(_testData.RawData.Span, qOutput.AsSpan(), period);
// Calculate QuanTAlib CRMA (streaming)
var crmaStreaming = new global::QuanTAlib.Crma(period);
var streamingResults = new List<double>();
foreach (var item in _testData.Data)
{
streamingResults.Add(crmaStreaming.Update(item).Value);
}
// Compare all records
for (int i = 0; i < qOutput.Length; i++)
{
Assert.Equal(streamingResults[i], qOutput[i], 1e-9);
}
}
_output.WriteLine("CRMA 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.Crma.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("CRMA Calculate returns hot indicator validated successfully");
}
[Fact]
public void Validate_LinearData_ExactFit()
{
// For linear data y = 2x + 5, cubic 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.Crma.Batch(values, output, period);
// After warmup, should match perfectly (linear is subset of cubic)
// Numerical precision degrades with large power sums (x^6), so use 1e-3
for (int i = period; i < count; i++)
{
Assert.Equal(values[i], output[i], 1e-3);
}
_output.WriteLine("CRMA linear data exact fit validated successfully");
}
[Fact]
public void Validate_QuadraticData_ExactFit()
{
// For quadratic data y = 0.5x² + x + 3, cubic 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.Crma.Batch(values, output, period);
// After warmup, should match well (quadratic is subset of cubic)
// Large x^6 power sums cause numerical conditioning issues
for (int i = period; i < count; i++)
{
Assert.Equal(values[i], output[i], 1.0);
}
_output.WriteLine("CRMA quadratic data exact fit validated successfully");
}
[Fact]
public void Validate_CubicData_ExactFit()
{
// For cubic data y = 0.001x³ + 0.01x² + x + 5, should fit exactly
// Use small coefficients to reduce numerical conditioning issues
const int period = 10;
const int count = 30;
var values = new double[count];
var output = new double[count];
for (int i = 0; i < count; i++)
{
values[i] = 0.001 * i * i * i + 0.01 * i * i + i + 5.0;
}
global::QuanTAlib.Crma.Batch(values, output, period);
// Cubic data within a cubic model should fit well but with numerical noise
for (int i = period; i < count; i++)
{
Assert.Equal(values[i], output[i], 1.0);
}
_output.WriteLine("CRMA cubic data exact fit validated successfully");
}
}
+431
View File
@@ -0,0 +1,431 @@
using System.Buffers;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace QuanTAlib;
/// <summary>
/// CRMA: Cubic Regression Moving Average
/// </summary>
/// <remarks>
/// Fits a degree-3 polynomial y = a0 + a1*x + a2*x² + a3*x³ to the most recent
/// N bars via least squares, returns the fitted endpoint value a0.
///
/// Calculation: Accumulate 7 power sums + 4 cross-products in O(N), solve 4×4
/// normal equations via Gaussian elimination with partial pivoting in O(1).
/// </remarks>
/// <seealso href="Crma.md">Detailed documentation</seealso>
[SkipLocalsInit]
public sealed class Crma : 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 CRMA with specified period.
/// </summary>
/// <param name="period">Lookback period (must be >= 4 for cubic regression)</param>
public Crma(int period)
{
if (period < 4)
{
throw new ArgumentException("Period must be at least 4 for cubic regression", nameof(period));
}
_period = period;
_buffer = new RingBuffer(period);
Name = $"Crma({period})";
WarmupPeriod = period;
_handler = Handle;
_state.LastValidValue = double.NaN;
}
public Crma(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 4×4 normal equation system for cubic polynomial regression.
/// Returns the intercept a0 (fitted value at x=0, the newest bar).
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static double SolveCubic(ReadOnlySpan<double> data, int count)
{
// Accumulate power sums S0..S6 and cross-products r0..r3
double s0 = 0, s1 = 0, s2 = 0, s3 = 0, s4 = 0, s5 = 0, s6 = 0;
double r0 = 0, r1 = 0, r2 = 0, r3 = 0;
for (int i = 0; i < count; i++)
{
double v = data[i];
double x = (double)i;
double x2 = x * x;
double x3 = x2 * x;
s0 += 1.0;
s1 += x;
s2 += x2;
s3 += x3;
s4 += x2 * x2;
s5 += x2 * x3;
s6 += x3 * x3;
r0 += v;
r1 = Math.FusedMultiplyAdd(x, v, r1);
r2 = Math.FusedMultiplyAdd(x2, v, r2);
r3 = Math.FusedMultiplyAdd(x3, v, r3);
}
// Build 4×5 augmented matrix (row-major, inline on stack)
// [s0 s1 s2 s3 | r0]
// [s1 s2 s3 s4 | r1]
// [s2 s3 s4 s5 | r2]
// [s3 s4 s5 s6 | r3]
Span<double> m = stackalloc double[20];
m[0] = s0; m[1] = s1; m[2] = s2; m[3] = s3; m[4] = r0;
m[5] = s1; m[6] = s2; m[7] = s3; m[8] = s4; m[9] = r1;
m[10] = s2; m[11] = s3; m[12] = s4; m[13] = s5; m[14] = r2;
m[15] = s3; m[16] = s4; m[17] = s5; m[18] = s6; m[19] = r3;
// Gaussian elimination with partial pivoting
for (int col = 0; col < 4; col++)
{
// Find pivot row
int pivotRow = col;
double pivotMax = Math.Abs(m[col * 5 + col]);
for (int row = col + 1; row < 4; row++)
{
double absVal = Math.Abs(m[row * 5 + col]);
if (absVal > pivotMax)
{
pivotMax = absVal;
pivotRow = row;
}
}
if (pivotMax < 1e-12)
{
return double.NaN; // Singular — caller will substitute raw price
}
// Swap rows if needed
if (pivotRow != col)
{
int colOff = col * 5;
int pivOff = pivotRow * 5;
for (int k = col; k < 5; k++)
{
(m[colOff + k], m[pivOff + k]) = (m[pivOff + k], m[colOff + k]);
}
}
// Eliminate below
double diag = m[col * 5 + col];
for (int row = col + 1; row < 4; row++)
{
double factor = m[row * 5 + col] / diag;
for (int k = col; k < 5; k++)
{
m[row * 5 + k] = Math.FusedMultiplyAdd(-factor, m[col * 5 + k], m[row * 5 + k]);
}
}
}
// Back-substitution
Span<double> a = stackalloc double[4];
for (int row = 3; row >= 0; row--)
{
double val = m[row * 5 + 4];
for (int k = row + 1; k < 4; k++)
{
val = Math.FusedMultiplyAdd(-m[row * 5 + k], a[k], val);
}
a[row] = val / m[row * 5 + row];
}
return a[0]; // Fitted value at x=0 (newest bar)
}
[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 < 4)
{
// Not enough points for cubic regression — return current value
result = _buffer.Newest;
}
else
{
// Get buffer data in chronological order (oldest=index 0, newest=last)
// We need newest at x=0, so we reverse the iteration in SolveCubic
// Actually, we pass data newest-first: data[0]=newest, data[count-1]=oldest
// This matches the PineScript convention: x=0 for 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 reverse chronological order (newest first)
var span = _buffer.GetSpan();
for (int i = 0; i < count; i++)
{
data[i] = span[count - 1 - i];
}
double solved = SolveCubic(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 crma = new Crma(period);
return crma.Update(source);
}
/// <summary>
/// Calculates CRMA 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 < 4)
{
throw new ArgumentException("Period must be at least 4 for cubic 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 cubic regression over the window
for (int i = 0; i < len; i++)
{
int n = Math.Min(i + 1, period);
if (n < 4)
{
output[i] = clean[i];
}
else
{
// Build newest-first data for SolveCubic
Span<double> data = dataBuffer[..n];
for (int j = 0; j < n; j++)
{
data[j] = clean[i - j]; // newest first (data[0]=bar i, data[1]=bar i-1, ...)
}
double solved = SolveCubic(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, Crma Indicator) Calculate(TSeries source, int period)
{
var indicator = new Crma(period);
TSeries results = indicator.Update(source);
return (results, indicator);
}
/// <summary>
/// Resets the CRMA state.
/// </summary>
public override void Reset()
{
_buffer.Clear();
_state = default;
_state.LastValidValue = double.NaN;
_p_state = default;
Last = default;
}
/// <summary>
/// Disposes the Crma 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);
}
}