Add unit tests for various moving average indicators

- Implement tests for HMA (Hull Moving Average) indicator to verify default settings, history depth calculations, and value computations during updates.
- Create tests for KAMA (Kaufman Adaptive Moving Average) indicator, ensuring correct defaults, history depth, and value calculations.
- Add tests for SMA (Simple Moving Average) indicator, checking default values, history depth, and value computations.
- Develop tests for T3 (Tillson T3 Moving Average) indicator, validating defaults, history depth, and value calculations.
- Implement tests for TEMA (Triple Exponential Moving Average) indicator, ensuring correct defaults and value computations.
- Create tests for TRIMA (Triangular Moving Average) indicator, verifying defaults, history depth, and value calculations.
- Add tests for WMA (Weighted Moving Average) indicator, checking default values, history depth, and value computations.
This commit is contained in:
Miha Kralj
2025-12-08 11:00:58 -08:00
parent 488de7ea1e
commit ed5e5c8209
72 changed files with 2834 additions and 92 deletions
+65
View File
@@ -0,0 +1,65 @@
using System.Drawing;
using TradingPlatform.BusinessLayer;
namespace QuanTAlib;
public class TemaIndicator : 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 Tema? ma;
protected LineSeries? Series;
protected string? SourceName;
private int _warmupBarIndex = -1;
public int MinHistoryDepths => Period;
int IWatchlistIndicator.MinHistoryDepths => MinHistoryDepths;
public override string ShortName => $"TEMA {Period}:{SourceName}";
public override string SourceCodeLink => "https://github.com/mihakralj/QuanTAlib/blob/main/lib/trends/tema/Tema.Quantower.cs";
public TemaIndicator()
{
OnBackGround = true;
SeparateWindow = false;
SourceName = Source.ToString();
Name = "TEMA - Triple Exponential Moving Average";
Description = "Triple Exponential Moving Average";
Series = new(name: $"TEMA {Period}", color: IndicatorExtensions.Averages, width: 2, style: LineStyle.Solid);
AddLineSeries(Series);
}
protected override void OnInit()
{
ma = new Tema(Period);
SourceName = Source.ToString();
_warmupBarIndex = -1;
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);
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);
}
}
+310
View File
@@ -0,0 +1,310 @@
namespace QuanTAlib.Tests;
#pragma warning disable S2245 // Random is acceptable for simulation/testing purposes
public class TemaTests
{
[Fact]
public void Tema_Constructor_Period_ValidatesInput()
{
Assert.Throws<ArgumentException>(() => new Tema(0));
Assert.Throws<ArgumentException>(() => new Tema(-1));
var tema = new Tema(10);
Assert.NotNull(tema);
}
[Fact]
public void Tema_Constructor_Alpha_ValidatesInput()
{
Assert.Throws<ArgumentException>(() => new Tema(0.0));
Assert.Throws<ArgumentException>(() => new Tema(-0.1));
Assert.Throws<ArgumentException>(() => new Tema(1.1));
var tema = new Tema(0.5);
Assert.NotNull(tema);
}
[Fact]
public void Tema_Calc_ReturnsValue()
{
var tema = new Tema(10);
Assert.Equal(0, tema.Last.Value);
TValue result = tema.Update(new TValue(DateTime.UtcNow, 100));
Assert.True(result.Value > 0);
Assert.Equal(result.Value, tema.Last.Value);
}
[Fact]
public void Tema_Calc_IsNew_AcceptsParameter()
{
var tema = new Tema(10);
tema.Update(new TValue(DateTime.UtcNow, 100), isNew: true);
double value1 = tema.Last.Value;
tema.Update(new TValue(DateTime.UtcNow, 105), isNew: true);
double value2 = tema.Last.Value;
// Values should change with new bars
Assert.NotEqual(value1, value2);
}
[Fact]
public void Tema_Calc_IsNew_False_UpdatesValue()
{
var tema = new Tema(10);
tema.Update(new TValue(DateTime.UtcNow, 100));
tema.Update(new TValue(DateTime.UtcNow, 110), isNew: true);
double beforeUpdate = tema.Last.Value;
tema.Update(new TValue(DateTime.UtcNow, 120), isNew: false);
double afterUpdate = tema.Last.Value;
// Update should change the value
Assert.NotEqual(beforeUpdate, afterUpdate);
}
[Fact]
public void Tema_Reset_ClearsState()
{
var tema = new Tema(10);
tema.Update(new TValue(DateTime.UtcNow, 100));
tema.Update(new TValue(DateTime.UtcNow, 105));
double valueBefore = tema.Last.Value;
tema.Reset();
Assert.Equal(0, tema.Last.Value);
// After reset, should accept new values
tema.Update(new TValue(DateTime.UtcNow, 50));
Assert.NotEqual(0, tema.Last.Value);
Assert.NotEqual(valueBefore, tema.Last.Value);
}
[Fact]
public void Tema_Properties_Accessible()
{
var tema = new Tema(10);
Assert.Equal(0, tema.Last.Value);
Assert.False(tema.IsHot);
tema.Update(new TValue(DateTime.UtcNow, 100));
Assert.NotEqual(0, tema.Last.Value);
}
[Fact]
public void Tema_IsHot_BecomesTrueAfterWarmup()
{
var tema = new Tema(10);
// Initially IsHot should be false
Assert.False(tema.IsHot);
// TEMA needs more warmup than EMA due to triple smoothing
int steps = 0;
while (!tema.IsHot && steps < 1000)
{
tema.Update(new TValue(DateTime.UtcNow, 100));
steps++;
}
Assert.True(tema.IsHot);
Assert.True(steps > 0);
}
[Fact]
public void Tema_PeriodEquivalence_BothConstructorsWork()
{
int period = 20;
double alpha = 2.0 / (period + 1);
var temaPeriod = new Tema(period);
var temaAlpha = new Tema(alpha);
// Both should accept Calc calls and produce same result
TValue result1 = temaPeriod.Update(new TValue(DateTime.UtcNow, 100));
TValue result2 = temaAlpha.Update(new TValue(DateTime.UtcNow, 100));
Assert.Equal(result1.Value, result2.Value, 1e-10);
}
[Fact]
public void Tema_IterativeCorrections_RestoreToOriginalState()
{
var tema = new Tema(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);
tema.Update(tenthInput, isNew: true);
}
// Remember TEMA state after 10 values
double temaAfterTen = tema.Last.Value;
// Generate 9 corrections with isNew=false (different values)
for (int i = 0; i < 9; i++)
{
var bar = gbm.Next(isNew: false);
tema.Update(new TValue(bar.Time, bar.Close), isNew: false);
}
// Feed the remembered 10th input again with isNew=false
TValue finalTema = tema.Update(tenthInput, isNew: false);
// TEMA should match the original state after 10 values
Assert.Equal(temaAfterTen, finalTema.Value, 1e-10);
}
[Fact]
public void Tema_BatchCalc_MatchesIterativeCalc()
{
var temaIterative = new Tema(10);
var temaBatch = new Tema(10);
var gbm = new GBM(startPrice: 100.0, mu: 0.02, sigma: 0.1);
// Generate data
var series = new TSeries();
for (int i = 0; i < 100; i++)
{
var bar = gbm.Next(isNew: true);
series.Add(bar.Time, bar.Close);
}
Assert.True(series.Count > 0);
// Calculate iteratively
var iterativeResults = new TSeries();
foreach (var item in series)
{
iterativeResults.Add(temaIterative.Update(item));
}
// Calculate batch
var batchResults = temaBatch.Update(series);
// Compare
Assert.Equal(iterativeResults.Count, batchResults.Count);
for (int i = 0; i < iterativeResults.Count; i++)
{
Assert.Equal(iterativeResults[i].Value, batchResults[i].Value, 1e-10);
Assert.Equal(iterativeResults[i].Time, batchResults[i].Time);
}
}
[Fact]
public void Tema_NaN_Input_UsesLastValidValue()
{
var tema = new Tema(10);
// Feed some valid values
tema.Update(new TValue(DateTime.UtcNow, 100));
tema.Update(new TValue(DateTime.UtcNow, 110));
// Feed NaN - should use last valid value (110)
var resultAfterNaN = tema.Update(new TValue(DateTime.UtcNow, double.NaN));
// Result should be finite (not NaN)
Assert.True(double.IsFinite(resultAfterNaN.Value));
Assert.NotEqual(0, resultAfterNaN.Value);
}
[Fact]
public void Tema_SpanCalc_MatchesTSeriesCalc()
{
var series = new TSeries();
double[] source = new double[100];
double[] output = new double[100];
var gbm = new GBM(startPrice: 100.0, mu: 0.02, sigma: 0.1, seed: 42);
for (int i = 0; i < 100; i++)
{
var bar = gbm.Next(isNew: true);
source[i] = bar.Close;
series.Add(bar.Time, bar.Close);
}
// Calculate with TSeries API
var tseriesResult = Tema.Calculate(series, 10);
// Calculate with Span API
Tema.Calculate(source.AsSpan(), output.AsSpan(), 10);
// Compare results
for (int i = 0; i < 100; i++)
{
Assert.Equal(tseriesResult[i].Value, output[i], 1e-9);
}
}
[Fact]
public void Tema_SpanCalc_ZeroAllocation()
{
double[] source = new double[10000];
double[] output = new double[10000];
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 42);
for (int i = 0; i < source.Length; i++)
source[i] = gbm.Next().Close;
// Warm up
Tema.Calculate(source.AsSpan(), output.AsSpan(), 100);
// This test verifies the method runs without throwing
Assert.True(double.IsFinite(output[^1]));
}
[Fact]
public void Tema_AllModes_ProduceSameResult()
{
// Arrange
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 = Tema.Calculate(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];
Tema.Calculate(spanInput, spanOutput, period);
double spanResult = spanOutput[^1];
// 3. Streaming Mode
var streamingInd = new Tema(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 Tema(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);
}
}
+233
View File
@@ -0,0 +1,233 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Skender.Stock.Indicators;
using TALib;
using Tulip;
using Xunit;
using Xunit.Abstractions;
namespace QuanTAlib.Tests;
public class TemaValidationTests
{
private readonly TBarSeries _bars;
private readonly TSeries _data;
private readonly List<Quote> _skenderQuotes;
private readonly ITestOutputHelper _output;
public TemaValidationTests(ITestOutputHelper output)
{
_output = output;
// 1. Generate 5000 records using GBM feed
var gbm = new GBM(startPrice: 100.0, mu: 0.05, sigma: 0.2);
_bars = gbm.Fetch(5000, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
// 2. Extract Close TSeries
_data = _bars.Close;
// 3. Prepare data for Skender (List<Quote>)
_skenderQuotes = new List<Quote>();
for (int i = 0; i < _bars.Count; i++)
{
_skenderQuotes.Add(new Quote
{
Date = new DateTime(_bars.Open.Times[i], DateTimeKind.Utc),
Open = (decimal)_bars.Open[i].Value,
High = (decimal)_bars.High[i].Value,
Low = (decimal)_bars.Low[i].Value,
Close = (decimal)_bars.Close[i].Value,
Volume = (decimal)_bars.Volume[i].Value
});
}
}
[Fact]
public void Validate_Skender_Batch()
{
int[] periods = { 5, 10, 20, 50, 100 };
foreach (var period in periods)
{
// Calculate QuanTAlib TEMA (batch TSeries)
var tema = new global::QuanTAlib.Tema(period);
var qResult = tema.Update(_data);
// Calculate Skender TEMA
var sResult = _skenderQuotes.GetTema(period).ToList();
// Compare last 100 records
VerifyData_Skender(qResult, sResult);
}
_output.WriteLine("TEMA Batch(TSeries) validated successfully against Skender.Stock.Indicators");
}
[Fact]
public void Validate_Talib_Batch()
{
int[] periods = { 5, 10, 20, 50, 100 };
// Prepare data for TA-Lib (double[])
double[] tData = _data.Select(x => x.Value).ToArray();
double[] output = new double[tData.Length];
foreach (var period in periods)
{
// Calculate QuanTAlib TEMA (batch TSeries)
var tema = new global::QuanTAlib.Tema(period);
var qResult = tema.Update(_data);
// Calculate TA-Lib TEMA
var retCode = TALib.Functions.Tema<double>(tData, 0..^0, output, out var outRange, period);
Assert.Equal(Core.RetCode.Success, retCode);
int lookback = TALib.Functions.TemaLookback(period);
// Compare last 100 records
VerifyData_Talib(qResult, output, outRange, lookback);
}
_output.WriteLine("TEMA Batch(TSeries) validated successfully against TA-Lib");
}
[Fact]
public void Validate_Tulip_Batch()
{
int[] periods = { 5, 10, 20, 50, 100 };
// Prepare data for Tulip (double[])
double[] tData = _data.Select(x => x.Value).ToArray();
foreach (var period in periods)
{
// Calculate QuanTAlib TEMA (batch TSeries)
var tema = new global::QuanTAlib.Tema(period);
var qResult = tema.Update(_data);
// Calculate Tulip TEMA
var temaIndicator = Tulip.Indicators.tema;
double[][] inputs = { tData };
double[] options = { period };
// Tulip TEMA lookback is 3*(period-1)
int lookback = 3 * (period - 1);
double[][] outputs = { new double[tData.Length - lookback] };
temaIndicator.Run(inputs, options, outputs);
var tResult = outputs[0];
// Compare last 100 records
VerifyData_Tulip(qResult, tResult, lookback);
}
_output.WriteLine("TEMA Batch(TSeries) validated successfully against Tulip");
}
[Fact]
public void Validate_Talib_Span()
{
int[] periods = { 5, 10, 20, 50, 100 };
// Prepare data
double[] sourceData = _data.Select(x => x.Value).ToArray();
double[] talibOutput = new double[sourceData.Length];
foreach (var period in periods)
{
// Calculate QuanTAlib TEMA (Span API)
double[] qOutput = new double[sourceData.Length];
global::QuanTAlib.Tema.Calculate(sourceData.AsSpan(), qOutput.AsSpan(), period);
// Calculate TA-Lib TEMA
var retCode = TALib.Functions.Tema<double>(sourceData, 0..^0, talibOutput, out var outRange, period);
Assert.Equal(Core.RetCode.Success, retCode);
int lookback = TALib.Functions.TemaLookback(period);
// Compare last 100 records
VerifyData_Talib_Span(qOutput, talibOutput, outRange, lookback);
}
_output.WriteLine("TEMA Span validated successfully against TA-Lib");
}
// ==================== Verification Helpers ====================
private static void VerifyData_Skender(TSeries qSeries, List<TemaResult> sSeries)
{
Assert.Equal(qSeries.Count, sSeries.Count);
int count = qSeries.Count;
int skip = count - 100;
for (int i = skip; i < count; i++)
{
double qValue = qSeries[i].Value;
double? sValue = sSeries[i].Tema;
if (!sValue.HasValue) continue;
Assert.Equal(sValue.Value, qValue, 1e-6);
}
}
private static void VerifyData_Talib(TSeries qSeries, double[] tOutput, Range outRange, int lookback)
{
int count = qSeries.Count;
int skip = count - 100;
int validCount = outRange.End.Value - outRange.Start.Value;
for (int i = skip; i < count; i++)
{
double qValue = qSeries[i].Value;
if (i < lookback) continue;
int tIndex = i - lookback;
if (tIndex >= validCount) continue;
double tValue = tOutput[tIndex];
Assert.Equal(tValue, qValue, 1e-5);
}
}
private static void VerifyData_Talib_Span(double[] qOutput, double[] tOutput, Range outRange, int lookback)
{
int count = qOutput.Length;
int skip = count - 100;
int validCount = outRange.End.Value - outRange.Start.Value;
for (int i = skip; i < count; i++)
{
double qValue = qOutput[i];
if (i < lookback) continue;
int tIndex = i - lookback;
if (tIndex >= validCount) continue;
double tValue = tOutput[tIndex];
Assert.Equal(tValue, qValue, 1e-5);
}
}
private static void VerifyData_Tulip(TSeries qSeries, double[] tOutput, int lookback)
{
int count = qSeries.Count;
int skip = count - 100;
for (int i = skip; i < count; i++)
{
double qValue = qSeries[i].Value;
if (i < lookback) continue;
int tIndex = i - lookback;
if (tIndex >= tOutput.Length) continue;
double tValue = tOutput[tIndex];
Assert.Equal(tValue, qValue, 1e-5);
}
}
}
+348
View File
@@ -0,0 +1,348 @@
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace QuanTAlib;
/// <summary>
/// TEMA: Triple Exponential Moving Average
/// </summary>
/// <remarks>
/// TEMA uses triple smoothing to reduce lag even further than DEMA.
///
/// Calculation:
/// EMA1 = EMA(input)
/// EMA2 = EMA(EMA1)
/// EMA3 = EMA(EMA2)
/// TEMA = 3 * EMA1 - 3 * EMA2 + EMA3
///
/// O(1) update:
/// Uses three EMA instances, each with O(1) update complexity.
///
/// IsHot:
/// Becomes true when the TEMA step response converges to within 5% error.
/// This happens when the third EMA's error factor drops below ~9% (approx 2.43/alpha steps),
/// which is faster than the standard EMA convergence (3/alpha steps).
/// </remarks>
[SkipLocalsInit]
public sealed class Tema : ITValuePublisher
{
private struct EmaState : IEquatable<EmaState>
{
public double Ema;
public double E;
public bool IsHot;
public bool IsCompensated;
public static EmaState New() => new() { Ema = 0, E = 1.0, IsHot = false, IsCompensated = false };
public override bool Equals(object? obj) => obj is EmaState other && Equals(other);
public bool Equals(EmaState other) =>
Ema == other.Ema &&
E == other.E &&
IsHot == other.IsHot &&
IsCompensated == other.IsCompensated;
public override int GetHashCode() => HashCode.Combine(Ema, E, IsHot, IsCompensated);
public static bool operator ==(EmaState left, EmaState right) => left.Equals(right);
public static bool operator !=(EmaState left, EmaState right) => !left.Equals(right);
}
private readonly double _alpha;
private readonly double _decay;
private EmaState _state1 = EmaState.New();
private EmaState _state2 = EmaState.New();
private EmaState _state3 = EmaState.New();
private EmaState _p_state1 = EmaState.New();
private EmaState _p_state2 = EmaState.New();
private EmaState _p_state3 = EmaState.New();
private double _lastValidValue;
public string Name { get; }
public TValue Last { get; private set; }
public bool IsHot => _state3.E <= 0.09;
public event Action<TValue>? Pub;
public Tema(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 = $"Tema({period})";
}
public Tema(ITValuePublisher source, int period) : this(period)
{
source.Pub += (item) => Update(item);
}
public Tema(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 = $"Tema(α={alpha:F4})";
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TValue Update(TValue input, bool isNew = true)
{
if (isNew)
{
_p_state1 = _state1;
_p_state2 = _state2;
_p_state3 = _state3;
}
else
{
_state1 = _p_state1;
_state2 = _p_state2;
_state3 = _p_state3;
}
// EMA1
double val = input.Value;
if (double.IsFinite(val))
_lastValidValue = val;
else
val = _lastValidValue;
double e1 = Compute(val, _alpha, _decay, ref _state1);
// EMA2 (input is e1)
double e2 = Compute(e1, _alpha, _decay, ref _state2);
// EMA3 (input is e2)
double e3 = Compute(e2, _alpha, _decay, ref _state3);
double result = 3 * e1 - 3 * e2 + e3;
Last = new TValue(input.Time, result);
Pub?.Invoke(Last);
return Last;
}
public TSeries Update(TSeries source)
{
if (source.Count == 0) return new TSeries(new List<long>(), new List<double>());
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);
source.Times.CopyTo(tSpan);
var sourceValues = source.Values;
// Use current state
EmaState s1 = _state1;
EmaState s2 = _state2;
EmaState s3 = _state3;
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;
double e1 = Compute(val, alpha, decay, ref s1);
double e2 = Compute(e1, alpha, decay, ref s2);
double e3 = Compute(e2, alpha, decay, ref s3);
vSpan[i] = 3 * e1 - 3 * e2 + e3;
}
// Update instance state
_state1 = s1;
_state2 = s2;
_state3 = s3;
_p_state1 = s1;
_p_state2 = s2;
_p_state3 = s3;
_lastValidValue = lastValid;
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 EmaState state)
{
state.Ema += alpha * (input - state.Ema);
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 Calculate(TSeries source, int period)
{
var tema = new Tema(period);
return tema.Update(source);
}
public static TSeries Calculate(TSeries source, double alpha)
{
var tema = new Tema(alpha);
return tema.Update(source);
}
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);
}
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;
double decay = 1.0 - alpha;
double lastValid = 0;
// State for EMA1
double ema1_val = 0;
double ema1_e = 1.0;
bool ema1_isCompensated = false;
// State for EMA2
double ema2_val = 0;
double ema2_e = 1.0;
bool ema2_isCompensated = false;
// State for EMA3
double ema3_val = 0;
double ema3_e = 1.0;
bool ema3_isCompensated = false;
for (int i = 0; i < source.Length; i++)
{
double val = source[i];
if (double.IsFinite(val))
lastValid = val;
else
val = lastValid;
// Update EMA1
ema1_val += alpha * (val - ema1_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;
}
// Update EMA2 (input is e1)
ema2_val += alpha * (e1 - ema2_val);
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;
}
// Update EMA3 (input is e2)
ema3_val += alpha * (e2 - ema3_val);
double e3;
if (!ema3_isCompensated)
{
ema3_e *= decay;
if (ema3_e <= 1e-10)
{
ema3_isCompensated = true;
e3 = ema3_val;
}
else
{
e3 = ema3_val / (1.0 - ema3_e);
}
}
else
{
e3 = ema3_val;
}
// TEMA = 3 * EMA1 - 3 * EMA2 + EMA3
output[i] = 3 * e1 - 3 * e2 + e3;
}
}
public void Reset()
{
_state1 = EmaState.New();
_state2 = EmaState.New();
_state3 = EmaState.New();
_p_state1 = EmaState.New();
_p_state2 = EmaState.New();
_p_state3 = EmaState.New();
_lastValidValue = 0;
Last = default;
}
}
+133
View File
@@ -0,0 +1,133 @@
# TEMA: Triple Exponential Moving Average
## Overview and Purpose
The Triple Exponential Moving Average (TEMA) is a technical indicator developed by Patrick Mulloy in 1994, introduced alongside DEMA. It takes the concept of lag reduction even further than DEMA by using a triple smoothing technique. TEMA is designed to be even more responsive to price changes than DEMA or traditional moving averages, effectively eliminating the lag associated with trend-following indicators.
TEMA is constructed using a combination of single, double, and triple Exponential Moving Averages (EMAs). This unique composition allows it to track price action very closely, making it a favorite among short-term traders and scalpers who require immediate signals.
## Core Concepts
* **Maximum Lag Reduction:** TEMA offers superior lag reduction compared to SMA, EMA, and even DEMA.
* **Triple Smoothing:** It utilizes three layers of EMA calculations to derive its value.
* **Composite Formula:** The formula cleverly combines $EMA_1$, $EMA_2$, and $EMA_3$ to subtract lag.
* **Trend Following:** Despite its speed, it remains a trend-following indicator, useful for identifying direction and reversals.
## Common Settings and Parameters
| Parameter | Default | Function | When to Adjust |
|-----------|---------|----------|---------------|
| Length | 20 | Controls responsiveness/smoothness | Shorter for scalping, longer for trend filtering |
| Source | Close | Data point used for calculation | Change to HL2 or HLC3 for typical price representation |
| Alpha | 3/(length+1) | Determines weighting decay | Direct alpha manipulation allows for precise tuning |
## Calculation and Mathematical Foundation
**Simplified explanation:**
TEMA uses a single EMA, a double EMA (EMA of EMA), and a triple EMA (EMA of EMA of EMA). It combines these three components to cancel out the lag inherent in the smoothing process.
**Technical formula:**
$$TEMA = 3 \times EMA_1 - 3 \times EMA_2 + EMA_3$$
Where:
* $EMA_1 = EMA(Price)$
* $EMA_2 = EMA(EMA_1)$
* $EMA_3 = EMA(EMA_2)$
The formula is derived from the error correction principle, similar to DEMA but extended to a third degree.
The lag error is estimated and subtracted from the original EMA, resulting in a highly responsive curve that often leads price turns.
> 🔍 **Technical Note:** The implementation leverages the optimized `Ema` class, which uses **Hunter's bias compensation**. This ensures that all three underlying EMAs are initialized correctly from the very first data point, providing accurate TEMA values immediately without a long warmup period.
## C# Implementation
The library provides a high-performance implementation of TEMA that supports both standard period-based initialization and direct alpha specification.
### Usage Examples
```csharp
using QuanTAlib;
// Initialize with period 14
var tema = new Tema(14);
// Or initialize with specific alpha
var temaAlpha = new Tema(0.15);
// Streaming update
TValue result = tema.Update(new TValue(time, price));
Console.WriteLine($"Current TEMA: {result.Value}");
// Batch calculation (TSeries API)
TSeries source = ...;
TSeries results = Tema.Calculate(source, 14);
// High-performance Span API (zero allocation)
double[] prices = new double[10000];
double[] output = new double[10000];
Tema.Calculate(prices.AsSpan(), output.AsSpan(), period: 14);
```
### Zero-Allocation Span API
For performance-critical scenarios, the static `Calculate` method uses `ArrayPool` internally to manage the intermediate buffers for the underlying EMAs, ensuring zero heap allocations for the user (beyond the input/output arrays).
```csharp
// Allocate buffers once
double[] source = new double[200000];
double[] temaOutput = new double[200000];
// Zero heap allocation during calculation
Tema.Calculate(source.AsSpan(), temaOutput.AsSpan(), period: 50);
```
### Eventing and Reactive Support
This indicator implements the `ITValuePublisher` interface, enabling event-driven and reactive workflows.
* **Subscription:** Can be constructed with an `ITValuePublisher` (e.g., `TSeries`) to automatically update when the source emits a new value.
* **Publication:** Emits a `Pub` event with the new `TValue` whenever it is updated.
```csharp
using QuanTAlib;
// 1. Setup a source (publisher)
var source = new TSeries();
// 2. Create indicator subscribed to source
// It waits for events from 'source'
var tema = new Tema(source, period: 14);
// 3. Optional: Subscribe to indicator's output
tema.Pub += (item) => Console.WriteLine($"TEMA Updated: {item.Value}");
// 4. Ingest data into source
// This triggers the chain: source -> tema -> Console.WriteLine
source.Add(new TValue(DateTime.Now, 100));
source.Add(new TValue(DateTime.Now, 105));
```
This pattern allows building complex, reactive processing pipelines without manual update loops.
### Handling Invalid Values
`Tema` delegates value handling to the underlying `Ema` instances, which use **last-value substitution** for `NaN` or `Infinity`. This ensures continuity and stability in the output series.
## Interpretation Details
* **Trend Direction:** Price above TEMA indicates an uptrend; price below indicates a downtrend.
* **Signal Line:** TEMA is often used as a signal line for other indicators due to its speed.
* **Crossovers:** TEMA crossovers with price or other averages provide very early entry/exit signals.
* **Volatility:** Due to its speed, TEMA can be volatile in choppy markets.
## Limitations and Considerations
* **Overshoot:** Like DEMA, TEMA can overshoot price action during sudden, sharp reversals.
* **Noise:** Its extreme responsiveness makes it susceptible to market noise and false signals in sideways markets.
* **Complexity:** The triple calculation is computationally more expensive than SMA or EMA, though negligible on modern hardware.
## References
1. Mulloy, P.G. (1994). "Smoothing Data with Faster Moving Averages." *Technical Analysis of Stocks & Commodities*, 12(1).
2. Achelis, S.B. (2000). *Technical Analysis from A to Z*. McGraw-Hill.