mirror of
https://github.com/mihakralj/QuanTAlib.git
synced 2026-08-17 01:58:06 +00:00
feat: add USI (Ehlers Ultimate Strength Index) - TASC Nov 2024
This commit is contained in:
@@ -381,6 +381,7 @@
|
||||
| [UCHANNEL](channels/uchannel/Uchannel.md) | Ehlers Ultimate Channel | Channels |
|
||||
| [UI](volatility/ui/Ui.md) | Ulcer Index | Volatility |
|
||||
| [ULTOSC](oscillators/ultosc/Ultosc.md) | Ultimate Oscillator | Oscillators |
|
||||
| [USI](oscillators/usi/Usi.md) | Ehlers Ultimate Strength Index | Oscillators |
|
||||
| [USF](filters/usf/Usf.md) | Ehlers Ultimate Smoother | Filters |
|
||||
| [VA](volume/va/Va.md) | Volume Accumulation | Volume |
|
||||
| [VAMA](trends_IIR/vama/Vama.md) | Volatility Adjusted MA | Trends (IIR) |
|
||||
|
||||
@@ -59,4 +59,5 @@ Oscillators fluctuate above and below a centerline or within bounded ranges. Use
|
||||
| [TRIX](trix/Trix.md) | Triple Exponential Average | ROC of triple EMA. Filters noise through three smoothings. |
|
||||
| [TTM_WAVE](ttm_wave/TtmWave.md) | TTM Wave | Fibonacci-period MACD composite (Waves A/B/C). John Carter. |
|
||||
| [ULTOSC](ultosc/Ultosc.md) | Ultimate Oscillator | Multi-timeframe oscillator. Combines 7, 14, 28 period buying pressure. |
|
||||
| [USI](usi/Usi.md) | Ehlers Ultimate Strength Index | Symmetric RSI replacement using UltimateSmoother. [-1, +1]. TASC Nov 2024. |
|
||||
| [WILLR](willr/Willr.md) | Williams %R | Inverse Stochastic. -100 to 0 range. Overbought/oversold. |
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
using System.Drawing;
|
||||
using System.Runtime.CompilerServices;
|
||||
using TradingPlatform.BusinessLayer;
|
||||
|
||||
namespace QuanTAlib;
|
||||
|
||||
[SkipLocalsInit]
|
||||
public sealed class UsiIndicator : Indicator, IWatchlistIndicator
|
||||
{
|
||||
[InputParameter("Period", sortIndex: 1, 1, 1000, 1, 0)]
|
||||
public int Period { get; set; } = 28;
|
||||
|
||||
[IndicatorExtensions.DataSourceInput]
|
||||
public SourceType Source { get; set; } = SourceType.Close;
|
||||
|
||||
[InputParameter("Show cold values", sortIndex: 21)]
|
||||
public bool ShowColdValues { get; set; } = true;
|
||||
|
||||
private Usi _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 => $"USI {Period}:{_sourceName}";
|
||||
public override string SourceCodeLink => "https://github.com/mihakralj/QuanTAlib/blob/main/lib/oscillators/usi/Usi.Quantower.cs";
|
||||
|
||||
public UsiIndicator()
|
||||
{
|
||||
OnBackGround = true;
|
||||
SeparateWindow = true;
|
||||
_sourceName = Source.ToString();
|
||||
Name = "USI - Ehlers Ultimate Strength Index";
|
||||
Description = "Symmetric RSI replacement using UltimateSmoother filter for reduced lag";
|
||||
_series = new LineSeries(name: $"USI {Period}", color: Color.Cyan, width: 2, style: LineStyle.Solid);
|
||||
AddLineSeries(_series);
|
||||
}
|
||||
|
||||
protected override void OnInit()
|
||||
{
|
||||
_ma = new Usi(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,364 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace QuanTAlib;
|
||||
|
||||
/// <summary>
|
||||
/// USI: Ehlers Ultimate Strength Index
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A symmetric RSI replacement that uses the UltimateSmoother filter instead of
|
||||
/// Wilder's exponential smoothing. Output ranges from -1 to +1 with significantly
|
||||
/// reduced lag compared to traditional RSI.
|
||||
///
|
||||
/// Pipeline:
|
||||
/// <list type="number">
|
||||
/// <item>SU = max(0, Close - Close[1]), SD = max(0, Close[1] - Close)</item>
|
||||
/// <item>avgSU = SMA(SU, 4), avgSD = SMA(SD, 4)</item>
|
||||
/// <item>USU = UltimateSmoother(avgSU, period), USD = UltimateSmoother(avgSD, period)</item>
|
||||
/// <item>USI = (USU - USD) / (USU + USD) when denom > 0</item>
|
||||
/// </list>
|
||||
///
|
||||
/// Reference: John F. Ehlers, "Ultimate Strength Index (USI)",
|
||||
/// Technical Analysis of Stocks & Commodities, November 2024.
|
||||
/// </remarks>
|
||||
/// <seealso href="Usi.md">Detailed documentation</seealso>
|
||||
/// <seealso href="usi.pine">Reference Pine Script implementation</seealso>
|
||||
[SkipLocalsInit]
|
||||
public sealed class Usi : AbstractBase
|
||||
{
|
||||
private const int SmaLen = 4;
|
||||
private const double MinSmoothed = 0.01;
|
||||
|
||||
[StructLayout(LayoutKind.Auto)]
|
||||
private record struct State(
|
||||
double PrevClose,
|
||||
// SMA(4) circular buffers
|
||||
double Su0, double Su1, double Su2, double Su3,
|
||||
double Sd0, double Sd1, double Sd2, double Sd3,
|
||||
int BufIdx,
|
||||
// UltimateSmoother IIR state for SU path
|
||||
double Usu1, double Usu2,
|
||||
double AvgSu1, double AvgSu2,
|
||||
// UltimateSmoother IIR state for SD path
|
||||
double Usd1, double Usd2,
|
||||
double AvgSd1, double AvgSd2,
|
||||
// Output
|
||||
double Usi,
|
||||
int Count, double LastValid)
|
||||
{
|
||||
public static State New() => new()
|
||||
{
|
||||
PrevClose = double.NaN,
|
||||
Su0 = 0, Su1 = 0, Su2 = 0, Su3 = 0,
|
||||
Sd0 = 0, Sd1 = 0, Sd2 = 0, Sd3 = 0,
|
||||
BufIdx = 0,
|
||||
Usu1 = 0, Usu2 = 0, AvgSu1 = 0, AvgSu2 = 0,
|
||||
Usd1 = 0, Usd2 = 0, AvgSd1 = 0, AvgSd2 = 0,
|
||||
Usi = 0,
|
||||
Count = 0, LastValid = 0
|
||||
};
|
||||
}
|
||||
|
||||
// USF precomputed coefficients
|
||||
private readonly double _k0; // (1 - c1)
|
||||
private readonly double _k1; // (2*c1 - c2)
|
||||
private readonly double _k2; // -(c1 + c3)
|
||||
private readonly double _c2;
|
||||
private readonly double _c3;
|
||||
|
||||
private State _s = State.New();
|
||||
private State _ps = State.New();
|
||||
|
||||
/// <summary>
|
||||
/// Creates USI with specified period.
|
||||
/// </summary>
|
||||
/// <param name="period">UltimateSmoother filter period (must be > 0, default 28)</param>
|
||||
public Usi(int period = 28)
|
||||
{
|
||||
if (period <= 0)
|
||||
{
|
||||
throw new ArgumentException("Period must be greater than 0", nameof(period));
|
||||
}
|
||||
|
||||
// UltimateSmoother coefficients (same as USF)
|
||||
double arg = Math.Sqrt(2) * Math.PI / period;
|
||||
double expArg = Math.Exp(-arg);
|
||||
_c2 = 2.0 * expArg * Math.Cos(arg);
|
||||
_c3 = -(expArg * expArg);
|
||||
double c1 = (1.0 + _c2 - _c3) / 4.0;
|
||||
|
||||
_k0 = 1.0 - c1;
|
||||
_k1 = 2.0 * c1 - _c2;
|
||||
_k2 = -(c1 + _c3);
|
||||
|
||||
Name = $"Usi({period})";
|
||||
WarmupPeriod = period + SmaLen;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates USI with specified source and period.
|
||||
/// </summary>
|
||||
public Usi(ITValuePublisher source, int period = 28) : this(period)
|
||||
{
|
||||
source.Pub += Handle;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates USI with a TSeries source, primes from history, then subscribes.
|
||||
/// </summary>
|
||||
public Usi(TSeries source, int period = 28) : 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 >= WarmupPeriod;
|
||||
|
||||
public override void Prime(ReadOnlySpan<double> source, TimeSpan? step = null)
|
||||
{
|
||||
if (source.Length == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_s = State.New();
|
||||
_ps = State.New();
|
||||
|
||||
for (int i = 0; i < source.Length; i++)
|
||||
{
|
||||
double val = source[i];
|
||||
if (double.IsFinite(val))
|
||||
{
|
||||
_s.LastValid = val;
|
||||
}
|
||||
else
|
||||
{
|
||||
val = _s.LastValid;
|
||||
}
|
||||
|
||||
Step(val);
|
||||
}
|
||||
|
||||
Last = new TValue(DateTime.MinValue, _s.Usi);
|
||||
_ps = _s;
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void Handle(object? sender, in TValueEventArgs e) => Update(e.Value, e.IsNew);
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
|
||||
public override TValue Update(TValue input, bool isNew = true)
|
||||
{
|
||||
if (isNew)
|
||||
{
|
||||
_ps = _s;
|
||||
}
|
||||
else
|
||||
{
|
||||
_s = _ps;
|
||||
}
|
||||
|
||||
double val = input.Value;
|
||||
if (double.IsFinite(val))
|
||||
{
|
||||
_s.LastValid = val;
|
||||
}
|
||||
else
|
||||
{
|
||||
val = _s.LastValid;
|
||||
}
|
||||
|
||||
Step(val);
|
||||
|
||||
Last = new TValue(input.Time, _s.Usi);
|
||||
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] = _s.Usi;
|
||||
}
|
||||
|
||||
_ps = _s;
|
||||
Last = new TValue(tSpan[len - 1], vSpan[len - 1]);
|
||||
|
||||
return new TSeries(t, v);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Core streaming step: SU/SD → SMA(4) → UltimateSmoother → normalize.
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
|
||||
private void Step(double close)
|
||||
{
|
||||
_s.Count++;
|
||||
|
||||
// First bar: seed PrevClose, no SU/SD yet
|
||||
if (double.IsNaN(_s.PrevClose))
|
||||
{
|
||||
_s.PrevClose = close;
|
||||
return;
|
||||
}
|
||||
|
||||
// --- Strength Up / Strength Down ---
|
||||
double diff = close - _s.PrevClose;
|
||||
double su = diff > 0 ? diff : 0.0;
|
||||
double sd = diff < 0 ? -diff : 0.0;
|
||||
_s.PrevClose = close;
|
||||
|
||||
// --- SMA(4) circular buffer for SU ---
|
||||
int idx = _s.BufIdx & 3; // idx mod 4
|
||||
switch (idx)
|
||||
{
|
||||
case 0: _s.Su0 = su; _s.Sd0 = sd; break;
|
||||
case 1: _s.Su1 = su; _s.Sd1 = sd; break;
|
||||
case 2: _s.Su2 = su; _s.Sd2 = sd; break;
|
||||
case 3: _s.Su3 = su; _s.Sd3 = sd; break;
|
||||
}
|
||||
_s.BufIdx++;
|
||||
|
||||
double avgSu = (_s.Su0 + _s.Su1 + _s.Su2 + _s.Su3) * 0.25;
|
||||
double avgSd = (_s.Sd0 + _s.Sd1 + _s.Sd2 + _s.Sd3) * 0.25;
|
||||
|
||||
// --- UltimateSmoother for USU and USD ---
|
||||
double usu, usd;
|
||||
if (_s.Count < 8)
|
||||
{
|
||||
// Bootstrap: pass-through before IIR has enough history
|
||||
usu = avgSu;
|
||||
usd = avgSd;
|
||||
}
|
||||
else
|
||||
{
|
||||
// USF IIR: k0*avg + k1*avg[1] + k2*avg[2] + c2*USF[1] + c3*USF[2]
|
||||
usu = Math.FusedMultiplyAdd(_c3, _s.Usu2,
|
||||
Math.FusedMultiplyAdd(_c2, _s.Usu1,
|
||||
Math.FusedMultiplyAdd(_k2, _s.AvgSu2,
|
||||
Math.FusedMultiplyAdd(_k1, _s.AvgSu1, _k0 * avgSu))));
|
||||
|
||||
usd = Math.FusedMultiplyAdd(_c3, _s.Usd2,
|
||||
Math.FusedMultiplyAdd(_c2, _s.Usd1,
|
||||
Math.FusedMultiplyAdd(_k2, _s.AvgSd2,
|
||||
Math.FusedMultiplyAdd(_k1, _s.AvgSd1, _k0 * avgSd))));
|
||||
}
|
||||
|
||||
// Shift IIR state
|
||||
_s.Usu2 = _s.Usu1;
|
||||
_s.Usu1 = usu;
|
||||
_s.AvgSu2 = _s.AvgSu1;
|
||||
_s.AvgSu1 = avgSu;
|
||||
|
||||
_s.Usd2 = _s.Usd1;
|
||||
_s.Usd1 = usd;
|
||||
_s.AvgSd2 = _s.AvgSd1;
|
||||
_s.AvgSd1 = avgSd;
|
||||
|
||||
// --- Normalization ---
|
||||
double denom = usu + usd;
|
||||
if (denom > MinSmoothed)
|
||||
{
|
||||
_s.Usi = Math.Clamp((usu - usd) / denom, -1.0, 1.0);
|
||||
}
|
||||
// else: keep previous _s.Usi value (denominator near zero = flat market)
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Batch calculation returning a TSeries.
|
||||
/// </summary>
|
||||
public static TSeries Batch(TSeries source, int period = 28)
|
||||
{
|
||||
var indicator = new Usi(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 = 28)
|
||||
{
|
||||
if (source.Length != output.Length)
|
||||
{
|
||||
throw new ArgumentException("Source and output must have the same length", nameof(output));
|
||||
}
|
||||
if (period <= 0)
|
||||
{
|
||||
throw new ArgumentException("Period must be greater than 0", nameof(period));
|
||||
}
|
||||
|
||||
if (source.Length == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var indicator = new Usi(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._s.Usi;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a hot indicator from historical data, ready for streaming.
|
||||
/// </summary>
|
||||
public static (TSeries Results, Usi Indicator) Calculate(TSeries source, int period = 28)
|
||||
{
|
||||
var indicator = new Usi(period);
|
||||
TSeries results = indicator.Update(source);
|
||||
return (results, indicator);
|
||||
}
|
||||
|
||||
public override void Reset()
|
||||
{
|
||||
_s = State.New();
|
||||
_ps = _s;
|
||||
Last = default;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
# USI: Ehlers Ultimate Strength Index
|
||||
|
||||
> *Where RSI plods with Wilder's smoothing, USI sprints with the UltimateSmoother — symmetric, lag-free, and ready for the modern trader.*
|
||||
|
||||
| Property | Value |
|
||||
| ---------------- | -------------------------------- |
|
||||
| **Category** | Oscillator |
|
||||
| **Inputs** | Source (close) |
|
||||
| **Parameters** | `period` (default 28) |
|
||||
| **Outputs** | Single series (Usi) |
|
||||
| **Output range** | Bounded [-1, +1] |
|
||||
| **Warmup** | `period + 4` bars |
|
||||
| **PineScript** | [usi.pine](usi.pine) |
|
||||
|
||||
- USI (Ultimate Strength Index) replaces the RSI's Wilder smoothing with Ehlers' UltimateSmoother filter, producing a symmetric oscillator bounded [-1, +1] with significantly reduced lag.
|
||||
- **Similar:** [RSI](../../momentum/rsi/Rsi.md), [RRSI](../rrsi/Rrsi.md), [RSIH](../rsih/Rsih.md) | **Complementary:** ADX for trend confirmation | **Trading note:** Bullish above 0, bearish below 0; ±0.4 levels indicate strong momentum. Typically uses longer periods than RSI (28 vs 14) for comparable behavior.
|
||||
- No external validation libraries implement USI. Validated through self-consistency and behavioral testing.
|
||||
|
||||
USI is Ehlers' 2024 reimagining of the classic RSI. Instead of Wilder's exponential smoothing, it applies the UltimateSmoother filter — which subtracts high-frequency noise via a highpass filter — to the short-term average of upward and downward price movements. The result is an oscillator that responds to trend changes faster than RSI while maintaining comparable smoothness with a longer lookback.
|
||||
|
||||
## Historical Context
|
||||
|
||||
John F. Ehlers published the Ultimate Strength Index in the November 2024 issue of *Technical Analysis of Stocks & Commodities* magazine under the title "Ultimate Strength Index (USI)." The article presents USI as a direct replacement for Wilder's RSI, leveraging the UltimateSmoother filter (introduced earlier in April 2024 TASC) to achieve dramatically reduced lag. Unlike RSI's 0-100 range, USI is centered at zero with a [-1, +1] range, making bullish/bearish conditions immediately apparent.
|
||||
|
||||
## Architecture & Physics
|
||||
|
||||
### Stage 1: Strength Extraction
|
||||
|
||||
$$\text{SU} = \max(0, \text{Close} - \text{Close}[1])$$
|
||||
$$\text{SD} = \max(0, \text{Close}[1] - \text{Close})$$
|
||||
|
||||
Simple decomposition of price changes into upward (SU) and downward (SD) components, identical to the RSI approach.
|
||||
|
||||
### Stage 2: Short-Term Averaging (SMA-4)
|
||||
|
||||
$$\text{avgSU} = \frac{1}{4}\sum_{k=0}^{3}\text{SU}[k]$$
|
||||
$$\text{avgSD} = \frac{1}{4}\sum_{k=0}^{3}\text{SD}[k]$$
|
||||
|
||||
A 4-bar simple moving average smooths the binary SU/SD signals into continuous streams before the UltimateSmoother processes them.
|
||||
|
||||
### Stage 3: UltimateSmoother Filter
|
||||
|
||||
$$\arg = \frac{\sqrt{2}\pi}{\text{period}}$$
|
||||
$$a_1 = e^{-\arg}, \quad c_2 = 2a_1\cos(\arg), \quad c_3 = -a_1^2$$
|
||||
$$c_1 = \frac{1 + c_2 - c_3}{4}$$
|
||||
|
||||
$$\text{USU} = (1 - c_1) \cdot \text{avgSU} + (2c_1 - c_2) \cdot \text{avgSU}[1] - (c_1 + c_3) \cdot \text{avgSU}[2] + c_2 \cdot \text{USU}[1] + c_3 \cdot \text{USU}[2]$$
|
||||
$$\text{USD} = (1 - c_1) \cdot \text{avgSD} + (2c_1 - c_2) \cdot \text{avgSD}[1] - (c_1 + c_3) \cdot \text{avgSD}[2] + c_2 \cdot \text{USD}[1] + c_3 \cdot \text{USD}[2]$$
|
||||
|
||||
The same UltimateSmoother IIR filter is applied independently to both the SU and SD paths.
|
||||
|
||||
### Stage 4: Symmetric Normalization
|
||||
|
||||
$$\text{USI} = \frac{\text{USU} - \text{USD}}{\text{USU} + \text{USD}}, \quad \text{when USU} > \varepsilon \text{ and USD} > \varepsilon$$
|
||||
|
||||
The normalization produces a [-1, +1] range (unlike RSI's [0, 100]). When the denominator is near zero or either component is below the minimum threshold (ε = 0.01), the previous USI value is held.
|
||||
|
||||
## Performance Profile
|
||||
|
||||
### Operation Count (Streaming Mode, Scalar)
|
||||
|
||||
| Step | Multiplications | Additions | Total |
|
||||
|------|----------------|-----------|-------|
|
||||
| SU/SD extraction | 0 | 1 comparison + 1 subtraction | 2 |
|
||||
| SMA(4) buffer update | 1 | 3 | 4 |
|
||||
| USF for SU path | 5 FMA | 0 | 5 |
|
||||
| USF for SD path | 5 FMA | 0 | 5 |
|
||||
| Normalization | 1 | 2 | 3 |
|
||||
| **Total** | **~12** | **~6** | **~19 ops** |
|
||||
|
||||
### Batch Mode (SIMD Analysis)
|
||||
|
||||
The UltimateSmoother is an IIR filter (output depends on previous outputs), limiting SIMD vectorization. However, the SU/SD extraction and SMA averaging stages could benefit from SIMD in large batches. Current implementation uses scalar FMA for maximum precision.
|
||||
|
||||
### Quality Metrics
|
||||
|
||||
| Metric | Value |
|
||||
|--------|-------|
|
||||
| Complexity | O(1) per bar |
|
||||
| Memory | ~160 bytes (State struct, no heap) |
|
||||
| Allocations | Zero in hot path |
|
||||
| FMA usage | 10 FMA operations (5 per USF path) |
|
||||
|
||||
## Validation
|
||||
|
||||
| Method | Result |
|
||||
|--------|--------|
|
||||
| 4-API consistency | Streaming, batch TSeries, batch Span, Calculate all match |
|
||||
| Bar correction | State rollback via `_s`/`_ps` pattern |
|
||||
| Constant input | USI → 0 (equal SU and SD after smoothing converges) |
|
||||
| Monotonic trend | USI → +1 (all SU, no SD) |
|
||||
| Monotonic downtrend | USI → -1 (all SD, no SU) |
|
||||
| NaN handling | Non-finite inputs substituted with last valid value |
|
||||
| Bounded output | Always in [-1, +1] after warmup |
|
||||
|
||||
### Behavioral Test Summary
|
||||
|
||||
| Test | Expected |
|
||||
|------|----------|
|
||||
| Constant series | USI = 0 (no strength differential) |
|
||||
| Strong uptrend | USI approaches +1 |
|
||||
| Strong downtrend | USI approaches -1 |
|
||||
| Alternating up/down | USI oscillates near 0 |
|
||||
| Long period smoother | Slower, less noisy response |
|
||||
| Short period sharper | Faster, more responsive |
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
1. **Period too short**: With period < 10, the UltimateSmoother provides insufficient smoothing and USI becomes noisy.
|
||||
2. **Comparing to RSI periods**: USI typically needs a longer period than RSI for comparable behavior (28 vs 14 is a common mapping).
|
||||
3. **Zero-denominator regime**: When prices are flat (both USU and USD near zero), USI holds its previous value rather than computing an undefined ratio.
|
||||
4. **Bootstrap phase**: The first ~8 bars use pass-through instead of the IIR filter, producing unreliable values during warmup.
|
||||
|
||||
## References
|
||||
|
||||
1. Ehlers, J.F. (2024). "Ultimate Strength Index (USI)." *Technical Analysis of Stocks & Commodities*, November 2024.
|
||||
2. Ehlers, J.F. (2024). "The Ultimate Smoother." *Technical Analysis of Stocks & Commodities*, March/April 2024.
|
||||
3. PineScript implementation: [usi.pine](usi.pine)
|
||||
@@ -0,0 +1,154 @@
|
||||
using TradingPlatform.BusinessLayer;
|
||||
|
||||
namespace QuanTAlib.Tests;
|
||||
|
||||
public class UsiIndicatorTests
|
||||
{
|
||||
[Fact]
|
||||
public void UsiIndicator_Constructor_SetsDefaults()
|
||||
{
|
||||
var indicator = new UsiIndicator();
|
||||
|
||||
Assert.Equal(28, indicator.Period);
|
||||
Assert.Equal(SourceType.Close, indicator.Source);
|
||||
Assert.True(indicator.ShowColdValues);
|
||||
Assert.Equal("USI - Ehlers Ultimate Strength Index", indicator.Name);
|
||||
Assert.True(indicator.SeparateWindow);
|
||||
Assert.True(indicator.OnBackGround);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UsiIndicator_MinHistoryDepths_EqualsZero()
|
||||
{
|
||||
var indicator = new UsiIndicator();
|
||||
|
||||
Assert.Equal(0, UsiIndicator.MinHistoryDepths);
|
||||
Assert.Equal(0, ((IWatchlistIndicator)indicator).MinHistoryDepths);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UsiIndicator_ShortName_IncludesPeriodAndSource()
|
||||
{
|
||||
var indicator = new UsiIndicator { Period = 14 };
|
||||
|
||||
Assert.Contains("USI", indicator.ShortName, StringComparison.Ordinal);
|
||||
Assert.Contains("14", indicator.ShortName, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UsiIndicator_SourceCodeLink_IsValid()
|
||||
{
|
||||
var indicator = new UsiIndicator();
|
||||
|
||||
Assert.Contains("github.com", indicator.SourceCodeLink, StringComparison.Ordinal);
|
||||
Assert.Contains("Usi.Quantower.cs", indicator.SourceCodeLink, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UsiIndicator_Initialize_CreatesInternalIndicator()
|
||||
{
|
||||
var indicator = new UsiIndicator { Period = 28 };
|
||||
|
||||
indicator.Initialize();
|
||||
|
||||
Assert.Single(indicator.LinesSeries);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UsiIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
|
||||
{
|
||||
var indicator = new UsiIndicator { Period = 5 };
|
||||
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 UsiIndicator_ProcessUpdate_NewBar_ComputesValue()
|
||||
{
|
||||
var indicator = new UsiIndicator { Period = 5 };
|
||||
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 UsiIndicator_InternalIndicator_HandlesBarCorrection()
|
||||
{
|
||||
var ma = new Usi(5);
|
||||
double[] prices = [100, 102, 99, 103, 97, 104, 98, 105, 97, 106,
|
||||
101, 103, 98, 104, 96, 105, 99, 107, 98, 108];
|
||||
|
||||
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 significantly different value
|
||||
ma.Update(new TValue(now.AddMinutes(19).Ticks, 200), isNew: false);
|
||||
double afterCorrection = ma.Last.Value;
|
||||
|
||||
Assert.NotEqual(beforeCorrection, afterCorrection);
|
||||
Assert.True(double.IsFinite(afterCorrection));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UsiIndicator_DifferentSourceTypes()
|
||||
{
|
||||
foreach (SourceType sourceType in new[] { SourceType.Close, SourceType.Open, SourceType.High, SourceType.Low })
|
||||
{
|
||||
var indicator = new UsiIndicator();
|
||||
indicator.Source = sourceType;
|
||||
Assert.Equal(sourceType, indicator.Source);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UsiIndicator_MultipleHistoricalBars()
|
||||
{
|
||||
var indicator = new UsiIndicator { 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 UsiIndicator_PeriodChange_UpdatesConfig()
|
||||
{
|
||||
var indicator = new UsiIndicator();
|
||||
indicator.Period = 14;
|
||||
Assert.Equal(14, indicator.Period);
|
||||
|
||||
indicator.Period = 56;
|
||||
Assert.Equal(56, indicator.Period);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,523 @@
|
||||
namespace QuanTAlib;
|
||||
|
||||
public class UsiTests
|
||||
{
|
||||
private const int DefaultPeriod = 28;
|
||||
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_ThrowsArgumentException()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Usi(0));
|
||||
Assert.Equal("period", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_NegativePeriod_ThrowsArgumentException()
|
||||
{
|
||||
var ex = Assert.Throws<ArgumentException>(() => new Usi(-5));
|
||||
Assert.Equal("period", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_ValidPeriod_SetsNameAndWarmup()
|
||||
{
|
||||
var indicator = new Usi(28);
|
||||
Assert.Equal("Usi(28)", indicator.Name);
|
||||
Assert.Equal(32, indicator.WarmupPeriod); // 28 + 4
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_PeriodOne_IsValid()
|
||||
{
|
||||
var indicator = new Usi(1);
|
||||
Assert.Equal("Usi(1)", indicator.Name);
|
||||
Assert.Equal(5, indicator.WarmupPeriod); // 1 + 4
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_DefaultPeriod_IsTwentyEight()
|
||||
{
|
||||
var indicator = new Usi();
|
||||
Assert.Equal("Usi(28)", indicator.Name);
|
||||
}
|
||||
|
||||
// ========== B) Basic Calculation ==========
|
||||
|
||||
[Fact]
|
||||
public void Update_ReturnsTValue_WithValidProperties()
|
||||
{
|
||||
var indicator = new Usi(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 Usi(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 Usi(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 Usi(10);
|
||||
|
||||
for (int i = 0; i < 50; 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(60), 200.0), isNew: true);
|
||||
TValue r2 = indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(61), 50.0), isNew: true);
|
||||
|
||||
Assert.NotEqual(r1.Value, r2.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsNew_False_RewritesCurrentBar()
|
||||
{
|
||||
var indicator = new Usi(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(prices.Length), 200.0), isNew: true);
|
||||
double afterNew = indicator.Last.Value;
|
||||
|
||||
indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(prices.Length), 50.0), isNew: false);
|
||||
double afterCorrection = indicator.Last.Value;
|
||||
|
||||
Assert.NotEqual(afterNew, afterCorrection);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IterativeCorrections_RestoreState()
|
||||
{
|
||||
var indicator = new Usi(10);
|
||||
TSeries data = MakeSeries();
|
||||
|
||||
for (int i = 0; i < 80; i++)
|
||||
{
|
||||
indicator.Update(data[i], isNew: true);
|
||||
}
|
||||
|
||||
indicator.Update(data[80], isNew: true);
|
||||
|
||||
for (int j = 0; j < 5; j++)
|
||||
{
|
||||
indicator.Update(data[80], isNew: false);
|
||||
}
|
||||
|
||||
double afterCorrections = indicator.Last.Value;
|
||||
|
||||
var fresh = new Usi(10);
|
||||
for (int i = 0; i <= 80; i++)
|
||||
{
|
||||
fresh.Update(data[i], isNew: true);
|
||||
}
|
||||
|
||||
Assert.Equal(fresh.Last.Value, afterCorrections, Tolerance);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reset_ClearsState()
|
||||
{
|
||||
var indicator = new Usi(DefaultPeriod);
|
||||
|
||||
for (int i = 0; i < 100; 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 Usi(10);
|
||||
int hotAt = -1;
|
||||
|
||||
for (int i = 0; i < 200; i++)
|
||||
{
|
||||
indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0 + i * 0.1));
|
||||
if (indicator.IsHot && hotAt < 0)
|
||||
{
|
||||
hotAt = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Assert.InRange(hotAt, 1, 200);
|
||||
}
|
||||
|
||||
// ========== E) Robustness ==========
|
||||
|
||||
[Fact]
|
||||
public void NaN_Input_UsesLastValidValue()
|
||||
{
|
||||
var indicator = new Usi(10);
|
||||
|
||||
for (int i = 0; i < 50; i++)
|
||||
{
|
||||
indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0 + i * 0.1));
|
||||
}
|
||||
|
||||
TValue nanResult = indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(50), double.NaN));
|
||||
|
||||
Assert.True(double.IsFinite(nanResult.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Infinity_Input_UsesLastValidValue()
|
||||
{
|
||||
var indicator = new Usi(10);
|
||||
|
||||
for (int i = 0; i < 50; i++)
|
||||
{
|
||||
indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0 + i * 0.1));
|
||||
}
|
||||
|
||||
TValue infResult = indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(50), 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;
|
||||
|
||||
Usi.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 = 14;
|
||||
TSeries data = MakeSeries();
|
||||
|
||||
// 1. Batch (TSeries)
|
||||
TSeries batchResults = Usi.Batch(data, period);
|
||||
double expected = batchResults.Last.Value;
|
||||
|
||||
// 2. Span batch
|
||||
var tValues = data.Values.ToArray();
|
||||
var spanOutput = new double[tValues.Length];
|
||||
Usi.Batch(new ReadOnlySpan<double>(tValues), spanOutput, period);
|
||||
double spanResult = spanOutput[^1];
|
||||
|
||||
// 3. Streaming
|
||||
var streaming = new Usi(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 Usi(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>(() => Usi.Batch(source, output, 14));
|
||||
Assert.Equal("output", ex.ParamName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SpanBatch_ZeroPeriod_ThrowsArgumentException()
|
||||
{
|
||||
double[] source = new double[10];
|
||||
double[] output = new double[10];
|
||||
|
||||
Assert.Throws<ArgumentException>(() => Usi.Batch(source, output, 0));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SpanBatch_EmptyInput_ProducesEmptyOutput()
|
||||
{
|
||||
double[] source = Array.Empty<double>();
|
||||
double[] output = Array.Empty<double>();
|
||||
var ex = Record.Exception(() => Usi.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;
|
||||
}
|
||||
|
||||
Usi.Batch(source, output, 28);
|
||||
|
||||
Assert.True(double.IsFinite(output[size - 1]));
|
||||
}
|
||||
|
||||
// ========== H) Chainability ==========
|
||||
|
||||
[Fact]
|
||||
public void Pub_EventFires_OnUpdate()
|
||||
{
|
||||
var indicator = new Usi(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 Usi(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, Usi indicator) = Usi.Calculate(data, DefaultPeriod);
|
||||
|
||||
Assert.Equal(data.Count, results.Count);
|
||||
Assert.True(indicator.IsHot);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void StaticCalculate_MatchesInstance()
|
||||
{
|
||||
const int period = 14;
|
||||
int count = 100;
|
||||
var source = new TSeries();
|
||||
var indicator = new Usi(period);
|
||||
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
source.Add(new TValue(DateTime.UtcNow.AddMinutes(i), i + 10));
|
||||
indicator.Update(source.Last);
|
||||
}
|
||||
|
||||
var staticResult = Usi.Batch(source, period);
|
||||
|
||||
Assert.Equal(source.Count, staticResult.Count);
|
||||
Assert.Equal(indicator.Last.Value, staticResult.Last.Value, 8);
|
||||
}
|
||||
|
||||
// ========== USI-specific: Oscillator behavior ==========
|
||||
|
||||
[Fact]
|
||||
public void ConstantInput_OutputConvergesToZero()
|
||||
{
|
||||
var indicator = new Usi(14);
|
||||
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 → SU=0, SD=0 → USI stays at 0
|
||||
Assert.Equal(0.0, lastResult, 1e-10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void StrongUptrend_USI_ApproachesPositiveOne()
|
||||
{
|
||||
var indicator = new Usi(14);
|
||||
double lastResult = 0.0;
|
||||
|
||||
for (int i = 0; i < 200; i++)
|
||||
{
|
||||
TValue r = indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0 + i * 2.0));
|
||||
lastResult = r.Value;
|
||||
}
|
||||
|
||||
// Strong uptrend: SU always > 0, SD always = 0
|
||||
// USI should approach +1
|
||||
Assert.True(lastResult > 0.5, $"Expected USI > 0.5 for uptrend, got {lastResult}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void StrongDowntrend_USI_ApproachesNegativeOne()
|
||||
{
|
||||
var indicator = new Usi(14);
|
||||
double lastResult = 0.0;
|
||||
|
||||
for (int i = 0; i < 200; i++)
|
||||
{
|
||||
TValue r = indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 500.0 - i * 2.0));
|
||||
lastResult = r.Value;
|
||||
}
|
||||
|
||||
// Strong downtrend: SD always > 0, SU always = 0
|
||||
// USI should approach -1
|
||||
Assert.True(lastResult < -0.5, $"Expected USI < -0.5 for downtrend, got {lastResult}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Output_IsBounded()
|
||||
{
|
||||
var indicator = new Usi(14);
|
||||
TSeries data = MakeSeries(500);
|
||||
|
||||
for (int i = 0; i < data.Count; i++)
|
||||
{
|
||||
TValue r = indicator.Update(data[i]);
|
||||
Assert.InRange(r.Value, -1.01, 1.01);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UsiIsSymmetric_UpVsDown()
|
||||
{
|
||||
var up = new Usi(14);
|
||||
var down = new Usi(14);
|
||||
|
||||
for (int i = 0; i < 100; 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(double.IsFinite(up.Last.Value));
|
||||
Assert.True(double.IsFinite(down.Last.Value));
|
||||
// USI of uptrend and downtrend should have opposite signs
|
||||
Assert.True(up.Last.Value > 0, "Uptrend USI should be positive");
|
||||
Assert.True(down.Last.Value < 0, "Downtrend USI should be negative");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UsiProducesFiniteValues_OnGBMData()
|
||||
{
|
||||
var indicator = new Usi(14);
|
||||
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);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(5)]
|
||||
[InlineData(14)]
|
||||
[InlineData(28)]
|
||||
[InlineData(56)]
|
||||
public void DifferentPeriods_AllProduceFiniteResults(int period)
|
||||
{
|
||||
var indicator = new Usi(period);
|
||||
TSeries data = MakeSeries(300);
|
||||
|
||||
for (int i = 0; i < data.Count; i++)
|
||||
{
|
||||
TValue r = indicator.Update(data[i]);
|
||||
Assert.True(double.IsFinite(r.Value), $"Non-finite at bar {i} with period {period}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
// Licensed under the Apache License, Version 2.0
|
||||
// © mihakralj
|
||||
//@version=6
|
||||
indicator("Ehlers Ultimate Strength Index (USI)", "USI", overlay = false)
|
||||
|
||||
//@function Ehlers Ultimate Strength Index — a symmetric RSI replacement that uses
|
||||
// the UltimateSmoother filter instead of Wilder's exponential smoothing.
|
||||
// Output is bounded [-1, +1], with bullish > 0 and bearish < 0.
|
||||
// Pipeline: SU/SD extraction → SMA(4) → UltimateSmoother(period) → normalize.
|
||||
//@param source Series of close prices
|
||||
//@param period UltimateSmoother filter period (default 28)
|
||||
//@returns USI value bounded [-1, +1]
|
||||
//@reference Ehlers, J.F. (2024). "Ultimate Strength Index (USI)."
|
||||
// Technical Analysis of Stocks & Commodities, Nov 2024.
|
||||
//@optimized O(1) per bar — inline SMA(4) circular buffer + IIR filter
|
||||
usi(series float source, simple int period) =>
|
||||
if period < 1
|
||||
runtime.error("Period must be at least 1")
|
||||
|
||||
float src = nz(source)
|
||||
float prevSrc = nz(source[1])
|
||||
|
||||
// --- Strength Up / Strength Down ---
|
||||
float su = src > prevSrc ? src - prevSrc : 0.0
|
||||
float sd = prevSrc > src ? prevSrc - src : 0.0
|
||||
|
||||
// --- Simple Moving Average of SU and SD over 4 bars ---
|
||||
float avgSU = math.avg(su, nz(su[1]), nz(su[2]), nz(su[3]))
|
||||
float avgSD = math.avg(sd, nz(sd[1]), nz(sd[2]), nz(sd[3]))
|
||||
|
||||
// --- UltimateSmoother coefficients ---
|
||||
float a1 = math.exp(-1.414 * math.pi / period)
|
||||
float c2 = 2.0 * a1 * math.cos(1.414 * math.pi / period)
|
||||
float c3 = -a1 * a1
|
||||
float c1 = (1.0 + c2 - c3) / 4.0
|
||||
|
||||
// --- UltimateSmoother of avgSU ---
|
||||
var float usu = 0.0
|
||||
if bar_index < 7
|
||||
usu := avgSU
|
||||
else
|
||||
usu := (1.0 - c1) * avgSU + (2.0 * c1 - c2) * nz(avgSU[1]) - (c1 + c3) * nz(avgSU[2]) + c2 * nz(usu[1]) + c3 * nz(usu[2])
|
||||
|
||||
// --- UltimateSmoother of avgSD ---
|
||||
var float usd = 0.0
|
||||
if bar_index < 7
|
||||
usd := avgSD
|
||||
else
|
||||
usd := (1.0 - c1) * avgSD + (2.0 * c1 - c2) * nz(avgSD[1]) - (c1 + c3) * nz(avgSD[2]) + c2 * nz(usd[1]) + c3 * nz(usd[2])
|
||||
|
||||
// --- USI normalization ---
|
||||
float denom = usu + usd
|
||||
float eps = 0.01
|
||||
var float usiVal = 0.0
|
||||
if denom > eps
|
||||
usiVal := (usu - usd) / denom
|
||||
usiVal
|
||||
|
||||
// ——— Inputs ———
|
||||
int prd = input.int(28, "Period", minval = 1, tooltip = "UltimateSmoother filter period")
|
||||
string src = input.string("Close", "Source", options = ["Open","High","Low","Close","HL2","HLC3","HLCC4","OHLC4"])
|
||||
|
||||
// ——— Source selector ———
|
||||
float price = switch src
|
||||
"Open" => open
|
||||
"High" => high
|
||||
"Low" => low
|
||||
"HL2" => hl2
|
||||
"HLC3" => hlc3
|
||||
"HLCC4" => (high + low + close + close) / 4.0
|
||||
"OHLC4" => ohlc4
|
||||
=> close
|
||||
|
||||
// ——— Calculation & plot ———
|
||||
float val = usi(price, prd)
|
||||
hline(0, "Zero", color.gray, hline.style_dotted)
|
||||
hline(0.4, "+0.4", color.new(color.green, 60), hline.style_dashed)
|
||||
hline(-0.4, "-0.4", color.new(color.red, 60), hline.style_dashed)
|
||||
plot(val, "USI", val >= 0 ? color.teal : color.red, 2)
|
||||
Reference in New Issue
Block a user