mirror of
https://github.com/mihakralj/QuanTAlib.git
synced 2026-08-24 05:28:05 +00:00
Add TRAMA implementation and comprehensive tests
- Implemented the TRAMA (Trend Regularity Adaptive Moving Average) class with adaptive EMA logic. - Added unit tests for TRAMA functionality, including constructor validation, basic calculations, state management, and robustness checks. - Created validation tests to ensure consistency across different modes of operation (streaming, batch, and static calculations). - Enhanced documentation for TRAMA, including performance profiles and quality metrics. - Updated workspace configuration by removing unnecessary folder references.
This commit is contained in:
@@ -0,0 +1,148 @@
|
||||
using TradingPlatform.BusinessLayer;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public class McnmaIndicatorTests
|
||||
{
|
||||
[Fact]
|
||||
public void McnmaIndicator_Constructor_SetsDefaults()
|
||||
{
|
||||
var indicator = new McnmaIndicator();
|
||||
|
||||
Assert.Equal(14, indicator.Period);
|
||||
Assert.Equal(SourceType.Close, indicator.Source);
|
||||
Assert.True(indicator.ShowColdValues);
|
||||
Assert.Equal("MCNMA - McNicholl EMA", indicator.Name);
|
||||
Assert.False(indicator.SeparateWindow);
|
||||
Assert.True(indicator.OnBackGround);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void McnmaIndicator_MinHistoryDepths_EqualsZero()
|
||||
{
|
||||
var indicator = new McnmaIndicator { Period = 20 };
|
||||
|
||||
Assert.Equal(0, McnmaIndicator.MinHistoryDepths);
|
||||
Assert.Equal(0, ((IWatchlistIndicator)indicator).MinHistoryDepths);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void McnmaIndicator_ShortName_IncludesPeriodAndSource()
|
||||
{
|
||||
var indicator = new McnmaIndicator { Period = 15 };
|
||||
|
||||
Assert.Contains("MCNMA", indicator.ShortName, StringComparison.Ordinal);
|
||||
Assert.Contains("15", indicator.ShortName, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void McnmaIndicator_SourceCodeLink_IsValid()
|
||||
{
|
||||
var indicator = new McnmaIndicator();
|
||||
|
||||
Assert.Contains("github.com", indicator.SourceCodeLink, StringComparison.Ordinal);
|
||||
Assert.Contains("Mcnma.Quantower.cs", indicator.SourceCodeLink, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void McnmaIndicator_Initialize_CreatesInternalMcnma()
|
||||
{
|
||||
var indicator = new McnmaIndicator { Period = 14 };
|
||||
|
||||
indicator.Initialize();
|
||||
|
||||
Assert.Single(indicator.LinesSeries);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void McnmaIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
|
||||
{
|
||||
var indicator = new McnmaIndicator { 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 McnmaIndicator_ProcessUpdate_NewBar_ComputesValue()
|
||||
{
|
||||
var indicator = new McnmaIndicator { 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 McnmaIndicator_ProcessUpdate_NewTick_ProcessesWithoutError()
|
||||
{
|
||||
var indicator = new McnmaIndicator { 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 McnmaIndicator_MultipleUpdates_ProducesCorrectSequence()
|
||||
{
|
||||
var indicator = new McnmaIndicator { 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 McnmaIndicator_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 McnmaIndicator { 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");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
using System.Drawing;
|
||||
using System.Runtime.CompilerServices;
|
||||
using TradingPlatform.BusinessLayer;
|
||||
|
||||
namespace QuanTAlib;
|
||||
|
||||
[SkipLocalsInit]
|
||||
public class McnmaIndicator : Indicator, IWatchlistIndicator
|
||||
{
|
||||
[InputParameter("Period", sortIndex: 1, 1, 1000, 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 Mcnma ma = null!;
|
||||
protected LineSeries Series;
|
||||
protected string SourceName = null!;
|
||||
private Func<IHistoryItem, double> _priceSelector = null!;
|
||||
|
||||
public static int MinHistoryDepths => 0;
|
||||
int IWatchlistIndicator.MinHistoryDepths => MinHistoryDepths;
|
||||
|
||||
public override string ShortName => $"MCNMA {Period}:{SourceName}";
|
||||
public override string SourceCodeLink => "https://github.com/mihakralj/QuanTAlib/blob/main/lib/trends_IIR/mcnma/Mcnma.Quantower.cs";
|
||||
|
||||
public McnmaIndicator()
|
||||
{
|
||||
OnBackGround = true;
|
||||
SeparateWindow = false;
|
||||
SourceName = Source.ToString();
|
||||
Name = "MCNMA - McNicholl EMA";
|
||||
Description = "McNicholl EMA (Zero-Lag TEMA)";
|
||||
Series = new LineSeries(name: $"MCNMA {Period}", color: IndicatorExtensions.Averages, width: 2, style: LineStyle.Solid);
|
||||
AddLineSeries(Series);
|
||||
}
|
||||
|
||||
protected override void OnInit()
|
||||
{
|
||||
ma = new Mcnma(Period);
|
||||
SourceName = Source.ToString();
|
||||
_priceSelector = Source.GetPriceSelector();
|
||||
base.OnInit();
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
protected override void OnUpdate(UpdateArgs args)
|
||||
{
|
||||
var item = HistoricalData[Count - 1, SeekOriginHistory.Begin];
|
||||
|
||||
TValue result = ma.Update(new TValue(item.TimeLeft.Ticks, _priceSelector(item)), isNew: args.IsNewBar());
|
||||
|
||||
Series.SetValue(result.Value, ma.IsHot, ShowColdValues);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public class McnmaTests
|
||||
{
|
||||
[Fact]
|
||||
public void Mcnma_Matches_ManualCalculation()
|
||||
{
|
||||
// MCNMA = 2*TEMA(src,N) - TEMA(TEMA(src,N),N)
|
||||
const int period = 10;
|
||||
var mcnma = new Mcnma(period);
|
||||
var tema1 = new Tema(period);
|
||||
var tema2 = new Tema(period);
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 123);
|
||||
|
||||
for (int i = 0; i < 100; i++)
|
||||
{
|
||||
var bar = gbm.Next(isNew: true);
|
||||
var tVal = new TValue(bar.Time, bar.Close);
|
||||
|
||||
var mVal = mcnma.Update(tVal);
|
||||
|
||||
var t1Val = tema1.Update(tVal);
|
||||
var t2Val = tema2.Update(t1Val);
|
||||
double expected = 2.0 * t1Val.Value - t2Val.Value;
|
||||
|
||||
Assert.Equal(expected, mVal.Value, 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void StaticCalculate_Matches_ObjectUpdate()
|
||||
{
|
||||
const int period = 10;
|
||||
var source = new TSeries();
|
||||
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 123);
|
||||
for (int i = 0; i < 100; i++)
|
||||
{
|
||||
var bar = gbm.Next(isNew: true);
|
||||
source.Add(new TValue(bar.Time, bar.Close));
|
||||
}
|
||||
|
||||
var mcnmaSeries = Mcnma.Batch(source, period);
|
||||
var mcnmaObj = new Mcnma(period);
|
||||
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
var val = mcnmaObj.Update(source[i]);
|
||||
Assert.Equal(val.Value, mcnmaSeries[i].Value, 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ZeroAllocCalculate_Matches_ObjectUpdate()
|
||||
{
|
||||
const int period = 10;
|
||||
const int count = 100;
|
||||
var source = new double[count];
|
||||
var output = new double[count];
|
||||
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 123);
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
source[i] = gbm.Next().Close;
|
||||
}
|
||||
|
||||
Mcnma.Batch(source, output, period);
|
||||
var mcnmaObj = new Mcnma(period);
|
||||
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
var val = mcnmaObj.Update(new TValue(DateTime.UtcNow, source[i]));
|
||||
Assert.Equal(val.Value, output[i], 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Alpha_Constructor_Matches_Period_Constructor()
|
||||
{
|
||||
const int period = 10;
|
||||
double alpha = 2.0 / (period + 1);
|
||||
var mcnmaPeriod = new Mcnma(period);
|
||||
var mcnmaAlpha = new Mcnma(alpha);
|
||||
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 123);
|
||||
|
||||
for (int i = 0; i < 100; i++)
|
||||
{
|
||||
var bar = gbm.Next(isNew: true);
|
||||
var tVal = new TValue(bar.Time, bar.Close);
|
||||
|
||||
var pVal = mcnmaPeriod.Update(tVal);
|
||||
var aVal = mcnmaAlpha.Update(tVal);
|
||||
|
||||
Assert.Equal(pVal.Value, aVal.Value, 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Alpha_Constructor_Sets_WarmupPeriod()
|
||||
{
|
||||
const int period = 10;
|
||||
double alpha = 2.0 / (period + 1);
|
||||
var mcnma = new Mcnma(alpha);
|
||||
Assert.Equal(period, mcnma.WarmupPeriod);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void StaticCalculate_Alpha_Matches_ObjectUpdate()
|
||||
{
|
||||
const double alpha = 0.15;
|
||||
var source = new TSeries();
|
||||
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 123);
|
||||
for (int i = 0; i < 100; i++)
|
||||
{
|
||||
var bar = gbm.Next(isNew: true);
|
||||
source.Add(new TValue(bar.Time, bar.Close));
|
||||
}
|
||||
|
||||
var mcnmaSeries = Mcnma.Batch(source, alpha);
|
||||
var mcnmaObj = new Mcnma(alpha);
|
||||
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
var val = mcnmaObj.Update(source[i]);
|
||||
Assert.Equal(val.Value, mcnmaSeries[i].Value, 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ZeroAllocCalculate_Alpha_Matches_ObjectUpdate()
|
||||
{
|
||||
const double alpha = 0.15;
|
||||
const int count = 100;
|
||||
var source = new double[count];
|
||||
var output = new double[count];
|
||||
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 123);
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
source[i] = gbm.Next().Close;
|
||||
}
|
||||
|
||||
Mcnma.Batch(source, output, alpha);
|
||||
var mcnmaObj = new Mcnma(alpha);
|
||||
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
var val = mcnmaObj.Update(new TValue(DateTime.UtcNow, source[i]));
|
||||
Assert.Equal(val.Value, output[i], 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Mcnma_Constructor_ValidatesInput()
|
||||
{
|
||||
Assert.Throws<ArgumentException>(() => new Mcnma(0));
|
||||
Assert.Throws<ArgumentException>(() => new Mcnma(-1));
|
||||
Assert.Throws<ArgumentException>(() => new Mcnma(0.0));
|
||||
Assert.Throws<ArgumentException>(() => new Mcnma(1.1));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Mcnma_Calc_IsNew_AcceptsParameter()
|
||||
{
|
||||
var mcnma = new Mcnma(10);
|
||||
mcnma.Update(new TValue(DateTime.UtcNow, 100), isNew: true);
|
||||
Assert.Equal(100, mcnma.Last.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Mcnma_Reset_ClearsState()
|
||||
{
|
||||
var mcnma = new Mcnma(10);
|
||||
mcnma.Update(new TValue(DateTime.UtcNow, 100));
|
||||
mcnma.Update(new TValue(DateTime.UtcNow, 110));
|
||||
|
||||
mcnma.Reset();
|
||||
|
||||
Assert.Equal(0, mcnma.Last.Value);
|
||||
Assert.False(mcnma.IsHot);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Mcnma_IterativeCorrections_RestoreToOriginalState()
|
||||
{
|
||||
var mcnma = new Mcnma(10);
|
||||
var gbm = new GBM(startPrice: 100.0, mu: 0.02, sigma: 0.1);
|
||||
|
||||
TValue tenthInput = default;
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
var bar = gbm.Next(isNew: true);
|
||||
tenthInput = new TValue(bar.Time, bar.Close);
|
||||
mcnma.Update(tenthInput, isNew: true);
|
||||
}
|
||||
|
||||
double valueAfterTen = mcnma.Last.Value;
|
||||
|
||||
for (int i = 0; i < 9; i++)
|
||||
{
|
||||
var bar = gbm.Next(isNew: false);
|
||||
mcnma.Update(new TValue(bar.Time, bar.Close), isNew: false);
|
||||
}
|
||||
|
||||
TValue finalValue = mcnma.Update(tenthInput, isNew: false);
|
||||
|
||||
Assert.Equal(valueAfterTen, finalValue.Value, 1e-9);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Mcnma_NaN_Input_UsesLastValidValue()
|
||||
{
|
||||
var mcnma = new Mcnma(10);
|
||||
mcnma.Update(new TValue(DateTime.UtcNow, 100));
|
||||
mcnma.Update(new TValue(DateTime.UtcNow, 110));
|
||||
|
||||
var resultAfterNaN = mcnma.Update(new TValue(DateTime.UtcNow, double.NaN));
|
||||
|
||||
Assert.True(double.IsFinite(resultAfterNaN.Value));
|
||||
Assert.NotEqual(0, resultAfterNaN.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Mcnma_SpanCalc_ValidatesInput()
|
||||
{
|
||||
double[] source = [1, 2, 3, 4, 5];
|
||||
double[] output = new double[5];
|
||||
double[] wrongSizeOutput = new double[3];
|
||||
|
||||
Assert.Throws<ArgumentException>(() => Mcnma.Batch(source.AsSpan(), output.AsSpan(), 0));
|
||||
Assert.Throws<ArgumentException>(() => Mcnma.Batch(source.AsSpan(), wrongSizeOutput.AsSpan(), 3));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Mcnma_SpanCalc_HandlesNaN()
|
||||
{
|
||||
double[] source = [100, 110, double.NaN, 120, 130];
|
||||
double[] output = new double[5];
|
||||
|
||||
Mcnma.Batch(source.AsSpan(), output.AsSpan(), 3);
|
||||
|
||||
foreach (var val in output)
|
||||
{
|
||||
Assert.True(double.IsFinite(val));
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Mcnma_AllModes_ProduceSameResult()
|
||||
{
|
||||
const int period = 10;
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 123);
|
||||
var bars = gbm.Fetch(1000, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
var series = bars.Close;
|
||||
|
||||
// 1. Batch Mode
|
||||
var batchSeries = Mcnma.Batch(series, period);
|
||||
double expected = batchSeries.Last.Value;
|
||||
|
||||
// 2. Span Mode
|
||||
var tValues = series.Values.ToArray();
|
||||
var spanInput = new ReadOnlySpan<double>(tValues);
|
||||
var spanOutput = new double[tValues.Length];
|
||||
Mcnma.Batch(spanInput, spanOutput, period);
|
||||
double spanResult = spanOutput[^1];
|
||||
|
||||
// 3. Streaming Mode
|
||||
var streamingInd = new Mcnma(period);
|
||||
for (int i = 0; i < series.Count; i++)
|
||||
{
|
||||
streamingInd.Update(series[i]);
|
||||
}
|
||||
double streamingResult = streamingInd.Last.Value;
|
||||
|
||||
// 4. Eventing Mode
|
||||
var pubSource = new TSeries();
|
||||
var eventingInd = new Mcnma(pubSource, period);
|
||||
for (int i = 0; i < series.Count; i++)
|
||||
{
|
||||
pubSource.Add(series[i]);
|
||||
}
|
||||
double eventingResult = eventingInd.Last.Value;
|
||||
|
||||
Assert.Equal(expected, spanResult, precision: 9);
|
||||
Assert.Equal(expected, streamingResult, precision: 9);
|
||||
Assert.Equal(expected, eventingResult, precision: 9);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void StaticCalculate_HandlesInitialNaN_Correctly()
|
||||
{
|
||||
double[] source = { double.NaN, double.NaN, 10.0, 11.0, 12.0 };
|
||||
double[] output = new double[source.Length];
|
||||
|
||||
Mcnma.Batch(source, output, 3);
|
||||
|
||||
Assert.True(double.IsNaN(output[0]), $"Output[0] should be NaN, but was {output[0]}");
|
||||
Assert.True(double.IsNaN(output[1]), $"Output[1] should be NaN, but was {output[1]}");
|
||||
|
||||
Assert.Equal(10.0, output[2], 1e-9);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
using Xunit.Abstractions;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public sealed class McnmaValidationTests : IDisposable
|
||||
{
|
||||
private readonly ValidationTestData _testData;
|
||||
private readonly ITestOutputHelper _output;
|
||||
private bool _disposed;
|
||||
|
||||
public McnmaValidationTests(ITestOutputHelper output)
|
||||
{
|
||||
_output = output;
|
||||
_testData = new ValidationTestData();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(true);
|
||||
}
|
||||
|
||||
private void Dispose(bool disposing)
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
|
||||
if (disposing)
|
||||
{
|
||||
_testData?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_ManualTemaComposition_Batch()
|
||||
{
|
||||
// MCNMA = 2*TEMA(src) - TEMA(TEMA(src))
|
||||
int[] periods = { 5, 10, 14, 20, 50 };
|
||||
|
||||
foreach (var period in periods)
|
||||
{
|
||||
var mcnma = new Mcnma(period);
|
||||
var qResult = mcnma.Update(_testData.Data);
|
||||
|
||||
// Manual composition using two TEMA instances
|
||||
var tema1 = new Tema(period);
|
||||
var tema2 = new Tema(period);
|
||||
var manualResults = new List<double>();
|
||||
|
||||
for (int i = 0; i < _testData.Data.Count; i++)
|
||||
{
|
||||
var item = _testData.Data[i];
|
||||
var t1 = tema1.Update(item);
|
||||
var t2 = tema2.Update(t1);
|
||||
manualResults.Add(2.0 * t1.Value - t2.Value);
|
||||
}
|
||||
|
||||
for (int i = 0; i < qResult.Count; i++)
|
||||
{
|
||||
Assert.Equal(manualResults[i], qResult[i].Value, 1e-9);
|
||||
}
|
||||
}
|
||||
_output.WriteLine("MCNMA Batch(TSeries) validated successfully against manual TEMA composition");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_StreamingVsBatch_Consistency()
|
||||
{
|
||||
int[] periods = { 5, 10, 14, 20 };
|
||||
|
||||
foreach (var period in periods)
|
||||
{
|
||||
var batchResult = Mcnma.Batch(_testData.Data, period);
|
||||
|
||||
var streaming = new Mcnma(period);
|
||||
for (int i = 0; i < _testData.Data.Count; i++)
|
||||
{
|
||||
streaming.Update(_testData.Data[i]);
|
||||
}
|
||||
|
||||
int start = Math.Max(0, _testData.Data.Count - 100);
|
||||
for (int i = start; i < _testData.Data.Count; i++)
|
||||
{
|
||||
Assert.Equal(batchResult[i].Value, batchResult[i].Value, 1e-9);
|
||||
}
|
||||
}
|
||||
_output.WriteLine("MCNMA Streaming vs Batch validated successfully");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_SpanVsStreaming_Consistency()
|
||||
{
|
||||
int[] periods = { 5, 10, 14, 20 };
|
||||
double[] sourceData = _testData.RawData.ToArray();
|
||||
|
||||
foreach (var period in periods)
|
||||
{
|
||||
double[] spanOutput = new double[sourceData.Length];
|
||||
Mcnma.Batch(sourceData.AsSpan(), spanOutput.AsSpan(), period);
|
||||
|
||||
var streaming = new Mcnma(period);
|
||||
for (int i = 0; i < sourceData.Length; i++)
|
||||
{
|
||||
var val = streaming.Update(new TValue(DateTime.UtcNow, sourceData[i]));
|
||||
Assert.Equal(val.Value, spanOutput[i], 1e-9);
|
||||
}
|
||||
}
|
||||
_output.WriteLine("MCNMA Span vs Streaming validated successfully");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_ConstantInput_ConvergesToInput()
|
||||
{
|
||||
// With constant input, all EMAs converge to the constant.
|
||||
// TEMA(const) = 3*const - 3*const + const = const
|
||||
// MCNMA = 2*const - const = const
|
||||
const double constantValue = 42.0;
|
||||
const int period = 10;
|
||||
|
||||
var mcnma = new Mcnma(period);
|
||||
double lastResult = 0;
|
||||
|
||||
for (int i = 0; i < 200; i++)
|
||||
{
|
||||
var result = mcnma.Update(new TValue(DateTime.UtcNow, constantValue));
|
||||
lastResult = result.Value;
|
||||
}
|
||||
|
||||
Assert.Equal(constantValue, lastResult, 1e-6);
|
||||
_output.WriteLine("MCNMA constant input convergence validated successfully");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_Against_ManualFormula()
|
||||
{
|
||||
// Validate the explicit formula: 2*TEMA(src,N) - TEMA(TEMA(src,N),N)
|
||||
int[] periods = { 5, 10, 14, 20 };
|
||||
|
||||
foreach (var period in periods)
|
||||
{
|
||||
var mcnma = new Mcnma(period);
|
||||
var tema1 = new Tema(period);
|
||||
var tema2 = new Tema(period);
|
||||
|
||||
for (int i = 0; i < _testData.Data.Count; i++)
|
||||
{
|
||||
var item = _testData.Data[i];
|
||||
|
||||
var qVal = mcnma.Update(item);
|
||||
|
||||
var t1 = tema1.Update(item);
|
||||
var t2 = tema2.Update(t1);
|
||||
double manualVal = 2.0 * t1.Value - t2.Value;
|
||||
|
||||
Assert.Equal(manualVal, qVal.Value, ValidationHelper.DefaultTolerance);
|
||||
}
|
||||
}
|
||||
_output.WriteLine("MCNMA validated successfully against manual formula (2*TEMA - TEMA(TEMA))");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_NaN_Robustness()
|
||||
{
|
||||
const int period = 10;
|
||||
var mcnma = new Mcnma(period);
|
||||
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
mcnma.Update(new TValue(DateTime.UtcNow, 100.0 + i));
|
||||
}
|
||||
|
||||
var nanResult = mcnma.Update(new TValue(DateTime.UtcNow, double.NaN));
|
||||
Assert.True(double.IsFinite(nanResult.Value), "MCNMA should handle NaN with last-valid substitution");
|
||||
|
||||
var infResult = mcnma.Update(new TValue(DateTime.UtcNow, double.PositiveInfinity));
|
||||
Assert.True(double.IsFinite(infResult.Value), "MCNMA should handle Infinity with last-valid substitution");
|
||||
|
||||
var negInfResult = mcnma.Update(new TValue(DateTime.UtcNow, double.NegativeInfinity));
|
||||
Assert.True(double.IsFinite(negInfResult.Value), "MCNMA should handle -Infinity with last-valid substitution");
|
||||
|
||||
var resumeResult = mcnma.Update(new TValue(DateTime.UtcNow, 125.0));
|
||||
Assert.True(double.IsFinite(resumeResult.Value), "MCNMA should resume cleanly after invalid inputs");
|
||||
|
||||
_output.WriteLine("MCNMA NaN/Infinity robustness validated successfully");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,400 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace QuanTAlib;
|
||||
|
||||
/// <summary>
|
||||
/// MCNMA: McNicholl EMA (Zero-Lag TEMA)
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Applies DEMA lag-cancellation to TEMA itself, using six cascaded EMA stages.
|
||||
/// Three stages compute inner TEMA from source, three more compute outer TEMA
|
||||
/// from the inner TEMA output. Result: 2×TEMA₁ - TEMA₂.
|
||||
///
|
||||
/// Dennis McNicholl, "Better Bollinger Bands," Futures Magazine, October 1998.
|
||||
///
|
||||
/// Calculation: <c>MCNMA = 2×TEMA(src,N) - TEMA(TEMA(src,N),N)</c>.
|
||||
/// </remarks>
|
||||
/// <seealso href="Mcnma.md">Detailed documentation</seealso>
|
||||
/// <seealso href="mcnma.pine">Reference Pine Script implementation</seealso>
|
||||
[SkipLocalsInit]
|
||||
public sealed class Mcnma : AbstractBase
|
||||
{
|
||||
[StructLayout(LayoutKind.Auto)]
|
||||
private record struct EmaState(double Ema, double E, bool IsHot, bool IsCompensated)
|
||||
{
|
||||
public static EmaState New() => new() { Ema = 0, E = 1.0, IsHot = false, IsCompensated = false };
|
||||
}
|
||||
|
||||
private readonly double _alpha;
|
||||
private readonly double _decay;
|
||||
|
||||
// Inner TEMA stages (source → EMA1 → EMA2 → EMA3)
|
||||
private EmaState _s1 = EmaState.New();
|
||||
private EmaState _s2 = EmaState.New();
|
||||
private EmaState _s3 = EmaState.New();
|
||||
// Outer TEMA stages (TEMA1 → EMA4 → EMA5 → EMA6)
|
||||
private EmaState _s4 = EmaState.New();
|
||||
private EmaState _s5 = EmaState.New();
|
||||
private EmaState _s6 = EmaState.New();
|
||||
|
||||
private EmaState _ps1 = EmaState.New();
|
||||
private EmaState _ps2 = EmaState.New();
|
||||
private EmaState _ps3 = EmaState.New();
|
||||
private EmaState _ps4 = EmaState.New();
|
||||
private EmaState _ps5 = EmaState.New();
|
||||
private EmaState _ps6 = EmaState.New();
|
||||
|
||||
private double _lastValidValue = double.NaN;
|
||||
private double _p_lastValidValue = double.NaN;
|
||||
private bool _isNew = true;
|
||||
private readonly ITValuePublisher? _publisher;
|
||||
private readonly TValuePublishedHandler? _listener;
|
||||
|
||||
public bool IsNew => _isNew;
|
||||
public override bool IsHot => _s6.IsHot;
|
||||
|
||||
public Mcnma(int period)
|
||||
{
|
||||
if (period <= 0)
|
||||
{
|
||||
throw new ArgumentException("Period must be greater than 0", nameof(period));
|
||||
}
|
||||
|
||||
_alpha = 2.0 / (period + 1);
|
||||
_decay = 1.0 - _alpha;
|
||||
Name = $"Mcnma({period})";
|
||||
WarmupPeriod = period;
|
||||
}
|
||||
|
||||
public Mcnma(ITValuePublisher source, int period) : this(period)
|
||||
{
|
||||
_publisher = source;
|
||||
_listener = Handle;
|
||||
source.Pub += _listener;
|
||||
}
|
||||
|
||||
public Mcnma(double alpha)
|
||||
{
|
||||
if (alpha <= 0 || alpha > 1)
|
||||
{
|
||||
throw new ArgumentException("Alpha must be between 0 and 1", nameof(alpha));
|
||||
}
|
||||
|
||||
_alpha = alpha;
|
||||
_decay = 1.0 - alpha;
|
||||
Name = $"Mcnma(α={alpha:F4})";
|
||||
WarmupPeriod = (int)((2.0 / alpha) - 1.0);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public override TValue Update(TValue input, bool isNew = true)
|
||||
{
|
||||
_isNew = isNew;
|
||||
if (isNew)
|
||||
{
|
||||
_ps1 = _s1; _ps2 = _s2; _ps3 = _s3;
|
||||
_ps4 = _s4; _ps5 = _s5; _ps6 = _s6;
|
||||
_p_lastValidValue = _lastValidValue;
|
||||
}
|
||||
else
|
||||
{
|
||||
_s1 = _ps1; _s2 = _ps2; _s3 = _ps3;
|
||||
_s4 = _ps4; _s5 = _ps5; _s6 = _ps6;
|
||||
_lastValidValue = _p_lastValidValue;
|
||||
}
|
||||
|
||||
double val = input.Value;
|
||||
if (double.IsFinite(val))
|
||||
{
|
||||
_lastValidValue = val;
|
||||
}
|
||||
else
|
||||
{
|
||||
val = _lastValidValue;
|
||||
}
|
||||
|
||||
if (double.IsNaN(val))
|
||||
{
|
||||
Last = new TValue(input.Time, double.NaN);
|
||||
PubEvent(Last, isNew);
|
||||
return Last;
|
||||
}
|
||||
|
||||
// Inner TEMA: 3 cascaded EMAs
|
||||
double c1 = Compute(val, _alpha, _decay, ref _s1);
|
||||
double c2 = Compute(c1, _alpha, _decay, ref _s2);
|
||||
double c3 = Compute(c2, _alpha, _decay, ref _s3);
|
||||
// TEMA1 = 3*c1 - 3*c2 + c3
|
||||
double tema1 = Math.FusedMultiplyAdd(3.0, c1, Math.FusedMultiplyAdd(-3.0, c2, c3));
|
||||
|
||||
// Outer TEMA: 3 cascaded EMAs of TEMA1
|
||||
double c4 = Compute(tema1, _alpha, _decay, ref _s4);
|
||||
double c5 = Compute(c4, _alpha, _decay, ref _s5);
|
||||
double c6 = Compute(c5, _alpha, _decay, ref _s6);
|
||||
// TEMA2 = 3*c4 - 3*c5 + c6
|
||||
double tema2 = Math.FusedMultiplyAdd(3.0, c4, Math.FusedMultiplyAdd(-3.0, c5, c6));
|
||||
|
||||
// MCNMA = 2*TEMA1 - TEMA2
|
||||
double result = Math.FusedMultiplyAdd(2.0, tema1, -tema2);
|
||||
Last = new TValue(input.Time, result);
|
||||
PubEvent(Last, isNew);
|
||||
return Last;
|
||||
}
|
||||
|
||||
public override TSeries Update(TSeries source)
|
||||
{
|
||||
if (source.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
int len = source.Count;
|
||||
List<long> t = new(len);
|
||||
List<double> v = new(len);
|
||||
CollectionsMarshal.SetCount(t, len);
|
||||
CollectionsMarshal.SetCount(v, len);
|
||||
|
||||
var tSpan = CollectionsMarshal.AsSpan(t);
|
||||
var vSpan = CollectionsMarshal.AsSpan(v);
|
||||
source.Times.CopyTo(tSpan);
|
||||
|
||||
var sourceValues = source.Values;
|
||||
|
||||
EmaState preBatch_s1 = _s1, preBatch_s2 = _s2, preBatch_s3 = _s3;
|
||||
EmaState preBatch_s4 = _s4, preBatch_s5 = _s5, preBatch_s6 = _s6;
|
||||
double preBatch_lastValid = _lastValidValue;
|
||||
|
||||
EmaState s1 = _s1, s2 = _s2, s3 = _s3;
|
||||
EmaState s4 = _s4, s5 = _s5, s6 = _s6;
|
||||
double lastValid = _lastValidValue;
|
||||
double alpha = _alpha;
|
||||
double decay = _decay;
|
||||
|
||||
for (int i = 0; i < len; i++)
|
||||
{
|
||||
double val = sourceValues[i];
|
||||
if (double.IsFinite(val))
|
||||
{
|
||||
lastValid = val;
|
||||
}
|
||||
else
|
||||
{
|
||||
val = lastValid;
|
||||
}
|
||||
|
||||
if (double.IsNaN(val))
|
||||
{
|
||||
vSpan[i] = double.NaN;
|
||||
continue;
|
||||
}
|
||||
|
||||
double c1 = Compute(val, alpha, decay, ref s1);
|
||||
double c2 = Compute(c1, alpha, decay, ref s2);
|
||||
double c3 = Compute(c2, alpha, decay, ref s3);
|
||||
double tema1 = Math.FusedMultiplyAdd(3.0, c1, Math.FusedMultiplyAdd(-3.0, c2, c3));
|
||||
|
||||
double c4 = Compute(tema1, alpha, decay, ref s4);
|
||||
double c5 = Compute(c4, alpha, decay, ref s5);
|
||||
double c6 = Compute(c5, alpha, decay, ref s6);
|
||||
double tema2 = Math.FusedMultiplyAdd(3.0, c4, Math.FusedMultiplyAdd(-3.0, c5, c6));
|
||||
|
||||
vSpan[i] = Math.FusedMultiplyAdd(2.0, tema1, -tema2);
|
||||
}
|
||||
|
||||
_s1 = s1; _s2 = s2; _s3 = s3;
|
||||
_s4 = s4; _s5 = s5; _s6 = s6;
|
||||
_lastValidValue = lastValid;
|
||||
|
||||
_ps1 = preBatch_s1; _ps2 = preBatch_s2; _ps3 = preBatch_s3;
|
||||
_ps4 = preBatch_s4; _ps5 = preBatch_s5; _ps6 = preBatch_s6;
|
||||
_p_lastValidValue = preBatch_lastValid;
|
||||
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
|
||||
private static double Compute(double input, double alpha, double decay, ref EmaState state)
|
||||
{
|
||||
state.Ema = Math.FusedMultiplyAdd(state.Ema, decay, alpha * input);
|
||||
|
||||
double result;
|
||||
if (!state.IsCompensated)
|
||||
{
|
||||
state.E *= decay;
|
||||
|
||||
if (!state.IsHot && state.E <= 0.05)
|
||||
{
|
||||
state.IsHot = true;
|
||||
}
|
||||
|
||||
if (state.E <= 1e-10)
|
||||
{
|
||||
state.IsCompensated = true;
|
||||
result = state.Ema;
|
||||
}
|
||||
else
|
||||
{
|
||||
result = state.Ema / (1.0 - state.E);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
result = state.Ema;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static TSeries Batch(TSeries source, int period)
|
||||
{
|
||||
var mcnma = new Mcnma(period);
|
||||
return mcnma.Update(source);
|
||||
}
|
||||
|
||||
public static TSeries Batch(TSeries source, double alpha)
|
||||
{
|
||||
var mcnma = new Mcnma(alpha);
|
||||
return mcnma.Update(source);
|
||||
}
|
||||
|
||||
public static void Batch(ReadOnlySpan<double> source, Span<double> output, int period)
|
||||
{
|
||||
if (period <= 0)
|
||||
{
|
||||
throw new ArgumentException("Period must be greater than 0", nameof(period));
|
||||
}
|
||||
|
||||
double alpha = 2.0 / (period + 1);
|
||||
Batch(source, output, alpha);
|
||||
}
|
||||
|
||||
public static void Batch(ReadOnlySpan<double> source, Span<double> output, double alpha)
|
||||
{
|
||||
if (source.Length != output.Length)
|
||||
{
|
||||
throw new ArgumentException("Source and output must have the same length", nameof(output));
|
||||
}
|
||||
|
||||
if (alpha <= 0 || alpha > 1)
|
||||
{
|
||||
throw new ArgumentException("Alpha must be between 0 and 1", nameof(alpha));
|
||||
}
|
||||
|
||||
if (source.Length == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
double decay = 1.0 - alpha;
|
||||
double lastValid = double.NaN;
|
||||
|
||||
// 6 EMA stages inlined for maximum performance
|
||||
double e1 = 0, e2 = 0, e3 = 0, e4 = 0, e5 = 0, e6 = 0;
|
||||
double d1 = 1.0, d2 = 1.0, d3 = 1.0, d4 = 1.0, d5 = 1.0, d6 = 1.0;
|
||||
bool comp1 = false, comp2 = false, comp3 = false;
|
||||
bool comp4 = false, comp5 = false, comp6 = false;
|
||||
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
double val = source[i];
|
||||
if (double.IsFinite(val))
|
||||
{
|
||||
lastValid = val;
|
||||
}
|
||||
else
|
||||
{
|
||||
val = lastValid;
|
||||
}
|
||||
|
||||
if (double.IsNaN(val))
|
||||
{
|
||||
output[i] = double.NaN;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Stage 1: EMA of source
|
||||
e1 = Math.FusedMultiplyAdd(e1, decay, alpha * val);
|
||||
double c1;
|
||||
if (!comp1) { d1 *= decay; if (d1 <= 1e-10) { comp1 = true; c1 = e1; } else { c1 = e1 / (1.0 - d1); } }
|
||||
else { c1 = e1; }
|
||||
|
||||
// Stage 2: EMA of c1
|
||||
e2 = Math.FusedMultiplyAdd(e2, decay, alpha * c1);
|
||||
double c2;
|
||||
if (!comp2) { d2 *= decay; if (d2 <= 1e-10) { comp2 = true; c2 = e2; } else { c2 = e2 / (1.0 - d2); } }
|
||||
else { c2 = e2; }
|
||||
|
||||
// Stage 3: EMA of c2
|
||||
e3 = Math.FusedMultiplyAdd(e3, decay, alpha * c2);
|
||||
double c3;
|
||||
if (!comp3) { d3 *= decay; if (d3 <= 1e-10) { comp3 = true; c3 = e3; } else { c3 = e3 / (1.0 - d3); } }
|
||||
else { c3 = e3; }
|
||||
|
||||
// TEMA1 = 3*c1 - 3*c2 + c3
|
||||
double tema1 = Math.FusedMultiplyAdd(3.0, c1, Math.FusedMultiplyAdd(-3.0, c2, c3));
|
||||
|
||||
// Stage 4: EMA of TEMA1
|
||||
e4 = Math.FusedMultiplyAdd(e4, decay, alpha * tema1);
|
||||
double c4;
|
||||
if (!comp4) { d4 *= decay; if (d4 <= 1e-10) { comp4 = true; c4 = e4; } else { c4 = e4 / (1.0 - d4); } }
|
||||
else { c4 = e4; }
|
||||
|
||||
// Stage 5: EMA of c4
|
||||
e5 = Math.FusedMultiplyAdd(e5, decay, alpha * c4);
|
||||
double c5;
|
||||
if (!comp5) { d5 *= decay; if (d5 <= 1e-10) { comp5 = true; c5 = e5; } else { c5 = e5 / (1.0 - d5); } }
|
||||
else { c5 = e5; }
|
||||
|
||||
// Stage 6: EMA of c5
|
||||
e6 = Math.FusedMultiplyAdd(e6, decay, alpha * c5);
|
||||
double c6;
|
||||
if (!comp6) { d6 *= decay; if (d6 <= 1e-10) { comp6 = true; c6 = e6; } else { c6 = e6 / (1.0 - d6); } }
|
||||
else { c6 = e6; }
|
||||
|
||||
// TEMA2 = 3*c4 - 3*c5 + c6
|
||||
double tema2 = Math.FusedMultiplyAdd(3.0, c4, Math.FusedMultiplyAdd(-3.0, c5, c6));
|
||||
|
||||
// MCNMA = 2*TEMA1 - TEMA2
|
||||
output[i] = Math.FusedMultiplyAdd(2.0, tema1, -tema2);
|
||||
}
|
||||
}
|
||||
|
||||
public static (TSeries Results, Mcnma Indicator) Calculate(TSeries source, int period)
|
||||
{
|
||||
var indicator = new Mcnma(period);
|
||||
TSeries results = indicator.Update(source);
|
||||
return (results, indicator);
|
||||
}
|
||||
|
||||
public override void Reset()
|
||||
{
|
||||
_s1 = EmaState.New(); _s2 = EmaState.New(); _s3 = EmaState.New();
|
||||
_s4 = EmaState.New(); _s5 = EmaState.New(); _s6 = EmaState.New();
|
||||
_ps1 = EmaState.New(); _ps2 = EmaState.New(); _ps3 = EmaState.New();
|
||||
_ps4 = EmaState.New(); _ps5 = EmaState.New(); _ps6 = EmaState.New();
|
||||
_lastValidValue = double.NaN;
|
||||
_p_lastValidValue = double.NaN;
|
||||
Last = default;
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing && _publisher != null && _listener != null)
|
||||
{
|
||||
_publisher.Pub -= _listener;
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
private void Handle(object? sender, in TValueEventArgs e) => Update(e.Value, e.IsNew);
|
||||
}
|
||||
Reference in New Issue
Block a user