mirror of
https://github.com/mihakralj/QuanTAlib.git
synced 2026-08-19 19:18:05 +00:00
feat(oscillators): add DSO - Ehlers Deviation-Scaled Oscillator
Implement DSO (TASC Oct 2018) with SSF 2-pole filter, RMS normalization, and Fisher Transform (±0.99 clamp). Sealed class, O(1) streaming RMS via RingBuffer, precomputed SSF coefficients. New files: Dso.cs, Dso.Quantower.cs, Dso.md, dso.pine, Dso.Tests.cs (27), Dso.Validation.Tests.cs (7), Dso.Quantower.Tests.cs (11) Updated: Exports.cs, _bridge.py, oscillators.py, SPEC.md, _sidebar.md, lib/_index.md, oscillators/_index.md, docs/indicators.md, docs/pinescript.md All 19,565 tests pass, 0 warnings.
This commit is contained in:
@@ -95,6 +95,7 @@
|
||||
| [DEMA](trends_IIR/dema/Dema.md) | Double Exponential MA | Trends (IIR) |
|
||||
| [DMX](dynamics/dmx/Dmx.md) | Jurik Directional Movement Index | Dynamics |
|
||||
| [DOSC](oscillators/dosc/Dosc.md) | Derivative Oscillator | Oscillators |
|
||||
| [DSO](oscillators/dso/Dso.md) | Ehlers Deviation-Scaled Oscillator | Oscillators |
|
||||
| [DPO](oscillators/dpo/Dpo.md) | Detrended Price Oscillator | Oscillators |
|
||||
| [DSTOCH](oscillators/dstoch/Dstoch.md) | Double Stochastic (Bressert) | Oscillators |
|
||||
| [DSMA](trends_IIR/dsma/Dsma.md) | Deviation-Scaled MA | Trends (IIR) |
|
||||
|
||||
@@ -19,6 +19,7 @@ Oscillators fluctuate above and below a centerline or within bounded ranges. Use
|
||||
| [DECO](deco/Deco.md) | Ehlers Decycler Oscillator | Dual HP bandpass isolating intermediate-frequency market cycles. |
|
||||
| [DEM](dem/Dem.md) | DeMarker Oscillator | Bounded 0-1 oscillator comparing sequential highs and lows. |
|
||||
| [DOSC](dosc/Dosc.md) | Derivative Oscillator | Double-smoothed RSI minus signal line. Momentum acceleration. |
|
||||
| [DSO](dso/Dso.md) | Ehlers Deviation-Scaled Oscillator | SSF-filtered zeros with RMS normalization and Fisher Transform. TASC Oct 2018. |
|
||||
| [DPO](dpo/Dpo.md) | Detrended Price Oscillator | Removes trend via displaced SMA. Reveals cycles. |
|
||||
| [DSTOCH](dstoch/Dstoch.md) | Double Stochastic (Bressert) | Stochastic applied to Stochastic with EMA smoothing. Bounded 0-100. |
|
||||
| [DYMI](dymi/Dymi.md) | Dynamic Momentum Index | RSI with volatility-adaptive period. Shorter in volatile markets. |
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
using System.Drawing;
|
||||
using System.Runtime.CompilerServices;
|
||||
using TradingPlatform.BusinessLayer;
|
||||
|
||||
namespace QuanTAlib;
|
||||
|
||||
[SkipLocalsInit]
|
||||
public sealed class DsoIndicator : Indicator, IWatchlistIndicator
|
||||
{
|
||||
[InputParameter("Period", sortIndex: 1, 2, 1000, 1, 0)]
|
||||
public int Period { get; set; } = 40;
|
||||
|
||||
[IndicatorExtensions.DataSourceInput]
|
||||
public SourceType Source { get; set; } = SourceType.Close;
|
||||
|
||||
[InputParameter("Show cold values", sortIndex: 21)]
|
||||
public bool ShowColdValues { get; set; } = true;
|
||||
|
||||
private Dso _ma = null!;
|
||||
private readonly LineSeries _series;
|
||||
private string _sourceName = null!;
|
||||
private Func<IHistoryItem, double> _priceSelector = null!;
|
||||
|
||||
public static int MinHistoryDepths => 0;
|
||||
int IWatchlistIndicator.MinHistoryDepths => MinHistoryDepths;
|
||||
|
||||
public override string ShortName => $"DSO {Period}:{_sourceName}";
|
||||
public override string SourceCodeLink => "https://github.com/mihakralj/QuanTAlib/blob/main/lib/oscillators/dso/Dso.Quantower.cs";
|
||||
|
||||
public DsoIndicator()
|
||||
{
|
||||
OnBackGround = true;
|
||||
SeparateWindow = true;
|
||||
_sourceName = Source.ToString();
|
||||
Name = "DSO - Ehlers Deviation-Scaled Oscillator";
|
||||
Description = "Fisher-transformed, RMS-normalized Super Smoother oscillator with input whitening";
|
||||
_series = new LineSeries(name: $"DSO {Period}", color: Color.Yellow, width: 2, style: LineStyle.Solid);
|
||||
AddLineSeries(_series);
|
||||
}
|
||||
|
||||
protected override void OnInit()
|
||||
{
|
||||
_ma = new Dso(Period);
|
||||
_sourceName = Source.ToString();
|
||||
_priceSelector = Source.GetPriceSelector();
|
||||
base.OnInit();
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
protected override void OnUpdate(UpdateArgs args)
|
||||
{
|
||||
var item = HistoricalData[Count - 1, SeekOriginHistory.Begin];
|
||||
TValue result = _ma.Update(new TValue(item.TimeLeft.Ticks, _priceSelector(item)), isNew: args.IsNewBar());
|
||||
_series.SetValue(result.Value, _ma.IsHot, ShowColdValues);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace QuanTAlib;
|
||||
|
||||
/// <summary>
|
||||
/// DSO: Ehlers Deviation-Scaled Oscillator
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A Fisher-transformed, RMS-normalized Super Smoother oscillator.
|
||||
/// Applies input whitening (Close - Close[2]), a 2-pole Super Smoother filter,
|
||||
/// rolling RMS normalization, and Fisher Transform with ±0.99 clamping.
|
||||
///
|
||||
/// Calculation:
|
||||
/// <c>Zeros = Close - Close[2]</c>
|
||||
/// <c>Filt = c1/2 * (Zeros + Zeros[1]) + c2*Filt[1] + c3*Filt[2]</c>
|
||||
/// <c>RMS = √(Σ(Filt²) / period)</c>
|
||||
/// <c>ScaledFilt = Filt / RMS</c>
|
||||
/// <c>DSO = 0.5 * ln((1 + clamp(ScaledFilt)) / (1 - clamp(ScaledFilt)))</c>
|
||||
/// </remarks>
|
||||
/// <seealso href="Dso.md">Detailed documentation</seealso>
|
||||
/// <seealso href="dso.pine">Reference Pine Script implementation</seealso>
|
||||
[SkipLocalsInit]
|
||||
public sealed class Dso : AbstractBase
|
||||
{
|
||||
[StructLayout(LayoutKind.Auto)]
|
||||
private record struct State(
|
||||
double Filt, double Filt1,
|
||||
double Zeros1, double Src1, double Src2,
|
||||
double SumSquared,
|
||||
int Count, double LastValid)
|
||||
{
|
||||
public static State New() => new()
|
||||
{
|
||||
Filt = 0, Filt1 = 0,
|
||||
Zeros1 = 0, Src1 = 0, Src2 = 0,
|
||||
SumSquared = 0,
|
||||
Count = 0, LastValid = 0
|
||||
};
|
||||
}
|
||||
|
||||
private readonly int _period;
|
||||
private readonly double _c1Half;
|
||||
private readonly double _c2;
|
||||
private readonly double _c3;
|
||||
private readonly double _periodRecip;
|
||||
|
||||
private State _s = State.New();
|
||||
private State _ps = State.New();
|
||||
|
||||
// RingBuffer for filt² values — enables O(1) rolling RMS
|
||||
private readonly RingBuffer _filtSqBuf;
|
||||
|
||||
private const double FisherClamp = 0.99;
|
||||
private const double MinRms = 1e-10;
|
||||
|
||||
/// <summary>
|
||||
/// Creates DSO with specified period.
|
||||
/// </summary>
|
||||
/// <param name="period">Lookback period for RMS calculation (must be ≥ 2)</param>
|
||||
public Dso(int period)
|
||||
{
|
||||
if (period < 2)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(period), period, "Period must be at least 2.");
|
||||
}
|
||||
|
||||
_period = period;
|
||||
_periodRecip = 1.0 / period;
|
||||
|
||||
// Super Smoother (2-pole Butterworth) at half-period cutoff
|
||||
double halfPeriod = period * 0.5;
|
||||
double a1 = Math.Exp(-1.414 * Math.PI / halfPeriod);
|
||||
double b1 = 2.0 * a1 * Math.Cos(1.414 * Math.PI / halfPeriod);
|
||||
_c2 = b1;
|
||||
_c3 = -(a1 * a1);
|
||||
double c1 = 1.0 - _c2 - _c3;
|
||||
_c1Half = c1 * 0.5;
|
||||
|
||||
_filtSqBuf = new RingBuffer(period);
|
||||
|
||||
Name = $"Dso({period})";
|
||||
WarmupPeriod = period;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates DSO with specified source and period.
|
||||
/// Subscribes to source.Pub event.
|
||||
/// </summary>
|
||||
public Dso(ITValuePublisher source, int period) : this(period)
|
||||
{
|
||||
source.Pub += Handle;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates DSO with a TSeries source, primes from history, then subscribes.
|
||||
/// </summary>
|
||||
public Dso(TSeries source, int period) : this(period)
|
||||
{
|
||||
Prime(source.Values);
|
||||
if (source.Count > 0)
|
||||
{
|
||||
Last = new TValue(source.LastTime, Last.Value);
|
||||
}
|
||||
source.Pub += Handle;
|
||||
}
|
||||
|
||||
public override bool IsHot => _s.Count >= _period;
|
||||
|
||||
public override void Prime(ReadOnlySpan<double> source, TimeSpan? step = null)
|
||||
{
|
||||
if (source.Length == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_s = State.New();
|
||||
_ps = State.New();
|
||||
_filtSqBuf.Clear();
|
||||
|
||||
int len = source.Length;
|
||||
for (int i = 0; i < len; i++)
|
||||
{
|
||||
double val = source[i];
|
||||
if (double.IsFinite(val))
|
||||
{
|
||||
_s.LastValid = val;
|
||||
}
|
||||
else
|
||||
{
|
||||
val = _s.LastValid;
|
||||
}
|
||||
|
||||
Step(val);
|
||||
}
|
||||
|
||||
Last = new TValue(DateTime.MinValue, ComputeResult());
|
||||
_ps = _s;
|
||||
_filtSqBuf.Snapshot();
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void Handle(object? sender, in TValueEventArgs e) => Update(e.Value, e.IsNew);
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static double GetValidValue(double input, ref State s)
|
||||
{
|
||||
if (double.IsFinite(input))
|
||||
{
|
||||
s.LastValid = input;
|
||||
return input;
|
||||
}
|
||||
return s.LastValid;
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
|
||||
public override TValue Update(TValue input, bool isNew = true)
|
||||
{
|
||||
if (isNew)
|
||||
{
|
||||
_ps = _s;
|
||||
_filtSqBuf.Snapshot();
|
||||
}
|
||||
else
|
||||
{
|
||||
_s = _ps;
|
||||
_filtSqBuf.Restore();
|
||||
}
|
||||
|
||||
double val = GetValidValue(input.Value, ref _s);
|
||||
Step(val);
|
||||
double result = ComputeResult();
|
||||
|
||||
Last = new TValue(input.Time, result);
|
||||
PubEvent(Last, isNew);
|
||||
return Last;
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
|
||||
public override TSeries Update(TSeries source)
|
||||
{
|
||||
if (source.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
int len = source.Count;
|
||||
var t = new List<long>(len);
|
||||
var v = new List<double>(len);
|
||||
CollectionsMarshal.SetCount(t, len);
|
||||
CollectionsMarshal.SetCount(v, len);
|
||||
|
||||
var tSpan = CollectionsMarshal.AsSpan(t);
|
||||
var vSpan = CollectionsMarshal.AsSpan(v);
|
||||
|
||||
source.Times.CopyTo(tSpan);
|
||||
|
||||
Reset();
|
||||
for (int i = 0; i < len; i++)
|
||||
{
|
||||
double val = source.Values[i];
|
||||
if (double.IsFinite(val))
|
||||
{
|
||||
_s.LastValid = val;
|
||||
}
|
||||
else
|
||||
{
|
||||
val = _s.LastValid;
|
||||
}
|
||||
|
||||
Step(val);
|
||||
vSpan[i] = ComputeResult();
|
||||
}
|
||||
|
||||
_ps = _s;
|
||||
_filtSqBuf.Snapshot();
|
||||
Last = new TValue(tSpan[len - 1], vSpan[len - 1]);
|
||||
|
||||
return new TSeries(t, v);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Core streaming step: whitening → SSF → RMS buffer update.
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
|
||||
private void Step(double input)
|
||||
{
|
||||
_s.Count++;
|
||||
|
||||
// Input whitening: Zeros = Close - Close[2]
|
||||
double zeros = input - _s.Src2;
|
||||
|
||||
// Super Smoother filter
|
||||
double filt;
|
||||
if (_s.Count <= 2)
|
||||
{
|
||||
filt = 0.0;
|
||||
}
|
||||
else
|
||||
{
|
||||
filt = Math.FusedMultiplyAdd(_c1Half, zeros + _s.Zeros1,
|
||||
Math.FusedMultiplyAdd(_c2, _s.Filt, _c3 * _s.Filt1));
|
||||
}
|
||||
|
||||
// Update RMS buffer with filt²
|
||||
double filtSq = filt * filt;
|
||||
double removed = _filtSqBuf.Add(filtSq);
|
||||
_s.SumSquared = Math.FusedMultiplyAdd(-1.0, removed, _s.SumSquared + filtSq);
|
||||
|
||||
// Update state
|
||||
_s.Zeros1 = zeros;
|
||||
_s.Filt1 = _s.Filt;
|
||||
_s.Filt = filt;
|
||||
_s.Src2 = _s.Src1;
|
||||
_s.Src1 = input;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes the final DSO value: RMS normalization → Fisher Transform.
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private double ComputeResult()
|
||||
{
|
||||
// RMS from running sum
|
||||
double rms = Math.Sqrt(Math.Max(_s.SumSquared * _periodRecip, MinRms));
|
||||
|
||||
// Scale by RMS
|
||||
double scaledFilt = rms > MinRms ? _s.Filt / rms : 0.0;
|
||||
|
||||
// Fisher Transform with clamping
|
||||
double clamped = Math.Max(-FisherClamp, Math.Min(FisherClamp, scaledFilt));
|
||||
return 0.5 * Math.Log((1.0 + clamped) / (1.0 - clamped));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Batch calculation returning a TSeries.
|
||||
/// </summary>
|
||||
public static TSeries Batch(TSeries source, int period)
|
||||
{
|
||||
var indicator = new Dso(period);
|
||||
return indicator.Update(source);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Batch calculation writing to a pre-allocated output span. Zero-allocation hot path.
|
||||
/// </summary>
|
||||
public static void Batch(ReadOnlySpan<double> source, Span<double> output, int period)
|
||||
{
|
||||
if (source.Length != output.Length)
|
||||
{
|
||||
throw new ArgumentException("Source and output must have the same length", nameof(output));
|
||||
}
|
||||
if (period < 2)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(period), period, "Period must be at least 2.");
|
||||
}
|
||||
|
||||
if (source.Length == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var indicator = new Dso(period);
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
double val = source[i];
|
||||
if (double.IsFinite(val))
|
||||
{
|
||||
indicator._s.LastValid = val;
|
||||
}
|
||||
else
|
||||
{
|
||||
val = indicator._s.LastValid;
|
||||
}
|
||||
|
||||
indicator.Step(val);
|
||||
output[i] = indicator.ComputeResult();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a hot indicator from historical data, ready for streaming.
|
||||
/// </summary>
|
||||
public static (TSeries Results, Dso Indicator) Calculate(TSeries source, int period)
|
||||
{
|
||||
var indicator = new Dso(period);
|
||||
TSeries results = indicator.Update(source);
|
||||
return (results, indicator);
|
||||
}
|
||||
|
||||
public override void Reset()
|
||||
{
|
||||
_s = State.New();
|
||||
_ps = _s;
|
||||
_filtSqBuf.Clear();
|
||||
Last = default;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
# DSO: Ehlers Deviation-Scaled Oscillator
|
||||
|
||||
> *When price deviates from its smoothed norm, DSO amplifies the signal through Fisher transformation—producing sharp, decisive oscillator readings that compress during noise and expand during trends.*
|
||||
|
||||
| Property | Value |
|
||||
| ---------------- | -------------------------------- |
|
||||
| **Category** | Oscillator |
|
||||
| **Inputs** | Source (close) |
|
||||
| **Parameters** | `period` (default 40) |
|
||||
| **Outputs** | Single series (Dso) |
|
||||
| **Output range** | Unbounded (typically ±3) |
|
||||
| **Warmup** | `period` bars |
|
||||
| **PineScript** | [dso.pine](dso.pine) |
|
||||
|
||||
- DSO (Deviation-Scaled Oscillator) is a Fisher-transformed, RMS-normalized Super Smoother oscillator that measures price deviation from its filtered trend, amplified through a nonlinear Fisher Transform.
|
||||
- **Similar:** [REFLEX](../reflex/Reflex.md), [TRENDFLEX](../trendflex/Trendflex.md) | **Complementary:** ADX for trend confirmation | **Trading note:** Values beyond ±2 indicate extreme deviation; zero crossings signal direction changes.
|
||||
- No external validation libraries implement DSO. Validated through self-consistency and behavioral testing.
|
||||
|
||||
DSO applies three stages of signal processing: (1) input whitening to remove DC bias and Nyquist aliasing, (2) a 2-pole Super Smoother filter for trend extraction, and (3) RMS normalization followed by a Fisher Transform that amplifies readings near the center and compresses extremes, producing sharp turning-point signals.
|
||||
|
||||
## Historical Context
|
||||
|
||||
The Deviation-Scaled Oscillator was published by John F. Ehlers in the October 2018 issue of *Technical Analysis of Stocks & Commodities* magazine. Ehlers described it as a "Fisherized" version of his deviation-scaled approach, combining the Super Smoother filter (his signature contribution to technical analysis) with RMS normalization and the Fisher Transform (inverse hyperbolic tangent) to produce an oscillator with Gaussian-distributed output—ideal for statistical threshold-based trading.
|
||||
|
||||
## Architecture & Physics
|
||||
|
||||
DSO operates in four stages:
|
||||
|
||||
### Stage 1: Input Whitening
|
||||
|
||||
The raw price is whitened by computing a 2-bar difference:
|
||||
|
||||
$$ \text{Zeros}_t = \text{Close}_t - \text{Close}_{t-2} $$
|
||||
|
||||
This removes the DC (constant) component and rejects Nyquist frequency aliasing, ensuring only meaningful mid-frequency cycles pass through to the filter.
|
||||
|
||||
### Stage 2: Super Smoother Filter (2-pole Butterworth)
|
||||
|
||||
The whitened input is smoothed using Ehlers' 2-pole Super Smoother at half-period cutoff:
|
||||
|
||||
$$ \text{Filt}_t = \frac{c_1}{2}(\text{Zeros}_t + \text{Zeros}_{t-1}) + c_2 \cdot \text{Filt}_{t-1} + c_3 \cdot \text{Filt}_{t-2} $$
|
||||
|
||||
Coefficients are precomputed from the period:
|
||||
|
||||
$$ a_1 = e^{-\sqrt{2} \cdot \pi / (\text{period}/2)} $$
|
||||
|
||||
$$ c_2 = 2 a_1 \cos\left(\sqrt{2} \cdot \pi / (\text{period}/2)\right), \quad c_3 = -a_1^2, \quad c_1 = 1 - c_2 - c_3 $$
|
||||
|
||||
### Stage 3: RMS Normalization
|
||||
|
||||
Root Mean Square over the period window normalizes the filtered signal by its recent volatility:
|
||||
|
||||
$$ \text{RMS}_t = \sqrt{\frac{1}{N} \sum_{i=0}^{N-1} \text{Filt}_{t-i}^2} $$
|
||||
|
||||
$$ \text{ScaledFilt}_t = \frac{\text{Filt}_t}{\text{RMS}_t} $$
|
||||
|
||||
Implemented using a `RingBuffer` for O(1) running sum updates. RMS is floored at `1e-10` to prevent division by zero.
|
||||
|
||||
### Stage 4: Fisher Transform
|
||||
|
||||
The scaled filter output is clamped to ±0.99 and passed through the Fisher (inverse hyperbolic tangent) Transform:
|
||||
|
||||
$$ \text{DSO}_t = \frac{1}{2} \ln\left(\frac{1 + \text{clamp}(\text{ScaledFilt}_t)}{1 - \text{clamp}(\text{ScaledFilt}_t)}\right) $$
|
||||
|
||||
The Fisher Transform converts the bounded [-1, 1] input into an unbounded Gaussian-like output, amplifying readings near zero (where reversals often originate) and compressing extreme values.
|
||||
|
||||
Implemented with FMA for the SSF filter:
|
||||
|
||||
```csharp
|
||||
filt = Math.FusedMultiplyAdd(_c1Half, zeros + _s.Zeros1,
|
||||
Math.FusedMultiplyAdd(_c2, _s.Filt, _c3 * _s.Filt1));
|
||||
```
|
||||
|
||||
## Performance Profile
|
||||
|
||||
DSO combines a 2-pole IIR filter, O(1) RMS via ring buffer, and the Fisher Transform logarithm.
|
||||
|
||||
### Operation Count (Streaming Mode, Scalar)
|
||||
|
||||
| Operation | Count | Cost (cycles) | Subtotal |
|
||||
| :--- | :---: | :---: | :---: |
|
||||
| **Stage 1: Input Whitening** | | | |
|
||||
| SUB (Close - Close[2]) | 1 | 1 | 1 |
|
||||
| **Stage 2: Super Smoother (2-pole Butterworth)** | | | |
|
||||
| ADD (zeros + zeros1) | 1 | 1 | 1 |
|
||||
| FMA (c1Half × sum + c2×filt + c3×filt1) | 2 | 4 | 8 |
|
||||
| MUL (c3 × filt1) | 1 | 3 | 3 |
|
||||
| **Stage 3: RMS Buffer Update** | | | |
|
||||
| MUL (filt × filt) | 1 | 3 | 3 |
|
||||
| ADD/SUB (sumSquared update) | 2 | 1 | 2 |
|
||||
| FMA (running sum) | 1 | 4 | 4 |
|
||||
| MUL (sumSquared × periodRecip) | 1 | 3 | 3 |
|
||||
| SQRT | 1 | 15 | 15 |
|
||||
| **Stage 4: Fisher Transform** | | | |
|
||||
| DIV (filt / rms) | 1 | 15 | 15 |
|
||||
| CLAMP (max/min) | 2 | 1 | 2 |
|
||||
| ADD/SUB (1±clamped) | 2 | 1 | 2 |
|
||||
| DIV (ratio) | 1 | 15 | 15 |
|
||||
| LOG | 1 | 20 | 20 |
|
||||
| MUL (0.5 × log) | 1 | 3 | 3 |
|
||||
| **Total** | | | **~97 cycles** |
|
||||
|
||||
**Dominant costs:**
|
||||
- LOG (20 cycles, 21%) — Fisher Transform
|
||||
- SQRT (15 cycles, 15%) — RMS calculation
|
||||
- DIV (2×15 cycles, 31%) — RMS normalization + Fisher ratio
|
||||
|
||||
### Batch Mode (SIMD Analysis)
|
||||
|
||||
DSO is **not SIMD-parallelizable** across bars due to:
|
||||
1. Super Smoother is a 2-pole IIR filter with recursive state
|
||||
2. RMS depends on running sum of squared values
|
||||
3. Fisher Transform LOG is inherently scalar
|
||||
|
||||
### Quality Metrics
|
||||
|
||||
| Metric | Score | Notes |
|
||||
| :--- | :---: | :--- |
|
||||
| **Accuracy** | 8/10 | Fisher Transform amplifies clean signals near zero |
|
||||
| **Timeliness** | 8/10 | Input whitening + SSF = low lag for oscillator class |
|
||||
| **Overshoot** | 7/10 | Clamping at ±0.99 prevents infinity, but Fisher amplifies |
|
||||
| **Smoothness** | 7/10 | Super Smoother provides good noise rejection |
|
||||
|
||||
## Validation
|
||||
|
||||
DSO is not implemented in mainstream libraries. Validation relies on behavioral testing.
|
||||
|
||||
| Library | Status | Notes |
|
||||
| :--- | :--- | :--- |
|
||||
| **TA-Lib** | N/A | Not implemented |
|
||||
| **Skender** | N/A | Not implemented |
|
||||
| **Tulip** | N/A | Not implemented |
|
||||
| **Ooples** | N/A | Not implemented |
|
||||
| **Behavioral** | ✅ | Validated: constant→zero, symmetry, mode consistency |
|
||||
|
||||
### Behavioral Test Summary
|
||||
|
||||
- **Constant Input → Zero**: Constant close → zeros=0 → filt=0 → scaledFilt=0 → Fisher(0)=0
|
||||
- **Fisher Symmetry**: DSO(-x) = -DSO(x) — output is antisymmetric
|
||||
- **Trending Input**: Strong trend produces non-zero DSO values
|
||||
- **Mode Consistency**: Streaming, batch, span, and event-driven modes produce identical results
|
||||
- **Bar Correction**: Snapshot/Restore via RingBuffer produces exact rollback
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
1. **Warmup Period**: DSO requires `Period` bars to fill the RMS buffer. Before warmup, output will be unstable. Use `IsHot` to detect readiness.
|
||||
|
||||
2. **Close[2] Dependency**: The whitening step `Close - Close[2]` requires tracking two-bar-ago close. State stores both `Src1` and `Src2` for this purpose. On the first two bars, the filter output is zero.
|
||||
|
||||
3. **Fisher Transform Singularity**: The Fisher Transform has a singularity at ±1 (ln(0)). Clamping at ±0.99 prevents this. The maximum possible DSO value is ±2.646 (`0.5 * ln(199) ≈ 2.646`).
|
||||
|
||||
4. **RMS Floor**: During perfectly flat markets (zero volatility), RMS approaches zero. The `MinRms = 1e-10` floor prevents division by zero but may produce large scaled values. The ±0.99 Fisher clamp provides a second safety net.
|
||||
|
||||
5. **Not a Bounded Oscillator**: Unlike RSI or Stochastics, DSO is unbounded. Values beyond ±2 indicate extreme deviation—roughly equivalent to a 2-sigma event in the Fisher-transformed space.
|
||||
|
||||
6. **Period Selection**: Ehlers recommends period=40 (approximately one market month of bars on daily charts). Shorter periods increase sensitivity but also noise; longer periods add lag.
|
||||
|
||||
7. **Bar Correction**: Like all QuanTAlib indicators, DSO supports bar correction via the `isNew` parameter. The RingBuffer `Snapshot()`/`Restore()` mechanism handles this atomically.
|
||||
@@ -0,0 +1,76 @@
|
||||
// Licensed under the Apache License, Version 2.0
|
||||
// © mihakralj
|
||||
//@version=6
|
||||
indicator("Ehlers Deviation-Scaled Oscillator (DSO)", "DSO", overlay = false)
|
||||
|
||||
//@function Ehlers Deviation-Scaled Oscillator — a Fisher-transformed, RMS-normalized
|
||||
// Super Smoother oscillator. Applies a 2-pole Super Smoother filter to the
|
||||
// whitened input (Close - Close[2]), computes a rolling RMS over the period,
|
||||
// normalizes the filtered signal by RMS, then applies the Fisher Transform
|
||||
// with ±0.99 clamping. Output is an unbounded oscillator (typically ±3).
|
||||
//@param source Series to analyze
|
||||
//@param period Lookback window / assumed cycle period (>= 2)
|
||||
//@returns DSO oscillator value (Fisher-transformed, unbounded)
|
||||
//@reference Ehlers, J.F. (2018). "A Fisherized Deviation-Scaled Oscillator."
|
||||
// Technical Analysis of Stocks & Commodities, Oct 2018.
|
||||
//@optimized O(1) per bar via running sum circular buffer for RMS
|
||||
dso(series float source, simple int period) =>
|
||||
if period < 2
|
||||
runtime.error("Period must be at least 2")
|
||||
|
||||
float price = nz(source)
|
||||
|
||||
// --- Super Smoother coefficients (2-pole Butterworth at half-period cutoff) ---
|
||||
float half_period = period * 0.5
|
||||
float a1 = math.exp(-1.414 * math.pi / half_period)
|
||||
float b1 = 2.0 * a1 * math.cos(1.414 * 180.0 / half_period)
|
||||
float c2 = b1
|
||||
float c3 = -(a1 * a1)
|
||||
float c1 = 1.0 - c2 - c3
|
||||
|
||||
// --- Whitening: zeros at DC and Nyquist ---
|
||||
float zeros = price - nz(source[2])
|
||||
|
||||
// --- 2-pole Super Smoother filter ---
|
||||
var float filt = 0.0
|
||||
var float filt1 = 0.0
|
||||
var float filt2 = 0.0
|
||||
float zeros1 = nz(zeros[1])
|
||||
filt2 := filt1
|
||||
filt1 := filt
|
||||
filt := c1 * 0.5 * (zeros + zeros1) + c2 * filt1 + c3 * filt2
|
||||
|
||||
// --- Rolling RMS via circular buffer ---
|
||||
var array<float> buf = array.new_float(period, 0.0)
|
||||
var int head = 0
|
||||
var float sum_sq = 0.0
|
||||
|
||||
float filt_sq = filt * filt
|
||||
float old_sq = array.get(buf, head)
|
||||
array.set(buf, head, filt_sq)
|
||||
sum_sq := sum_sq - old_sq + filt_sq
|
||||
head := (head + 1) % period
|
||||
|
||||
float rms = math.sqrt(math.max(sum_sq / period, 1e-10))
|
||||
|
||||
// --- Scale by RMS ---
|
||||
float scaled_filt = rms != 0.0 ? filt / rms : 0.0
|
||||
|
||||
// --- Fisher Transform (clamp to ±0.99) ---
|
||||
float clamped = math.max(-0.99, math.min(0.99, scaled_filt))
|
||||
float fisher_filt = 0.5 * math.log((1.0 + clamped) / (1.0 - clamped))
|
||||
|
||||
fisher_filt
|
||||
|
||||
// ── Inputs ──
|
||||
int p_period = input.int(40, "Period", minval = 2)
|
||||
float p_src = input.source(close, "Source")
|
||||
|
||||
// ── Calculation ──
|
||||
float out = dso(p_src, p_period)
|
||||
|
||||
// ── Plot ──
|
||||
plot(out, "DSO", color.yellow, 2)
|
||||
hline(0, "Zero", color.gray)
|
||||
hline(2.0, "+2", color.new(color.red, 60))
|
||||
hline(-2.0, "-2", color.new(color.green, 60))
|
||||
@@ -0,0 +1,157 @@
|
||||
using TradingPlatform.BusinessLayer;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public class DsoIndicatorTests
|
||||
{
|
||||
[Fact]
|
||||
public void DsoIndicator_Constructor_SetsDefaults()
|
||||
{
|
||||
var indicator = new DsoIndicator();
|
||||
|
||||
Assert.Equal(40, indicator.Period);
|
||||
Assert.Equal(SourceType.Close, indicator.Source);
|
||||
Assert.True(indicator.ShowColdValues);
|
||||
Assert.Equal("DSO - Ehlers Deviation-Scaled Oscillator", indicator.Name);
|
||||
Assert.True(indicator.SeparateWindow);
|
||||
Assert.True(indicator.OnBackGround);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DsoIndicator_MinHistoryDepths_EqualsZero()
|
||||
{
|
||||
var indicator = new DsoIndicator();
|
||||
|
||||
Assert.Equal(0, DsoIndicator.MinHistoryDepths);
|
||||
Assert.Equal(0, ((IWatchlistIndicator)indicator).MinHistoryDepths);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DsoIndicator_ShortName_IncludesPeriodAndSource()
|
||||
{
|
||||
var indicator = new DsoIndicator { Period = 30 };
|
||||
|
||||
Assert.Contains("DSO", indicator.ShortName, StringComparison.Ordinal);
|
||||
Assert.Contains("30", indicator.ShortName, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DsoIndicator_SourceCodeLink_IsValid()
|
||||
{
|
||||
var indicator = new DsoIndicator();
|
||||
|
||||
Assert.Contains("github.com", indicator.SourceCodeLink, StringComparison.Ordinal);
|
||||
Assert.Contains("Dso.Quantower.cs", indicator.SourceCodeLink, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DsoIndicator_Initialize_CreatesInternalIndicator()
|
||||
{
|
||||
var indicator = new DsoIndicator { Period = 40 };
|
||||
|
||||
indicator.Initialize();
|
||||
|
||||
// After init, one line series should exist (DSO is single output)
|
||||
Assert.Single(indicator.LinesSeries);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DsoIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
|
||||
{
|
||||
var indicator = new DsoIndicator { Period = 3 };
|
||||
indicator.Initialize();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
indicator.HistoricalData.AddBar(now, 100, 105, 95, 102);
|
||||
|
||||
var args = new UpdateArgs(UpdateReason.HistoricalBar);
|
||||
indicator.ProcessUpdate(args);
|
||||
|
||||
Assert.Equal(1, indicator.LinesSeries[0].Count);
|
||||
Assert.True(double.IsFinite(indicator.LinesSeries[0].GetValue(0)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DsoIndicator_ProcessUpdate_NewBar_ComputesValue()
|
||||
{
|
||||
var indicator = new DsoIndicator { Period = 3 };
|
||||
indicator.Initialize();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
indicator.HistoricalData.AddBar(now, 100, 105, 95, 102);
|
||||
indicator.HistoricalData.AddBar(now.AddMinutes(1), 102, 108, 100, 106);
|
||||
|
||||
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
|
||||
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.NewBar));
|
||||
|
||||
Assert.Equal(2, indicator.LinesSeries[0].Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DsoIndicator_InternalIndicator_HandlesBarCorrection()
|
||||
{
|
||||
// Test the underlying Dso with isNew=false (bar correction)
|
||||
// Use zigzag data to avoid saturation at Fisher clamp
|
||||
var ma = new Dso(3);
|
||||
double[] prices = [100, 102, 99, 103, 97, 104, 98, 105, 97, 106];
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
for (int i = 0; i < prices.Length; i++)
|
||||
{
|
||||
ma.Update(new TValue(now.AddMinutes(i).Ticks, prices[i]), isNew: true);
|
||||
}
|
||||
|
||||
double beforeCorrection = ma.Last.Value;
|
||||
|
||||
// Correct last bar with a moderately different value
|
||||
ma.Update(new TValue(now.AddMinutes(9).Ticks, 100), isNew: false);
|
||||
double afterCorrection = ma.Last.Value;
|
||||
|
||||
Assert.NotEqual(beforeCorrection, afterCorrection);
|
||||
Assert.True(double.IsFinite(afterCorrection));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DsoIndicator_DifferentSourceTypes()
|
||||
{
|
||||
foreach (SourceType sourceType in new[] { SourceType.Close, SourceType.Open, SourceType.High, SourceType.Low })
|
||||
{
|
||||
var indicator = new DsoIndicator();
|
||||
indicator.Source = sourceType;
|
||||
Assert.Equal(sourceType, indicator.Source);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DsoIndicator_MultipleHistoricalBars()
|
||||
{
|
||||
var indicator = new DsoIndicator { Period = 5 };
|
||||
indicator.Initialize();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
indicator.HistoricalData.AddBar(now.AddMinutes(i), 100 + i, 105 + i, 95 + i, 102 + i);
|
||||
indicator.ProcessUpdate(new UpdateArgs(i == 0 ? UpdateReason.HistoricalBar : UpdateReason.NewBar));
|
||||
}
|
||||
|
||||
Assert.Equal(20, indicator.LinesSeries[0].Count);
|
||||
|
||||
// All values should be finite
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
Assert.True(double.IsFinite(indicator.LinesSeries[0].GetValue(i)));
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DsoIndicator_PeriodChange_UpdatesConfig()
|
||||
{
|
||||
var indicator = new DsoIndicator();
|
||||
indicator.Period = 25;
|
||||
Assert.Equal(25, indicator.Period);
|
||||
|
||||
indicator.Period = 50;
|
||||
Assert.Equal(50, indicator.Period);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,479 @@
|
||||
namespace QuanTAlib;
|
||||
|
||||
public class DsoTests
|
||||
{
|
||||
private const int DefaultPeriod = 40;
|
||||
private const double Tolerance = 1e-12;
|
||||
|
||||
private static TSeries MakeSeries(int count = 500)
|
||||
{
|
||||
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.5, seed: 42);
|
||||
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
|
||||
return bars.Close;
|
||||
}
|
||||
|
||||
// ========== A) Constructor Validation ==========
|
||||
|
||||
[Fact]
|
||||
public void Constructor_ZeroPeriod_ThrowsArgumentOutOfRangeException()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentOutOfRangeException>(() => new Dso(0));
|
||||
Assert.Equal("period", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_OnePeriod_ThrowsArgumentOutOfRangeException()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentOutOfRangeException>(() => new Dso(1));
|
||||
Assert.Equal("period", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_NegativePeriod_ThrowsArgumentOutOfRangeException()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentOutOfRangeException>(() => new Dso(-5));
|
||||
Assert.Equal("period", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_ValidPeriod_SetsNameAndWarmup()
|
||||
{
|
||||
var indicator = new Dso(40);
|
||||
Assert.Equal("Dso(40)", indicator.Name);
|
||||
Assert.Equal(40, indicator.WarmupPeriod);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_PeriodTwo_IsValid()
|
||||
{
|
||||
var indicator = new Dso(2);
|
||||
Assert.Equal("Dso(2)", indicator.Name);
|
||||
Assert.Equal(2, indicator.WarmupPeriod);
|
||||
}
|
||||
|
||||
// ========== B) Basic Calculation ==========
|
||||
|
||||
[Fact]
|
||||
public void Update_ReturnsTValue_WithValidProperties()
|
||||
{
|
||||
var indicator = new Dso(DefaultPeriod);
|
||||
var input = new TValue(DateTime.UtcNow, 100.0);
|
||||
TValue result = indicator.Update(input);
|
||||
|
||||
Assert.Equal(input.Time, result.Time);
|
||||
Assert.True(double.IsFinite(result.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Update_AfterWarmup_IsHotBecomesTrue()
|
||||
{
|
||||
var indicator = new Dso(DefaultPeriod);
|
||||
Assert.False(indicator.IsHot);
|
||||
|
||||
for (int i = 0; i < 500; i++)
|
||||
{
|
||||
indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0 + i * 0.1));
|
||||
}
|
||||
|
||||
Assert.True(indicator.IsHot);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Update_LastProperty_MatchesReturnValue()
|
||||
{
|
||||
var indicator = new Dso(DefaultPeriod);
|
||||
var input = new TValue(DateTime.UtcNow, 42.0);
|
||||
TValue result = indicator.Update(input);
|
||||
|
||||
Assert.Equal(result.Value, indicator.Last.Value, Tolerance);
|
||||
}
|
||||
|
||||
// ========== C) State + Bar Correction ==========
|
||||
|
||||
[Fact]
|
||||
public void IsNew_True_AdvancesState()
|
||||
{
|
||||
var indicator = new Dso(10);
|
||||
|
||||
// Warm up past the period threshold first
|
||||
for (int i = 0; i < 15; i++)
|
||||
{
|
||||
indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0 + i * 0.5), isNew: true);
|
||||
}
|
||||
|
||||
TValue r1 = indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(30), 120.0), isNew: true);
|
||||
TValue r2 = indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(31), 80.0), isNew: true);
|
||||
|
||||
// Two very different bars after warmup must produce different results
|
||||
Assert.NotEqual(r1.Value, r2.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsNew_False_RewritesCurrentBar()
|
||||
{
|
||||
var indicator = new Dso(10);
|
||||
|
||||
// Use mixed zigzag data to avoid saturation at Fisher clamp
|
||||
double[] prices = [100, 102, 99, 103, 97, 104, 98, 105, 97, 106,
|
||||
101, 103, 98, 104, 96, 105, 99, 107, 98, 108,
|
||||
100, 102, 99, 103, 97, 104, 98, 105, 97, 106,
|
||||
101, 103, 98, 104, 96, 105, 99, 107, 98, 108,
|
||||
100, 102, 99, 103, 97, 104, 98, 105, 97, 106];
|
||||
|
||||
for (int i = 0; i < prices.Length; i++)
|
||||
{
|
||||
indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(i), prices[i]));
|
||||
}
|
||||
|
||||
indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(50), 110.0), isNew: true);
|
||||
double afterNew = indicator.Last.Value;
|
||||
|
||||
indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(50), 90.0), isNew: false);
|
||||
double afterCorrection = indicator.Last.Value;
|
||||
|
||||
Assert.NotEqual(afterNew, afterCorrection);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IterativeCorrections_RestoreState()
|
||||
{
|
||||
var indicator = new Dso(10);
|
||||
TSeries data = MakeSeries();
|
||||
|
||||
for (int i = 0; i < 50; i++)
|
||||
{
|
||||
indicator.Update(data[i], isNew: true);
|
||||
}
|
||||
|
||||
indicator.Update(data[50], isNew: true);
|
||||
|
||||
for (int j = 0; j < 5; j++)
|
||||
{
|
||||
indicator.Update(data[50], isNew: false);
|
||||
}
|
||||
|
||||
double afterCorrections = indicator.Last.Value;
|
||||
|
||||
var fresh = new Dso(10);
|
||||
for (int i = 0; i <= 50; i++)
|
||||
{
|
||||
fresh.Update(data[i], isNew: true);
|
||||
}
|
||||
|
||||
Assert.Equal(fresh.Last.Value, afterCorrections, Tolerance);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reset_ClearsState()
|
||||
{
|
||||
var indicator = new Dso(DefaultPeriod);
|
||||
|
||||
for (int i = 0; i < 50; i++)
|
||||
{
|
||||
indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0 + i));
|
||||
}
|
||||
|
||||
Assert.True(indicator.IsHot);
|
||||
|
||||
indicator.Reset();
|
||||
|
||||
Assert.False(indicator.IsHot);
|
||||
Assert.Equal(default, indicator.Last);
|
||||
}
|
||||
|
||||
// ========== D) Warmup/Convergence ==========
|
||||
|
||||
[Fact]
|
||||
public void IsHot_FlipsAtCorrectTime()
|
||||
{
|
||||
var indicator = new Dso(10);
|
||||
int hotAt = -1;
|
||||
|
||||
for (int i = 0; i < 200; i++)
|
||||
{
|
||||
indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0));
|
||||
if (indicator.IsHot && hotAt < 0)
|
||||
{
|
||||
hotAt = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Assert.InRange(hotAt, 1, 200);
|
||||
}
|
||||
|
||||
// ========== E) Robustness ==========
|
||||
|
||||
[Fact]
|
||||
public void NaN_Input_UsesLastValidValue()
|
||||
{
|
||||
var indicator = new Dso(10);
|
||||
|
||||
for (int i = 0; i < 30; i++)
|
||||
{
|
||||
indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0));
|
||||
}
|
||||
|
||||
TValue nanResult = indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(30), double.NaN));
|
||||
|
||||
Assert.True(double.IsFinite(nanResult.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Infinity_Input_UsesLastValidValue()
|
||||
{
|
||||
var indicator = new Dso(10);
|
||||
|
||||
for (int i = 0; i < 30; i++)
|
||||
{
|
||||
indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0));
|
||||
}
|
||||
|
||||
TValue infResult = indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(30), double.PositiveInfinity));
|
||||
Assert.True(double.IsFinite(infResult.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BatchNaN_DoesNotPropagate()
|
||||
{
|
||||
int period = 10;
|
||||
double[] source = new double[100];
|
||||
double[] output = new double[100];
|
||||
|
||||
for (int i = 0; i < 100; i++)
|
||||
{
|
||||
source[i] = 100.0 + i * 0.5;
|
||||
}
|
||||
|
||||
source[50] = double.NaN;
|
||||
source[51] = double.NaN;
|
||||
|
||||
Dso.Batch(source, output, period);
|
||||
|
||||
for (int i = 0; i < 100; i++)
|
||||
{
|
||||
Assert.True(double.IsFinite(output[i]), $"Output[{i}] is not finite");
|
||||
}
|
||||
}
|
||||
|
||||
// ========== F) Consistency (4 API modes) ==========
|
||||
|
||||
[Fact]
|
||||
public void AllModes_ProduceSameResult()
|
||||
{
|
||||
int period = 10;
|
||||
TSeries data = MakeSeries();
|
||||
|
||||
// 1. Batch (TSeries)
|
||||
TSeries batchResults = Dso.Batch(data, period);
|
||||
double expected = batchResults.Last.Value;
|
||||
|
||||
// 2. Span batch
|
||||
var tValues = data.Values.ToArray();
|
||||
var spanOutput = new double[tValues.Length];
|
||||
Dso.Batch(new ReadOnlySpan<double>(tValues), spanOutput, period);
|
||||
double spanResult = spanOutput[^1];
|
||||
|
||||
// 3. Streaming
|
||||
var streaming = new Dso(period);
|
||||
for (int i = 0; i < data.Count; i++)
|
||||
{
|
||||
streaming.Update(data[i]);
|
||||
}
|
||||
double streamingResult = streaming.Last.Value;
|
||||
|
||||
// 4. Eventing
|
||||
var pubSource = new TSeries();
|
||||
var eventBased = new Dso(pubSource, period);
|
||||
for (int i = 0; i < data.Count; i++)
|
||||
{
|
||||
pubSource.Add(data[i]);
|
||||
}
|
||||
double eventingResult = eventBased.Last.Value;
|
||||
|
||||
Assert.Equal(expected, spanResult, precision: 9);
|
||||
Assert.Equal(expected, streamingResult, precision: 9);
|
||||
Assert.Equal(expected, eventingResult, precision: 9);
|
||||
}
|
||||
|
||||
// ========== G) Span API Tests ==========
|
||||
|
||||
[Fact]
|
||||
public void SpanBatch_MismatchedLengths_ThrowsArgumentException()
|
||||
{
|
||||
double[] source = new double[10];
|
||||
double[] output = new double[5];
|
||||
|
||||
var ex = Assert.Throws<ArgumentException>(() => Dso.Batch(source, output, 5));
|
||||
Assert.Equal("output", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SpanBatch_PeriodOne_ThrowsArgumentOutOfRangeException()
|
||||
{
|
||||
double[] source = new double[10];
|
||||
double[] output = new double[10];
|
||||
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => Dso.Batch(source, output, 1));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SpanBatch_EmptyInput_ProducesEmptyOutput()
|
||||
{
|
||||
double[] source = Array.Empty<double>();
|
||||
double[] output = Array.Empty<double>();
|
||||
var ex = Record.Exception(() => Dso.Batch(source, output, 10));
|
||||
Assert.Null(ex);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SpanBatch_LargeData_DoesNotStackOverflow()
|
||||
{
|
||||
int size = 5000;
|
||||
double[] source = new double[size];
|
||||
double[] output = new double[size];
|
||||
|
||||
for (int i = 0; i < size; i++)
|
||||
{
|
||||
source[i] = 100.0 + i * 0.1;
|
||||
}
|
||||
|
||||
Dso.Batch(source, output, 20);
|
||||
|
||||
Assert.True(double.IsFinite(output[size - 1]));
|
||||
}
|
||||
|
||||
// ========== H) Chainability ==========
|
||||
|
||||
[Fact]
|
||||
public void Pub_EventFires_OnUpdate()
|
||||
{
|
||||
var indicator = new Dso(DefaultPeriod);
|
||||
int eventCount = 0;
|
||||
|
||||
indicator.Pub += (object? sender, in TValueEventArgs args) => eventCount++;
|
||||
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0 + i));
|
||||
}
|
||||
|
||||
Assert.Equal(10, eventCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EventBased_Chaining_Works()
|
||||
{
|
||||
var source = new TSeries();
|
||||
var indicator = new Dso(source, 5);
|
||||
|
||||
source.Add(new TValue(DateTime.UtcNow, 100));
|
||||
source.Add(new TValue(DateTime.UtcNow, 110));
|
||||
source.Add(new TValue(DateTime.UtcNow, 120));
|
||||
|
||||
Assert.True(double.IsFinite(indicator.Last.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Calculate_ReturnsHotIndicator()
|
||||
{
|
||||
TSeries data = MakeSeries();
|
||||
(TSeries results, Dso indicator) = Dso.Calculate(data, DefaultPeriod);
|
||||
|
||||
Assert.Equal(data.Count, results.Count);
|
||||
Assert.True(indicator.IsHot);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void StaticCalculate_MatchesInstance()
|
||||
{
|
||||
const int period = 10;
|
||||
int count = 100;
|
||||
var source = new TSeries();
|
||||
var indicator = new Dso(period);
|
||||
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
source.Add(new TValue(DateTime.UtcNow.AddMinutes(i), i + 10));
|
||||
indicator.Update(source.Last);
|
||||
}
|
||||
|
||||
var staticResult = Dso.Batch(source, period);
|
||||
|
||||
Assert.Equal(source.Count, staticResult.Count);
|
||||
Assert.Equal(indicator.Last.Value, staticResult.Last.Value, 8);
|
||||
}
|
||||
|
||||
// ========== DSO-specific: Oscillator behavior ==========
|
||||
|
||||
[Fact]
|
||||
public void ConstantInput_OutputConvergesToZero()
|
||||
{
|
||||
var indicator = new Dso(10);
|
||||
double lastResult = double.NaN;
|
||||
|
||||
for (int i = 0; i < 300; i++)
|
||||
{
|
||||
TValue r = indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0));
|
||||
lastResult = r.Value;
|
||||
}
|
||||
|
||||
// Constant input → zeros=0 → filt=0 → Fisher(0)=0
|
||||
Assert.Equal(0.0, lastResult, 1e-10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TrendingInput_ProducesNonZero()
|
||||
{
|
||||
var indicator = new Dso(10);
|
||||
double lastResult = 0.0;
|
||||
|
||||
for (int i = 0; i < 100; i++)
|
||||
{
|
||||
TValue r = indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0 + i * 2.0));
|
||||
lastResult = r.Value;
|
||||
}
|
||||
|
||||
// Strong uptrend should produce non-zero DSO
|
||||
Assert.NotEqual(0.0, lastResult);
|
||||
Assert.True(double.IsFinite(lastResult));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FisherOutput_IsSymmetric()
|
||||
{
|
||||
// DSO of ascending sequence should be opposite sign to DSO of descending sequence
|
||||
var up = new Dso(10);
|
||||
var down = new Dso(10);
|
||||
|
||||
for (int i = 0; i < 50; i++)
|
||||
{
|
||||
up.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0 + i));
|
||||
down.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 200.0 - i));
|
||||
}
|
||||
|
||||
// Both should be finite and opposite in sign
|
||||
Assert.True(double.IsFinite(up.Last.Value));
|
||||
Assert.True(double.IsFinite(down.Last.Value));
|
||||
Assert.True(up.Last.Value * down.Last.Value < 0, "Ascending and descending should produce opposite signs");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DsoProducesFiniteValues_OnGBMData()
|
||||
{
|
||||
var indicator = new Dso(10);
|
||||
TSeries data = MakeSeries(200);
|
||||
|
||||
int nonFiniteCount = 0;
|
||||
for (int i = 0; i < data.Count; i++)
|
||||
{
|
||||
TValue r = indicator.Update(data[i]);
|
||||
if (!double.IsFinite(r.Value))
|
||||
{
|
||||
nonFiniteCount++;
|
||||
}
|
||||
}
|
||||
|
||||
Assert.Equal(0, nonFiniteCount);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
using Xunit;
|
||||
using Xunit.Abstractions;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public sealed class DsoValidationTests : IDisposable
|
||||
{
|
||||
private readonly ITestOutputHelper _output;
|
||||
private readonly ValidationTestData _testData;
|
||||
private const int DefaultPeriod = 40;
|
||||
|
||||
public DsoValidationTests(ITestOutputHelper output)
|
||||
{
|
||||
_output = output;
|
||||
_testData = new ValidationTestData(10000);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_testData.Dispose();
|
||||
}
|
||||
|
||||
// ========== Self-consistency Validation ==========
|
||||
|
||||
[Fact]
|
||||
public void Dso_BatchStreaming_Match()
|
||||
{
|
||||
// Streaming
|
||||
var streaming = new Dso(DefaultPeriod);
|
||||
var streamResults = new List<double>(_testData.Data.Count);
|
||||
for (int i = 0; i < _testData.Data.Count; i++)
|
||||
{
|
||||
TValue r = streaming.Update(_testData.Data[i], isNew: true);
|
||||
streamResults.Add(r.Value);
|
||||
}
|
||||
|
||||
// Batch
|
||||
TSeries batchResults = Dso.Batch(_testData.Data, DefaultPeriod);
|
||||
|
||||
int mismatchCount = 0;
|
||||
double maxDiff = 0;
|
||||
for (int i = 0; i < streamResults.Count; i++)
|
||||
{
|
||||
double diff = Math.Abs(streamResults[i] - batchResults[i].Value);
|
||||
if (diff > 1e-10)
|
||||
{
|
||||
mismatchCount++;
|
||||
maxDiff = Math.Max(maxDiff, diff);
|
||||
}
|
||||
}
|
||||
|
||||
_output.WriteLine($"Dso({DefaultPeriod}) Batch vs Streaming: {mismatchCount} mismatches, max diff = {maxDiff:E3}");
|
||||
Assert.Equal(0, mismatchCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Dso_SpanBatch_MatchesStreaming()
|
||||
{
|
||||
// Streaming
|
||||
var streaming = new Dso(DefaultPeriod);
|
||||
var streamResults = new List<double>(_testData.Data.Count);
|
||||
for (int i = 0; i < _testData.Data.Count; i++)
|
||||
{
|
||||
TValue r = streaming.Update(_testData.Data[i], isNew: true);
|
||||
streamResults.Add(r.Value);
|
||||
}
|
||||
|
||||
// Span batch
|
||||
double[] output = new double[_testData.Data.Count];
|
||||
Dso.Batch(_testData.Data.Values, output, DefaultPeriod);
|
||||
|
||||
int mismatchCount = 0;
|
||||
double maxDiff = 0;
|
||||
for (int i = 0; i < streamResults.Count; i++)
|
||||
{
|
||||
double diff = Math.Abs(streamResults[i] - output[i]);
|
||||
if (diff > 1e-10)
|
||||
{
|
||||
mismatchCount++;
|
||||
maxDiff = Math.Max(maxDiff, diff);
|
||||
}
|
||||
}
|
||||
|
||||
_output.WriteLine($"Dso({DefaultPeriod}) Span vs Streaming: {mismatchCount} mismatches, max diff = {maxDiff:E3}");
|
||||
Assert.Equal(0, mismatchCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Dso_DifferentPeriods_ProduceDifferentResults()
|
||||
{
|
||||
TSeries result10 = Dso.Batch(_testData.Data, 10);
|
||||
TSeries result40 = Dso.Batch(_testData.Data, 40);
|
||||
|
||||
int lastIdx = _testData.Data.Count - 1;
|
||||
_output.WriteLine($"Dso(10) last = {result10[lastIdx].Value:F6}");
|
||||
_output.WriteLine($"Dso(40) last = {result40[lastIdx].Value:F6}");
|
||||
|
||||
Assert.NotEqual(result10[lastIdx].Value, result40[lastIdx].Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Dso_ConstantInput_ConvergesToZero()
|
||||
{
|
||||
var indicator = new Dso(10);
|
||||
double constantVal = 100.0;
|
||||
|
||||
double lastResult = double.NaN;
|
||||
for (int i = 0; i < 1000; i++)
|
||||
{
|
||||
TValue r = indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(i), constantVal));
|
||||
lastResult = r.Value;
|
||||
}
|
||||
|
||||
_output.WriteLine($"Dso(10) constant input result after 1000 bars: {lastResult:E6}");
|
||||
Assert.True(Math.Abs(lastResult) < 1e-6, $"Expected near-zero for constant input, got {lastResult}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Dso_Calculate_ReturnsHotIndicator()
|
||||
{
|
||||
(TSeries results, Dso indicator) = Dso.Calculate(_testData.Data, DefaultPeriod);
|
||||
|
||||
Assert.Equal(_testData.Data.Count, results.Count);
|
||||
Assert.True(indicator.IsHot);
|
||||
|
||||
// Verify the indicator can continue streaming
|
||||
TValue next = indicator.Update(new TValue(DateTime.UtcNow, 100.0), isNew: true);
|
||||
Assert.True(double.IsFinite(next.Value));
|
||||
|
||||
_output.WriteLine($"Dso({DefaultPeriod}) Calculate: {results.Count} bars, last = {results[results.Count - 1].Value:F6}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Dso_BarCorrection_ProducesConsistentResults()
|
||||
{
|
||||
// Build reference: 100 bars then bar 101
|
||||
var reference = new Dso(DefaultPeriod);
|
||||
for (int i = 0; i < 100; i++)
|
||||
{
|
||||
reference.Update(_testData.Data[i], isNew: true);
|
||||
}
|
||||
reference.Update(new TValue(DateTime.UtcNow, 50.0), isNew: true);
|
||||
double referenceVal = reference.Last.Value;
|
||||
|
||||
// Build test: 100 bars, wrong bar 101, then correct bar 101
|
||||
var test = new Dso(DefaultPeriod);
|
||||
for (int i = 0; i < 100; i++)
|
||||
{
|
||||
test.Update(_testData.Data[i], isNew: true);
|
||||
}
|
||||
test.Update(new TValue(DateTime.UtcNow, 999.0), isNew: true); // wrong
|
||||
test.Update(new TValue(DateTime.UtcNow, 50.0), isNew: false); // correct
|
||||
double testVal = test.Last.Value;
|
||||
|
||||
_output.WriteLine($"Reference: {referenceVal:F10}, Corrected: {testVal:F10}");
|
||||
Assert.Equal(referenceVal, testVal, 1e-10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Dso_SubsetValidation_StableBehavior()
|
||||
{
|
||||
using var subset = _testData.CreateSubset(200);
|
||||
|
||||
TSeries results = Dso.Batch(subset.Data, DefaultPeriod);
|
||||
|
||||
int nanCount = 0;
|
||||
for (int i = 0; i < results.Count; i++)
|
||||
{
|
||||
if (!double.IsFinite(results[i].Value))
|
||||
{
|
||||
nanCount++;
|
||||
}
|
||||
}
|
||||
|
||||
_output.WriteLine($"Dso({DefaultPeriod}) on 200-bar subset: {nanCount} non-finite values");
|
||||
Assert.Equal(0, nanCount);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user