mirror of
https://github.com/mihakralj/QuanTAlib.git
synced 2026-08-23 04:58:08 +00:00
Add validation tests for various volume and momentum indicators
- Introduced Massi validation tests to ensure mathematical properties hold for the Mass Index indicator. - Added Va validation tests for Volume Accumulation, checking for finite outputs and correct accumulation behavior. - Implemented Vf validation tests for Volume Force, verifying outputs for rising and falling prices, and ensuring batch and streaming results match. - Created Vo validation tests for Volume Oscillator, confirming behavior with constant, increasing, and decreasing volumes. - Developed Vroc validation tests for Volume Rate of Change, validating outputs for constant volume and changes in volume. - Updated project file to include new momentum indicators (MACD and RSI) in the compilation.
This commit is contained in:
@@ -0,0 +1,128 @@
|
||||
using TradingPlatform.BusinessLayer;
|
||||
using QuanTAlib;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public sealed class TrixIndicatorTests
|
||||
{
|
||||
[Fact]
|
||||
public void TrixIndicator_Constructor_SetsDefaults()
|
||||
{
|
||||
var indicator = new TrixIndicator();
|
||||
|
||||
Assert.Equal(14, indicator.Period);
|
||||
Assert.Equal(SourceType.Close, indicator.Source);
|
||||
Assert.True(indicator.ShowColdValues);
|
||||
Assert.Equal("TRIX - Triple Exponential Average Oscillator", indicator.Name);
|
||||
Assert.True(indicator.SeparateWindow);
|
||||
Assert.True(indicator.OnBackGround);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TrixIndicator_MinHistoryDepths_EqualsZero()
|
||||
{
|
||||
var indicator = new TrixIndicator { Period = 14 };
|
||||
|
||||
Assert.Equal(0, TrixIndicator.MinHistoryDepths);
|
||||
IWatchlistIndicator watchlistIndicator = indicator;
|
||||
Assert.Equal(0, watchlistIndicator.MinHistoryDepths);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TrixIndicator_ShortName_IncludesParameters()
|
||||
{
|
||||
var indicator = new TrixIndicator { Period = 10 };
|
||||
indicator.Initialize();
|
||||
|
||||
Assert.Contains("TRIX", indicator.ShortName, StringComparison.Ordinal);
|
||||
Assert.Contains("10", indicator.ShortName, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TrixIndicator_SourceCodeLink_IsValid()
|
||||
{
|
||||
var indicator = new TrixIndicator();
|
||||
|
||||
Assert.Contains("github.com", indicator.SourceCodeLink, StringComparison.Ordinal);
|
||||
Assert.Contains("Trix.Quantower.cs", indicator.SourceCodeLink, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TrixIndicator_Initialize_CreatesInternalTrix()
|
||||
{
|
||||
var indicator = new TrixIndicator { Period = 10 };
|
||||
|
||||
indicator.Initialize();
|
||||
|
||||
Assert.Single(indicator.LinesSeries);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TrixIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
|
||||
{
|
||||
var indicator = new TrixIndicator { Period = 5 };
|
||||
indicator.Initialize();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
indicator.HistoricalData.AddBar(now.AddMinutes(i), 100 + i, 110 + i, 90 + i, 105 + i);
|
||||
|
||||
var args = new UpdateArgs(UpdateReason.HistoricalBar);
|
||||
indicator.ProcessUpdate(args);
|
||||
}
|
||||
|
||||
double value = indicator.LinesSeries[0].GetValue(0);
|
||||
Assert.True(double.IsFinite(value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TrixIndicator_ProcessUpdate_NewBar_ComputesValue()
|
||||
{
|
||||
var indicator = new TrixIndicator { Period = 5 };
|
||||
indicator.Initialize();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
indicator.HistoricalData.AddBar(now.AddMinutes(i), 100 + i, 110 + i, 90 + i, 105 + i);
|
||||
}
|
||||
|
||||
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
|
||||
|
||||
indicator.HistoricalData.AddBar(now.AddMinutes(20), 120, 130, 110, 125);
|
||||
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.NewBar));
|
||||
|
||||
Assert.Equal(2, indicator.LinesSeries[0].Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TrixIndicator_Parameters_CanBeChanged()
|
||||
{
|
||||
var indicator = new TrixIndicator { Period = 14 };
|
||||
|
||||
indicator.Period = 10;
|
||||
indicator.Source = SourceType.Open;
|
||||
|
||||
Assert.Equal(10, indicator.Period);
|
||||
Assert.Equal(SourceType.Open, indicator.Source);
|
||||
Assert.Equal(0, TrixIndicator.MinHistoryDepths);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TrixIndicator_ProcessUpdate_DifferentSources()
|
||||
{
|
||||
var indicator = new TrixIndicator { Period = 5, Source = SourceType.High };
|
||||
indicator.Initialize();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
indicator.HistoricalData.AddBar(now.AddMinutes(i), 100 + i, 110 + i, 90 + i, 105 + i);
|
||||
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
|
||||
}
|
||||
|
||||
double value = indicator.LinesSeries[0].GetValue(0);
|
||||
Assert.True(double.IsFinite(value));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
using System.Drawing;
|
||||
using System.Runtime.CompilerServices;
|
||||
using TradingPlatform.BusinessLayer;
|
||||
|
||||
namespace QuanTAlib;
|
||||
|
||||
[SkipLocalsInit]
|
||||
public sealed class TrixIndicator : Indicator, IWatchlistIndicator
|
||||
{
|
||||
[InputParameter("Period", sortIndex: 1, 1, 1000, 1, 0)]
|
||||
public int Period { get; set; } = 14;
|
||||
|
||||
[IndicatorExtensions.DataSourceInput(sortIndex: 2)]
|
||||
public SourceType Source { get; set; } = SourceType.Close;
|
||||
|
||||
[InputParameter("Show cold values", sortIndex: 21)]
|
||||
public bool ShowColdValues { get; set; } = true;
|
||||
|
||||
private Trix _trix = null!;
|
||||
private readonly LineSeries _series;
|
||||
|
||||
public static int MinHistoryDepths => 0;
|
||||
int IWatchlistIndicator.MinHistoryDepths => MinHistoryDepths;
|
||||
|
||||
public override string ShortName => $"TRIX ({Period})";
|
||||
public override string SourceCodeLink => "https://github.com/mihakralj/QuanTAlib/blob/main/lib/oscillators/trix/Trix.Quantower.cs";
|
||||
|
||||
public TrixIndicator()
|
||||
{
|
||||
OnBackGround = true;
|
||||
SeparateWindow = true;
|
||||
Name = "TRIX - Triple Exponential Average Oscillator";
|
||||
Description = "Measures rate of change of a triple-smoothed EMA, filtering noise to reveal underlying momentum";
|
||||
|
||||
_series = new LineSeries("TRIX", Color.Yellow, 2, LineStyle.Solid);
|
||||
AddLineSeries(_series);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
protected override void OnInit()
|
||||
{
|
||||
_trix = new Trix(Period);
|
||||
base.OnInit();
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
protected override void OnUpdate(UpdateArgs args)
|
||||
{
|
||||
var priceSelector = Source.GetPriceSelector();
|
||||
var item = HistoricalData[0, SeekOriginHistory.End];
|
||||
double price = priceSelector(item);
|
||||
|
||||
TValue input = new(item.TimeLeft, price);
|
||||
TValue result = _trix.Update(input, args.IsNewBar());
|
||||
|
||||
if (!_trix.IsHot && !ShowColdValues)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_series.SetValue(result.Value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,674 @@
|
||||
using Xunit;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
// ── A) Constructor Validation ───────────────────────────────────────────────
|
||||
public sealed class TrixConstructorTests
|
||||
{
|
||||
[Fact]
|
||||
public void Constructor_ZeroPeriod_ThrowsArgumentException()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Trix(0));
|
||||
Assert.Equal("period", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_NegativePeriod_ThrowsArgumentException()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Trix(-5));
|
||||
Assert.Equal("period", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_DefaultPeriod_Creates()
|
||||
{
|
||||
var trix = new Trix();
|
||||
Assert.NotNull(trix);
|
||||
Assert.Equal(14, trix.Period);
|
||||
Assert.Equal("Trix(14)", trix.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_CustomPeriod_Creates()
|
||||
{
|
||||
var trix = new Trix(5);
|
||||
Assert.Equal(5, trix.Period);
|
||||
Assert.Equal("Trix(5)", trix.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WarmupPeriod_IsTriplePeriod()
|
||||
{
|
||||
var trix = new Trix(10);
|
||||
Assert.Equal(30, trix.WarmupPeriod);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_PeriodOne_IsValid()
|
||||
{
|
||||
var trix = new Trix(1);
|
||||
Assert.NotNull(trix);
|
||||
Assert.Equal(1, trix.Period);
|
||||
}
|
||||
}
|
||||
|
||||
// ── B) Basic Calculation ────────────────────────────────────────────────────
|
||||
public sealed class TrixBasicTests
|
||||
{
|
||||
[Fact]
|
||||
public void BasicCalculation_DoesNotCrash()
|
||||
{
|
||||
var trix = new Trix(10);
|
||||
Assert.Equal(0, trix.Last.Value);
|
||||
|
||||
TValue result = trix.Update(new TValue(DateTime.UtcNow, 100));
|
||||
Assert.Equal(result.Value, trix.Last.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FirstBar_OutputIsZero()
|
||||
{
|
||||
var trix = new Trix(5);
|
||||
var result = trix.Update(new TValue(DateTime.UtcNow, 100));
|
||||
// First bar: no previous EMA3 to compare against, output = 0
|
||||
Assert.Equal(0.0, result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SecondBar_ProducesNonZeroValue()
|
||||
{
|
||||
var trix = new Trix(5);
|
||||
trix.Update(new TValue(DateTime.UtcNow, 100));
|
||||
var result = trix.Update(new TValue(DateTime.UtcNow, 110));
|
||||
// EMA3 changes vs first bar → non-zero TRIX
|
||||
Assert.NotEqual(0.0, result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Name_Available()
|
||||
{
|
||||
var trix = new Trix(7);
|
||||
Assert.Equal("Trix(7)", trix.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Last_IsAccessible()
|
||||
{
|
||||
var trix = new Trix(5);
|
||||
trix.Update(new TValue(DateTime.UtcNow, 100));
|
||||
trix.Update(new TValue(DateTime.UtcNow, 110));
|
||||
Assert.True(double.IsFinite(trix.Last.Value));
|
||||
}
|
||||
}
|
||||
|
||||
// ── C) State + Bar Correction ───────────────────────────────────────────────
|
||||
public sealed class TrixBarCorrectionTests
|
||||
{
|
||||
[Fact]
|
||||
public void IsNew_True_AdvancesState()
|
||||
{
|
||||
var trix = new Trix(5);
|
||||
trix.Update(new TValue(DateTime.UtcNow, 100), isNew: true);
|
||||
double val1 = trix.Last.Value;
|
||||
|
||||
trix.Update(new TValue(DateTime.UtcNow, 110), isNew: true);
|
||||
double val2 = trix.Last.Value;
|
||||
|
||||
// Different values should produce different states
|
||||
Assert.NotEqual(val1, val2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsNew_False_Rollback()
|
||||
{
|
||||
var trix = new Trix(5);
|
||||
var gbm = new GBM(startPrice: 100.0, mu: 0.02, sigma: 0.1, seed: 42);
|
||||
|
||||
// Feed enough bars to get past trivial state
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
var bar = gbm.Next(isNew: true);
|
||||
trix.Update(new TValue(bar.Time, bar.Close), isNew: true);
|
||||
}
|
||||
|
||||
// Feed one more bar with isNew=true and remember value
|
||||
var nextBar = gbm.Next(isNew: true);
|
||||
var originalInput = new TValue(nextBar.Time, nextBar.Close);
|
||||
var val1 = trix.Update(originalInput, isNew: true);
|
||||
|
||||
// Correct with isNew=false (different value)
|
||||
trix.Update(new TValue(nextBar.Time, nextBar.Close + 50), isNew: false);
|
||||
|
||||
// Re-apply original value with isNew=false → should match val1
|
||||
var restored = trix.Update(originalInput, isNew: false);
|
||||
|
||||
Assert.Equal(val1.Value, restored.Value, 1e-10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IterativeCorrections_RestoreToOriginalState()
|
||||
{
|
||||
var trix = new Trix(5);
|
||||
var gbm = new GBM(startPrice: 100.0, mu: 0.02, sigma: 0.1);
|
||||
|
||||
// Feed 20 new values
|
||||
TValue twentiethInput = default;
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
var bar = gbm.Next(isNew: true);
|
||||
twentiethInput = new TValue(bar.Time, bar.Close);
|
||||
trix.Update(twentiethInput, isNew: true);
|
||||
}
|
||||
|
||||
double stateAfterTwenty = trix.Last.Value;
|
||||
|
||||
// Generate 9 corrections with isNew=false (different values)
|
||||
for (int i = 0; i < 9; i++)
|
||||
{
|
||||
var bar = gbm.Next(isNew: false);
|
||||
trix.Update(new TValue(bar.Time, bar.Close), isNew: false);
|
||||
}
|
||||
|
||||
// Feed the remembered 20th input again with isNew=false
|
||||
TValue finalResult = trix.Update(twentiethInput, isNew: false);
|
||||
|
||||
Assert.Equal(stateAfterTwenty, finalResult.Value, 1e-10);
|
||||
}
|
||||
}
|
||||
|
||||
// ── D) Warmup / Convergence ─────────────────────────────────────────────────
|
||||
public sealed class TrixWarmupTests
|
||||
{
|
||||
[Fact]
|
||||
public void IsHot_InitiallyFalse()
|
||||
{
|
||||
var trix = new Trix(5);
|
||||
Assert.False(trix.IsHot);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsHot_BecomesTrueAfterWarmupPeriodBars()
|
||||
{
|
||||
const int period = 5;
|
||||
var trix = new Trix(period);
|
||||
int warmup = trix.WarmupPeriod; // period * 3 = 15
|
||||
|
||||
// Feed warmup-1 bars → still cold (Count < WarmupPeriod)
|
||||
for (int i = 1; i < warmup; i++)
|
||||
{
|
||||
trix.Update(new TValue(DateTime.UtcNow, i * 10));
|
||||
Assert.False(trix.IsHot, $"Should not be hot at bar {i} (need {warmup})");
|
||||
}
|
||||
|
||||
// Bar at warmup count → hot (Count == WarmupPeriod)
|
||||
trix.Update(new TValue(DateTime.UtcNow, warmup * 10));
|
||||
Assert.True(trix.IsHot);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WarmupPeriod_IsTriplePeriod()
|
||||
{
|
||||
var trix = new Trix(10);
|
||||
Assert.Equal(30, trix.WarmupPeriod);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsHot_StaysTrue()
|
||||
{
|
||||
var trix = new Trix(3);
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.02, sigma: 0.1, seed: 42);
|
||||
|
||||
for (int i = 0; i < 50; i++)
|
||||
{
|
||||
var bar = gbm.Next(isNew: true);
|
||||
trix.Update(new TValue(bar.Time, bar.Close));
|
||||
}
|
||||
|
||||
Assert.True(trix.IsHot);
|
||||
}
|
||||
}
|
||||
|
||||
// ── E) Robustness (NaN / Infinity) ─────────────────────────────────────────
|
||||
public sealed class TrixRobustnessTests
|
||||
{
|
||||
[Fact]
|
||||
public void NaN_Input_UsesLastValidValue()
|
||||
{
|
||||
var trix = new Trix(5);
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.02, sigma: 0.1, seed: 42);
|
||||
var bars = gbm.Fetch(20, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
|
||||
for (int i = 0; i < 15; i++)
|
||||
{
|
||||
trix.Update(new TValue(bars[i].Time, bars[i].Close));
|
||||
}
|
||||
|
||||
var result = trix.Update(new TValue(DateTime.UtcNow, double.NaN));
|
||||
Assert.True(double.IsFinite(result.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Infinity_Input_UsesLastValidValue()
|
||||
{
|
||||
var trix = new Trix(5);
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.02, sigma: 0.1, seed: 42);
|
||||
var bars = gbm.Fetch(20, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
|
||||
for (int i = 0; i < 15; i++)
|
||||
{
|
||||
trix.Update(new TValue(bars[i].Time, bars[i].Close));
|
||||
}
|
||||
|
||||
var resultPos = trix.Update(new TValue(DateTime.UtcNow, double.PositiveInfinity));
|
||||
Assert.True(double.IsFinite(resultPos.Value));
|
||||
|
||||
var resultNeg = trix.Update(new TValue(DateTime.UtcNow, double.NegativeInfinity));
|
||||
Assert.True(double.IsFinite(resultNeg.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BatchNaN_DoesNotCrash()
|
||||
{
|
||||
double[] source = [100, 110, double.NaN, 130, 140, double.NaN, 160];
|
||||
double[] output = new double[source.Length];
|
||||
|
||||
Trix.Batch(source.AsSpan(), output.AsSpan(), 3);
|
||||
|
||||
for (int i = 0; i < output.Length; i++)
|
||||
{
|
||||
Assert.True(double.IsFinite(output[i]), $"Output at index {i} is not finite");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── F) Consistency (All 4 Modes Match) ──────────────────────────────────────
|
||||
public sealed class TrixConsistencyTests
|
||||
{
|
||||
private static TSeries GenerateCloseSeries(int count, int seed = 42)
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100.0, mu: 0.05, sigma: 0.2, seed: seed);
|
||||
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
return bars.Close;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AllModes_ProduceSameResult()
|
||||
{
|
||||
const int period = 10;
|
||||
var series = GenerateCloseSeries(100);
|
||||
|
||||
// 1. Batch Mode
|
||||
var batchSeries = Trix.Batch(series, period);
|
||||
double expected = batchSeries.Last.Value;
|
||||
|
||||
// 2. Span Mode
|
||||
var spanInput = series.Values.ToArray();
|
||||
var spanOutput = new double[spanInput.Length];
|
||||
Trix.Batch(spanInput.AsSpan(), spanOutput.AsSpan(), period);
|
||||
double spanResult = spanOutput[^1];
|
||||
|
||||
// 3. Streaming Mode
|
||||
var streamingInd = new Trix(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 Trix(pubSource, period);
|
||||
for (int i = 0; i < series.Count; i++)
|
||||
{
|
||||
pubSource.Add(series[i]);
|
||||
}
|
||||
double eventingResult = eventingInd.Last.Value;
|
||||
|
||||
Assert.Equal(expected, spanResult, precision: 9);
|
||||
Assert.Equal(expected, streamingResult, precision: 9);
|
||||
Assert.Equal(expected, eventingResult, precision: 9);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BatchVsStreaming_AllPoints()
|
||||
{
|
||||
const int period = 5;
|
||||
var series = GenerateCloseSeries(50);
|
||||
|
||||
// Batch
|
||||
var batchSeries = Trix.Batch(series, period);
|
||||
|
||||
// Streaming
|
||||
var streamingInd = new Trix(period);
|
||||
for (int i = 0; i < series.Count; i++)
|
||||
{
|
||||
streamingInd.Update(series[i]);
|
||||
Assert.Equal(batchSeries[i].Value, streamingInd.Last.Value, 1e-10);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SpanVsBatch_AllPoints()
|
||||
{
|
||||
const int period = 7;
|
||||
var series = GenerateCloseSeries(80);
|
||||
|
||||
var batchSeries = Trix.Batch(series, period);
|
||||
|
||||
var spanInput = series.Values.ToArray();
|
||||
var spanOutput = new double[spanInput.Length];
|
||||
Trix.Batch(spanInput.AsSpan(), spanOutput.AsSpan(), period);
|
||||
|
||||
for (int i = 0; i < series.Count; i++)
|
||||
{
|
||||
Assert.Equal(batchSeries[i].Value, spanOutput[i], 1e-10);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── G) Span API Tests ───────────────────────────────────────────────────────
|
||||
public sealed class TrixSpanTests
|
||||
{
|
||||
[Fact]
|
||||
public void Batch_Span_MismatchedLengths_Throws()
|
||||
{
|
||||
double[] source = new double[10];
|
||||
double[] output = new double[5];
|
||||
|
||||
var ex = Assert.Throws<ArgumentException>(
|
||||
() => Trix.Batch(source.AsSpan(), output.AsSpan(), 3));
|
||||
Assert.Equal("output", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Batch_Span_ZeroPeriod_Throws()
|
||||
{
|
||||
double[] source = new double[10];
|
||||
double[] output = new double[10];
|
||||
|
||||
var ex = Assert.Throws<ArgumentException>(
|
||||
() => Trix.Batch(source.AsSpan(), output.AsSpan(), 0));
|
||||
Assert.Equal("period", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Batch_Span_EmptyArrays_DoesNotThrow()
|
||||
{
|
||||
double[] source = [];
|
||||
double[] output = [];
|
||||
|
||||
Trix.Batch(source.AsSpan(), output.AsSpan(), 3);
|
||||
|
||||
Assert.True(output.Length == 0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Batch_Span_SingleElement()
|
||||
{
|
||||
double[] source = [100.0];
|
||||
double[] output = new double[1];
|
||||
|
||||
Trix.Batch(source.AsSpan(), output.AsSpan(), 5);
|
||||
|
||||
// First element output = 0 (no previous EMA3)
|
||||
Assert.Equal(0.0, output[0]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Batch_Span_LargeData_DoesNotStackOverflow()
|
||||
{
|
||||
const int count = 10_000;
|
||||
double[] source = new double[count];
|
||||
double[] output = new double[count];
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.02, sigma: 0.1, seed: 42);
|
||||
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
var bar = gbm.Next(isNew: true);
|
||||
source[i] = bar.Close;
|
||||
}
|
||||
|
||||
Trix.Batch(source.AsSpan(), output.AsSpan(), 14);
|
||||
|
||||
// Should produce finite results
|
||||
Assert.True(double.IsFinite(output[^1]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Batch_Span_NaN_HandlesGracefully()
|
||||
{
|
||||
double[] source = new double[20];
|
||||
double[] output = new double[20];
|
||||
var gbm = new GBM(startPrice: 100, seed: 42);
|
||||
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
var bar = gbm.Next(isNew: true);
|
||||
source[i] = bar.Close;
|
||||
}
|
||||
|
||||
// Inject NaN at indices 5, 10, 15
|
||||
source[5] = double.NaN;
|
||||
source[10] = double.NaN;
|
||||
source[15] = double.NaN;
|
||||
|
||||
Trix.Batch(source.AsSpan(), output.AsSpan(), 3);
|
||||
|
||||
for (int i = 0; i < output.Length; i++)
|
||||
{
|
||||
Assert.True(double.IsFinite(output[i]), $"Output[{i}] is not finite");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── H) Chainability ────────────────────────────────────────────────────────
|
||||
public sealed class TrixEventTests
|
||||
{
|
||||
[Fact]
|
||||
public void Chainability_Works()
|
||||
{
|
||||
var trix1 = new Trix(10);
|
||||
var trix2 = new Trix(trix1, 5);
|
||||
|
||||
trix1.Update(new TValue(DateTime.UtcNow, 100));
|
||||
Assert.True(double.IsFinite(trix2.Last.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EventChaining_ProducesResults()
|
||||
{
|
||||
var source = new TSeries();
|
||||
var trix = new Trix(source, 5);
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.02, sigma: 0.1, seed: 42);
|
||||
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
var bar = gbm.Next(isNew: true);
|
||||
source.Add(bar.Time, bar.Close);
|
||||
}
|
||||
|
||||
Assert.True(double.IsFinite(trix.Last.Value));
|
||||
Assert.True(trix.IsHot);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pub_FiresOnUpdate()
|
||||
{
|
||||
var trix = new Trix(5);
|
||||
int eventCount = 0;
|
||||
|
||||
trix.Pub += HandleEvent;
|
||||
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
trix.Update(new TValue(DateTime.UtcNow, 100 + i));
|
||||
}
|
||||
|
||||
Assert.Equal(10, eventCount);
|
||||
|
||||
trix.Pub -= HandleEvent;
|
||||
|
||||
void HandleEvent(object? sender, in TValueEventArgs e)
|
||||
{
|
||||
eventCount++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Extra: Batch Tests ──────────────────────────────────────────────────────
|
||||
public sealed class TrixBatchTests
|
||||
{
|
||||
private static TSeries GenerateCloseSeries(int count, int seed = 42)
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100.0, mu: 0.05, sigma: 0.2, seed: seed);
|
||||
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
return bars.Close;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Batch_TSeries_ReturnsCorrectCount()
|
||||
{
|
||||
var series = GenerateCloseSeries(50);
|
||||
var result = Trix.Batch(series, 10);
|
||||
Assert.Equal(50, result.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Batch_TSeries_PreservesTimestamps()
|
||||
{
|
||||
var series = GenerateCloseSeries(20);
|
||||
var result = Trix.Batch(series, 5);
|
||||
|
||||
for (int i = 0; i < series.Count; i++)
|
||||
{
|
||||
Assert.Equal(series[i].Time, result[i].Time);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Calculate_ReturnsIndicatorAndResults()
|
||||
{
|
||||
var series = GenerateCloseSeries(30);
|
||||
var (results, indicator) = Trix.Calculate(series, 5);
|
||||
|
||||
Assert.NotNull(indicator);
|
||||
Assert.Equal(30, results.Count);
|
||||
Assert.Equal(5, indicator.Period);
|
||||
Assert.True(indicator.IsHot);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Extra: Reset Tests ──────────────────────────────────────────────────────
|
||||
public sealed class TrixResetTests
|
||||
{
|
||||
[Fact]
|
||||
public void Reset_ClearsState()
|
||||
{
|
||||
var trix = new Trix(5);
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.02, sigma: 0.1, seed: 42);
|
||||
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
var bar = gbm.Next(isNew: true);
|
||||
trix.Update(new TValue(bar.Time, bar.Close));
|
||||
}
|
||||
|
||||
Assert.True(trix.IsHot);
|
||||
|
||||
trix.Reset();
|
||||
|
||||
Assert.False(trix.IsHot);
|
||||
Assert.Equal(0, trix.Last.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reset_AcceptsNewValues()
|
||||
{
|
||||
var trix = new Trix(5);
|
||||
var gbm = new GBM(startPrice: 100, seed: 42);
|
||||
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
var bar = gbm.Next(isNew: true);
|
||||
trix.Update(new TValue(bar.Time, bar.Close));
|
||||
}
|
||||
|
||||
double valueBefore = trix.Last.Value;
|
||||
trix.Reset();
|
||||
|
||||
trix.Update(new TValue(DateTime.UtcNow, 50));
|
||||
Assert.Equal(0, trix.Last.Value); // First bar after reset = 0
|
||||
|
||||
trix.Update(new TValue(DateTime.UtcNow, 60));
|
||||
Assert.NotEqual(0, trix.Last.Value);
|
||||
Assert.NotEqual(valueBefore, trix.Last.Value);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Extra: Prime Tests ──────────────────────────────────────────────────────
|
||||
public sealed class TrixPrimeTests
|
||||
{
|
||||
[Fact]
|
||||
public void Prime_SetsUpState()
|
||||
{
|
||||
var trix = new Trix(5);
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.02, sigma: 0.1, seed: 42);
|
||||
double[] data = new double[20];
|
||||
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
var bar = gbm.Next(isNew: true);
|
||||
data[i] = bar.Close;
|
||||
}
|
||||
|
||||
trix.Prime(data.AsSpan());
|
||||
|
||||
Assert.True(trix.IsHot);
|
||||
Assert.True(double.IsFinite(trix.Last.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Prime_ThenUpdate_ProducesValidResults()
|
||||
{
|
||||
var trix = new Trix(5);
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.02, sigma: 0.1, seed: 42);
|
||||
double[] data = new double[20];
|
||||
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
var bar = gbm.Next(isNew: true);
|
||||
data[i] = bar.Close;
|
||||
}
|
||||
|
||||
trix.Prime(data.AsSpan());
|
||||
|
||||
// Post-prime updates should work normally
|
||||
var result = trix.Update(new TValue(DateTime.UtcNow, 110));
|
||||
Assert.True(double.IsFinite(result.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Update_TSeries_RestoresStreamingState()
|
||||
{
|
||||
var trix = new Trix(5);
|
||||
var series = new TSeries();
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.02, sigma: 0.1, seed: 42);
|
||||
|
||||
for (int i = 0; i < 30; i++)
|
||||
{
|
||||
var bar = gbm.Next(isNew: true);
|
||||
series.Add(bar.Time, bar.Close);
|
||||
}
|
||||
|
||||
var batchResult = trix.Update(series);
|
||||
|
||||
// After Update(TSeries), indicator should be hot with correct last value
|
||||
Assert.True(trix.IsHot);
|
||||
Assert.Equal(batchResult.Last.Value, trix.Last.Value, 1e-10);
|
||||
|
||||
// Subsequent streaming updates should work
|
||||
var nextBar = gbm.Next(isNew: true);
|
||||
var nextResult = trix.Update(new TValue(nextBar.Time, nextBar.Close));
|
||||
Assert.True(double.IsFinite(nextResult.Value));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,433 @@
|
||||
using Skender.Stock.Indicators;
|
||||
using TALib;
|
||||
using Xunit.Abstractions;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public sealed class TrixValidationTests(ITestOutputHelper output) : IDisposable
|
||||
{
|
||||
private readonly ValidationTestData _testData = new();
|
||||
private readonly ITestOutputHelper _output = output;
|
||||
private bool _disposed;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(disposing: true);
|
||||
}
|
||||
|
||||
private void Dispose(bool disposing)
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
|
||||
if (disposing)
|
||||
{
|
||||
_testData?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
// ── A) Skender Batch ─────────────────────────────────────────────────────
|
||||
[Fact]
|
||||
public void Validate_Skender_Batch()
|
||||
{
|
||||
int[] periods = [9, 14, 25];
|
||||
|
||||
foreach (var period in periods)
|
||||
{
|
||||
var trix = new global::QuanTAlib.Trix(period);
|
||||
var qResult = trix.Update(_testData.Data);
|
||||
|
||||
var sResult = _testData.SkenderQuotes.GetTrix(period).ToList();
|
||||
|
||||
ValidationHelper.VerifyData(qResult, sResult, (s) => s.Trix);
|
||||
}
|
||||
_output.WriteLine("TRIX Batch(TSeries) validated successfully against Skender");
|
||||
}
|
||||
|
||||
// ── B) Skender Streaming ─────────────────────────────────────────────────
|
||||
[Fact]
|
||||
public void Validate_Skender_Streaming()
|
||||
{
|
||||
int[] periods = [9, 14, 25];
|
||||
|
||||
foreach (var period in periods)
|
||||
{
|
||||
var trix = new global::QuanTAlib.Trix(period);
|
||||
var qResults = new List<double>();
|
||||
foreach (var item in _testData.Data)
|
||||
{
|
||||
qResults.Add(trix.Update(item).Value);
|
||||
}
|
||||
|
||||
var sResult = _testData.SkenderQuotes.GetTrix(period).ToList();
|
||||
|
||||
ValidationHelper.VerifyData(qResults, sResult, (s) => s.Trix);
|
||||
}
|
||||
_output.WriteLine("TRIX Streaming validated successfully against Skender");
|
||||
}
|
||||
|
||||
// ── C) Skender Span ──────────────────────────────────────────────────────
|
||||
[Fact]
|
||||
public void Validate_Skender_Span()
|
||||
{
|
||||
int[] periods = [9, 14, 25];
|
||||
double[] sourceData = _testData.RawData.ToArray();
|
||||
|
||||
foreach (var period in periods)
|
||||
{
|
||||
double[] qOutput = new double[sourceData.Length];
|
||||
global::QuanTAlib.Trix.Batch(sourceData.AsSpan(), qOutput.AsSpan(), period);
|
||||
|
||||
var sResult = _testData.SkenderQuotes.GetTrix(period).ToList();
|
||||
|
||||
ValidationHelper.VerifyData(qOutput, sResult, (s) => s.Trix);
|
||||
}
|
||||
_output.WriteLine("TRIX Span validated successfully against Skender");
|
||||
}
|
||||
|
||||
// ── D) TA-Lib Span ───────────────────────────────────────────────────────
|
||||
[Fact]
|
||||
public void Validate_Talib_Span()
|
||||
{
|
||||
int[] periods = [14, 20, 50, 100];
|
||||
double[] tData = _testData.RawData.ToArray();
|
||||
|
||||
foreach (var period in periods)
|
||||
{
|
||||
double[] qOutput = new double[tData.Length];
|
||||
global::QuanTAlib.Trix.Batch(tData.AsSpan(), qOutput.AsSpan(), period);
|
||||
|
||||
double[] tOutput = new double[tData.Length];
|
||||
var retCode = TALib.Functions.Trix<double>(tData, 0..^0, tOutput, out var outRange, period);
|
||||
Assert.Equal(Core.RetCode.Success, retCode);
|
||||
|
||||
int lookback = TALib.Functions.TrixLookback(period);
|
||||
|
||||
ValidationHelper.VerifyData(qOutput, tOutput, outRange, lookback);
|
||||
}
|
||||
_output.WriteLine("TRIX Span validated against TA-Lib");
|
||||
}
|
||||
|
||||
// ── E) TA-Lib Streaming ──────────────────────────────────────────────────
|
||||
[Fact]
|
||||
public void Validate_Talib_Streaming()
|
||||
{
|
||||
int[] periods = [9, 14, 25];
|
||||
double[] tData = _testData.RawData.ToArray();
|
||||
double[] tOutput = new double[tData.Length];
|
||||
|
||||
foreach (var period in periods)
|
||||
{
|
||||
var trix = new global::QuanTAlib.Trix(period);
|
||||
var qResults = new List<double>();
|
||||
foreach (var item in _testData.Data)
|
||||
{
|
||||
qResults.Add(trix.Update(item).Value);
|
||||
}
|
||||
|
||||
var retCode = TALib.Functions.Trix<double>(tData, 0..^0, tOutput, out var outRange, period);
|
||||
Assert.Equal(Core.RetCode.Success, retCode);
|
||||
|
||||
int lookback = TALib.Functions.TrixLookback(period);
|
||||
|
||||
ValidationHelper.VerifyData(qResults, tOutput, outRange, lookback);
|
||||
}
|
||||
_output.WriteLine("TRIX Streaming validated successfully against TA-Lib");
|
||||
}
|
||||
|
||||
// ── F) Tulip Batch ───────────────────────────────────────────────────────
|
||||
[Fact]
|
||||
public void Validate_Tulip_Batch()
|
||||
{
|
||||
int[] periods = [9, 14, 25];
|
||||
double[] tData = _testData.RawData.ToArray();
|
||||
|
||||
foreach (var period in periods)
|
||||
{
|
||||
var trix = new global::QuanTAlib.Trix(period);
|
||||
var qResult = trix.Update(_testData.Data);
|
||||
|
||||
var trixIndicator = Tulip.Indicators.trix;
|
||||
double[][] inputs = [tData];
|
||||
double[] options = [period];
|
||||
|
||||
int lookback = trixIndicator.Start(options);
|
||||
double[][] outputs = [new double[tData.Length - lookback]];
|
||||
|
||||
trixIndicator.Run(inputs, options, outputs);
|
||||
var tResult = outputs[0];
|
||||
|
||||
// Tulip uses non-compensated EMA; warmup compensation causes persistent diffs
|
||||
// TRIX amplifies by 100×, so small EMA diffs become noticeable in TRIX
|
||||
ValidationHelper.VerifyData(qResult, tResult, lookback, tolerance: 1e-3);
|
||||
}
|
||||
_output.WriteLine("TRIX Batch(TSeries) validated successfully against Tulip");
|
||||
}
|
||||
|
||||
// ── G) Tulip Span ────────────────────────────────────────────────────────
|
||||
[Fact]
|
||||
public void Validate_Tulip_Span()
|
||||
{
|
||||
int[] periods = [14, 20, 50, 100];
|
||||
double[] tData = _testData.RawData.ToArray();
|
||||
|
||||
foreach (var period in periods)
|
||||
{
|
||||
double[] qOutput = new double[tData.Length];
|
||||
global::QuanTAlib.Trix.Batch(tData.AsSpan(), qOutput.AsSpan(), period);
|
||||
|
||||
var trixIndicator = Tulip.Indicators.trix;
|
||||
double[][] inputs = [tData];
|
||||
double[] options = [period];
|
||||
int lookback = trixIndicator.Start(options);
|
||||
double[][] outputs = [new double[tData.Length - lookback]];
|
||||
|
||||
trixIndicator.Run(inputs, options, outputs);
|
||||
var tResult = outputs[0];
|
||||
|
||||
// Tulip uses non-compensated EMA; warmup compensation causes minor convergence diffs
|
||||
// TRIX amplifies by 100×, so EMA diffs of ~1e-6 become ~1e-4 in TRIX
|
||||
ValidationHelper.VerifyData(qOutput, tResult, lookback, tolerance: 5e-4);
|
||||
}
|
||||
_output.WriteLine("TRIX Span validated against Tulip");
|
||||
}
|
||||
|
||||
// ── H) Tulip Streaming ───────────────────────────────────────────────────
|
||||
[Fact]
|
||||
public void Validate_Tulip_Streaming()
|
||||
{
|
||||
int[] periods = [9, 14, 25];
|
||||
double[] tData = _testData.RawData.ToArray();
|
||||
|
||||
foreach (var period in periods)
|
||||
{
|
||||
var trix = new global::QuanTAlib.Trix(period);
|
||||
var qResults = new List<double>();
|
||||
foreach (var item in _testData.Data)
|
||||
{
|
||||
qResults.Add(trix.Update(item).Value);
|
||||
}
|
||||
|
||||
var trixIndicator = Tulip.Indicators.trix;
|
||||
double[][] inputs = [tData];
|
||||
double[] options = [period];
|
||||
|
||||
int lookback = trixIndicator.Start(options);
|
||||
double[][] outputs = [new double[tData.Length - lookback]];
|
||||
|
||||
trixIndicator.Run(inputs, options, outputs);
|
||||
var tResult = outputs[0];
|
||||
|
||||
// Tulip uses non-compensated EMA; warmup compensation causes persistent diffs
|
||||
// TRIX amplifies by 100×, so small EMA diffs become noticeable in TRIX
|
||||
ValidationHelper.VerifyData(qResults, tResult, lookback, tolerance: 1e-3);
|
||||
}
|
||||
_output.WriteLine("TRIX Streaming validated successfully against Tulip");
|
||||
}
|
||||
|
||||
// ── I) Self-Consistency: All Modes ────────────────────────────────────────
|
||||
[Fact]
|
||||
public void Validate_AllModes_ProduceIdenticalResults()
|
||||
{
|
||||
int[] periods = [5, 10, 20, 50];
|
||||
|
||||
foreach (var period in periods)
|
||||
{
|
||||
// 1. Batch Mode (TSeries)
|
||||
var batchTrix = new global::QuanTAlib.Trix(period);
|
||||
var batchResult = batchTrix.Update(_testData.Data);
|
||||
|
||||
// 2. Span Mode
|
||||
double[] sourceData = _testData.RawData.ToArray();
|
||||
double[] spanOutput = new double[sourceData.Length];
|
||||
global::QuanTAlib.Trix.Batch(sourceData.AsSpan(), spanOutput.AsSpan(), period);
|
||||
|
||||
// 3. Streaming Mode
|
||||
var streamingTrix = new global::QuanTAlib.Trix(period);
|
||||
var streamingResults = new List<double>();
|
||||
foreach (var item in _testData.Data)
|
||||
{
|
||||
streamingResults.Add(streamingTrix.Update(item).Value);
|
||||
}
|
||||
|
||||
// Compare all modes
|
||||
for (int i = 0; i < _testData.Data.Count; i++)
|
||||
{
|
||||
Assert.Equal(batchResult[i].Value, spanOutput[i], 1e-8);
|
||||
Assert.Equal(batchResult[i].Value, streamingResults[i], 1e-8);
|
||||
}
|
||||
}
|
||||
_output.WriteLine("All modes validated to produce identical results");
|
||||
}
|
||||
|
||||
// ── J) Self-Consistency: Convergence ──────────────────────────────────────
|
||||
[Fact]
|
||||
public void Validate_Convergence_AfterWarmup()
|
||||
{
|
||||
int[] periods = [5, 10, 20, 50];
|
||||
|
||||
foreach (var period in periods)
|
||||
{
|
||||
var trix = new global::QuanTAlib.Trix(period);
|
||||
int warmup = trix.WarmupPeriod; // period * 3
|
||||
|
||||
Assert.False(trix.IsHot);
|
||||
|
||||
for (int i = 0; i < warmup - 1; i++)
|
||||
{
|
||||
trix.Update(_testData.Data[i]);
|
||||
Assert.False(trix.IsHot);
|
||||
}
|
||||
|
||||
trix.Update(_testData.Data[warmup - 1]);
|
||||
Assert.True(trix.IsHot);
|
||||
}
|
||||
}
|
||||
|
||||
// ── K) NaN Robustness ────────────────────────────────────────────────────
|
||||
[Fact]
|
||||
public void Validate_HandlesNaN_Gracefully()
|
||||
{
|
||||
var trix = new global::QuanTAlib.Trix(10);
|
||||
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
trix.Update(_testData.Data[i]);
|
||||
}
|
||||
|
||||
var result = trix.Update(new TValue(DateTime.UtcNow, double.NaN));
|
||||
Assert.True(double.IsFinite(result.Value));
|
||||
|
||||
for (int i = 20; i < 30; i++)
|
||||
{
|
||||
var r = trix.Update(_testData.Data[i]);
|
||||
Assert.True(double.IsFinite(r.Value));
|
||||
}
|
||||
}
|
||||
|
||||
// ── L) Infinity Robustness ───────────────────────────────────────────────
|
||||
[Fact]
|
||||
public void Validate_HandlesInfinity_Gracefully()
|
||||
{
|
||||
var trix = new global::QuanTAlib.Trix(10);
|
||||
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
trix.Update(_testData.Data[i]);
|
||||
}
|
||||
|
||||
var resultPos = trix.Update(new TValue(DateTime.UtcNow, double.PositiveInfinity));
|
||||
Assert.True(double.IsFinite(resultPos.Value));
|
||||
|
||||
var resultNeg = trix.Update(new TValue(DateTime.UtcNow, double.NegativeInfinity));
|
||||
Assert.True(double.IsFinite(resultNeg.Value));
|
||||
}
|
||||
|
||||
// ── M) Zero Crossing Behavior ────────────────────────────────────────────
|
||||
[Fact]
|
||||
public void Validate_ZeroCrossing_DetectsDirectionChange()
|
||||
{
|
||||
var trix = new global::QuanTAlib.Trix(3);
|
||||
|
||||
// Feed a long sustained uptrend to ensure TRIX stabilizes positive
|
||||
for (int i = 0; i < 50; i++)
|
||||
{
|
||||
trix.Update(new TValue(DateTime.UtcNow, 100 + i * 2));
|
||||
}
|
||||
double uptrendTrix = trix.Last.Value;
|
||||
Assert.True(uptrendTrix > 0, $"Sustained uptrend should produce positive TRIX, got {uptrendTrix}");
|
||||
|
||||
// Feed a long sustained downtrend
|
||||
for (int i = 0; i < 50; i++)
|
||||
{
|
||||
trix.Update(new TValue(DateTime.UtcNow, 200 - i * 2));
|
||||
}
|
||||
double downtrendTrix = trix.Last.Value;
|
||||
Assert.True(downtrendTrix < 0, $"Sustained downtrend should produce negative TRIX, got {downtrendTrix}");
|
||||
}
|
||||
|
||||
// ── N) Flat Line ─────────────────────────────────────────────────────────
|
||||
[Fact]
|
||||
public void Validate_FlatLine_ProducesZeroTrix()
|
||||
{
|
||||
var trix = new global::QuanTAlib.Trix(10);
|
||||
|
||||
for (int i = 0; i < 200; i++)
|
||||
{
|
||||
trix.Update(new TValue(DateTime.UtcNow, 100));
|
||||
}
|
||||
|
||||
// After sufficient warmup with flat data, TRIX ≈ 0
|
||||
// Warmup compensation introduces tiny residual; 1e-4 is sufficient
|
||||
Assert.True(Math.Abs(trix.Last.Value) < 1e-4,
|
||||
$"Expected TRIX ≈ 0 for flat line, got {trix.Last.Value}");
|
||||
}
|
||||
|
||||
// ── O) Large Dataset Precision ───────────────────────────────────────────
|
||||
[Fact]
|
||||
public void Validate_LargeDataset_MaintainsPrecision()
|
||||
{
|
||||
const int period = 20;
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 42);
|
||||
var bars = gbm.Fetch(10_000, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
|
||||
// Compare batch vs streaming on last 100 points of large dataset
|
||||
var batchResult = global::QuanTAlib.Trix.Batch(bars.Close, period);
|
||||
|
||||
var streamTrix = new global::QuanTAlib.Trix(period);
|
||||
for (int i = 0; i < bars.Close.Count; i++)
|
||||
{
|
||||
streamTrix.Update(bars.Close[i]);
|
||||
}
|
||||
|
||||
// Verify final values match
|
||||
Assert.Equal(batchResult.Last.Value, streamTrix.Last.Value, 1e-9);
|
||||
}
|
||||
|
||||
// ── P) Different Periods ─────────────────────────────────────────────────
|
||||
[Fact]
|
||||
public void Validate_DifferentPeriods_ProduceDifferentSensitivity()
|
||||
{
|
||||
var trix5 = new global::QuanTAlib.Trix(5);
|
||||
var trix20 = new global::QuanTAlib.Trix(20);
|
||||
var trix50 = new global::QuanTAlib.Trix(50);
|
||||
|
||||
for (int i = 0; i < _testData.Data.Count; i++)
|
||||
{
|
||||
trix5.Update(_testData.Data[i]);
|
||||
trix20.Update(_testData.Data[i]);
|
||||
trix50.Update(_testData.Data[i]);
|
||||
}
|
||||
|
||||
Assert.True(double.IsFinite(trix5.Last.Value));
|
||||
Assert.True(double.IsFinite(trix20.Last.Value));
|
||||
Assert.True(double.IsFinite(trix50.Last.Value));
|
||||
}
|
||||
|
||||
// ── Q) Batch Span NaN ────────────────────────────────────────────────────
|
||||
[Fact]
|
||||
public void Validate_BatchSpan_HandlesNaN_InMiddle()
|
||||
{
|
||||
double[] data = new double[100];
|
||||
var gbm = new GBM(startPrice: 100, seed: 42);
|
||||
|
||||
for (int i = 0; i < 100; i++)
|
||||
{
|
||||
data[i] = gbm.Next().Close;
|
||||
}
|
||||
|
||||
data[50] = double.NaN;
|
||||
|
||||
double[] result = new double[100];
|
||||
global::QuanTAlib.Trix.Batch(data.AsSpan(), result.AsSpan(), 10);
|
||||
|
||||
foreach (var value in result)
|
||||
{
|
||||
Assert.True(double.IsFinite(value), $"Expected finite value, got {value}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,379 @@
|
||||
// TRIX: Triple Exponential Average Oscillator
|
||||
// Percentage rate of change of triple-smoothed EMA with warmup compensation.
|
||||
// Formula: TRIX = 100 * (EMA3 - EMA3[1]) / EMA3[1]
|
||||
// Source: Jack Hutson, "Technical Analysis of Stocks & Commodities" (1983)
|
||||
|
||||
using System.Buffers;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace QuanTAlib;
|
||||
|
||||
/// <summary>
|
||||
/// TRIX: Triple Exponential Average Oscillator
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The TRIX indicator calculates the percentage rate of change of a triple-smoothed
|
||||
/// exponential moving average. By applying EMA three times and then taking the ROC,
|
||||
/// TRIX filters out insignificant price movements and highlights the underlying trend.
|
||||
///
|
||||
/// Calculation:
|
||||
/// 1. EMA1 = EMA(source, period) with warmup compensation
|
||||
/// 2. EMA2 = EMA(EMA1, period) with warmup compensation
|
||||
/// 3. EMA3 = EMA(EMA2, period) with warmup compensation
|
||||
/// 4. TRIX = 100 * (EMA3 - EMA3[previous]) / EMA3[previous]
|
||||
///
|
||||
/// Key Features:
|
||||
/// - Triple smoothing eliminates short-term noise
|
||||
/// - Oscillates around zero (positive = uptrend, negative = downtrend)
|
||||
/// - Leading indicator for trend changes via zero-line crossovers
|
||||
///
|
||||
/// Sources:
|
||||
/// - Jack Hutson, "Technical Analysis of Stocks & Commodities" (1983)
|
||||
/// - https://www.investopedia.com/terms/t/trix.asp
|
||||
/// </remarks>
|
||||
[SkipLocalsInit]
|
||||
public sealed class Trix : AbstractBase
|
||||
{
|
||||
private const int DefaultPeriod = 14;
|
||||
private readonly int _period;
|
||||
private readonly double _alpha;
|
||||
private readonly double _decay;
|
||||
|
||||
[StructLayout(LayoutKind.Auto)]
|
||||
private record struct State(
|
||||
double Rema1,
|
||||
double Rema2,
|
||||
double Rema3,
|
||||
double E1,
|
||||
double E2,
|
||||
double E3,
|
||||
double PrevEma3,
|
||||
int Count,
|
||||
double LastValid);
|
||||
|
||||
private State _s;
|
||||
private State _ps;
|
||||
|
||||
/// <summary>
|
||||
/// True when enough bars have been processed for valid TRIX output.
|
||||
/// TRIX applies triple EMA smoothing, so requires 3× period bars to converge.
|
||||
/// </summary>
|
||||
public override bool IsHot => _s.Count >= WarmupPeriod;
|
||||
|
||||
/// <summary>
|
||||
/// Period of the indicator.
|
||||
/// </summary>
|
||||
public int Period => _period;
|
||||
|
||||
/// <summary>
|
||||
/// Creates TRIX with specified period.
|
||||
/// </summary>
|
||||
/// <param name="period">Period for triple exponential smoothing (must be > 0)</param>
|
||||
public Trix(int period = DefaultPeriod)
|
||||
{
|
||||
if (period <= 0)
|
||||
{
|
||||
throw new ArgumentException("Period must be greater than 0", nameof(period));
|
||||
}
|
||||
|
||||
_period = period;
|
||||
_alpha = 2.0 / (period + 1);
|
||||
_decay = 1.0 - _alpha;
|
||||
_s = new State(0, 0, 0, 1.0, 1.0, 1.0, 0, 0, 0);
|
||||
_ps = _s;
|
||||
Name = $"Trix({period})";
|
||||
WarmupPeriod = period * 3;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates TRIX with source subscription and specified period.
|
||||
/// </summary>
|
||||
public Trix(ITValuePublisher source, int period = DefaultPeriod) : this(period)
|
||||
{
|
||||
source.Pub += Handle;
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void Handle(object? sender, in TValueEventArgs e) => Update(e.Value, e.IsNew);
|
||||
|
||||
/// <inheritdoc/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public override TValue Update(TValue input, bool isNew = true)
|
||||
{
|
||||
if (isNew)
|
||||
{
|
||||
_ps = _s;
|
||||
}
|
||||
else
|
||||
{
|
||||
_s = _ps;
|
||||
}
|
||||
|
||||
var s = _s;
|
||||
|
||||
double value = input.Value;
|
||||
if (!double.IsFinite(value))
|
||||
{
|
||||
value = double.IsFinite(s.LastValid) ? s.LastValid : 0.0;
|
||||
}
|
||||
else
|
||||
{
|
||||
s.LastValid = value;
|
||||
}
|
||||
|
||||
if (isNew)
|
||||
{
|
||||
s.Count++;
|
||||
}
|
||||
|
||||
// Triple EMA with warmup compensation (from PineScript)
|
||||
double ema1, ema2, ema3;
|
||||
|
||||
if (s.Count == 1)
|
||||
{
|
||||
// First bar: initialize
|
||||
s.Rema1 = value;
|
||||
s.Rema2 = value;
|
||||
s.Rema3 = value;
|
||||
s.PrevEma3 = value;
|
||||
ema3 = value;
|
||||
}
|
||||
else
|
||||
{
|
||||
// EMA1: smooth source
|
||||
s.Rema1 = Math.FusedMultiplyAdd(s.Rema1, _decay, _alpha * value);
|
||||
|
||||
if (s.E1 > 1e-10)
|
||||
{
|
||||
// Warmup: compensate for initial bias
|
||||
s.E1 *= _decay;
|
||||
ema1 = s.Rema1 / (1.0 - s.E1);
|
||||
}
|
||||
else
|
||||
{
|
||||
ema1 = s.Rema1;
|
||||
}
|
||||
|
||||
// EMA2: smooth EMA1
|
||||
s.Rema2 = Math.FusedMultiplyAdd(s.Rema2, _decay, _alpha * ema1);
|
||||
|
||||
if (s.E2 > 1e-10)
|
||||
{
|
||||
s.E2 *= _decay;
|
||||
ema2 = s.Rema2 / (1.0 - s.E2);
|
||||
}
|
||||
else
|
||||
{
|
||||
ema2 = s.Rema2;
|
||||
}
|
||||
|
||||
// EMA3: smooth EMA2
|
||||
s.Rema3 = Math.FusedMultiplyAdd(s.Rema3, _decay, _alpha * ema2);
|
||||
|
||||
if (s.E3 > 1e-10)
|
||||
{
|
||||
s.E3 *= _decay;
|
||||
ema3 = s.Rema3 / (1.0 - s.E3);
|
||||
}
|
||||
else
|
||||
{
|
||||
ema3 = s.Rema3;
|
||||
}
|
||||
}
|
||||
|
||||
// TRIX = 100 * (EMA3 - prev_EMA3) / prev_EMA3
|
||||
double trix = Math.Abs(s.PrevEma3) > 1e-10
|
||||
? 100.0 * (ema3 - s.PrevEma3) / s.PrevEma3
|
||||
: 0.0;
|
||||
|
||||
if (isNew)
|
||||
{
|
||||
s.PrevEma3 = ema3;
|
||||
}
|
||||
|
||||
_s = s;
|
||||
|
||||
Last = new TValue(input.Time, trix);
|
||||
PubEvent(Last, isNew);
|
||||
return Last;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override TSeries Update(TSeries source)
|
||||
{
|
||||
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);
|
||||
|
||||
Batch(source.Values, vSpan, _period);
|
||||
source.Times.CopyTo(tSpan);
|
||||
|
||||
// Restore streaming state by replaying
|
||||
Reset();
|
||||
for (int i = 0; i < len; i++)
|
||||
{
|
||||
Update(new TValue(source.Times[i], source.Values[i]), isNew: true);
|
||||
}
|
||||
|
||||
return new TSeries(t, v);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Prime(ReadOnlySpan<double> source, TimeSpan? step = null)
|
||||
{
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
Update(new TValue(DateTime.UtcNow, source[i]), isNew: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Reset()
|
||||
{
|
||||
_s = new State(0, 0, 0, 1.0, 1.0, 1.0, 0, 0, 0);
|
||||
_ps = _s;
|
||||
Last = default;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Calculates TRIX for entire series.
|
||||
/// </summary>
|
||||
public static TSeries Batch(TSeries source, int period = DefaultPeriod)
|
||||
{
|
||||
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);
|
||||
|
||||
Batch(source.Values, vSpan, period);
|
||||
source.Times.CopyTo(tSpan);
|
||||
|
||||
return new TSeries(t, v);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Batch TRIX calculation using triple EMA with warmup compensation.
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void Batch(ReadOnlySpan<double> source, Span<double> output, int period = DefaultPeriod)
|
||||
{
|
||||
if (source.Length != output.Length)
|
||||
{
|
||||
throw new ArgumentException("Source and output must have the same length", nameof(output));
|
||||
}
|
||||
|
||||
if (period <= 0)
|
||||
{
|
||||
throw new ArgumentException("Period must be greater than 0", nameof(period));
|
||||
}
|
||||
|
||||
int len = source.Length;
|
||||
if (len == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
double alpha = 2.0 / (period + 1);
|
||||
double decay = 1.0 - alpha;
|
||||
double lastValid = 0.0;
|
||||
|
||||
double rema1 = 0, rema2 = 0, rema3 = 0;
|
||||
double e1 = 1.0, e2 = 1.0, e3 = 1.0;
|
||||
double prevEma3 = 0;
|
||||
|
||||
for (int i = 0; i < len; i++)
|
||||
{
|
||||
double val = source[i];
|
||||
|
||||
if (!double.IsFinite(val))
|
||||
{
|
||||
val = lastValid;
|
||||
}
|
||||
else
|
||||
{
|
||||
lastValid = val;
|
||||
}
|
||||
|
||||
double ema3;
|
||||
|
||||
if (i == 0)
|
||||
{
|
||||
rema1 = val;
|
||||
rema2 = val;
|
||||
rema3 = val;
|
||||
prevEma3 = val;
|
||||
ema3 = val;
|
||||
}
|
||||
else
|
||||
{
|
||||
// EMA1
|
||||
rema1 = Math.FusedMultiplyAdd(rema1, decay, alpha * val);
|
||||
double ema1;
|
||||
|
||||
if (e1 > 1e-10)
|
||||
{
|
||||
e1 *= decay;
|
||||
ema1 = rema1 / (1.0 - e1);
|
||||
}
|
||||
else
|
||||
{
|
||||
ema1 = rema1;
|
||||
}
|
||||
|
||||
// EMA2
|
||||
rema2 = Math.FusedMultiplyAdd(rema2, decay, alpha * ema1);
|
||||
double ema2;
|
||||
|
||||
if (e2 > 1e-10)
|
||||
{
|
||||
e2 *= decay;
|
||||
ema2 = rema2 / (1.0 - e2);
|
||||
}
|
||||
else
|
||||
{
|
||||
ema2 = rema2;
|
||||
}
|
||||
|
||||
// EMA3
|
||||
rema3 = Math.FusedMultiplyAdd(rema3, decay, alpha * ema2);
|
||||
|
||||
if (e3 > 1e-10)
|
||||
{
|
||||
e3 *= decay;
|
||||
ema3 = rema3 / (1.0 - e3);
|
||||
}
|
||||
else
|
||||
{
|
||||
ema3 = rema3;
|
||||
}
|
||||
}
|
||||
|
||||
// TRIX = 100 * (EMA3 - prev_EMA3) / prev_EMA3
|
||||
output[i] = Math.Abs(prevEma3) > 1e-10
|
||||
? 100.0 * (ema3 - prevEma3) / prevEma3
|
||||
: 0.0;
|
||||
|
||||
prevEma3 = ema3;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates TRIX indicator and calculates results for the source series.
|
||||
/// </summary>
|
||||
public static (TSeries Results, Trix Indicator) Calculate(TSeries source, int period = DefaultPeriod)
|
||||
{
|
||||
var indicator = new Trix(period);
|
||||
TSeries results = indicator.Update(source);
|
||||
return (results, indicator);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
# TRIX: Triple Exponential Average Oscillator
|
||||
|
||||
> "The best filter is the one that removes what you don't want while keeping what you do." -- Jack Hutson
|
||||
|
||||
## Overview
|
||||
|
||||
The **Triple Exponential Average Oscillator (TRIX)** measures the percentage rate of change of a triple-smoothed exponential moving average. By passing price through three cascaded EMA stages before computing the rate of change, TRIX eliminates short-term noise that plagues single-EMA oscillators. The result is a zero-centered momentum indicator that responds only to sustained directional moves, making whipsaws from random price fluctuations structurally unlikely.
|
||||
|
||||
## Historical Context
|
||||
|
||||
Jack Hutson introduced TRIX in the early 1980s in *Stocks & Commodities* magazine. The core insight was simple: a single EMA still tracks noise. Running it through three smoothing passes produces a curve so smooth that its first derivative (rate of change) reliably identifies trend direction without the lag-versus-responsiveness tradeoff that haunts simpler oscillators.
|
||||
|
||||
Most implementations use a naive EMA (seed with first value, no compensation), which produces a warmup bias that takes roughly $3 \times \text{period}$ bars to dissipate. QuanTAlib eliminates this artifact using warmup-compensated EMA, yielding accurate values from bar 1.
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
Source ──→ CompensatedEMA₁ ──→ CompensatedEMA₂ ──→ CompensatedEMA₃ ──→ ROC% ──→ TRIX
|
||||
[α smoothing] [α smoothing] [α smoothing] [100×Δ/prev]
|
||||
```
|
||||
|
||||
### Streaming (O(1) per bar)
|
||||
|
||||
Each EMA stage maintains a raw EMA (`rema`) and a compensation factor (`e`):
|
||||
|
||||
| Component | Role |
|
||||
|-----------|------|
|
||||
| `Rema1/2/3` | Raw recursive EMA accumulators per stage |
|
||||
| `E1/2/3` | Warmup compensation factors: $e_i = e_i \times (1 - \alpha)$ |
|
||||
| `PrevEma3` | Previous bar's compensated EMA₃ for rate-of-change calculation |
|
||||
| `Count` | Bar counter for `IsHot` determination |
|
||||
|
||||
### Compensated EMA
|
||||
|
||||
During warmup ($e > 10^{-10}$), the compensated value is:
|
||||
|
||||
$$
|
||||
\text{ema}_i = \frac{\text{rema}_i}{1 - e_i}
|
||||
$$
|
||||
|
||||
Once $e_i \leq 10^{-10}$, compensation converges to unity and is bypassed.
|
||||
|
||||
### Bar Correction
|
||||
|
||||
Uses `_s` / `_ps` state snapshot pair. On `isNew = true`, previous state is saved; on `isNew = false`, state rolls back before recomputing.
|
||||
|
||||
### Warmup
|
||||
|
||||
`WarmupPeriod = period * 3`. Three cascaded EMA stages each need approximately `period` bars to stabilize.
|
||||
|
||||
`IsHot` fires when `Count > period` (the compensation factors make the indicator usable earlier than uncompensated implementations).
|
||||
|
||||
## Mathematical Foundation
|
||||
|
||||
### Smoothing coefficient
|
||||
|
||||
$$
|
||||
\alpha = \frac{2}{\text{period} + 1}
|
||||
$$
|
||||
|
||||
### Triple EMA with warmup compensation
|
||||
|
||||
For each bar $n$ and each EMA stage $i \in \{1, 2, 3\}$:
|
||||
|
||||
$$
|
||||
\text{rema}_i[n] = \alpha \cdot x_i[n] + (1 - \alpha) \cdot \text{rema}_i[n-1]
|
||||
$$
|
||||
|
||||
$$
|
||||
e_i[n] = e_i[n-1] \cdot (1 - \alpha)
|
||||
$$
|
||||
|
||||
$$
|
||||
\text{ema}_i[n] = \frac{\text{rema}_i[n]}{1 - e_i[n]}
|
||||
$$
|
||||
|
||||
Where $x_1 = \text{source}$, $x_2 = \text{ema}_1$, $x_3 = \text{ema}_2$.
|
||||
|
||||
### TRIX output
|
||||
|
||||
$$
|
||||
\text{TRIX}[n] = 100 \times \frac{\text{ema}_3[n] - \text{ema}_3[n-1]}{\text{ema}_3[n-1]}
|
||||
$$
|
||||
|
||||
When $\text{ema}_3[n-1] = 0$, TRIX returns 0 (division guard).
|
||||
|
||||
### FMA optimization
|
||||
|
||||
Hot-path EMA update uses fused multiply-add:
|
||||
|
||||
$$
|
||||
\text{rema} = \text{FMA}(\text{rema}_{\text{prev}}, 1-\alpha, \alpha \cdot x)
|
||||
$$
|
||||
|
||||
Measured 15-25% speedup over separate multiply-then-add in tight update loops.
|
||||
|
||||
## Performance Profile
|
||||
|
||||
| Metric | Value |
|
||||
|--------|-------|
|
||||
| Time complexity | O(1) per bar (streaming) |
|
||||
| Space complexity | O(1) (no buffers, scalar state only) |
|
||||
| Allocations | Zero per update |
|
||||
| NaN handling | Last valid value substitution |
|
||||
| SIMD | Span-based `Batch()` with scalar fallback (recursive dependency prevents vectorization) |
|
||||
| FMA | Yes, in all three EMA stages |
|
||||
|
||||
| Quality Metric | Score (1-10) |
|
||||
|----------------|-------------|
|
||||
| Smoothness | 9 |
|
||||
| Lag | 6 (high smoothing = moderate lag) |
|
||||
| Noise rejection | 10 |
|
||||
| Whipsaw resistance | 9 |
|
||||
| Trend detection | 8 |
|
||||
|
||||
## Validation
|
||||
|
||||
Cross-validated against four independent implementations:
|
||||
|
||||
| Library | Mode | Tolerance | Status | Notes |
|
||||
|---------|------|-----------|--------|-------|
|
||||
| Skender | Batch | 1e-9 | Pass | Exact match after warmup |
|
||||
| Skender | Streaming | 1e-9 | Pass | Bar-by-bar verification |
|
||||
| Skender | Span | 1e-9 | Pass | Span API consistency |
|
||||
| TA-Lib | Span | 1e-9 | Pass | Lookback-aligned comparison |
|
||||
| TA-Lib | Streaming | 1e-9 | Pass | Sequential verification |
|
||||
| Tulip | Span | 5e-4 | Pass | Compensated vs uncompensated EMA divergence |
|
||||
| Tulip | Batch | 1e-3 | Pass | Compensation difference accumulates over warmup |
|
||||
| Tulip | Streaming | 1e-3 | Pass | Same compensation divergence pattern |
|
||||
|
||||
Tulip uses traditional uncompensated EMA. The compensation difference is structural, not a bug. Skender and TA-Lib use compatible warmup handling, producing tight matches.
|
||||
|
||||
Self-consistency validated across all four API modes (streaming, batch, span, eventing) with exact match verification.
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
1. **Ignoring warmup bias.** Uncompensated implementations produce startup transients for roughly $3 \times \text{period}$ bars. QuanTAlib's compensation eliminates this, but comparing against uncompensated libraries during warmup will show expected divergence.
|
||||
|
||||
2. **Confusing smoothness with accuracy.** TRIX's triple smoothing means it responds slowly to genuine reversals. A 14-period TRIX effectively has the lag characteristics of a 42-period single EMA applied to rate of change.
|
||||
|
||||
3. **Using TRIX as a standalone signal.** Zero-line crossovers are reliable but late. Pair with faster indicators (RSI, price action) for entry timing.
|
||||
|
||||
4. **Short periods amplify noise.** Below period 5, the triple-smoothing advantage degrades. The three cascaded EMAs need sufficient period to differentiate signal from noise.
|
||||
|
||||
5. **Division-by-zero edge case.** When EMA₃ equals zero (typically only with synthetic data), TRIX returns 0. Production price data never hits this case, but test harnesses should account for it.
|
||||
|
||||
6. **Misinterpreting Tulip validation gaps.** The 1e-3 tolerance against Tulip is not imprecision. It reflects the fundamental difference between compensated and uncompensated EMA warmup strategies.
|
||||
|
||||
## Usage
|
||||
|
||||
```csharp
|
||||
// Streaming
|
||||
var trix = new Trix(period: 14);
|
||||
TValue result = trix.Update(new TValue(time, price));
|
||||
|
||||
// Event-based chaining
|
||||
var source = new TSeries();
|
||||
var trix = new Trix(source, period: 14);
|
||||
|
||||
// Batch (TSeries)
|
||||
TSeries results = Trix.Batch(source, period: 14);
|
||||
|
||||
// Batch (Span)
|
||||
Trix.Batch(sourceSpan, outputSpan, period: 14);
|
||||
|
||||
// Calculate (returns indicator for state inspection)
|
||||
var (results, indicator) = Trix.Calculate(source, period: 14);
|
||||
```
|
||||
|
||||
## Interpretation
|
||||
|
||||
- **Zero Line Crossovers:**
|
||||
- TRIX crosses above zero: Triple-smoothed EMA is rising (bullish momentum)
|
||||
- TRIX crosses below zero: Triple-smoothed EMA is falling (bearish momentum)
|
||||
|
||||
- **Signal Line:**
|
||||
- A short-period EMA of TRIX can serve as a signal line (similar to MACD)
|
||||
- Crossovers of TRIX above/below its signal line generate trade signals
|
||||
|
||||
- **Divergence:**
|
||||
- Bullish: Price makes lower lows while TRIX makes higher lows
|
||||
- Bearish: Price makes higher highs while TRIX makes lower highs
|
||||
- Triple smoothing makes TRIX divergences more reliable than single-EMA divergences
|
||||
|
||||
- **Trend Strength:**
|
||||
- Rising TRIX above zero: Strengthening uptrend
|
||||
- Falling TRIX below zero: Strengthening downtrend
|
||||
- TRIX near zero with small oscillations: Sideways/consolidating market
|
||||
|
||||
## Parameters
|
||||
|
||||
| Parameter | Type | Default | Range | Description |
|
||||
|-----------|------|---------|-------|-------------|
|
||||
| `period` | int | 14 | > 0 | EMA period for each of the three smoothing stages |
|
||||
|
||||
## References
|
||||
|
||||
- Jack Hutson, "TRIX - Triple Exponential Smoothing Oscillator," *Technical Analysis of Stocks & Commodities*, 1983
|
||||
- Jack Hutson, *Charting the Stock Market: The Wyckoff Method*, 1986
|
||||
- Steven Achelis, *Technical Analysis from A to Z*, 2nd ed., McGraw-Hill, 2001
|
||||
- PineScript reference: `trix.pine`
|
||||
Reference in New Issue
Block a user