refactoring

This commit is contained in:
Miha Kralj
2025-12-16 21:16:50 -08:00
parent a67ad65fa5
commit d277e08056
137 changed files with 5074 additions and 3178 deletions
+65 -65
View File
@@ -1,65 +1,65 @@
using System.Drawing;
using TradingPlatform.BusinessLayer;
namespace QuanTAlib;
public class EmaIndicator : 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 Ema? ma;
protected LineSeries? Series;
protected string? SourceName;
private int _warmupBarIndex = -1;
public int MinHistoryDepths => Period;
int IWatchlistIndicator.MinHistoryDepths => MinHistoryDepths;
public override string ShortName => $"EMA {Period}:{SourceName}";
public EmaIndicator()
{
OnBackGround = true;
SeparateWindow = false;
SourceName = Source.ToString();
Name = "EMA - Exponential Moving Average";
Description = "Exponential Moving Average";
Series = new(name: $"EMA {Period}", color: IndicatorExtensions.Averages, width: 2, style: LineStyle.Solid);
AddLineSeries(Series);
}
protected override void OnInit()
{
ma = new Ema(Period);
SourceName = Source.ToString();
_warmupBarIndex = -1; // Reset warmup tracking when period changes
base.OnInit();
}
protected override void OnUpdate(UpdateArgs args)
{
TValue input = this.GetInputValue(args, Source);
bool isNew = args.Reason == UpdateReason.NewBar || args.Reason == UpdateReason.HistoricalBar;
TValue result = ma!.Update(input, isNew);
Series!.SetValue(result.Value);
Series!.SetMarker(0, Color.Transparent); //OnPaintChart draws the line, hidden here
// Track when IsHot becomes true for the first time
if (_warmupBarIndex < 0 && ma!.IsHot)
_warmupBarIndex = Count;
}
public override void OnPaintChart(PaintChartEventArgs args)
{
base.OnPaintChart(args);
int warmupPeriod = _warmupBarIndex > 0 ? _warmupBarIndex : Count;
this.PaintSmoothCurve(args, Series!, warmupPeriod, showColdValues: ShowColdValues, tension: 0.2);
}
}
using System.Drawing;
using TradingPlatform.BusinessLayer;
namespace QuanTAlib;
public class EmaIndicator : 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 Ema? ma;
protected LineSeries? Series;
protected string? SourceName;
private int _warmupBarIndex = -1;
public int MinHistoryDepths => Period;
int IWatchlistIndicator.MinHistoryDepths => MinHistoryDepths;
public override string ShortName => $"EMA {Period}:{SourceName}";
public EmaIndicator()
{
OnBackGround = true;
SeparateWindow = false;
SourceName = Source.ToString();
Name = "EMA - Exponential Moving Average";
Description = "Exponential Moving Average";
Series = new(name: $"EMA {Period}", color: IndicatorExtensions.Averages, width: 2, style: LineStyle.Solid);
AddLineSeries(Series);
}
protected override void OnInit()
{
ma = new Ema(Period);
SourceName = Source.ToString();
_warmupBarIndex = -1; // Reset warmup tracking when period changes
base.OnInit();
}
protected override void OnUpdate(UpdateArgs args)
{
TValue input = this.GetInputValue(args, Source);
bool isNew = args.Reason == UpdateReason.NewBar || args.Reason == UpdateReason.HistoricalBar;
TValue result = ma!.Update(input, isNew);
Series!.SetValue(result.Value);
Series!.SetMarker(0, Color.Transparent); //OnPaintChart draws the line, hidden here
// Track when IsHot becomes true for the first time
if (_warmupBarIndex < 0 && ma!.IsHot)
_warmupBarIndex = Count;
}
public override void OnPaintChart(PaintChartEventArgs args)
{
base.OnPaintChart(args);
int warmupPeriod = _warmupBarIndex > 0 ? _warmupBarIndex : Count;
this.PaintSmoothCurve(args, Series!, warmupPeriod, showColdValues: ShowColdValues, tension: 0.2);
}
}
+103 -24
View File
@@ -363,34 +363,34 @@ public class EmaTests
// ============== Span API Tests ==============
[Fact]
public void Ema_SpanCalc_Period_ValidatesInput()
public void Ema_SpanBatch_Period_ValidatesInput()
{
double[] source = [1, 2, 3, 4, 5];
double[] output = new double[5];
double[] wrongSizeOutput = new double[3];
// Period must be > 0
Assert.Throws<ArgumentException>(() => Ema.Calculate(source.AsSpan(), output.AsSpan(), 0));
Assert.Throws<ArgumentException>(() => Ema.Calculate(source.AsSpan(), output.AsSpan(), -1));
Assert.Throws<ArgumentException>(() => Ema.Batch(source.AsSpan(), output.AsSpan(), 0));
Assert.Throws<ArgumentException>(() => Ema.Batch(source.AsSpan(), output.AsSpan(), -1));
// Output must be same length as source
Assert.Throws<ArgumentException>(() => Ema.Calculate(source.AsSpan(), wrongSizeOutput.AsSpan(), 3));
Assert.Throws<ArgumentException>(() => Ema.Batch(source.AsSpan(), wrongSizeOutput.AsSpan(), 3));
}
[Fact]
public void Ema_SpanCalc_Alpha_ValidatesInput()
public void Ema_SpanBatch_Alpha_ValidatesInput()
{
double[] source = [1, 2, 3, 4, 5];
double[] output = new double[5];
// Alpha must be > 0 and <= 1
Assert.Throws<ArgumentException>(() => Ema.Calculate(source.AsSpan(), output.AsSpan(), 0.0));
Assert.Throws<ArgumentException>(() => Ema.Calculate(source.AsSpan(), output.AsSpan(), -0.1));
Assert.Throws<ArgumentException>(() => Ema.Calculate(source.AsSpan(), output.AsSpan(), 1.1));
Assert.Throws<ArgumentException>(() => Ema.Batch(source.AsSpan(), output.AsSpan(), 0.0));
Assert.Throws<ArgumentException>(() => Ema.Batch(source.AsSpan(), output.AsSpan(), -0.1));
Assert.Throws<ArgumentException>(() => Ema.Batch(source.AsSpan(), output.AsSpan(), 1.1));
}
[Fact]
public void Ema_SpanCalc_MatchesTSeriesCalc()
public void Ema_SpanBatch_MatchesTSeriesBatch()
{
var series = new TSeries();
double[] source = new double[100];
@@ -405,10 +405,10 @@ public class EmaTests
}
// Calculate with TSeries API
var tseriesResult = Ema.Calculate(series, 10);
var tseriesResult = Ema.Batch(series, 10);
// Calculate with Span API
Ema.Calculate(source.AsSpan(), output.AsSpan(), 10);
Ema.Batch(source.AsSpan(), output.AsSpan(), 10);
// Compare results - allow small tolerance due to bias correction differences
for (int i = 0; i < 100; i++)
@@ -418,7 +418,7 @@ public class EmaTests
}
[Fact]
public void Ema_SpanCalc_PeriodAndAlphaEquivalent()
public void Ema_SpanBatch_PeriodAndAlphaEquivalent()
{
double[] source = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100];
double[] outputPeriod = new double[10];
@@ -427,8 +427,8 @@ public class EmaTests
int period = 5;
double alpha = 2.0 / (period + 1);
Ema.Calculate(source.AsSpan(), outputPeriod.AsSpan(), period);
Ema.Calculate(source.AsSpan(), outputAlpha.AsSpan(), alpha);
Ema.Batch(source.AsSpan(), outputPeriod.AsSpan(), period);
Ema.Batch(source.AsSpan(), outputAlpha.AsSpan(), alpha);
// Results should be identical
for (int i = 0; i < 10; i++)
@@ -438,7 +438,7 @@ public class EmaTests
}
[Fact]
public void Ema_SpanCalc_ZeroAllocation()
public void Ema_SpanBatch_ZeroAllocation()
{
double[] source = new double[10000];
double[] output = new double[10000];
@@ -448,19 +448,19 @@ public class EmaTests
source[i] = gbm.Next().Close;
// Warm up
Ema.Calculate(source.AsSpan(), output.AsSpan(), 100);
Ema.Batch(source.AsSpan(), output.AsSpan(), 100);
// This test verifies the method runs without throwing
Assert.True(double.IsFinite(output[^1]));
}
[Fact]
public void Ema_SpanCalc_HandlesNaN()
public void Ema_SpanBatch_HandlesNaN()
{
double[] source = [100, 110, double.NaN, 120, 130];
double[] output = new double[5];
Ema.Calculate(source.AsSpan(), output.AsSpan(), 3);
Ema.Batch(source.AsSpan(), output.AsSpan(), 3);
// All outputs should be finite
foreach (var val in output)
@@ -470,12 +470,12 @@ public class EmaTests
}
[Fact]
public void Ema_SpanCalc_BiasCorrection_Works()
public void Ema_SpanBatch_BiasCorrection_Works()
{
double[] source = [100, 100, 100, 100, 100];
double[] output = new double[5];
Ema.Calculate(source.AsSpan(), output.AsSpan(), 3);
Ema.Batch(source.AsSpan(), output.AsSpan(), 3);
// With bias correction, first value should equal input
Assert.Equal(100.0, output[0], 1e-10);
@@ -488,18 +488,97 @@ public class EmaTests
}
[Fact]
public void Ema_SpanCalc_Alpha_DirectUsage()
public void Ema_SpanBatch_Alpha_DirectUsage()
{
double[] source = [10, 20, 30, 40, 50];
double[] output = new double[5];
// Use alpha = 0.5 directly
Ema.Calculate(source.AsSpan(), output.AsSpan(), 0.5);
Ema.Batch(source.AsSpan(), output.AsSpan(), 0.5);
// Results should be finite and reasonable
Assert.True(double.IsFinite(output[^1]));
Assert.True(output[^1] > 10 && output[^1] <= 50);
}
[Fact]
public void Chainability_Works()
{
var source = new TSeries();
var ema = new Ema(source, 10);
source.Add(new TValue(DateTime.UtcNow, 100));
Assert.Equal(100, ema.Last.Value, 1e-10);
}
[Fact]
public void Prime_SetsStateCorrectly()
{
var ema = new Ema(5);
double[] history = [10, 20, 30, 40, 50];
ema.Prime(history);
// EMA(5) of 10,20,30,40,50
// Alpha = 2/6 = 1/3
// 10 -> 10
// 20 -> 10 + 1/3(10) = 13.33...
// ...
// We can verify against a fresh EMA fed with same data
var verifyEma = new Ema(5);
foreach (var val in history) verifyEma.Update(new TValue(DateTime.UtcNow, val));
Assert.Equal(verifyEma.Last.Value, ema.Last.Value, 1e-10);
Assert.Equal(verifyEma.IsHot, ema.IsHot);
// Verify it continues correctly
ema.Update(new TValue(DateTime.UtcNow, 60));
verifyEma.Update(new TValue(DateTime.UtcNow, 60));
Assert.Equal(verifyEma.Last.Value, ema.Last.Value, 1e-10);
}
[Fact]
public void Prime_HandlesNaN_InHistory()
{
var ema = new Ema(5);
double[] history = [10, 20, double.NaN, 40, 50];
ema.Prime(history);
var verifyEma = new Ema(5);
foreach (var val in history) verifyEma.Update(new TValue(DateTime.UtcNow, val));
Assert.Equal(verifyEma.Last.Value, ema.Last.Value, 1e-10);
}
[Fact]
public void Calculate_ReturnsCorrectResultsAndHotIndicator()
{
var series = new TSeries();
for (int i = 1; i <= 20; i++) series.Add(DateTime.UtcNow, i * 10);
// EMA(5)
var (results, indicator) = Ema.Calculate(series, 5);
// Check results
Assert.Equal(20, results.Count);
// Verify against standard calculation
var verifyEma = new Ema(5);
var verifyResults = verifyEma.Update(series);
Assert.Equal(verifyResults.Last.Value, results.Last.Value, 1e-10);
Assert.Equal(verifyEma.Last.Value, indicator.Last.Value, 1e-10);
// Check indicator state
Assert.True(indicator.IsHot);
// Verify indicator continues correctly
indicator.Update(new TValue(DateTime.UtcNow, 210));
verifyEma.Update(new TValue(DateTime.UtcNow, 210));
Assert.Equal(verifyEma.Last.Value, indicator.Last.Value, 1e-10);
}
[Fact]
public void Ema_AllModes_ProduceSameResult()
{
@@ -510,14 +589,14 @@ public class EmaTests
var series = bars.Close;
// 1. Batch Mode
var batchSeries = Ema.Calculate(series, period);
var batchSeries = Ema.Batch(series, period);
double expected = batchSeries.Last.Value;
// 2. Span Mode
var tValues = series.Values.ToArray(); // Need array for Span modification safety if any
var spanInput = new ReadOnlySpan<double>(tValues);
var spanOutput = new double[tValues.Length];
Ema.Calculate(spanInput, spanOutput, period);
Ema.Batch(spanInput, spanOutput, period);
double spanResult = spanOutput[^1];
// 3. Streaming Mode
+3 -3
View File
@@ -91,7 +91,7 @@ public class EmaValidationTests : IDisposable
{
// Calculate QuanTAlib EMA (Span API)
double[] qOutput = new double[sourceData.Length];
global::QuanTAlib.Ema.Calculate(sourceData.AsSpan(), qOutput.AsSpan(), period);
global::QuanTAlib.Ema.Batch(sourceData.AsSpan(), qOutput.AsSpan(), period);
// Calculate Skender EMA
var sResult = _testData.SkenderQuotes.GetEma(period).ToList();
@@ -173,7 +173,7 @@ public class EmaValidationTests : IDisposable
{
// Calculate QuanTAlib EMA (Span API)
double[] qOutput = new double[sourceData.Length];
global::QuanTAlib.Ema.Calculate(sourceData.AsSpan(), qOutput.AsSpan(), period);
global::QuanTAlib.Ema.Batch(sourceData.AsSpan(), qOutput.AsSpan(), period);
// Calculate TA-Lib EMA
var retCode = TALib.Functions.Ema<double>(sourceData, 0..^0, talibOutput, out var outRange, period);
@@ -261,7 +261,7 @@ public class EmaValidationTests : IDisposable
{
// Calculate QuanTAlib EMA (Span API)
double[] qOutput = new double[sourceData.Length];
global::QuanTAlib.Ema.Calculate(sourceData.AsSpan(), qOutput.AsSpan(), period);
global::QuanTAlib.Ema.Batch(sourceData.AsSpan(), qOutput.AsSpan(), period);
// Calculate Tulip EMA
var emaIndicator = Tulip.Indicators.ema;
+394 -296
View File
@@ -1,296 +1,394 @@
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace QuanTAlib;
/// <summary>
/// EMA: Exponential Moving Average
/// </summary>
/// <remarks>
/// EMA applies exponential weighting to data points, giving more weight to recent values.
/// Uses a single state variable for O(1) complexity per update.
///
/// Calculation:
/// alpha = 2 / (period + 1)
/// EMA_new = EMA_old + alpha * (newest - EMA_old)
///
/// Initialization:
/// Uses a compensator factor to correct early-stage bias (when n < period).
/// Output = EMA_state / (1 - (1-alpha)^n)
///
/// O(1) update:
/// No buffer required, only previous EMA value and compensator state.
///
/// IsHot:
/// Becomes true when n = ln(0.05) / ln(1 - alpha)
/// </remarks>
[SkipLocalsInit]
public sealed class Ema : ITValuePublisher
{
private record struct State(double Ema, double E, bool IsHot, bool IsCompensated)
{
public static State New() => new() { Ema = 0, E = 1.0, IsHot = false, IsCompensated = false };
}
private readonly double _alpha;
private readonly double _decay;
private State _state = State.New();
private State _p_state = State.New();
private double _lastValidValue;
private double _p_lastValidValue;
/// <summary>
/// Display name for the indicator.
/// </summary>
public string Name { get; }
public event Action<TValue>? Pub;
/// <summary>
/// Creates EMA with specified period.
/// Alpha = 2 / (period + 1)
/// </summary>
/// <param name="period">Period for EMA calculation (must be > 0)</param>
public Ema(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 = $"Ema({period})";
}
/// <summary>
/// Creates EMA with specified source and period.
/// Subscribes to source.Pub event.
/// </summary>
/// <param name="source">Source to subscribe to</param>
/// <param name="period">Period for EMA calculation</param>
public Ema(ITValuePublisher source, int period) : this(period)
{
source.Pub += (item) => Update(item);
}
/// <summary>
/// Creates EMA with specified alpha smoothing factor.
/// </summary>
/// <param name="alpha">Smoothing factor (0 &lt; alpha &lt;= 1)</param>
public Ema(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 = $"Ema(α={alpha:F4})";
}
/// <summary>
/// Current EMA value.
/// </summary>
public TValue Last { get; private set; }
/// <summary>
/// True if the EMA has warmed up and is providing valid results.
/// </summary>
public bool IsHot => _state.IsHot;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private double GetValidValue(double input)
{
if (double.IsFinite(input))
{
_lastValidValue = input;
return input;
}
return _lastValidValue;
}
private const double COVERAGE_THRESHOLD = 0.05;
private const double COMPENSATOR_THRESHOLD = 1e-10;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TValue Update(TValue input, bool isNew = true)
{
if (isNew)
{
_p_state = _state;
_p_lastValidValue = _lastValidValue;
}
else
{
_state = _p_state;
_lastValidValue = _p_lastValidValue;
}
double val = GetValidValue(input.Value);
val = Compute(val, _alpha, _decay, ref _state);
Last = new TValue(input.Time, val);
Pub?.Invoke(Last);
return Last;
}
public TSeries Update(TSeries source)
{
if (source.Count == 0) return [];
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);
var sourceValues = source.Values;
var sourceTimes = source.Times;
State state = _state;
double lastValidValue = _lastValidValue;
CalculateCore(sourceValues, vSpan, _alpha, ref state, ref lastValidValue);
_state = state;
_lastValidValue = lastValidValue;
sourceTimes.CopyTo(tSpan);
_p_state = _state;
_p_lastValidValue = _lastValidValue;
Last = new TValue(tSpan[len - 1], vSpan[len - 1]);
return new TSeries(t, v);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static double Compute(double input, double alpha, double decay, ref State state)
{
state.Ema += alpha * (input - state.Ema);
double result;
if (!state.IsCompensated)
{
state.E *= decay;
if (!state.IsHot && state.E <= COVERAGE_THRESHOLD)
state.IsHot = true;
if (state.E <= COMPENSATOR_THRESHOLD)
{
state.IsCompensated = true;
result = state.Ema;
}
else
{
result = state.Ema / (1.0 - state.E);
}
}
else
{
result = state.Ema;
}
return result;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void CalculateCore(ReadOnlySpan<double> source, Span<double> output, double alpha, ref State state, ref double lastValidValue)
{
int len = source.Length;
double decay = 1.0 - alpha;
int i = 0;
if (!state.IsCompensated)
{
for (; i < len && state.E > COMPENSATOR_THRESHOLD; i++)
{
double val = source[i];
if (double.IsFinite(val))
lastValidValue = val;
else
val = lastValidValue;
state.Ema += alpha * (val - state.Ema);
state.E *= decay;
if (!state.IsHot && state.E <= COVERAGE_THRESHOLD)
state.IsHot = true;
output[i] = state.Ema / (1.0 - state.E);
}
if (state.E <= COMPENSATOR_THRESHOLD)
state.IsCompensated = true;
}
for (; i < len; i++)
{
double val = source[i];
if (double.IsFinite(val))
lastValidValue = val;
else
val = lastValidValue;
state.Ema += alpha * (val - state.Ema);
output[i] = state.Ema;
}
}
/// <summary>
/// Calculates EMA for the entire series using a new instance.
/// </summary>
/// <param name="source">Input series</param>
/// <param name="period">EMA period</param>
/// <returns>EMA series</returns>
public static TSeries Calculate(TSeries source, int period)
{
var ema = new Ema(period);
return ema.Update(source);
}
/// <summary>
/// Calculates EMA in-place using period, writing results to pre-allocated output span.
/// Zero-allocation method for maximum performance.
/// Alpha = 2 / (period + 1)
/// </summary>
/// <param name="source">Input values</param>
/// <param name="output">Output span (must be same length as source)</param>
/// <param name="period">EMA period (must be > 0)</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Calculate(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);
Calculate(source, output, alpha);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Calculate(ReadOnlySpan<double> source, Span<double> output, double alpha)
{
if (source.Length != output.Length)
throw new ArgumentException("Source and output must have the same length");
if (alpha <= 0 || alpha > 1)
throw new ArgumentException("Alpha must be between 0 and 1", nameof(alpha));
if (source.Length == 0) return;
var state = State.New();
double lastValid = 0;
CalculateCore(source, output, alpha, ref state, ref lastValid);
}
/// <summary>
/// Resets the EMA state.
/// </summary>
public void Reset()
{
_state = State.New();
_p_state = _state;
_lastValidValue = 0;
_p_lastValidValue = 0;
Last = default;
}
}
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace QuanTAlib;
/// <summary>
/// EMA: Exponential Moving Average
/// </summary>
/// <remarks>
/// EMA applies exponential weighting to data points, giving more weight to recent values.
/// Uses a single state variable for O(1) complexity per update.
///
/// Calculation:
/// alpha = 2 / (period + 1)
/// EMA_new = EMA_old + alpha * (newest - EMA_old)
///
/// Initialization:
/// Uses a compensator factor to correct early-stage bias (when n < period).
/// Output = EMA_state / (1 - (1-alpha)^n)
///
/// O(1) update:
/// No buffer required, only previous EMA value and compensator state.
///
/// IsHot:
/// Becomes true when n = ln(0.05) / ln(1 - alpha)
/// </remarks>
[SkipLocalsInit]
public sealed class Ema : AbstractBase
{
private record struct State(double Ema, double E, bool IsHot, bool IsCompensated)
{
public static State New() => new() { Ema = 0, E = 1.0, IsHot = false, IsCompensated = false };
}
private readonly double _alpha;
private readonly double _decay;
private State _state = State.New();
private State _p_state = State.New();
private double _lastValidValue;
private double _p_lastValidValue;
/// <summary>
/// Creates EMA with specified period.
/// Alpha = 2 / (period + 1)
/// </summary>
/// <param name="period">Period for EMA calculation (must be > 0)</param>
public Ema(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 = $"Ema({period})";
WarmupPeriod = period;
}
/// <summary>
/// Creates EMA with specified source and period.
/// Subscribes to source.Pub event.
/// </summary>
/// <param name="source">Source to subscribe to</param>
/// <param name="period">Period for EMA calculation</param>
public Ema(ITValuePublisher source, int period) : this(period)
{
source.Pub += (item) => Update(item);
}
public Ema(TSeries source, int period) : this(period)
{
Prime(source.Values);
if (source.Count > 0)
{
Last = new TValue(source.LastTime, Last.Value);
}
source.Pub += (item) => Update(item);
}
/// <summary>
/// Creates EMA with specified alpha smoothing factor.
/// </summary>
/// <param name="alpha">Smoothing factor (0 < alpha <= 1)</param>
public Ema(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 = $"Ema(α={alpha:F4})";
// Approximate period from alpha: alpha = 2/(N+1) => N = 2/alpha - 1
WarmupPeriod = (int)(2.0 / alpha - 1.0);
}
/// <summary>
/// True if the EMA has warmed up and is providing valid results.
/// </summary>
public override bool IsHot => _state.IsHot;
/// <summary>
/// Initializes the indicator state using the provided history.
/// </summary>
/// <param name="source">Historical data</param>
public override void Prime(ReadOnlySpan<double> source)
{
if (source.Length == 0) return;
// Reset state
_state = State.New();
_p_state = State.New();
_lastValidValue = 0;
_p_lastValidValue = 0;
// Run the calculation on the history to update state
// We don't need the output, just the final state
int len = source.Length;
double decay = _decay;
int i = 0;
// Find first valid value to seed lastValid
for (int k = 0; k < len; k++)
{
if (double.IsFinite(source[k]))
{
_lastValidValue = source[k];
break;
}
}
if (!_state.IsCompensated)
{
for (; i < len && _state.E > COMPENSATOR_THRESHOLD; i++)
{
double val = source[i];
if (double.IsFinite(val))
_lastValidValue = val;
else
val = _lastValidValue;
_state.Ema += _alpha * (val - _state.Ema);
_state.E *= decay;
if (!_state.IsHot && _state.E <= COVERAGE_THRESHOLD)
_state.IsHot = true;
}
if (_state.E <= COMPENSATOR_THRESHOLD)
_state.IsCompensated = true;
}
for (; i < len; i++)
{
double val = source[i];
if (double.IsFinite(val))
_lastValidValue = val;
else
val = _lastValidValue;
_state.Ema += _alpha * (val - _state.Ema);
}
// Calculate the initial "Last" value
double result = _state.IsCompensated ? _state.Ema : _state.Ema / (1.0 - _state.E);
// Note: We can't infer accurate Time from a simple Span<double>,
// so we leave 'Last' with default time or user updates it on next Tick.
Last = new TValue(DateTime.MinValue, result);
// Backup state for the next update cycle
_p_state = _state;
_p_lastValidValue = _lastValidValue;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private double GetValidValue(double input)
{
if (double.IsFinite(input))
{
_lastValidValue = input;
return input;
}
return _lastValidValue;
}
private const double COVERAGE_THRESHOLD = 0.05;
private const double COMPENSATOR_THRESHOLD = 1e-10;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override TValue Update(TValue input, bool isNew = true)
{
if (isNew)
{
_p_state = _state;
_p_lastValidValue = _lastValidValue;
}
else
{
_state = _p_state;
_lastValidValue = _p_lastValidValue;
}
double val = GetValidValue(input.Value);
val = Compute(val, _alpha, _decay, ref _state);
Last = new TValue(input.Time, val);
PubEvent(Last);
return Last;
}
public override TSeries Update(TSeries source)
{
if (source.Count == 0) return [];
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);
var sourceValues = source.Values;
var sourceTimes = source.Times;
State state = _state;
double lastValidValue = _lastValidValue;
CalculateCore(sourceValues, vSpan, _alpha, ref state, ref lastValidValue);
_state = state;
_lastValidValue = lastValidValue;
sourceTimes.CopyTo(tSpan);
_p_state = _state;
_p_lastValidValue = _lastValidValue;
Last = new TValue(tSpan[len - 1], vSpan[len - 1]);
return new TSeries(t, v);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static double Compute(double input, double alpha, double decay, ref State state)
{
state.Ema += alpha * (input - state.Ema);
double result;
if (!state.IsCompensated)
{
state.E *= decay;
if (!state.IsHot && state.E <= COVERAGE_THRESHOLD)
state.IsHot = true;
if (state.E <= COMPENSATOR_THRESHOLD)
{
state.IsCompensated = true;
result = state.Ema;
}
else
{
result = state.Ema / (1.0 - state.E);
}
}
else
{
result = state.Ema;
}
return result;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void CalculateCore(ReadOnlySpan<double> source, Span<double> output, double alpha, ref State state, ref double lastValidValue)
{
int len = source.Length;
double decay = 1.0 - alpha;
int i = 0;
if (!state.IsCompensated)
{
for (; i < len && state.E > COMPENSATOR_THRESHOLD; i++)
{
double val = source[i];
if (double.IsFinite(val))
lastValidValue = val;
else
val = lastValidValue;
state.Ema += alpha * (val - state.Ema);
state.E *= decay;
if (!state.IsHot && state.E <= COVERAGE_THRESHOLD)
state.IsHot = true;
output[i] = state.Ema / (1.0 - state.E);
}
if (state.E <= COMPENSATOR_THRESHOLD)
state.IsCompensated = true;
}
for (; i < len; i++)
{
double val = source[i];
if (double.IsFinite(val))
lastValidValue = val;
else
val = lastValidValue;
state.Ema += alpha * (val - state.Ema);
output[i] = state.Ema;
}
}
/// <summary>
/// Runs a high-performance batch calculation on history and returns
/// a "Hot" Ema instance ready to process the next tick immediately.
/// </summary>
/// <param name="source">Historical time series</param>
/// <param name="period">EMA Period</param>
/// <returns>A tuple containing the full calculation results and the hot indicator instance</returns>
public static (TSeries Results, Ema Indicator) Calculate(TSeries source, int period)
{
var ema = new Ema(period);
TSeries results = ema.Update(source);
return (results, ema);
}
/// <summary>
/// Calculates EMA for the entire series using a new instance.
/// </summary>
/// <param name="source">Input series</param>
/// <param name="period">EMA period</param>
/// <returns>EMA series</returns>
public static TSeries Batch(TSeries source, int period)
{
var ema = new Ema(period);
return ema.Update(source);
}
/// <summary>
/// Calculates EMA in-place using period, writing results to pre-allocated output span.
/// Zero-allocation method for maximum performance.
/// Alpha = 2 / (period + 1)
/// </summary>
/// <param name="source">Input values</param>
/// <param name="output">Output span (must be same length as source)</param>
/// <param name="period">EMA period (must be > 0)</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
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);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
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");
if (alpha <= 0 || alpha > 1)
throw new ArgumentException("Alpha must be between 0 and 1", nameof(alpha));
if (source.Length == 0) return;
var state = State.New();
double lastValid = 0;
// Find first valid value to seed lastValid
for (int k = 0; k < source.Length; k++)
{
if (double.IsFinite(source[k]))
{
lastValid = source[k];
break;
}
}
CalculateCore(source, output, alpha, ref state, ref lastValid);
}
/// <summary>
/// Resets the EMA state.
/// </summary>
public override void Reset()
{
_state = State.New();
_p_state = _state;
_lastValidValue = 0;
_p_lastValidValue = 0;
Last = default;
}
}
+5 -5
View File
@@ -79,14 +79,14 @@ Console.WriteLine($"Current Value: {ema.Value.Value}");
// Batch calculation (TSeries API)
TSeries source = ...;
TSeries results = Ema.Calculate(source, 10);
TSeries results = Ema.Batch(source, 10);
// High-performance Span API (zero allocation)
double[] prices = new double[10000];
double[] output = new double[10000];
Ema.Calculate(prices.AsSpan(), output.AsSpan(), period: 10);
Ema.Batch(prices.AsSpan(), output.AsSpan(), period: 10);
// Or with direct alpha:
Ema.Calculate(prices.AsSpan(), output.AsSpan(), alpha: 0.1818);
Ema.Batch(prices.AsSpan(), output.AsSpan(), alpha: 0.1818);
```
### Zero-Allocation Span API
@@ -99,10 +99,10 @@ double[] source = new double[200000];
double[] emaOutput = new double[200000];
// Zero heap allocation during calculation - by period
Ema.Calculate(source.AsSpan(), emaOutput.AsSpan(), period: 100);
Ema.Batch(source.AsSpan(), emaOutput.AsSpan(), period: 100);
// Or by alpha for direct control
Ema.Calculate(source.AsSpan(), emaOutput.AsSpan(), alpha: 0.02);
Ema.Batch(source.AsSpan(), emaOutput.AsSpan(), alpha: 0.02);
// Results are written directly to output buffer
Console.WriteLine($"Last EMA: {emaOutput[^1]}");