mirror of
https://github.com/mihakralj/QuanTAlib.git
synced 2026-08-23 21:18:04 +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,154 @@
|
||||
using TradingPlatform.BusinessLayer;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public class LemaIndicatorTests
|
||||
{
|
||||
[Fact]
|
||||
public void LemaIndicator_Constructor_SetsDefaults()
|
||||
{
|
||||
var indicator = new LemaIndicator();
|
||||
|
||||
Assert.Equal(10, indicator.Period);
|
||||
Assert.Equal(SourceType.Close, indicator.Source);
|
||||
Assert.True(indicator.ShowColdValues);
|
||||
Assert.Equal("LEMA - Leader Exponential Moving Average", indicator.Name);
|
||||
Assert.False(indicator.SeparateWindow);
|
||||
Assert.True(indicator.OnBackGround);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LemaIndicator_MinHistoryDepths_EqualsPeriod()
|
||||
{
|
||||
var indicator = new LemaIndicator { Period = 20 };
|
||||
|
||||
Assert.Equal(0, LemaIndicator.MinHistoryDepths);
|
||||
Assert.Equal(0, ((IWatchlistIndicator)indicator).MinHistoryDepths);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LemaIndicator_ShortName_IncludesPeriodAndSource()
|
||||
{
|
||||
var indicator = new LemaIndicator { Period = 15 };
|
||||
|
||||
Assert.Contains("LEMA", indicator.ShortName, StringComparison.Ordinal);
|
||||
Assert.Contains("15", indicator.ShortName, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LemaIndicator_SourceCodeLink_IsValid()
|
||||
{
|
||||
var indicator = new LemaIndicator();
|
||||
|
||||
Assert.Contains("github.com", indicator.SourceCodeLink, StringComparison.Ordinal);
|
||||
Assert.Contains("Lema.Quantower.cs", indicator.SourceCodeLink, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LemaIndicator_Initialize_CreatesInternalLema()
|
||||
{
|
||||
var indicator = new LemaIndicator { Period = 10 };
|
||||
|
||||
// Initialize should not throw
|
||||
indicator.Initialize();
|
||||
|
||||
// After init, line series should exist
|
||||
Assert.Single(indicator.LinesSeries);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LemaIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
|
||||
{
|
||||
var indicator = new LemaIndicator { Period = 3 };
|
||||
indicator.Initialize();
|
||||
|
||||
// Add historical data
|
||||
var now = DateTime.UtcNow;
|
||||
indicator.HistoricalData.AddBar(now, 100, 105, 95, 102);
|
||||
|
||||
// Process update
|
||||
var args = new UpdateArgs(UpdateReason.HistoricalBar);
|
||||
indicator.ProcessUpdate(args);
|
||||
|
||||
// Line series should have a value
|
||||
Assert.Equal(1, indicator.LinesSeries[0].Count);
|
||||
Assert.True(double.IsFinite(indicator.LinesSeries[0].GetValue(0)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LemaIndicator_ProcessUpdate_NewBar_ComputesValue()
|
||||
{
|
||||
var indicator = new LemaIndicator { 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 LemaIndicator_ProcessUpdate_NewTick_ProcessesWithoutError()
|
||||
{
|
||||
var indicator = new LemaIndicator { 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 LemaIndicator_MultipleUpdates_ProducesCorrectLemaSequence()
|
||||
{
|
||||
var indicator = new LemaIndicator { 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);
|
||||
}
|
||||
|
||||
// All values should be finite
|
||||
for (int i = 0; i < closes.Length; i++)
|
||||
{
|
||||
Assert.True(double.IsFinite(indicator.LinesSeries[0].GetValue(closes.Length - 1 - i)));
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LemaIndicator_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 LemaIndicator { 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 LemaIndicator : Indicator, IWatchlistIndicator
|
||||
{
|
||||
[InputParameter("Period", sortIndex: 1, 1, 1000, 1, 0)]
|
||||
public int Period { get; set; } = 10;
|
||||
|
||||
[IndicatorExtensions.DataSourceInput]
|
||||
public SourceType Source { get; set; } = SourceType.Close;
|
||||
|
||||
[InputParameter("Show cold values", sortIndex: 21)]
|
||||
public bool ShowColdValues { get; set; } = true;
|
||||
|
||||
private Lema 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 => $"LEMA {Period}:{SourceName}";
|
||||
public override string SourceCodeLink => "https://github.com/mihakralj/QuanTAlib/blob/main/lib/trends_IIR/lema/Lema.Quantower.cs";
|
||||
|
||||
public LemaIndicator()
|
||||
{
|
||||
OnBackGround = true;
|
||||
SeparateWindow = false;
|
||||
SourceName = Source.ToString();
|
||||
Name = "LEMA - Leader Exponential Moving Average";
|
||||
Description = "Leader Exponential Moving Average";
|
||||
Series = new LineSeries(name: $"LEMA {Period}", color: IndicatorExtensions.Averages, width: 2, style: LineStyle.Solid);
|
||||
AddLineSeries(Series);
|
||||
}
|
||||
|
||||
protected override void OnInit()
|
||||
{
|
||||
ma = new Lema(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,329 @@
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public class LemaTests
|
||||
{
|
||||
[Fact]
|
||||
public void Lema_Matches_ManualCalculation()
|
||||
{
|
||||
// Arrange
|
||||
const int period = 10;
|
||||
var lema = new Lema(period);
|
||||
var ema1 = new Ema(period);
|
||||
var ema2 = new Ema(period);
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 123);
|
||||
|
||||
// Act & Assert
|
||||
for (int i = 0; i < 100; i++)
|
||||
{
|
||||
var bar = gbm.Next(isNew: true);
|
||||
var tVal = new TValue(bar.Time, bar.Close);
|
||||
|
||||
var lVal = lema.Update(tVal);
|
||||
|
||||
var e1Val = ema1.Update(tVal);
|
||||
double error = tVal.Value - e1Val.Value;
|
||||
var e2Val = ema2.Update(new TValue(tVal.Time, error));
|
||||
double expected = e1Val.Value + e2Val.Value;
|
||||
|
||||
Assert.Equal(expected, lVal.Value, 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void StaticCalculate_Matches_ObjectUpdate()
|
||||
{
|
||||
// Arrange
|
||||
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));
|
||||
}
|
||||
|
||||
// Act
|
||||
var lemaSeries = Lema.Batch(source, period);
|
||||
var lemaObj = new Lema(period);
|
||||
|
||||
// Assert
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
var val = lemaObj.Update(source[i]);
|
||||
Assert.Equal(val.Value, lemaSeries[i].Value, 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ZeroAllocCalculate_Matches_ObjectUpdate()
|
||||
{
|
||||
// Arrange
|
||||
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;
|
||||
}
|
||||
|
||||
// Act
|
||||
Lema.Batch(source, output, period);
|
||||
var lemaObj = new Lema(period);
|
||||
|
||||
// Assert
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
var val = lemaObj.Update(new TValue(DateTime.UtcNow, source[i]));
|
||||
Assert.Equal(val.Value, output[i], 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Alpha_Constructor_Matches_Period_Constructor()
|
||||
{
|
||||
// Arrange
|
||||
const int period = 10;
|
||||
double alpha = 2.0 / (period + 1);
|
||||
var lemaPeriod = new Lema(period);
|
||||
var lemaAlpha = new Lema(alpha);
|
||||
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 123);
|
||||
|
||||
// Act & Assert
|
||||
for (int i = 0; i < 100; i++)
|
||||
{
|
||||
var bar = gbm.Next(isNew: true);
|
||||
var tVal = new TValue(bar.Time, bar.Close);
|
||||
|
||||
var pVal = lemaPeriod.Update(tVal);
|
||||
var aVal = lemaAlpha.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 lema = new Lema(alpha);
|
||||
Assert.Equal(period, lema.WarmupPeriod);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void StaticCalculate_Alpha_Matches_ObjectUpdate()
|
||||
{
|
||||
// Arrange
|
||||
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));
|
||||
}
|
||||
|
||||
// Act
|
||||
var lemaSeries = Lema.Batch(source, alpha);
|
||||
var lemaObj = new Lema(alpha);
|
||||
|
||||
// Assert
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
var val = lemaObj.Update(source[i]);
|
||||
Assert.Equal(val.Value, lemaSeries[i].Value, 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ZeroAllocCalculate_Alpha_Matches_ObjectUpdate()
|
||||
{
|
||||
// Arrange
|
||||
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;
|
||||
}
|
||||
|
||||
// Act
|
||||
Lema.Batch(source, output, alpha);
|
||||
var lemaObj = new Lema(alpha);
|
||||
|
||||
// Assert
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
var val = lemaObj.Update(new TValue(DateTime.UtcNow, source[i]));
|
||||
Assert.Equal(val.Value, output[i], 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Lema_Constructor_ValidatesInput()
|
||||
{
|
||||
Assert.Throws<ArgumentException>(() => new Lema(0));
|
||||
Assert.Throws<ArgumentException>(() => new Lema(-1));
|
||||
Assert.Throws<ArgumentException>(() => new Lema(0.0));
|
||||
Assert.Throws<ArgumentException>(() => new Lema(1.1));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Lema_Calc_IsNew_AcceptsParameter()
|
||||
{
|
||||
var lema = new Lema(10);
|
||||
lema.Update(new TValue(DateTime.UtcNow, 100), isNew: true);
|
||||
Assert.Equal(100, lema.Last.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Lema_Reset_ClearsState()
|
||||
{
|
||||
var lema = new Lema(10);
|
||||
lema.Update(new TValue(DateTime.UtcNow, 100));
|
||||
lema.Update(new TValue(DateTime.UtcNow, 110));
|
||||
|
||||
lema.Reset();
|
||||
|
||||
Assert.Equal(0, lema.Last.Value);
|
||||
Assert.False(lema.IsHot);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Lema_IterativeCorrections_RestoreToOriginalState()
|
||||
{
|
||||
var lema = new Lema(10);
|
||||
var gbm = new GBM(startPrice: 100.0, mu: 0.02, sigma: 0.1);
|
||||
|
||||
// Feed 10 new values
|
||||
TValue tenthInput = default;
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
var bar = gbm.Next(isNew: true);
|
||||
tenthInput = new TValue(bar.Time, bar.Close);
|
||||
lema.Update(tenthInput, isNew: true);
|
||||
}
|
||||
|
||||
// Remember state after 10 values
|
||||
double valueAfterTen = lema.Last.Value;
|
||||
|
||||
// Generate 9 corrections with isNew=false (different values)
|
||||
for (int i = 0; i < 9; i++)
|
||||
{
|
||||
var bar = gbm.Next(isNew: false);
|
||||
lema.Update(new TValue(bar.Time, bar.Close), isNew: false);
|
||||
}
|
||||
|
||||
// Feed the remembered 10th input again with isNew=false
|
||||
TValue finalValue = lema.Update(tenthInput, isNew: false);
|
||||
|
||||
// Should match the original state after 10 values
|
||||
Assert.Equal(valueAfterTen, finalValue.Value, 1e-9);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Lema_NaN_Input_UsesLastValidValue()
|
||||
{
|
||||
var lema = new Lema(10);
|
||||
lema.Update(new TValue(DateTime.UtcNow, 100));
|
||||
lema.Update(new TValue(DateTime.UtcNow, 110));
|
||||
|
||||
var resultAfterNaN = lema.Update(new TValue(DateTime.UtcNow, double.NaN));
|
||||
|
||||
Assert.True(double.IsFinite(resultAfterNaN.Value));
|
||||
Assert.NotEqual(0, resultAfterNaN.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Lema_SpanCalc_ValidatesInput()
|
||||
{
|
||||
double[] source = [1, 2, 3, 4, 5];
|
||||
double[] output = new double[5];
|
||||
double[] wrongSizeOutput = new double[3];
|
||||
|
||||
Assert.Throws<ArgumentException>(() => Lema.Batch(source.AsSpan(), output.AsSpan(), 0));
|
||||
Assert.Throws<ArgumentException>(() => Lema.Batch(source.AsSpan(), wrongSizeOutput.AsSpan(), 3));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Lema_SpanCalc_HandlesNaN()
|
||||
{
|
||||
double[] source = [100, 110, double.NaN, 120, 130];
|
||||
double[] output = new double[5];
|
||||
|
||||
Lema.Batch(source.AsSpan(), output.AsSpan(), 3);
|
||||
|
||||
foreach (var val in output)
|
||||
{
|
||||
Assert.True(double.IsFinite(val));
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Lema_AllModes_ProduceSameResult()
|
||||
{
|
||||
// Arrange
|
||||
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 = Lema.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];
|
||||
Lema.Batch(spanInput, spanOutput, period);
|
||||
double spanResult = spanOutput[^1];
|
||||
|
||||
// 3. Streaming Mode
|
||||
var streamingInd = new Lema(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 Lema(pubSource, period);
|
||||
for (int i = 0; i < series.Count; i++)
|
||||
{
|
||||
pubSource.Add(series[i]);
|
||||
}
|
||||
double eventingResult = eventingInd.Last.Value;
|
||||
|
||||
// Assert
|
||||
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];
|
||||
|
||||
Lema.Batch(source, output, 3);
|
||||
|
||||
// We expect the first two outputs to be NaN because the input was NaN
|
||||
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]}");
|
||||
|
||||
// The first valid value is 10.0.
|
||||
Assert.Equal(10.0, output[2], 1e-9);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
using Xunit.Abstractions;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public sealed class LemaValidationTests : IDisposable
|
||||
{
|
||||
private readonly ValidationTestData _testData;
|
||||
private readonly ITestOutputHelper _output;
|
||||
private bool _disposed;
|
||||
|
||||
public LemaValidationTests(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_ManualEmaComposition_Batch()
|
||||
{
|
||||
// LEMA = EMA(source) + EMA(source - EMA(source))
|
||||
// Validate batch mode against manual two-EMA composition
|
||||
int[] periods = { 5, 10, 20, 50, 100 };
|
||||
|
||||
foreach (var period in periods)
|
||||
{
|
||||
var lema = new Lema(period);
|
||||
var qResult = lema.Update(_testData.Data);
|
||||
|
||||
// Manual composition
|
||||
var ema1 = new Ema(period);
|
||||
var ema2 = new Ema(period);
|
||||
var manualResults = new List<double>();
|
||||
|
||||
for (int i = 0; i < _testData.Data.Count; i++)
|
||||
{
|
||||
var item = _testData.Data[i];
|
||||
var e1 = ema1.Update(item);
|
||||
double error = item.Value - e1.Value;
|
||||
var e2 = ema2.Update(new TValue(item.Time, error));
|
||||
manualResults.Add(e1.Value + e2.Value);
|
||||
}
|
||||
|
||||
// Compare all records
|
||||
for (int i = 0; i < qResult.Count; i++)
|
||||
{
|
||||
Assert.Equal(manualResults[i], qResult[i].Value, 1e-9);
|
||||
}
|
||||
}
|
||||
_output.WriteLine("LEMA Batch(TSeries) validated successfully against manual EMA composition");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_StreamingVsBatch_Consistency()
|
||||
{
|
||||
// Streaming mode must match batch mode exactly
|
||||
int[] periods = { 5, 10, 20, 50 };
|
||||
|
||||
foreach (var period in periods)
|
||||
{
|
||||
// Batch
|
||||
var batchResult = Lema.Batch(_testData.Data, period);
|
||||
|
||||
// Streaming
|
||||
var streaming = new Lema(period);
|
||||
for (int i = 0; i < _testData.Data.Count; i++)
|
||||
{
|
||||
streaming.Update(_testData.Data[i]);
|
||||
}
|
||||
|
||||
// Compare last 100 records
|
||||
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("LEMA Streaming vs Batch validated successfully");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_SpanVsStreaming_Consistency()
|
||||
{
|
||||
// Span API must match streaming exactly
|
||||
int[] periods = { 5, 10, 20, 50 };
|
||||
double[] sourceData = _testData.RawData.ToArray();
|
||||
|
||||
foreach (var period in periods)
|
||||
{
|
||||
// Span
|
||||
double[] spanOutput = new double[sourceData.Length];
|
||||
Lema.Batch(sourceData.AsSpan(), spanOutput.AsSpan(), period);
|
||||
|
||||
// Streaming
|
||||
var streaming = new Lema(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("LEMA Span vs Streaming validated successfully");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_ConstantInput_ConvergesToInput()
|
||||
{
|
||||
// LEMA of constant series should converge to the constant value
|
||||
// Since error = source - EMA(source) → 0, and EMA(0) → 0,
|
||||
// LEMA → EMA(source) + 0 = source (at convergence)
|
||||
const double constantValue = 42.0;
|
||||
const int period = 10;
|
||||
|
||||
var lema = new Lema(period);
|
||||
double lastResult = 0;
|
||||
|
||||
for (int i = 0; i < 200; i++)
|
||||
{
|
||||
var result = lema.Update(new TValue(DateTime.UtcNow, constantValue));
|
||||
lastResult = result.Value;
|
||||
}
|
||||
|
||||
// After enough iterations, LEMA should converge to the constant
|
||||
Assert.Equal(constantValue, lastResult, 1e-6);
|
||||
_output.WriteLine("LEMA constant input convergence validated successfully");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_Against_ManualFormula()
|
||||
{
|
||||
// Validate against the explicit LEMA formula:
|
||||
// LEMA = EMA(source, N) + EMA(source - EMA(source, N), N)
|
||||
// Using our own Ema class as reference (Ooples-equivalent validation)
|
||||
|
||||
int[] periods = { 5, 10, 14, 20 };
|
||||
|
||||
foreach (var period in periods)
|
||||
{
|
||||
var lema = new Lema(period);
|
||||
var ema1 = new Ema(period);
|
||||
var ema2 = new Ema(period);
|
||||
|
||||
for (int i = 0; i < _testData.Data.Count; i++)
|
||||
{
|
||||
var item = _testData.Data[i];
|
||||
|
||||
// QuanTAlib LEMA
|
||||
var qVal = lema.Update(item);
|
||||
|
||||
// Manual LEMA formula
|
||||
var e1 = ema1.Update(item);
|
||||
double error = item.Value - e1.Value;
|
||||
var e2 = ema2.Update(new TValue(item.Time, error));
|
||||
double manualVal = e1.Value + e2.Value;
|
||||
|
||||
Assert.Equal(manualVal, qVal.Value, ValidationHelper.DefaultTolerance);
|
||||
}
|
||||
}
|
||||
_output.WriteLine("LEMA validated successfully against manual formula (EMA + EMA(error))");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_NaN_Robustness()
|
||||
{
|
||||
// Feed data with interspersed NaN values and verify output stays finite
|
||||
const int period = 10;
|
||||
var lema = new Lema(period);
|
||||
|
||||
// Feed some valid values first to establish state
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
lema.Update(new TValue(DateTime.UtcNow, 100.0 + i));
|
||||
}
|
||||
|
||||
// Feed NaN
|
||||
var nanResult = lema.Update(new TValue(DateTime.UtcNow, double.NaN));
|
||||
Assert.True(double.IsFinite(nanResult.Value), "LEMA should handle NaN with last-valid substitution");
|
||||
|
||||
// Feed Infinity
|
||||
var infResult = lema.Update(new TValue(DateTime.UtcNow, double.PositiveInfinity));
|
||||
Assert.True(double.IsFinite(infResult.Value), "LEMA should handle Infinity with last-valid substitution");
|
||||
|
||||
// Feed negative Infinity
|
||||
var negInfResult = lema.Update(new TValue(DateTime.UtcNow, double.NegativeInfinity));
|
||||
Assert.True(double.IsFinite(negInfResult.Value), "LEMA should handle -Infinity with last-valid substitution");
|
||||
|
||||
// Resume with valid value
|
||||
var resumeResult = lema.Update(new TValue(DateTime.UtcNow, 125.0));
|
||||
Assert.True(double.IsFinite(resumeResult.Value), "LEMA should resume cleanly after invalid inputs");
|
||||
|
||||
_output.WriteLine("LEMA NaN/Infinity robustness validated successfully");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,388 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace QuanTAlib;
|
||||
|
||||
/// <summary>
|
||||
/// LEMA: Leader Exponential Moving Average
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Adds a smoothed error correction to the standard EMA, making it respond
|
||||
/// faster than EMA while maintaining smoothness. The error term captures the
|
||||
/// systematic tracking deficit and adds it back.
|
||||
///
|
||||
/// Calculation: <c>LEMA = EMA(source, N) + EMA(source - EMA(source, N), N)</c>.
|
||||
/// </remarks>
|
||||
/// <seealso href="Lema.md">Detailed documentation</seealso>
|
||||
/// <seealso href="lema.pine">Reference Pine Script implementation</seealso>
|
||||
[SkipLocalsInit]
|
||||
public sealed class Lema : 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;
|
||||
|
||||
private EmaState _state1 = EmaState.New();
|
||||
private EmaState _state2 = EmaState.New();
|
||||
private EmaState _p_state1 = EmaState.New();
|
||||
private EmaState _p_state2 = 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 => _state2.IsHot;
|
||||
|
||||
public Lema(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 = $"Lema({period})";
|
||||
WarmupPeriod = period;
|
||||
}
|
||||
|
||||
public Lema(ITValuePublisher source, int period) : this(period)
|
||||
{
|
||||
_publisher = source;
|
||||
_listener = Handle;
|
||||
source.Pub += _listener;
|
||||
}
|
||||
|
||||
public Lema(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 = $"Lema(α={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)
|
||||
{
|
||||
_p_state1 = _state1;
|
||||
_p_state2 = _state2;
|
||||
_p_lastValidValue = _lastValidValue;
|
||||
}
|
||||
else
|
||||
{
|
||||
_state1 = _p_state1;
|
||||
_state2 = _p_state2;
|
||||
_lastValidValue = _p_lastValidValue;
|
||||
}
|
||||
|
||||
// Sanitize input
|
||||
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;
|
||||
}
|
||||
|
||||
// EMA1: standard EMA of source
|
||||
double e1 = Compute(val, _alpha, _decay, ref _state1);
|
||||
|
||||
// Error: source - EMA(source)
|
||||
double error = val - e1;
|
||||
|
||||
// EMA2: EMA of the error series
|
||||
double e2 = Compute(error, _alpha, _decay, ref _state2);
|
||||
|
||||
// LEMA = EMA(source) + EMA(error)
|
||||
double result = e1 + e2;
|
||||
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;
|
||||
|
||||
// Capture pre-batch state for rollback
|
||||
EmaState preBatch_s1 = _state1;
|
||||
EmaState preBatch_s2 = _state2;
|
||||
double preBatch_lastValid = _lastValidValue;
|
||||
|
||||
// Use current state for calculation
|
||||
EmaState s1 = _state1;
|
||||
EmaState s2 = _state2;
|
||||
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 e1 = Compute(val, alpha, decay, ref s1);
|
||||
double error = val - e1;
|
||||
double e2 = Compute(error, alpha, decay, ref s2);
|
||||
|
||||
vSpan[i] = e1 + e2;
|
||||
}
|
||||
|
||||
// Update instance state with post-batch values
|
||||
_state1 = s1;
|
||||
_state2 = s2;
|
||||
_lastValidValue = lastValid;
|
||||
|
||||
// Preserve pre-batch state for rollback (isNew=false)
|
||||
_p_state1 = preBatch_s1;
|
||||
_p_state2 = preBatch_s2;
|
||||
_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) // COVERAGE_THRESHOLD
|
||||
{
|
||||
state.IsHot = true;
|
||||
}
|
||||
|
||||
if (state.E <= 1e-10) // COMPENSATOR_THRESHOLD
|
||||
{
|
||||
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 lema = new Lema(period);
|
||||
return lema.Update(source);
|
||||
}
|
||||
|
||||
public static TSeries Batch(TSeries source, double alpha)
|
||||
{
|
||||
var lema = new Lema(alpha);
|
||||
return lema.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;
|
||||
|
||||
// State for EMA1 (source)
|
||||
double ema1_val = 0;
|
||||
double ema1_e = 1.0;
|
||||
bool ema1_isCompensated = false;
|
||||
|
||||
// State for EMA2 (error)
|
||||
double ema2_val = 0;
|
||||
double ema2_e = 1.0;
|
||||
bool ema2_isCompensated = 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;
|
||||
}
|
||||
|
||||
// Update EMA1 (source)
|
||||
ema1_val = Math.FusedMultiplyAdd(ema1_val, decay, alpha * val);
|
||||
double e1;
|
||||
if (!ema1_isCompensated)
|
||||
{
|
||||
ema1_e *= decay;
|
||||
if (ema1_e <= 1e-10)
|
||||
{
|
||||
ema1_isCompensated = true;
|
||||
e1 = ema1_val;
|
||||
}
|
||||
else
|
||||
{
|
||||
e1 = ema1_val / (1.0 - ema1_e);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
e1 = ema1_val;
|
||||
}
|
||||
|
||||
// Error = source - EMA(source)
|
||||
double error = val - e1;
|
||||
|
||||
// Update EMA2 (error)
|
||||
ema2_val = Math.FusedMultiplyAdd(ema2_val, decay, alpha * error);
|
||||
double e2;
|
||||
if (!ema2_isCompensated)
|
||||
{
|
||||
ema2_e *= decay;
|
||||
if (ema2_e <= 1e-10)
|
||||
{
|
||||
ema2_isCompensated = true;
|
||||
e2 = ema2_val;
|
||||
}
|
||||
else
|
||||
{
|
||||
e2 = ema2_val / (1.0 - ema2_e);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
e2 = ema2_val;
|
||||
}
|
||||
|
||||
// LEMA = EMA(source) + EMA(error)
|
||||
output[i] = e1 + e2;
|
||||
}
|
||||
}
|
||||
|
||||
public static (TSeries Results, Lema Indicator) Calculate(TSeries source, int period)
|
||||
{
|
||||
var indicator = new Lema(period);
|
||||
TSeries results = indicator.Update(source);
|
||||
return (results, indicator);
|
||||
}
|
||||
|
||||
public override void Reset()
|
||||
{
|
||||
_state1 = EmaState.New();
|
||||
_state2 = EmaState.New();
|
||||
_p_state1 = EmaState.New();
|
||||
_p_state2 = 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