mirror of
https://github.com/mihakralj/QuanTAlib.git
synced 2026-08-24 21:48:03 +00:00
docs: remove C# Implementation Considerations sections, clean up temp scripts, reorganize test files
- Remove 'C# Implementation Considerations' sections from 34 indicator .md files - Delete 29 temp PowerShell scripts (_fix_mojibake.ps1, _hex_scan.ps1, etc.) - Move test files into tests/ subdirectories for consistent project structure - Add trader-focused bullet points to indicator documentation
This commit is contained in:
@@ -0,0 +1,111 @@
|
||||
using TradingPlatform.BusinessLayer;
|
||||
using QuanTAlib;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public sealed class FisherIndicatorTests
|
||||
{
|
||||
[Fact]
|
||||
public void FisherIndicator_Constructor_SetsDefaults()
|
||||
{
|
||||
var indicator = new FisherIndicator();
|
||||
|
||||
Assert.Equal(10, indicator.Period);
|
||||
Assert.Equal(SourceType.Close, indicator.Source);
|
||||
Assert.True(indicator.ShowColdValues);
|
||||
Assert.Equal("FISHER - Ehlers Fisher Transform", indicator.Name);
|
||||
Assert.True(indicator.SeparateWindow);
|
||||
Assert.True(indicator.OnBackGround);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FisherIndicator_MinHistoryDepths_EqualsZero()
|
||||
{
|
||||
var indicator = new FisherIndicator { Period = 10 };
|
||||
|
||||
Assert.Equal(0, FisherIndicator.MinHistoryDepths);
|
||||
IWatchlistIndicator watchlistIndicator = indicator;
|
||||
Assert.Equal(0, watchlistIndicator.MinHistoryDepths);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FisherIndicator_ShortName_IncludesParameters()
|
||||
{
|
||||
var indicator = new FisherIndicator { Period = 20 };
|
||||
indicator.Initialize();
|
||||
|
||||
Assert.Contains("Fisher", indicator.ShortName, StringComparison.Ordinal);
|
||||
Assert.Contains("20", indicator.ShortName, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FisherIndicator_SourceCodeLink_IsValid()
|
||||
{
|
||||
var indicator = new FisherIndicator();
|
||||
|
||||
Assert.Contains("github.com", indicator.SourceCodeLink, StringComparison.Ordinal);
|
||||
Assert.Contains("Fisher.Quantower.cs", indicator.SourceCodeLink, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FisherIndicator_Initialize_CreatesInternalFisher()
|
||||
{
|
||||
var indicator = new FisherIndicator { Period = 10 };
|
||||
|
||||
indicator.Initialize();
|
||||
|
||||
Assert.Equal(2, indicator.LinesSeries.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FisherIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
|
||||
{
|
||||
var indicator = new FisherIndicator { 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 FisherIndicator_ProcessUpdate_NewBar_ComputesValue()
|
||||
{
|
||||
var indicator = new FisherIndicator { 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 FisherIndicator_Parameters_CanBeChanged()
|
||||
{
|
||||
var indicator = new FisherIndicator { Period = 10 };
|
||||
|
||||
indicator.Period = 20;
|
||||
indicator.Source = SourceType.Open;
|
||||
|
||||
Assert.Equal(20, indicator.Period);
|
||||
Assert.Equal(SourceType.Open, indicator.Source);
|
||||
Assert.Equal(0, FisherIndicator.MinHistoryDepths);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,414 @@
|
||||
using Xunit;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public sealed class FisherTests
|
||||
{
|
||||
private const double Tolerance = 1e-9;
|
||||
|
||||
// ───── A) Constructor validation ─────
|
||||
|
||||
[Fact]
|
||||
public void Constructor_DefaultPeriod_IsValid()
|
||||
{
|
||||
var fisher = new Fisher();
|
||||
Assert.Equal(10, fisher.Period);
|
||||
Assert.Equal("Fisher(10)", fisher.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_InvalidPeriod_Throws()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Fisher(period: 0));
|
||||
Assert.Equal("period", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_NegativePeriod_Throws()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Fisher(period: -5));
|
||||
Assert.Equal("period", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_InvalidAlpha_Zero_Throws()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Fisher(period: 10, alpha: 0));
|
||||
Assert.Equal("alpha", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_InvalidAlpha_OverOne_Throws()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Fisher(period: 10, alpha: 1.5));
|
||||
Assert.Equal("alpha", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_CustomPeriod_SetsCorrectly()
|
||||
{
|
||||
var fisher = new Fisher(period: 20);
|
||||
Assert.Equal(20, fisher.Period);
|
||||
Assert.Equal("Fisher(20)", fisher.Name);
|
||||
}
|
||||
|
||||
// ───── B) Basic calculation ─────
|
||||
|
||||
[Fact]
|
||||
public void Update_ReturnsTValue()
|
||||
{
|
||||
var fisher = new Fisher(period: 5);
|
||||
var result = fisher.Update(new TValue(DateTime.UtcNow, 100.0));
|
||||
Assert.IsType<TValue>(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Update_Last_IsAccessible()
|
||||
{
|
||||
var fisher = new Fisher(period: 5);
|
||||
fisher.Update(new TValue(DateTime.UtcNow, 100.0));
|
||||
Assert.True(double.IsFinite(fisher.Last.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Update_FisherAndSignal_Accessible()
|
||||
{
|
||||
var fisher = new Fisher(period: 5);
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
fisher.Update(new TValue(DateTime.UtcNow, 100.0 + i));
|
||||
}
|
||||
Assert.True(double.IsFinite(fisher.FisherValue));
|
||||
Assert.True(double.IsFinite(fisher.Signal));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Update_RisingPrices_PositiveFisher()
|
||||
{
|
||||
var fisher = new Fisher(period: 5);
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
fisher.Update(new TValue(DateTime.UtcNow, 100.0 + i * 2));
|
||||
}
|
||||
Assert.True(fisher.FisherValue > 0, "Rising prices should produce positive Fisher");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Update_FallingPrices_NegativeFisher()
|
||||
{
|
||||
var fisher = new Fisher(period: 5);
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
fisher.Update(new TValue(DateTime.UtcNow, 200.0 - i * 2));
|
||||
}
|
||||
Assert.True(fisher.FisherValue < 0, "Falling prices should produce negative Fisher");
|
||||
}
|
||||
|
||||
// ───── C) State + bar correction ─────
|
||||
|
||||
[Fact]
|
||||
public void Update_IsNew_False_RollsBack()
|
||||
{
|
||||
var fisher = new Fisher(period: 5);
|
||||
for (int i = 0; i < 12; i++)
|
||||
{
|
||||
fisher.Update(new TValue(DateTime.UtcNow, 100.0 + i), isNew: true);
|
||||
}
|
||||
|
||||
fisher.Update(new TValue(DateTime.UtcNow, 105.0), isNew: false);
|
||||
var corrected = fisher.Last;
|
||||
|
||||
fisher.Update(new TValue(DateTime.UtcNow, 105.0), isNew: false);
|
||||
var corrected2 = fisher.Last;
|
||||
|
||||
Assert.Equal(corrected.Value, corrected2.Value, Tolerance);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Update_IterativeCorrections_Restore()
|
||||
{
|
||||
var fisher = new Fisher(period: 5);
|
||||
double[] data = new double[15];
|
||||
for (int i = 0; i < data.Length; i++)
|
||||
{
|
||||
data[i] = 100 + i * 2;
|
||||
}
|
||||
|
||||
for (int i = 0; i < data.Length; i++)
|
||||
{
|
||||
fisher.Update(new TValue(DateTime.UtcNow, data[i]), isNew: true);
|
||||
}
|
||||
|
||||
var baseline = fisher.Last.Value;
|
||||
|
||||
fisher.Update(new TValue(DateTime.UtcNow, 999.0), isNew: false);
|
||||
fisher.Update(new TValue(DateTime.UtcNow, 888.0), isNew: false);
|
||||
fisher.Update(new TValue(DateTime.UtcNow, data[^1]), isNew: false);
|
||||
|
||||
Assert.Equal(baseline, fisher.Last.Value, Tolerance);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reset_ClearsState()
|
||||
{
|
||||
var fisher = new Fisher(period: 5);
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
fisher.Update(new TValue(DateTime.UtcNow, 100.0 + i));
|
||||
}
|
||||
|
||||
fisher.Reset();
|
||||
|
||||
Assert.False(fisher.IsHot);
|
||||
Assert.Equal(0.0, fisher.Last.Value);
|
||||
}
|
||||
|
||||
// ───── D) Warmup/convergence ─────
|
||||
|
||||
[Fact]
|
||||
public void IsHot_FlipsAfterPeriod()
|
||||
{
|
||||
int period = 10;
|
||||
var fisher = new Fisher(period);
|
||||
|
||||
for (int i = 0; i < period - 1; i++)
|
||||
{
|
||||
fisher.Update(new TValue(DateTime.UtcNow, 100.0 + i));
|
||||
Assert.False(fisher.IsHot);
|
||||
}
|
||||
|
||||
fisher.Update(new TValue(DateTime.UtcNow, 110.0));
|
||||
Assert.True(fisher.IsHot);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WarmupPeriod_MatchesPeriod()
|
||||
{
|
||||
var fisher = new Fisher(period: 14);
|
||||
Assert.Equal(14, fisher.WarmupPeriod);
|
||||
}
|
||||
|
||||
// ───── E) Robustness ─────
|
||||
|
||||
[Fact]
|
||||
public void Update_NaN_UsesLastValid()
|
||||
{
|
||||
var fisher = new Fisher(period: 5);
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
fisher.Update(new TValue(DateTime.UtcNow, 100.0 + i));
|
||||
}
|
||||
|
||||
_ = fisher.Last.Value;
|
||||
fisher.Update(new TValue(DateTime.UtcNow, double.NaN));
|
||||
Assert.True(double.IsFinite(fisher.Last.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Update_Infinity_UsesLastValid()
|
||||
{
|
||||
var fisher = new Fisher(period: 5);
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
fisher.Update(new TValue(DateTime.UtcNow, 100.0 + i));
|
||||
}
|
||||
|
||||
fisher.Update(new TValue(DateTime.UtcNow, double.PositiveInfinity));
|
||||
Assert.True(double.IsFinite(fisher.Last.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Update_BatchNaN_RemainsFinite()
|
||||
{
|
||||
var fisher = new Fisher(period: 5);
|
||||
for (int i = 0; i < 3; i++)
|
||||
{
|
||||
fisher.Update(new TValue(DateTime.UtcNow, double.NaN));
|
||||
}
|
||||
Assert.True(double.IsFinite(fisher.Last.Value));
|
||||
}
|
||||
|
||||
// ───── F) Consistency (4 modes match) ─────
|
||||
|
||||
[Fact]
|
||||
public void AllModes_ProduceSameResults()
|
||||
{
|
||||
int period = 10;
|
||||
var gbm = new GBM(startPrice: 100.0, mu: 0.02, sigma: 0.1, seed: 42);
|
||||
var bars = gbm.Fetch(500, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
TSeries source = bars.Close;
|
||||
|
||||
// 1. Streaming
|
||||
var streaming = new Fisher(period);
|
||||
var streamResults = new double[source.Count];
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
streamResults[i] = streaming.Update(source[i]).Value;
|
||||
}
|
||||
|
||||
// 2. Batch TSeries
|
||||
TSeries batchSeries = Fisher.Batch(source, period);
|
||||
|
||||
// 3. Batch Span
|
||||
var spanOutput = new double[source.Count];
|
||||
Fisher.Batch(source.Values, spanOutput, period);
|
||||
|
||||
// 4. Event-based
|
||||
var eventSource = new TSeries();
|
||||
var eventIndicator = new Fisher(eventSource, period);
|
||||
var eventResults = new double[source.Count];
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
eventSource.Add(source[i]);
|
||||
eventResults[i] = eventIndicator.Last.Value;
|
||||
}
|
||||
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
Assert.Equal(streamResults[i], batchSeries.Values[i], Tolerance);
|
||||
Assert.Equal(streamResults[i], spanOutput[i], Tolerance);
|
||||
Assert.Equal(streamResults[i], eventResults[i], Tolerance);
|
||||
}
|
||||
}
|
||||
|
||||
// ───── G) Span API tests ─────
|
||||
|
||||
[Fact]
|
||||
public void Batch_Span_MismatchedLengths_Throws()
|
||||
{
|
||||
var src = new double[10];
|
||||
var output = new double[5];
|
||||
var ex = Assert.Throws<ArgumentException>(() => Fisher.Batch(src, output, 5));
|
||||
Assert.Equal("output", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Batch_Span_InvalidPeriod_Throws()
|
||||
{
|
||||
var src = new double[10];
|
||||
var output = new double[10];
|
||||
var ex = Assert.Throws<ArgumentException>(() => Fisher.Batch(src, output, 0));
|
||||
Assert.Equal("period", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Batch_Span_Empty_NoException()
|
||||
{
|
||||
var src = ReadOnlySpan<double>.Empty;
|
||||
var output = Span<double>.Empty;
|
||||
Fisher.Batch(src, output, 5);
|
||||
Assert.True(true);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Batch_Span_MatchesTSeries()
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100.0, mu: 0.02, sigma: 0.1, seed: 42);
|
||||
var bars = gbm.Fetch(200, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
TSeries source = bars.Close;
|
||||
|
||||
TSeries batchSeries = Fisher.Batch(source, 10);
|
||||
|
||||
var spanOutput = new double[source.Count];
|
||||
Fisher.Batch(source.Values, spanOutput, 10);
|
||||
|
||||
for (int i = 0; i < source.Count; i++)
|
||||
{
|
||||
Assert.Equal(batchSeries.Values[i], spanOutput[i], 12);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Batch_Span_NaN_Handled()
|
||||
{
|
||||
double[] src = [100, 101, double.NaN, 103, 104, 105, 106, 107, 108, 109];
|
||||
var output = new double[src.Length];
|
||||
Fisher.Batch(src, output, 5);
|
||||
|
||||
for (int i = 0; i < output.Length; i++)
|
||||
{
|
||||
Assert.True(double.IsFinite(output[i]));
|
||||
}
|
||||
}
|
||||
|
||||
// ───── H) Chainability ─────
|
||||
|
||||
[Fact]
|
||||
public void Event_PubFires()
|
||||
{
|
||||
var source = new TSeries();
|
||||
var fisher = new Fisher(source, period: 5);
|
||||
int count = 0;
|
||||
fisher.Pub += (object? _, in TValueEventArgs _) => count++;
|
||||
|
||||
source.Add(new TValue(DateTime.UtcNow, 100.0));
|
||||
Assert.Equal(1, count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Event_ChainingWorks()
|
||||
{
|
||||
var source = new TSeries();
|
||||
var fisher = new Fisher(source, period: 5);
|
||||
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
source.Add(new TValue(DateTime.UtcNow, 100.0 + i));
|
||||
}
|
||||
|
||||
Assert.True(fisher.IsHot);
|
||||
Assert.True(double.IsFinite(fisher.Last.Value));
|
||||
}
|
||||
|
||||
// ───── Domain-specific tests ─────
|
||||
|
||||
[Fact]
|
||||
public void FisherTransform_MathematicalProperties()
|
||||
{
|
||||
// Fisher Transform is arctanh: should be odd function
|
||||
// For normalized input 0, Fisher should be 0
|
||||
var fisher = new Fisher(period: 5);
|
||||
|
||||
// Feed constant price → normalized = 0 → Fisher ≈ 0
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
fisher.Update(new TValue(DateTime.UtcNow, 100.0));
|
||||
}
|
||||
|
||||
Assert.True(Math.Abs(fisher.FisherValue) < 0.1,
|
||||
$"Constant price should produce Fisher near 0, got {fisher.FisherValue}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FisherTransform_OutputIsUnbounded()
|
||||
{
|
||||
// Fisher can exceed ±2 with strong trends
|
||||
var fisher = new Fisher(period: 5);
|
||||
|
||||
// Create a very strong uptrend
|
||||
for (int i = 0; i < 30; i++)
|
||||
{
|
||||
fisher.Update(new TValue(DateTime.UtcNow, 100.0 + i * 10));
|
||||
}
|
||||
|
||||
// Fisher should be significantly positive
|
||||
Assert.True(fisher.FisherValue > 1.0,
|
||||
$"Strong uptrend should produce Fisher > 1, got {fisher.FisherValue}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Signal_LagseFisher()
|
||||
{
|
||||
// Signal is EMA of Fisher, so under strong trend it should lag
|
||||
var fisher = new Fisher(period: 5);
|
||||
|
||||
for (int i = 0; i < 30; i++)
|
||||
{
|
||||
fisher.Update(new TValue(DateTime.UtcNow, 100.0 + i * 5));
|
||||
}
|
||||
|
||||
// Both should be positive in uptrend
|
||||
Assert.True(fisher.FisherValue > 0);
|
||||
Assert.True(fisher.Signal > 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,436 @@
|
||||
using OoplesFinance.StockIndicators;
|
||||
using OoplesFinance.StockIndicators.Models;
|
||||
using Skender.Stock.Indicators;
|
||||
using System.Runtime.CompilerServices;
|
||||
using Tulip;
|
||||
using Xunit;
|
||||
using Xunit.Abstractions;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Validates Fisher Transform against Skender, Tulip, Ooples, and manual computation.
|
||||
/// Primary reference: Skender (Ehlers 2002 IIR algorithm with HL2 input).
|
||||
/// </summary>
|
||||
public sealed class FisherValidationTests(ITestOutputHelper output) : IDisposable
|
||||
{
|
||||
private readonly ValidationTestData _testData = new();
|
||||
private readonly ITestOutputHelper _output = output;
|
||||
private bool _disposed;
|
||||
|
||||
private const int TestPeriod = 10;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(disposing: true);
|
||||
}
|
||||
|
||||
private void Dispose(bool disposing)
|
||||
{
|
||||
if (_disposed) { return; }
|
||||
_disposed = true;
|
||||
if (disposing) { _testData?.Dispose(); }
|
||||
}
|
||||
|
||||
#region Manual arctanh Cross-Validation
|
||||
|
||||
[Fact]
|
||||
[SkipLocalsInit]
|
||||
public void Validate_Against_Manual_Arctanh()
|
||||
{
|
||||
// Validate that our Fisher Transform correctly computes arctanh
|
||||
// by testing with known normalized inputs
|
||||
double[] testValues = [-0.9, -0.5, 0.0, 0.5, 0.9];
|
||||
|
||||
foreach (double v in testValues)
|
||||
{
|
||||
double expected = 0.5 * Math.Log((1.0 + v) / (1.0 - v));
|
||||
double actual = Math.Atanh(v);
|
||||
|
||||
Assert.True(Math.Abs(expected - actual) < 1e-12,
|
||||
$"arctanh({v}): expected={expected}, actual={actual}");
|
||||
}
|
||||
|
||||
_output.WriteLine("arctanh mathematical identity verified.");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
[SkipLocalsInit]
|
||||
public void Validate_Against_Manual_Computation()
|
||||
{
|
||||
double[] values = _testData.RawData.ToArray();
|
||||
int[] periods = [5, 10, 20];
|
||||
|
||||
foreach (int period in periods)
|
||||
{
|
||||
double[] batchOutput = new double[values.Length];
|
||||
Fisher.Batch(values.AsSpan(), batchOutput.AsSpan(), period);
|
||||
|
||||
// Manual computation — Ehlers 2002 TASC algorithm
|
||||
double[] manualOutput = new double[values.Length];
|
||||
double emaValue = 0.0;
|
||||
double fisherValue = 0.0;
|
||||
var buffer = new double[period];
|
||||
int bufCount = 0;
|
||||
int bufIdx = 0;
|
||||
|
||||
for (int i = 0; i < values.Length; i++)
|
||||
{
|
||||
double val = values[i];
|
||||
|
||||
// Add to circular buffer
|
||||
if (bufCount < period)
|
||||
{
|
||||
buffer[bufCount] = val;
|
||||
bufCount++;
|
||||
}
|
||||
else
|
||||
{
|
||||
buffer[bufIdx] = val;
|
||||
bufIdx = (bufIdx + 1) % period;
|
||||
}
|
||||
|
||||
// Find min/max
|
||||
double highest = double.MinValue;
|
||||
double lowest = double.MaxValue;
|
||||
for (int j = 0; j < bufCount; j++)
|
||||
{
|
||||
if (buffer[j] > highest)
|
||||
{
|
||||
highest = buffer[j];
|
||||
}
|
||||
if (buffer[j] < lowest)
|
||||
{
|
||||
lowest = buffer[j];
|
||||
}
|
||||
}
|
||||
|
||||
double range = highest - lowest;
|
||||
if (range != 0.0)
|
||||
{
|
||||
emaValue = (0.66 * (((val - lowest) / range) - 0.5))
|
||||
+ (0.67 * emaValue);
|
||||
}
|
||||
else
|
||||
{
|
||||
emaValue = 0.0; // Skender: xv[i] = 0 when range=0
|
||||
}
|
||||
|
||||
// Ehlers/Skender: snap to ±0.999 when |Value1| > 0.99
|
||||
// Clamped value stored back — Skender stores array2[i] clamped
|
||||
if (emaValue > 0.99)
|
||||
{
|
||||
emaValue = 0.999;
|
||||
}
|
||||
else if (emaValue < -0.99)
|
||||
{
|
||||
emaValue = -0.999;
|
||||
}
|
||||
|
||||
// Ehlers 2002: Fish = arctanh(Value1) + 0.5 * Fish[1] (IIR feedback)
|
||||
fisherValue = 0.5 * Math.Log((1.0 + emaValue) / (1.0 - emaValue)) + 0.5 * fisherValue;
|
||||
manualOutput[i] = fisherValue;
|
||||
}
|
||||
|
||||
int validCount = 0;
|
||||
for (int i = period; i < values.Length; i++)
|
||||
{
|
||||
Assert.True(Math.Abs(manualOutput[i] - batchOutput[i]) < 1e-9,
|
||||
$"Fisher mismatch at i={i}, period={period}: manual={manualOutput[i]}, batch={batchOutput[i]}");
|
||||
validCount++;
|
||||
}
|
||||
|
||||
Assert.True(validCount > 0, $"No valid comparison points for period {period}");
|
||||
_output.WriteLine($"Fisher period={period}: validated {validCount} points against manual computation.");
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(5)]
|
||||
[InlineData(10)]
|
||||
[InlineData(20)]
|
||||
[InlineData(50)]
|
||||
public void Validate_Manual_DifferentPeriods(int period)
|
||||
{
|
||||
double[] values = _testData.RawData.ToArray();
|
||||
|
||||
double[] batchOutput = new double[values.Length];
|
||||
Fisher.Batch(values.AsSpan(), batchOutput.AsSpan(), period);
|
||||
|
||||
// Verify all outputs are finite
|
||||
for (int i = 0; i < values.Length; i++)
|
||||
{
|
||||
Assert.True(double.IsFinite(batchOutput[i]),
|
||||
$"Fisher output not finite at i={i}, period={period}: {batchOutput[i]}");
|
||||
}
|
||||
|
||||
_output.WriteLine($"Fisher period={period}: all {values.Length} outputs finite.");
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Consistency Validation
|
||||
|
||||
[Fact]
|
||||
[SkipLocalsInit]
|
||||
public void Validate_Streaming_Batch_Span_Agree()
|
||||
{
|
||||
double[] tData = _testData.RawData.ToArray();
|
||||
|
||||
// Batch TSeries
|
||||
TSeries batchSeries = Fisher.Batch(_testData.Data, TestPeriod);
|
||||
|
||||
// Batch Span
|
||||
var spanOutput = new double[tData.Length];
|
||||
Fisher.Batch(tData.AsSpan(), spanOutput.AsSpan(), TestPeriod);
|
||||
|
||||
// Batch and Span should be identical (same code path)
|
||||
for (int i = 0; i < tData.Length; i++)
|
||||
{
|
||||
Assert.Equal(batchSeries.Values[i], spanOutput[i], 12);
|
||||
}
|
||||
|
||||
// Streaming
|
||||
var fisher = new Fisher(TestPeriod);
|
||||
var streamResults = new double[tData.Length];
|
||||
for (int i = 0; i < tData.Length; i++)
|
||||
{
|
||||
streamResults[i] = fisher.Update(_testData.Data[i]).Value;
|
||||
}
|
||||
|
||||
// Streaming vs Batch should match exactly (same algorithm, same state)
|
||||
for (int i = 0; i < tData.Length; i++)
|
||||
{
|
||||
Assert.Equal(streamResults[i], batchSeries.Values[i], 9);
|
||||
}
|
||||
|
||||
_output.WriteLine("Fisher streaming/batch/span agreement verified.");
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Tulip Cross-Validation
|
||||
|
||||
/// <summary>
|
||||
/// Structural validation against Tulip <c>fisher</c> indicator.
|
||||
/// Algorithm variant: Tulip fisher uses two inputs (high[], low[]) and computes the
|
||||
/// Fisher Transform from the high-low price range midpoint normalized over a rolling window.
|
||||
/// QuanTAlib Fisher uses a single price series with EMA-based normalization via alpha parameter.
|
||||
/// Direct numeric equality is not asserted; both must produce finite output on the same data.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Fisher_Tulip_StructuralVariant_BothFinite()
|
||||
{
|
||||
const int period = 10;
|
||||
double[] highData = _testData.HighPrices.ToArray();
|
||||
double[] lowData = _testData.LowPrices.ToArray();
|
||||
|
||||
// Tulip fisher — uses high/low range normalization
|
||||
var tulipIndicator = Tulip.Indicators.fisher;
|
||||
double[][] inputs = { highData, lowData };
|
||||
double[] options = { period };
|
||||
int lookback = tulipIndicator.Start(options);
|
||||
double[][] outputs = { new double[highData.Length - lookback], new double[highData.Length - lookback] };
|
||||
tulipIndicator.Run(inputs, options, outputs);
|
||||
double[] tResult = outputs[0];
|
||||
|
||||
// QuanTAlib Fisher — single price series (close)
|
||||
var fisher = new Fisher(TestPeriod);
|
||||
foreach (var item in _testData.Data) { fisher.Update(item); }
|
||||
|
||||
// Structural: Tulip must produce finite output
|
||||
Assert.True(tResult.Length > 0, "Tulip fisher must produce output");
|
||||
foreach (double v in tResult)
|
||||
{
|
||||
Assert.True(double.IsFinite(v), $"Tulip fisher produced non-finite value: {v}");
|
||||
}
|
||||
|
||||
// QuanTAlib must also be hot and finite
|
||||
Assert.True(fisher.IsHot, "QuanTAlib Fisher must be hot after sufficient bars");
|
||||
Assert.True(double.IsFinite(fisher.Last.Value), "QuanTAlib Fisher last value must be finite");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
[SkipLocalsInit]
|
||||
public void Validate_Event_Matches_Streaming()
|
||||
{
|
||||
// Streaming
|
||||
var streamFisher = new Fisher(TestPeriod);
|
||||
var streamResults = new double[_testData.Data.Count];
|
||||
for (int i = 0; i < _testData.Data.Count; i++)
|
||||
{
|
||||
streamResults[i] = streamFisher.Update(_testData.Data[i]).Value;
|
||||
}
|
||||
|
||||
// Event-based
|
||||
var eventSource = new TSeries();
|
||||
var eventFisher = new Fisher(eventSource, TestPeriod);
|
||||
var eventResults = new double[_testData.Data.Count];
|
||||
for (int i = 0; i < _testData.Data.Count; i++)
|
||||
{
|
||||
eventSource.Add(_testData.Data[i]);
|
||||
eventResults[i] = eventFisher.Last.Value;
|
||||
}
|
||||
|
||||
for (int i = 0; i < _testData.Data.Count; i++)
|
||||
{
|
||||
Assert.Equal(streamResults[i], eventResults[i], 12);
|
||||
}
|
||||
|
||||
_output.WriteLine("Fisher event-based matches streaming.");
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Ooples Validation
|
||||
|
||||
/// <summary>
|
||||
/// Structural validation against Ooples <c>CalculateEhlersFisherTransform</c>.
|
||||
/// Ooples uses the Ehlers variant: HL2 (high-low midpoint) normalized over rolling period,
|
||||
/// then arctanh transformed. QuanTAlib Fisher uses a single price series with EMA-based
|
||||
/// normalization via alpha parameter. Input types differ (OHLCV vs close-only); numeric
|
||||
/// equality not asserted. Both must produce finite output on the same underlying data.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Fisher_Ooples_StructuralVariant_BothFinite()
|
||||
{
|
||||
var ooplesData = _testData.SkenderQuotes.Select(q => new TickerData
|
||||
{
|
||||
Date = q.Date,
|
||||
Open = (double)q.Open,
|
||||
High = (double)q.High,
|
||||
Low = (double)q.Low,
|
||||
Close = (double)q.Close,
|
||||
Volume = (double)q.Volume
|
||||
}).ToList();
|
||||
|
||||
var stockData = new StockData(ooplesData);
|
||||
var oResult = stockData.CalculateEhlersFisherTransform(length: TestPeriod);
|
||||
var oValues = oResult.OutputValues.Values.First();
|
||||
|
||||
// QuanTAlib Fisher — single price series (close)
|
||||
var fisher = new Fisher(TestPeriod);
|
||||
foreach (var item in _testData.Data) { fisher.Update(item); }
|
||||
|
||||
// Structural: Ooples must produce finite output
|
||||
Assert.True(oValues.Count > 0, "Ooples Fisher must produce output");
|
||||
int finiteCount = 0;
|
||||
for (int i = TestPeriod; i < oValues.Count; i++)
|
||||
{
|
||||
if (double.IsFinite(oValues[i])) { finiteCount++; }
|
||||
}
|
||||
|
||||
Assert.True(finiteCount > 100, $"Expected >100 finite Ooples values, got {finiteCount}");
|
||||
Assert.True(fisher.IsHot, "QuanTAlib Fisher must be hot after sufficient bars");
|
||||
Assert.True(double.IsFinite(fisher.Last.Value), "QuanTAlib Fisher last value must be finite");
|
||||
|
||||
_output.WriteLine($"Fisher Ooples structural: {finiteCount} finite Ooples values, QuanTAlib last={fisher.Last.Value:F6}");
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Skender Cross-Validation
|
||||
|
||||
/// <summary>
|
||||
/// Numeric validation against Skender <c>GetFisherTransform</c>.
|
||||
/// Both use Ehlers 2002 IIR algorithm: <c>Fish = arctanh(Value1) + 0.5 * Fish[1]</c>.
|
||||
/// Skender uses HL2 input with expanding window during warmup.
|
||||
/// QuanTAlib uses same HL2 input via RingBuffer (expanding window when not full).
|
||||
/// Both should converge; tolerance allows warmup-phase divergence.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Validate_Skender_FisherTransform_Numeric()
|
||||
{
|
||||
const int period = 10;
|
||||
var sResult = _testData.SkenderQuotes.GetFisherTransform(period).ToList();
|
||||
|
||||
// Feed HL2 to QuanTAlib (same input as Skender)
|
||||
var quotes = _testData.SkenderQuotes.ToList();
|
||||
var fisher = new Fisher(period);
|
||||
var qtFisher = new double[quotes.Count];
|
||||
var qtSignal = new double[quotes.Count];
|
||||
for (int i = 0; i < quotes.Count; i++)
|
||||
{
|
||||
// Match Skender's HL2 computation: decimal arithmetic then convert
|
||||
double hl2 = (double)((quotes[i].High + quotes[i].Low) / 2m);
|
||||
fisher.Update(new TValue(quotes[i].Date, hl2));
|
||||
qtFisher[i] = fisher.FisherValue;
|
||||
qtSignal[i] = fisher.Signal;
|
||||
}
|
||||
|
||||
// Numeric comparison — skip warmup (first 2*period bars)
|
||||
int startIdx = period * 2;
|
||||
int validCount = 0;
|
||||
for (int i = startIdx; i < sResult.Count; i++)
|
||||
{
|
||||
if (sResult[i].Fisher is null) { continue; }
|
||||
double sFisher = sResult[i].Fisher!.Value;
|
||||
|
||||
Assert.True(Math.Abs(sFisher - qtFisher[i]) < 1e-9,
|
||||
$"Fisher mismatch at i={i}: Skender={sFisher:F9}, QuanTAlib={qtFisher[i]:F9}");
|
||||
validCount++;
|
||||
}
|
||||
|
||||
Assert.True(validCount > 100, $"Expected >100 valid comparisons, got {validCount}");
|
||||
_output.WriteLine($"Fisher Skender numeric: validated {validCount} points at 1e-9 tolerance.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates signal line (Trigger = Fish[1]) matches Skender's Trigger output.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Validate_Skender_Signal_Numeric()
|
||||
{
|
||||
const int period = 10;
|
||||
var sResult = _testData.SkenderQuotes.GetFisherTransform(period).ToList();
|
||||
|
||||
// Feed HL2 to QuanTAlib
|
||||
var quotes = _testData.SkenderQuotes.ToList();
|
||||
var fisher = new Fisher(period);
|
||||
var qtSignal = new double[quotes.Count];
|
||||
for (int i = 0; i < quotes.Count; i++)
|
||||
{
|
||||
double hl2 = (double)((quotes[i].High + quotes[i].Low) / 2m);
|
||||
fisher.Update(new TValue(quotes[i].Date, hl2));
|
||||
qtSignal[i] = fisher.Signal;
|
||||
}
|
||||
|
||||
// Signal comparison — skip warmup
|
||||
int startIdx = period * 2;
|
||||
int validCount = 0;
|
||||
for (int i = startIdx; i < sResult.Count; i++)
|
||||
{
|
||||
if (sResult[i].Trigger is null) { continue; }
|
||||
double sTrigger = sResult[i].Trigger!.Value;
|
||||
|
||||
Assert.True(Math.Abs(sTrigger - qtSignal[i]) < 1e-9,
|
||||
$"Signal mismatch at i={i}: Skender={sTrigger:F9}, QuanTAlib={qtSignal[i]:F9}");
|
||||
validCount++;
|
||||
}
|
||||
|
||||
Assert.True(validCount > 100, $"Expected >100 valid signal comparisons, got {validCount}");
|
||||
_output.WriteLine($"Fisher Signal Skender numeric: validated {validCount} points at 1e-9 tolerance.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Structural validation: both Skender and QuanTAlib produce finite output.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Validate_Skender_FisherTransform_Structural()
|
||||
{
|
||||
var sResult = _testData.SkenderQuotes.GetFisherTransform(TestPeriod).ToList();
|
||||
|
||||
var fisher = new Fisher(TestPeriod);
|
||||
foreach (var item in _testData.Data) { fisher.Update(item); }
|
||||
|
||||
int finiteCount = sResult.Count(r => r.Fisher is not null && double.IsFinite(r.Fisher.Value));
|
||||
Assert.True(finiteCount > 100, $"Skender should produce >100 finite Fisher values, got {finiteCount}");
|
||||
Assert.True(fisher.IsHot, "QuanTAlib Fisher must be hot");
|
||||
Assert.True(double.IsFinite(fisher.Last.Value), "QuanTAlib Fisher last must be finite");
|
||||
|
||||
_output.WriteLine($"Fisher Skender structural: {finiteCount} finite Skender values, " +
|
||||
$"QuanTAlib last={fisher.Last.Value:F6}, Skender last={sResult[^1].Fisher:F6}");
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
Reference in New Issue
Block a user