mirror of
https://github.com/mihakralj/QuanTAlib.git
synced 2026-08-05 12:37:43 +00:00
feat: add RSIH (Ehlers Hann-Windowed RSI) indicator
This commit is contained in:
@@ -163,6 +163,7 @@
|
||||
* [REVERSEEMA - Ehlers Reverse EMA](/lib/oscillators/reverseema/ReverseEma.md)
|
||||
* [RVGI - Ehlers Relative Vigor Index](/lib/oscillators/rvgi/Rvgi.md)
|
||||
* [RRSI - Ehlers Rocket RSI](/lib/oscillators/rrsi/Rrsi.md)
|
||||
* [RSIH - Ehlers Hann-Windowed RSI](/lib/oscillators/rsih/Rsih.md)
|
||||
* [SMI - Stochastic Momentum Index](/lib/oscillators/smi/Smi.md)
|
||||
* [SQUEEZE - Squeeze Momentum](/lib/oscillators/squeeze/Squeeze.md)
|
||||
* [SQUEEZE_PRO - Squeeze Pro](/lib/oscillators/squeeze_pro/squeeze_pro.md)
|
||||
|
||||
@@ -203,6 +203,7 @@ Bounded indicators that oscillate around a centerline or between fixed extremes.
|
||||
| [**REFLEX**](../lib/oscillators/reflex/Reflex.md) | Ehlers Reflex | Zero-centered reversal oscillator |
|
||||
| [**REVERSEEMA**](../lib/oscillators/reverseema/ReverseEma.md) | Ehlers Reverse EMA | 8-stage cascaded Z-transform inversion oscillator |
|
||||
| [**RVGI**](../lib/oscillators/rvgi/Rvgi.md) | Ehlers Relative Vigor Index | Open-close vs high-low ratio with smoothing |
|
||||
| [**RSIH**](../lib/oscillators/rsih/Rsih.md) | Ehlers Hann-Windowed RSI | Hann-weighted zero-mean RSI [-1, +1] |
|
||||
| [**SMI**](../lib/oscillators/smi/Smi.md) | Stochastic Momentum Index | Distance from range midpoint (K/D lines) |
|
||||
| [**SQUEEZE**](../lib/oscillators/squeeze/Squeeze.md) | Squeeze Momentum | BB inside KC squeeze with momentum |
|
||||
| [**STC**](../lib/oscillators/stc/Stc.md) | Schaff Trend Cycle | MACD + double Stochastic (0-100) |
|
||||
|
||||
@@ -233,6 +233,7 @@ Numbers that bounce between limits. Overbought, oversold, divergence. You know t
|
||||
| REFLEX | Ehlers Reflex | [reflex.pine](../lib/oscillators/reflex/reflex.pine) |
|
||||
| REVERSEEMA | Ehlers Reverse EMA | [reverseema.pine](../lib/oscillators/reverseema/reverseema.pine) |
|
||||
| RVGI | Relative Vigor Index | [rvgi.pine](../lib/oscillators/rvgi/rvgi.pine) |
|
||||
| RSIH | Ehlers Hann-Windowed RSI | [rsih.pine](../lib/oscillators/rsih/rsih.pine) |
|
||||
| SMI | Stochastic Momentum Index | [smi.pine](../lib/oscillators/smi/smi.pine) |
|
||||
| SQUEEZE | Squeeze Momentum | [squeeze.pine](../lib/oscillators/squeeze/squeeze.pine) |
|
||||
| STC | Schaff Trend Cycle | [stc.pine](../lib/oscillators/stc/stc.pine) |
|
||||
|
||||
@@ -311,6 +311,7 @@
|
||||
| [RVI](volatility/rvi/Rvi.md) | Relative Volatility Index | Volatility |
|
||||
| [RVGI](oscillators/rvgi/Rvgi.md) | Ehlers Relative Vigor Index | Oscillators |
|
||||
| [RRSI](oscillators/rrsi/Rrsi.md) | Ehlers Rocket RSI | Oscillators |
|
||||
| [RSIH](oscillators/rsih/Rsih.md) | Ehlers Hann-Windowed RSI | Oscillators |
|
||||
| [RWMA](trends_FIR/rwma/Rwma.md) | Range Weighted MA | Trends (FIR) |
|
||||
| [SAK](filters/sak/Sak.md) | Ehlers Swiss Army Knife | Filters |
|
||||
| [SAM](momentum/sam/Sam.md) | Ehlers Smoothed Adaptive Momentum | Momentum |
|
||||
|
||||
@@ -44,6 +44,7 @@ Oscillators fluctuate above and below a centerline or within bounded ranges. Use
|
||||
| [REVERSEEMA](reverseema/ReverseEma.md) | Ehlers Reverse EMA | 8-stage cascaded Z-transform inversion subtracts EMA lag, producing zero-centered oscillator signal. |
|
||||
| [RVGI](rvgi/Rvgi.md) | Ehlers Relative Vigor Index | Open-close vs high-low ratio with SMA smoothing. Measures conviction. |
|
||||
| [RRSI](rrsi/Rrsi.md) | Ehlers Rocket RSI | Fisher Transform of Super Smoother–filtered RSI. Sharp cyclic reversal signals. |
|
||||
| [RSIH](rsih/Rsih.md) | Ehlers Hann-Windowed RSI | Hann-weighted CU/CD RSI, zero-mean [-1, +1]. FIR filter. TASC Jan 2022. |
|
||||
| [SMI](smi/Smi.md) | Stochastic Momentum Index | Distance from range midpoint. More sensitive than classic Stochastic. |
|
||||
| [SQUEEZE](squeeze/Squeeze.md) | Squeeze | BB width < KC width indicates consolidation. Breakout imminent. |
|
||||
| [SQUEEZE_PRO](squeeze_pro/squeeze_pro.md) | Squeeze Pro | Multi-level BB vs KC squeeze (wide/normal/narrow) with MOM-smoothed momentum. LazyBear. |
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
using System.Drawing;
|
||||
using System.Runtime.CompilerServices;
|
||||
using TradingPlatform.BusinessLayer;
|
||||
|
||||
namespace QuanTAlib;
|
||||
|
||||
[SkipLocalsInit]
|
||||
public sealed class RsihIndicator : Indicator, IWatchlistIndicator
|
||||
{
|
||||
[InputParameter("Period", sortIndex: 1, 1, 1000, 1, 0)]
|
||||
public int Period { get; set; } = 14;
|
||||
|
||||
[IndicatorExtensions.DataSourceInput]
|
||||
public SourceType Source { get; set; } = SourceType.Close;
|
||||
|
||||
[InputParameter("Show cold values", sortIndex: 21)]
|
||||
public bool ShowColdValues { get; set; } = true;
|
||||
|
||||
private Rsih _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 => $"RSIH {Period}:{_sourceName}";
|
||||
public override string SourceCodeLink => "https://github.com/mihakralj/QuanTAlib/blob/main/lib/oscillators/rsih/Rsih.Quantower.cs";
|
||||
|
||||
public RsihIndicator()
|
||||
{
|
||||
OnBackGround = true;
|
||||
SeparateWindow = true;
|
||||
_sourceName = Source.ToString();
|
||||
Name = "RSIH - Ehlers Hann-Windowed RSI";
|
||||
Description = "Zero-mean RSI variant using Hann window coefficients for inherent smoothing";
|
||||
_series = new LineSeries(name: $"RSIH {Period}", color: Color.Yellow, width: 2, style: LineStyle.Solid);
|
||||
AddLineSeries(_series);
|
||||
}
|
||||
|
||||
protected override void OnInit()
|
||||
{
|
||||
_ma = new Rsih(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,318 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace QuanTAlib;
|
||||
|
||||
/// <summary>
|
||||
/// RSIH: Ehlers Hann-Windowed RSI
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A zero-mean RSI variant that uses Hann window coefficients to weight
|
||||
/// price differences, producing a bounded [-1, +1] oscillator with inherent
|
||||
/// smoothing. FIR filter — fixed lookback window, not recursive.
|
||||
///
|
||||
/// Calculation:
|
||||
/// <c>w(k) = 1 - cos(2π·k / (period + 1)) for k = 1..period</c>
|
||||
/// <c>CU = Σ w(k) · max(Close[k-1] - Close[k], 0)</c>
|
||||
/// <c>CD = Σ w(k) · max(Close[k] - Close[k-1], 0)</c>
|
||||
/// <c>RSIH = (CU - CD) / (CU + CD)</c>
|
||||
/// </remarks>
|
||||
/// <seealso href="Rsih.md">Detailed documentation</seealso>
|
||||
/// <seealso href="rsih.pine">Reference Pine Script implementation</seealso>
|
||||
[SkipLocalsInit]
|
||||
public sealed class Rsih : AbstractBase
|
||||
{
|
||||
[StructLayout(LayoutKind.Auto)]
|
||||
private record struct State(int Count, double LastValid)
|
||||
{
|
||||
public static State New() => new() { Count = 0, LastValid = 0 };
|
||||
}
|
||||
|
||||
private readonly int _period;
|
||||
private readonly double[] _hannCoeffs;
|
||||
|
||||
private State _s = State.New();
|
||||
private State _ps = State.New();
|
||||
|
||||
// RingBuffer stores close prices — needs period+1 slots for period differences
|
||||
private readonly RingBuffer _closeBuf;
|
||||
|
||||
private const double Epsilon = 1e-10;
|
||||
|
||||
/// <summary>
|
||||
/// Creates RSIH with specified period.
|
||||
/// </summary>
|
||||
/// <param name="period">Lookback period for Hann-windowed RSI (must be ≥ 1)</param>
|
||||
public Rsih(int period)
|
||||
{
|
||||
if (period < 1)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(period), period, "Period must be at least 1.");
|
||||
}
|
||||
|
||||
_period = period;
|
||||
|
||||
// Precompute Hann window coefficients: w(k) = 1 - cos(2π·k / (period+1))
|
||||
_hannCoeffs = new double[period];
|
||||
double angleStep = 2.0 * Math.PI / (period + 1);
|
||||
for (int k = 1; k <= period; k++)
|
||||
{
|
||||
_hannCoeffs[k - 1] = 1.0 - Math.Cos(angleStep * k);
|
||||
}
|
||||
|
||||
_closeBuf = new RingBuffer(period + 1);
|
||||
|
||||
Name = $"Rsih({period})";
|
||||
WarmupPeriod = period + 1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates RSIH with specified source and period.
|
||||
/// Subscribes to source.Pub event.
|
||||
/// </summary>
|
||||
public Rsih(ITValuePublisher source, int period) : this(period)
|
||||
{
|
||||
source.Pub += Handle;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates RSIH with a TSeries source, primes from history, then subscribes.
|
||||
/// </summary>
|
||||
public Rsih(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 + 1;
|
||||
|
||||
public override void Prime(ReadOnlySpan<double> source, TimeSpan? step = null)
|
||||
{
|
||||
if (source.Length == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_s = State.New();
|
||||
_ps = State.New();
|
||||
_closeBuf.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;
|
||||
_closeBuf.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;
|
||||
_closeBuf.Snapshot();
|
||||
}
|
||||
else
|
||||
{
|
||||
_s = _ps;
|
||||
_closeBuf.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;
|
||||
_closeBuf.Snapshot();
|
||||
Last = new TValue(tSpan[len - 1], vSpan[len - 1]);
|
||||
|
||||
return new TSeries(t, v);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Core streaming step: add close price to ring buffer.
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void Step(double input)
|
||||
{
|
||||
_s.Count++;
|
||||
_closeBuf.Add(input);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes RSIH from the close buffer using Hann-weighted CU/CD sums.
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
|
||||
private double ComputeResult()
|
||||
{
|
||||
int available = Math.Min(_s.Count, _period + 1);
|
||||
int pairs = available - 1;
|
||||
if (pairs <= 0)
|
||||
{
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
double cu = 0.0;
|
||||
double cd = 0.0;
|
||||
|
||||
// k = 1..pairs: newer = closeBuf[available - k], older = closeBuf[available - k - 1]
|
||||
// Hann coeff index = k - 1 (0-based)
|
||||
int effectivePairs = Math.Min(pairs, _period);
|
||||
for (int k = 1; k <= effectivePairs; k++)
|
||||
{
|
||||
double newer = _closeBuf[available - k];
|
||||
double older = _closeBuf[available - k - 1];
|
||||
double diff = newer - older;
|
||||
double w = _hannCoeffs[k - 1];
|
||||
|
||||
if (diff > 0.0)
|
||||
{
|
||||
cu = Math.FusedMultiplyAdd(w, diff, cu);
|
||||
}
|
||||
else if (diff < 0.0)
|
||||
{
|
||||
cd = Math.FusedMultiplyAdd(w, -diff, cd);
|
||||
}
|
||||
}
|
||||
|
||||
double denom = cu + cd;
|
||||
return denom > Epsilon ? (cu - cd) / denom : 0.0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Batch calculation returning a TSeries.
|
||||
/// </summary>
|
||||
public static TSeries Batch(TSeries source, int period)
|
||||
{
|
||||
var indicator = new Rsih(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 < 1)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(period), period, "Period must be at least 1.");
|
||||
}
|
||||
|
||||
if (source.Length == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var indicator = new Rsih(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, Rsih Indicator) Calculate(TSeries source, int period)
|
||||
{
|
||||
var indicator = new Rsih(period);
|
||||
TSeries results = indicator.Update(source);
|
||||
return (results, indicator);
|
||||
}
|
||||
|
||||
public override void Reset()
|
||||
{
|
||||
_s = State.New();
|
||||
_ps = _s;
|
||||
_closeBuf.Clear();
|
||||
Last = default;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
# RSIH: Ehlers Hann-Windowed RSI
|
||||
|
||||
> *By replacing Wilder's exponential smoothing with a Hann window, Ehlers produces an RSI that is zero-mean, bounded, and inherently smooth—no supplemental filtering required.*
|
||||
|
||||
| Property | Value |
|
||||
| ---------------- | -------------------------------- |
|
||||
| **Category** | Oscillator |
|
||||
| **Inputs** | Source (close) |
|
||||
| **Parameters** | `period` (default 14) |
|
||||
| **Outputs** | Single series (Rsih) |
|
||||
| **Output range** | [-1, +1] |
|
||||
| **Zero mean** | Yes |
|
||||
| **Warmup** | `period + 1` bars |
|
||||
| **PineScript** | [rsih.pine](rsih.pine) |
|
||||
|
||||
- RSIH (Hann-Windowed RSI) is a zero-mean relative strength oscillator that uses Hann window coefficients to weight price differences, producing a bounded [-1, +1] output with inherent smoothing.
|
||||
- **Similar:** [RSI](../../momentum/rsi/Rsi.md), [LRSI](../lrsi/Lrsi.md), [RRSI](../rrsi/Rrsi.md) | **Complementary:** Moving averages for trend confirmation | **Trading note:** Zero crossings signal direction changes; ±0.5 levels indicate strong momentum.
|
||||
- No external validation libraries implement RSIH. Validated through self-consistency and behavioral testing.
|
||||
|
||||
RSIH applies Hann window weighting to consecutive price differences, computes separate weighted sums of up-moves (CU) and down-moves (CD), then normalizes as (CU - CD) / (CU + CD). The Hann window provides inherent smoothing that eliminates the need for supplemental filtering, while the normalization produces a zero-mean output bounded to [-1, +1].
|
||||
|
||||
## Historical Context
|
||||
|
||||
The Hann-Windowed RSI was published by John F. Ehlers in the January 2022 issue of *Technical Analysis of Stocks & Commodities* magazine under the title "(Yet Another) Improved RSI." Ehlers observed that classic RSI suffers from two fundamental issues: (1) Wilder's exponential smoothing introduces lag and spectral leakage, and (2) the 0–100 output range obscures the zero-mean nature of momentum. By replacing the smoothing with a Hann window FIR filter and using a symmetric [-1, +1] normalization, Ehlers created an RSI variant that is both mathematically cleaner and practically more responsive.
|
||||
|
||||
## Architecture & Physics
|
||||
|
||||
RSIH operates as a single-stage FIR filter:
|
||||
|
||||
### Hann Window Coefficients
|
||||
|
||||
The weighting function is precomputed in the constructor:
|
||||
|
||||
$$ w(k) = 1 - \cos\left(\frac{2\pi k}{N + 1}\right) \quad \text{for } k = 1, 2, \ldots, N $$
|
||||
|
||||
where $N$ is the period. Note: Ehlers uses $(N + 1)$ in the denominator, not the standard symmetric Hann formula $(N - 1)$.
|
||||
|
||||
### Weighted CU/CD Accumulation
|
||||
|
||||
For each bar, consecutive price differences are weighted by the Hann coefficients:
|
||||
|
||||
$$ \text{CU} = \sum_{k=1}^{N} w(k) \cdot \max(\text{Close}_{t-k+1} - \text{Close}_{t-k}, \; 0) $$
|
||||
|
||||
$$ \text{CD} = \sum_{k=1}^{N} w(k) \cdot \max(\text{Close}_{t-k} - \text{Close}_{t-k+1}, \; 0) $$
|
||||
|
||||
### Normalization
|
||||
|
||||
$$ \text{RSIH}_t = \frac{\text{CU} - \text{CD}}{\text{CU} + \text{CD}} $$
|
||||
|
||||
When $\text{CU} + \text{CD} = 0$ (flat market), RSIH returns 0.
|
||||
|
||||
Implemented with FMA for the coefficient multiplication:
|
||||
|
||||
```csharp
|
||||
cu = Math.FusedMultiplyAdd(w, diff, cu);
|
||||
```
|
||||
|
||||
## Performance Profile
|
||||
|
||||
RSIH is an O(N) FIR filter — each bar requires scanning the full window.
|
||||
|
||||
### Operation Count (Streaming Mode, Scalar)
|
||||
|
||||
| Operation | Count | Cost (cycles) | Subtotal |
|
||||
| :--- | :---: | :---: | :---: |
|
||||
| **Hann Window Scan** | | | |
|
||||
| SUB (newer - older) | N | 1 | N |
|
||||
| CMP (diff > 0, diff < 0) | N | 1 | N |
|
||||
| FMA (w × diff + acc) | N | 4 | 4N |
|
||||
| **Normalization** | | | |
|
||||
| ADD (CU + CD) | 1 | 1 | 1 |
|
||||
| SUB (CU - CD) | 1 | 1 | 1 |
|
||||
| DIV (ratio) | 1 | 15 | 15 |
|
||||
| **Total** | | | **~6N + 17 cycles** |
|
||||
|
||||
For default N=14: ~101 cycles per bar.
|
||||
|
||||
**Dominant cost:** FMA loop (4N cycles, ~67%)
|
||||
|
||||
### Batch Mode (SIMD Analysis)
|
||||
|
||||
RSIH is **not SIMD-parallelizable** across bars because each bar's window overlaps with adjacent bars. However, the inner loop (coefficient × difference accumulation) could potentially benefit from SIMD vectorization within a single bar's computation.
|
||||
|
||||
### Quality Metrics
|
||||
|
||||
| Metric | Score | Notes |
|
||||
| :--- | :---: | :--- |
|
||||
| **Accuracy** | 9/10 | Hann window provides excellent spectral properties |
|
||||
| **Timeliness** | 8/10 | FIR filter with minimal lag for oscillator class |
|
||||
| **Overshoot** | 9/10 | Bounded [-1, +1] — no possibility of divergence |
|
||||
| **Smoothness** | 8/10 | Hann window provides inherent anti-aliasing |
|
||||
|
||||
## Validation
|
||||
|
||||
RSIH 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 → all diffs = 0 → CU = CD = 0 → RSIH = 0
|
||||
- **Output Symmetry**: RSIH(ascending) = -RSIH(descending) — output is antisymmetric
|
||||
- **Bounded Output**: All outputs in [-1, +1] regardless of input magnitude
|
||||
- **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**: RSIH requires `Period + 1` bars to fill the close buffer for `Period` differences. Use `IsHot` to detect readiness.
|
||||
|
||||
2. **Hann Window Denominator**: Ehlers uses `(period + 1)` in the Hann formula, NOT the standard symmetric `(period - 1)`. Using the wrong denominator will produce incorrect coefficients.
|
||||
|
||||
3. **Zero-Mean Output**: Unlike classic RSI (0–100), RSIH oscillates around zero with range [-1, +1]. Overbought/oversold levels should be set around ±0.5, not 70/30.
|
||||
|
||||
4. **FIR Complexity**: RSIH is O(N) per bar, not O(1) like IIR indicators. For very large periods, this may impact performance in high-frequency applications.
|
||||
|
||||
5. **Flat Market Edge Case**: When all prices in the window are identical, CU + CD = 0. The implementation returns 0.0 in this case (using an epsilon floor of 1e-10).
|
||||
|
||||
6. **Period Selection**: Ehlers recommends using the dominant cycle period (not half-cycle like classic RSI). Default period of 14 works well for daily charts.
|
||||
|
||||
7. **Bar Correction**: Like all QuanTAlib indicators, RSIH supports bar correction via the `isNew` parameter. The RingBuffer `Snapshot()`/`Restore()` mechanism handles this atomically.
|
||||
@@ -0,0 +1,50 @@
|
||||
// Licensed under the Apache License, Version 2.0
|
||||
// © mihakralj
|
||||
//@version=6
|
||||
indicator("Ehlers Hann-Windowed RSI (RSIH)", "RSIH", overlay = false)
|
||||
|
||||
//@function Ehlers Hann-Windowed RSI — a zero-mean RSI variant using Hann window
|
||||
// coefficients to weight price differences. Produces a bounded [-1, +1]
|
||||
// oscillator with inherent smoothing via the Hann window. FIR filter.
|
||||
//@param source Series to analyze
|
||||
//@param period Lookback window for RSI calculation (>= 1)
|
||||
//@returns RSIH oscillator value [-1, +1]
|
||||
//@reference Ehlers, J.F. (2022). "(Yet Another) Improved RSI."
|
||||
// Technical Analysis of Stocks & Commodities, Jan 2022.
|
||||
//@optimized O(N) per bar — FIR scan over Hann-weighted window
|
||||
rsih(series float source, simple int period) =>
|
||||
if period < 1
|
||||
runtime.error("Period must be at least 1")
|
||||
|
||||
float price = nz(source)
|
||||
|
||||
// --- Hann window coefficients precomputed per bar ---
|
||||
float angle_step = 2.0 * math.pi / (period + 1)
|
||||
float cu = 0.0
|
||||
float cd = 0.0
|
||||
|
||||
for k = 1 to period
|
||||
float newer = nz(source[k - 1])
|
||||
float older = nz(source[k])
|
||||
float diff = newer - older
|
||||
float w = 1.0 - math.cos(angle_step * k)
|
||||
if diff > 0
|
||||
cu += w * diff
|
||||
if diff < 0
|
||||
cd += w * (-diff)
|
||||
|
||||
float result = (cu + cd) != 0.0 ? (cu - cd) / (cu + cd) : 0.0
|
||||
result
|
||||
|
||||
// ── Inputs ──
|
||||
int p_period = input.int(14, "Period", minval = 1)
|
||||
float p_src = input.source(close, "Source")
|
||||
|
||||
// ── Calculation ──
|
||||
float out = rsih(p_src, p_period)
|
||||
|
||||
// ── Plot ──
|
||||
plot(out, "RSIH", color.yellow, 2)
|
||||
hline(0, "Zero", color.gray)
|
||||
hline(0.5, "+0.5", color.new(color.red, 60))
|
||||
hline(-0.5, "-0.5", color.new(color.green, 60))
|
||||
@@ -0,0 +1,152 @@
|
||||
using TradingPlatform.BusinessLayer;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public class RsihIndicatorTests
|
||||
{
|
||||
[Fact]
|
||||
public void RsihIndicator_Constructor_SetsDefaults()
|
||||
{
|
||||
var indicator = new RsihIndicator();
|
||||
|
||||
Assert.Equal(14, indicator.Period);
|
||||
Assert.Equal(SourceType.Close, indicator.Source);
|
||||
Assert.True(indicator.ShowColdValues);
|
||||
Assert.Equal("RSIH - Ehlers Hann-Windowed RSI", indicator.Name);
|
||||
Assert.True(indicator.SeparateWindow);
|
||||
Assert.True(indicator.OnBackGround);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RsihIndicator_MinHistoryDepths_EqualsZero()
|
||||
{
|
||||
var indicator = new RsihIndicator();
|
||||
|
||||
Assert.Equal(0, RsihIndicator.MinHistoryDepths);
|
||||
Assert.Equal(0, ((IWatchlistIndicator)indicator).MinHistoryDepths);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RsihIndicator_ShortName_IncludesPeriodAndSource()
|
||||
{
|
||||
var indicator = new RsihIndicator { Period = 20 };
|
||||
|
||||
Assert.Contains("RSIH", indicator.ShortName, StringComparison.Ordinal);
|
||||
Assert.Contains("20", indicator.ShortName, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RsihIndicator_SourceCodeLink_IsValid()
|
||||
{
|
||||
var indicator = new RsihIndicator();
|
||||
|
||||
Assert.Contains("github.com", indicator.SourceCodeLink, StringComparison.Ordinal);
|
||||
Assert.Contains("Rsih.Quantower.cs", indicator.SourceCodeLink, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RsihIndicator_Initialize_CreatesInternalIndicator()
|
||||
{
|
||||
var indicator = new RsihIndicator { Period = 14 };
|
||||
|
||||
indicator.Initialize();
|
||||
|
||||
Assert.Single(indicator.LinesSeries);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RsihIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
|
||||
{
|
||||
var indicator = new RsihIndicator { 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 RsihIndicator_ProcessUpdate_NewBar_ComputesValue()
|
||||
{
|
||||
var indicator = new RsihIndicator { 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 RsihIndicator_InternalIndicator_HandlesBarCorrection()
|
||||
{
|
||||
var ma = new Rsih(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;
|
||||
|
||||
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 RsihIndicator_DifferentSourceTypes()
|
||||
{
|
||||
foreach (SourceType sourceType in new[] { SourceType.Close, SourceType.Open, SourceType.High, SourceType.Low })
|
||||
{
|
||||
var indicator = new RsihIndicator();
|
||||
indicator.Source = sourceType;
|
||||
Assert.Equal(sourceType, indicator.Source);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RsihIndicator_MultipleHistoricalBars()
|
||||
{
|
||||
var indicator = new RsihIndicator { 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);
|
||||
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
Assert.True(double.IsFinite(indicator.LinesSeries[0].GetValue(i)));
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RsihIndicator_PeriodChange_UpdatesConfig()
|
||||
{
|
||||
var indicator = new RsihIndicator();
|
||||
indicator.Period = 25;
|
||||
Assert.Equal(25, indicator.Period);
|
||||
|
||||
indicator.Period = 50;
|
||||
Assert.Equal(50, indicator.Period);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,479 @@
|
||||
namespace QuanTAlib;
|
||||
|
||||
public class RsihTests
|
||||
{
|
||||
private const int DefaultPeriod = 14;
|
||||
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 Rsih(0));
|
||||
Assert.Equal("period", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_NegativePeriod_ThrowsArgumentOutOfRangeException()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentOutOfRangeException>(() => new Rsih(-5));
|
||||
Assert.Equal("period", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_ValidPeriod_SetsNameAndWarmup()
|
||||
{
|
||||
var indicator = new Rsih(14);
|
||||
Assert.Equal("Rsih(14)", indicator.Name);
|
||||
Assert.Equal(15, indicator.WarmupPeriod);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_PeriodOne_IsValid()
|
||||
{
|
||||
var indicator = new Rsih(1);
|
||||
Assert.Equal("Rsih(1)", indicator.Name);
|
||||
Assert.Equal(2, indicator.WarmupPeriod);
|
||||
}
|
||||
|
||||
// ========== B) Basic Calculation ==========
|
||||
|
||||
[Fact]
|
||||
public void Update_ReturnsTValue_WithValidProperties()
|
||||
{
|
||||
var indicator = new Rsih(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 Rsih(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 Rsih(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 Rsih(10);
|
||||
|
||||
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);
|
||||
|
||||
Assert.NotEqual(r1.Value, r2.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsNew_False_RewritesCurrentBar()
|
||||
{
|
||||
var indicator = new Rsih(10);
|
||||
|
||||
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 Rsih(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 Rsih(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 Rsih(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 Rsih(10);
|
||||
int hotAt = -1;
|
||||
|
||||
for (int i = 0; i < 200; i++)
|
||||
{
|
||||
indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0 + i));
|
||||
if (indicator.IsHot && hotAt < 0)
|
||||
{
|
||||
hotAt = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Assert.InRange(hotAt, 1, 200);
|
||||
}
|
||||
|
||||
// ========== E) Robustness ==========
|
||||
|
||||
[Fact]
|
||||
public void NaN_Input_UsesLastValidValue()
|
||||
{
|
||||
var indicator = new Rsih(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 Rsih(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;
|
||||
|
||||
Rsih.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 = Rsih.Batch(data, period);
|
||||
double expected = batchResults.Last.Value;
|
||||
|
||||
// 2. Span batch
|
||||
var tValues = data.Values.ToArray();
|
||||
var spanOutput = new double[tValues.Length];
|
||||
Rsih.Batch(new ReadOnlySpan<double>(tValues), spanOutput, period);
|
||||
double spanResult = spanOutput[^1];
|
||||
|
||||
// 3. Streaming
|
||||
var streaming = new Rsih(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 Rsih(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>(() => Rsih.Batch(source, output, 5));
|
||||
Assert.Equal("output", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SpanBatch_PeriodZero_ThrowsArgumentOutOfRangeException()
|
||||
{
|
||||
double[] source = new double[10];
|
||||
double[] output = new double[10];
|
||||
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => Rsih.Batch(source, output, 0));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SpanBatch_EmptyInput_ProducesEmptyOutput()
|
||||
{
|
||||
double[] source = Array.Empty<double>();
|
||||
double[] output = Array.Empty<double>();
|
||||
var ex = Record.Exception(() => Rsih.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;
|
||||
}
|
||||
|
||||
Rsih.Batch(source, output, 20);
|
||||
|
||||
Assert.True(double.IsFinite(output[size - 1]));
|
||||
}
|
||||
|
||||
// ========== H) Chainability ==========
|
||||
|
||||
[Fact]
|
||||
public void Pub_EventFires_OnUpdate()
|
||||
{
|
||||
var indicator = new Rsih(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 Rsih(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, Rsih indicator) = Rsih.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 Rsih(period);
|
||||
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
source.Add(new TValue(DateTime.UtcNow.AddMinutes(i), i + 10));
|
||||
indicator.Update(source.Last);
|
||||
}
|
||||
|
||||
var staticResult = Rsih.Batch(source, period);
|
||||
|
||||
Assert.Equal(source.Count, staticResult.Count);
|
||||
Assert.Equal(indicator.Last.Value, staticResult.Last.Value, 8);
|
||||
}
|
||||
|
||||
// ========== RSIH-specific: Oscillator behavior ==========
|
||||
|
||||
[Fact]
|
||||
public void ConstantInput_OutputConvergesToZero()
|
||||
{
|
||||
var indicator = new Rsih(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 → all diffs = 0 → CU = CD = 0 → RSIH = 0
|
||||
Assert.Equal(0.0, lastResult, 1e-10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TrendingInput_ProducesNonZero()
|
||||
{
|
||||
var indicator = new Rsih(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 positive RSIH close to +1
|
||||
Assert.True(lastResult > 0.0);
|
||||
Assert.True(double.IsFinite(lastResult));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OutputIsBounded()
|
||||
{
|
||||
var indicator = new Rsih(10);
|
||||
TSeries data = MakeSeries(500);
|
||||
|
||||
for (int i = 0; i < data.Count; i++)
|
||||
{
|
||||
TValue r = indicator.Update(data[i]);
|
||||
Assert.InRange(r.Value, -1.0, 1.0);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpTrend_Positive_DownTrend_Negative()
|
||||
{
|
||||
var up = new Rsih(10);
|
||||
var down = new Rsih(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));
|
||||
}
|
||||
|
||||
Assert.True(up.Last.Value > 0, "Ascending should produce positive RSIH");
|
||||
Assert.True(down.Last.Value < 0, "Descending should produce negative RSIH");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RsihProducesFiniteValues_OnGBMData()
|
||||
{
|
||||
var indicator = new Rsih(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 RsihValidationTests : IDisposable
|
||||
{
|
||||
private readonly ITestOutputHelper _output;
|
||||
private readonly ValidationTestData _testData;
|
||||
private const int DefaultPeriod = 14;
|
||||
|
||||
public RsihValidationTests(ITestOutputHelper output)
|
||||
{
|
||||
_output = output;
|
||||
_testData = new ValidationTestData(10000);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_testData.Dispose();
|
||||
}
|
||||
|
||||
// ========== Self-consistency Validation ==========
|
||||
|
||||
[Fact]
|
||||
public void Rsih_BatchStreaming_Match()
|
||||
{
|
||||
// Streaming
|
||||
var streaming = new Rsih(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 = Rsih.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($"Rsih({DefaultPeriod}) Batch vs Streaming: {mismatchCount} mismatches, max diff = {maxDiff:E3}");
|
||||
Assert.Equal(0, mismatchCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Rsih_SpanBatch_MatchesStreaming()
|
||||
{
|
||||
// Streaming
|
||||
var streaming = new Rsih(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];
|
||||
Rsih.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($"Rsih({DefaultPeriod}) Span vs Streaming: {mismatchCount} mismatches, max diff = {maxDiff:E3}");
|
||||
Assert.Equal(0, mismatchCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Rsih_DifferentPeriods_ProduceDifferentResults()
|
||||
{
|
||||
TSeries result10 = Rsih.Batch(_testData.Data, 10);
|
||||
TSeries result20 = Rsih.Batch(_testData.Data, 20);
|
||||
|
||||
int lastIdx = _testData.Data.Count - 1;
|
||||
_output.WriteLine($"Rsih(10) last = {result10[lastIdx].Value:F6}");
|
||||
_output.WriteLine($"Rsih(20) last = {result20[lastIdx].Value:F6}");
|
||||
|
||||
Assert.NotEqual(result10[lastIdx].Value, result20[lastIdx].Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Rsih_ConstantInput_ConvergesToZero()
|
||||
{
|
||||
var indicator = new Rsih(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($"Rsih(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 Rsih_Calculate_ReturnsHotIndicator()
|
||||
{
|
||||
(TSeries results, Rsih indicator) = Rsih.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($"Rsih({DefaultPeriod}) Calculate: {results.Count} bars, last = {results[results.Count - 1].Value:F6}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Rsih_BarCorrection_ProducesConsistentResults()
|
||||
{
|
||||
// Build reference: 100 bars then bar 101
|
||||
var reference = new Rsih(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 Rsih(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 Rsih_SubsetValidation_StableBehavior()
|
||||
{
|
||||
using var subset = _testData.CreateSubset(200);
|
||||
|
||||
TSeries results = Rsih.Batch(subset.Data, DefaultPeriod);
|
||||
|
||||
int nanCount = 0;
|
||||
for (int i = 0; i < results.Count; i++)
|
||||
{
|
||||
if (!double.IsFinite(results[i].Value))
|
||||
{
|
||||
nanCount++;
|
||||
}
|
||||
}
|
||||
|
||||
_output.WriteLine($"Rsih({DefaultPeriod}) on 200-bar subset: {nanCount} non-finite values");
|
||||
Assert.Equal(0, nanCount);
|
||||
}
|
||||
}
|
||||
@@ -653,6 +653,7 @@ packages = ["quantalib"]
|
||||
| dstoch | `Dstoch` | E (HLC) | period |
|
||||
| dosc | `Dosc` | A | rsiPeriod, ema1Period, ema2Period, sigPeriod |
|
||||
| dso | `Dso` | A | period |
|
||||
| rsih | `Rsih` | A | period |
|
||||
| dymi | `Dymi` | A | basePeriod, shortPeriod, longPeriod... |
|
||||
| er | `Er` | A | period |
|
||||
| fisher | `Fisher` | A | period, alpha |
|
||||
|
||||
@@ -448,6 +448,7 @@ HAS_PSL = _bind("qtl_psl", [_dp, _ci, _dp, _ci])
|
||||
HAS_DECO = _bind("qtl_deco", [_dp, _ci, _dp, _ci, _ci])
|
||||
HAS_DOSC = _bind("qtl_dosc", [_dp, _ci, _dp, _ci, _ci, _ci, _ci])
|
||||
HAS_DSO = _bind("qtl_dso", [_dp, _ci, _dp, _ci])
|
||||
HAS_RSIH = _bind("qtl_rsih", [_dp, _ci, _dp, _ci])
|
||||
HAS_DYMI = _bind("qtl_dymi", [_dp, _ci, _dp, _ci, _ci, _ci, _ci, _ci])
|
||||
HAS_CRSI = _bind("qtl_crsi", [_dp, _ci, _dp, _ci, _ci, _ci])
|
||||
HAS_BBB = _bind("qtl_bbb", [_dp, _ci, _dp, _ci, _cd])
|
||||
|
||||
@@ -50,6 +50,7 @@ __all__ = [
|
||||
"deco",
|
||||
"dosc",
|
||||
"dso",
|
||||
"rsih",
|
||||
"dymi",
|
||||
"crsi",
|
||||
"bbb",
|
||||
@@ -556,6 +557,14 @@ def dso(close: object, period: int = 40, offset: int = 0, **kwargs) -> object:
|
||||
return _wrap(dst, idx, f"DSO_{period}", "oscillators", offset)
|
||||
|
||||
|
||||
def rsih(close: object, period: int = 14, offset: int = 0, **kwargs) -> object:
|
||||
"""Ehlers Hann-Windowed RSI."""
|
||||
period = int(kwargs.get("length", period)); offset = int(offset)
|
||||
src, idx = _arr(close); n = len(src); dst = _out(n)
|
||||
_check(_lib.qtl_rsih(_ptr(src), n, _ptr(dst), period))
|
||||
return _wrap(dst, idx, f"RSIH_{period}", "oscillators", offset)
|
||||
|
||||
|
||||
def dymi(close: object, base_period: int = 14, short_period: int = 5,
|
||||
long_period: int = 10, min_period: int = 3, max_period: int = 30,
|
||||
offset: int = 0, **kwargs) -> object:
|
||||
|
||||
@@ -428,6 +428,16 @@ public static unsafe partial class Exports
|
||||
catch { return StatusCodes.QTL_ERR_INTERNAL; }
|
||||
}
|
||||
|
||||
// Rsih: Pattern A (src, out, int period)
|
||||
[UnmanagedCallersOnly(EntryPoint = "qtl_rsih")]
|
||||
public static int QtlRsih(double* src, int n, double* dst, int period)
|
||||
{
|
||||
int v = Chk1(src, dst, n); if (v != 0) return v;
|
||||
v = ChkPeriod(period); if (v != 0) return v;
|
||||
try { Rsih.Batch(Src(src, n), Dst(dst, n), period); return StatusCodes.QTL_OK; }
|
||||
catch { return StatusCodes.QTL_ERR_INTERNAL; }
|
||||
}
|
||||
|
||||
// Dymi: Pattern A (src, out, int p1..p5)
|
||||
[UnmanagedCallersOnly(EntryPoint = "qtl_dymi")]
|
||||
public static int QtlDymi(double* src, int n, double* dst, int p1, int p2, int p3, int p4, int p5)
|
||||
|
||||
Reference in New Issue
Block a user