feat(dynamics): add PlusDI, MinusDI, PlusDM, MinusDM indicators

Complete thin Dx-composition wrapper indicators with full test coverage:

- PlusDi/MinusDi: Directional Indicator wrappers (DiPlus/DiMinus from Dx)
- PlusDm/MinusDm: Directional Movement wrappers (DmPlus/DmMinus from Dx)
- Individual validation tests per indicator directory (TALib, Skender, bounds)
- Combined unit tests (DiDm.Tests.cs) and validation tests (DiDm.Validation.Tests.cs)
- Quantower wrappers + tests for all 4 indicators
- PineScript v6 implementations with compensated RMA
- Normalized .md documentation for all indicators and categories
- 182 tests passing, 0 failures
This commit is contained in:
Miha Kralj
2026-03-11 20:21:52 -07:00
parent 56b86bebfb
commit 33d20f2a18
437 changed files with 4589 additions and 2792 deletions
@@ -0,0 +1,73 @@
using TradingPlatform.BusinessLayer;
using QuanTAlib;
namespace QuanTAlib.Tests;
public class MinusDiIndicatorTests
{
[Fact]
public void MinusDiIndicator_Constructor_SetsDefaults()
{
var indicator = new MinusDiIndicator();
Assert.Equal(14, indicator.Period);
Assert.True(indicator.ShowColdValues);
Assert.Equal("-DI - Minus Directional Indicator", indicator.Name);
Assert.True(indicator.SeparateWindow);
Assert.True(indicator.OnBackGround);
}
[Fact]
public void MinusDiIndicator_MinHistoryDepths_EqualsZero()
{
var indicator = new MinusDiIndicator { Period = 20 };
Assert.Equal(0, MinusDiIndicator.MinHistoryDepths);
IWatchlistIndicator watchlistIndicator = indicator;
Assert.Equal(0, watchlistIndicator.MinHistoryDepths);
}
[Fact]
public void MinusDiIndicator_Initialize_CreatesInternal()
{
var indicator = new MinusDiIndicator { Period = 14 };
indicator.Initialize();
Assert.Single(indicator.LinesSeries);
}
[Fact]
public void MinusDiIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
{
var indicator = new MinusDiIndicator { Period = 5 };
indicator.Initialize();
var now = DateTime.UtcNow;
for (int i = 0; i < 20; i++)
{
indicator.HistoricalData.AddBar(now.AddMinutes(i), 100 + i, 110 + i, 90 + i, 105 + i);
var args = new UpdateArgs(UpdateReason.HistoricalBar);
indicator.ProcessUpdate(args);
}
double value = indicator.LinesSeries[0].GetValue(0);
Assert.True(double.IsFinite(value));
}
[Fact]
public void MinusDiIndicator_ShortName_IsCorrect()
{
var indicator = new MinusDiIndicator { Period = 20 };
Assert.Equal("-DI 20", indicator.ShortName);
}
[Fact]
public void MinusDiIndicator_SourceCodeLink_IsValid()
{
var indicator = new MinusDiIndicator();
Assert.Contains("github.com", indicator.SourceCodeLink, StringComparison.OrdinalIgnoreCase);
Assert.Contains("MinusDi.Quantower.cs", indicator.SourceCodeLink, StringComparison.OrdinalIgnoreCase);
}
}
+51
View File
@@ -0,0 +1,51 @@
using System.Drawing;
using System.Runtime.CompilerServices;
using TradingPlatform.BusinessLayer;
namespace QuanTAlib;
[SkipLocalsInit]
public sealed class MinusDiIndicator : Indicator, IWatchlistIndicator
{
[InputParameter("Period", sortIndex: 1, 1, 1000, 1, 0)]
public int Period { get; set; } = 14;
[InputParameter("Show cold values", sortIndex: 21)]
public bool ShowColdValues { get; set; } = true;
private MinusDi _minusDi = null!;
private readonly LineSeries _minusDiSeries;
public static int MinHistoryDepths => 0;
int IWatchlistIndicator.MinHistoryDepths => MinHistoryDepths;
public override string ShortName => $"-DI {Period}";
public override string SourceCodeLink => "https://github.com/mihakralj/QuanTAlib/blob/main/lib/dynamics/minusdi/MinusDi.Quantower.cs";
public MinusDiIndicator()
{
OnBackGround = true;
SeparateWindow = true;
Name = "-DI - Minus Directional Indicator";
Description = "Measures downward directional movement as a percentage of true range";
_minusDiSeries = new LineSeries(name: "-DI", color: Color.Red, width: 2, style: LineStyle.Solid);
AddLineSeries(_minusDiSeries);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override void OnInit()
{
_minusDi = new MinusDi(Period);
base.OnInit();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override void OnUpdate(UpdateArgs args)
{
TValue result = _minusDi.Update(this.GetInputBar(args), args.IsNewBar());
_minusDiSeries.SetValue(result.Value, _minusDi.IsHot, ShowColdValues);
}
}
@@ -0,0 +1,288 @@
using OoplesFinance.StockIndicators;
using OoplesFinance.StockIndicators.Models;
using OoplesFinance.StockIndicators.Enums;
using Skender.Stock.Indicators;
using TALib;
using QuanTAlib.Tests;
namespace QuanTAlib;
/// <summary>
/// Validation tests for MinusDi (-DI). Cross-validates against TA-Lib, Skender,
/// OoplesFinance, and internal Dx equivalence with multiple periods.
/// </summary>
public sealed class MinusDiValidationTests : IDisposable
{
private readonly ValidationTestData _data;
public MinusDiValidationTests()
{
_data = new ValidationTestData();
}
public void Dispose()
{
_data.Dispose();
}
// ═══════════════════════════════════════════════
// TA-Lib Validation
// ═══════════════════════════════════════════════
[Fact]
public void MatchesTalib()
{
var indicator = new MinusDi(14);
var results = new List<double>();
for (int i = 0; i < _data.Bars.Count; i++)
{
indicator.Update(_data.Bars[i]);
results.Add(indicator.Last.Value);
}
double[] hData = _data.Bars.High.Select(x => x.Value).ToArray();
double[] lData = _data.Bars.Low.Select(x => x.Value).ToArray();
double[] cData = _data.Bars.Close.Select(x => x.Value).ToArray();
double[] outReal = new double[_data.Bars.Count];
var retCode = Functions.MinusDI(hData, lData, cData, 0..^0, outReal, out var outRange, 14);
Assert.Equal(TALib.Core.RetCode.Success, retCode);
int lookback = Functions.MinusDILookback(14);
ValidationHelper.VerifyData(results, outReal, outRange, lookback);
}
[Theory]
[InlineData(7)]
[InlineData(21)]
[InlineData(28)]
public void MatchesTalib_VariousPeriods(int period)
{
var indicator = new MinusDi(period);
var results = new List<double>();
for (int i = 0; i < _data.Bars.Count; i++)
{
indicator.Update(_data.Bars[i]);
results.Add(indicator.Last.Value);
}
double[] hData = _data.Bars.High.Select(x => x.Value).ToArray();
double[] lData = _data.Bars.Low.Select(x => x.Value).ToArray();
double[] cData = _data.Bars.Close.Select(x => x.Value).ToArray();
double[] outReal = new double[_data.Bars.Count];
var retCode = Functions.MinusDI(hData, lData, cData, 0..^0, outReal, out var outRange, period);
Assert.Equal(TALib.Core.RetCode.Success, retCode);
int lookback = Functions.MinusDILookback(period);
ValidationHelper.VerifyData(results, outReal, outRange, lookback);
}
// ═══════════════════════════════════════════════
// Skender Validation
// ═══════════════════════════════════════════════
[Fact]
public void MatchesSkender()
{
var indicator = new MinusDi(14);
var results = new List<double>();
for (int i = 0; i < _data.Bars.Count; i++)
{
indicator.Update(_data.Bars[i]);
results.Add(indicator.Last.Value);
}
var skenderResults = _data.SkenderQuotes.GetAdx(14).ToList();
ValidationHelper.VerifyData(results, skenderResults, x => x.Mdi);
}
[Theory]
[InlineData(7)]
[InlineData(21)]
[InlineData(28)]
public void MatchesSkender_VariousPeriods(int period)
{
var indicator = new MinusDi(period);
var results = new List<double>();
for (int i = 0; i < _data.Bars.Count; i++)
{
indicator.Update(_data.Bars[i]);
results.Add(indicator.Last.Value);
}
var skenderResults = _data.SkenderQuotes.GetAdx(period).ToList();
ValidationHelper.VerifyData(results, skenderResults, x => x.Mdi);
}
// ═══════════════════════════════════════════════
// Dx Equivalence
// ═══════════════════════════════════════════════
[Fact]
public void ExactlyMatchesDx_DiMinus()
{
var indicator = new MinusDi(14);
var dx = new Dx(14);
for (int i = 0; i < _data.Bars.Count; i++)
{
indicator.Update(_data.Bars[i]);
dx.Update(_data.Bars[i]);
Assert.Equal(dx.DiMinus.Value, indicator.Last.Value, 1e-12);
}
}
// ═══════════════════════════════════════════════
// OoplesFinance Structural Validation
// ═══════════════════════════════════════════════
[Fact]
public void MatchesOoples_Structural()
{
var ooplesData = _data.SkenderQuotes
.Select(q => new TickerData
{
Date = q.Date,
Open = (double)q.Open,
High = (double)q.High,
Low = (double)q.Low,
Close = (double)q.Close,
Volume = (double)q.Volume
})
.ToList();
var stockData = new StockData(ooplesData);
var adxResults = stockData.CalculateAverageDirectionalIndex(MovingAvgType.WildersSmoothingMethod, 14);
var allValues = adxResults.OutputValues.Values.SelectMany(v => v).ToList();
int finiteCount = allValues.Count(v => double.IsFinite(v));
Assert.True(finiteCount > 100, $"Expected >100 finite Ooples DI values, got {finiteCount}");
}
// ═══════════════════════════════════════════════
// Self-Consistency: Batch == Streaming
// ═══════════════════════════════════════════════
[Fact]
public void BatchEqualsStreaming()
{
var batchResults = MinusDi.Batch(_data.Bars, 14);
var streaming = new MinusDi(14);
var streamResults = new List<double>();
for (int i = 0; i < _data.Bars.Count; i++)
{
streamResults.Add(streaming.Update(_data.Bars[i]).Value);
}
Assert.Equal(streamResults.Count, batchResults.Count);
for (int i = 0; i < batchResults.Count; i++)
{
Assert.Equal(streamResults[i], batchResults.Values[i], 1e-9);
}
}
[Fact]
public void BatchMatchesTalib()
{
var batchResults = MinusDi.Batch(_data.Bars, 14);
double[] hData = _data.Bars.High.Select(x => x.Value).ToArray();
double[] lData = _data.Bars.Low.Select(x => x.Value).ToArray();
double[] cData = _data.Bars.Close.Select(x => x.Value).ToArray();
double[] outReal = new double[_data.Bars.Count];
var retCode = Functions.MinusDI(hData, lData, cData, 0..^0, outReal, out var outRange, 14);
Assert.Equal(TALib.Core.RetCode.Success, retCode);
int lookback = Functions.MinusDILookback(14);
ValidationHelper.VerifyData(batchResults.Select(x => x.Value).ToList(), outReal, outRange, lookback);
}
// ═══════════════════════════════════════════════
// Determinism
// ═══════════════════════════════════════════════
[Fact]
public void ConsistentAcrossMultipleRuns()
{
var ind1 = new MinusDi(14);
var ind2 = new MinusDi(14);
var results1 = new List<double>();
var results2 = new List<double>();
for (int i = 0; i < _data.Bars.Count; i++)
{
ind1.Update(_data.Bars[i]);
results1.Add(ind1.Last.Value);
}
for (int i = 0; i < _data.Bars.Count; i++)
{
ind2.Update(_data.Bars[i]);
results2.Add(ind2.Last.Value);
}
for (int i = 0; i < _data.Bars.Count; i++)
{
Assert.Equal(results1[i], results2[i], 1e-10);
}
}
// ═══════════════════════════════════════════════
// Output Range Validation
// ═══════════════════════════════════════════════
[Fact]
public void OutputIsNonNegative()
{
var indicator = new MinusDi(14);
for (int i = 0; i < _data.Bars.Count; i++)
{
indicator.Update(_data.Bars[i]);
Assert.True(indicator.Last.Value >= 0, $"-DI output at bar {i} was {indicator.Last.Value}");
}
}
[Fact]
public void OutputBounded0To100()
{
var indicator = new MinusDi(14);
for (int i = 0; i < _data.Bars.Count; i++)
{
indicator.Update(_data.Bars[i]);
double val = indicator.Last.Value;
if (i >= 14)
{
Assert.True(val >= 0 && val <= 100, $"-DI at bar {i} was {val}, expected [0,100]");
}
}
}
// ═══════════════════════════════════════════════
// Different Periods Produce Different Results
// ═══════════════════════════════════════════════
[Fact]
public void DifferentPeriods_ProduceDifferentResults()
{
var short7 = new MinusDi(7);
var long28 = new MinusDi(28);
for (int i = 0; i < _data.Bars.Count; i++)
{
short7.Update(_data.Bars[i]);
long28.Update(_data.Bars[i]);
}
Assert.NotEqual(short7.Last.Value, long28.Last.Value);
}
}
+91 -21
View File
@@ -1,30 +1,100 @@
# MINUS_DI: Minus Directional Indicator
Measures downward directional movement strength as a percentage (0-100).
> *-DI isolates downward directional thrust as a fraction of true range — the bearish arm of Wilder's directional system.*
## Introduction
The Minus Directional Indicator (-DI) measures the strength of downward price movement relative to the true range. It is one of the components of the Directional Movement System developed by J. Welles Wilder Jr.
| Property | Value |
| ---------------- | -------------------------------- |
| **Category** | Dynamic |
| **Inputs** | OHLCV bar (TBar) |
| **Parameters** | `period` (default 14) |
| **Outputs** | Single series |
| **Output range** | 0 to 100 |
| **Warmup** | `period` bars |
| **PineScript** | [minusdi.pine](minusdi.pine) |
When -DI is rising, downward price pressure is increasing. When -DI crosses above +DI, it signals a potential bearish trend. The -DI line is commonly plotted alongside +DI to visualize directional balance.
- The Minus Directional Indicator measures the strength of downward price movement relative to true range.
- Parameterized by `period` (default 14).
- Output range: 0 to 100.
- Requires `period` bars of warmup before first valid output (IsHot = true).
- Validated against TA-Lib, Skender, and Dx equivalence.
## Calculation
-DI = Smoothed(-DM) / Smoothed(TR) × 100
The Minus Directional Indicator (-DI) is one component of J. Welles Wilder Jr.'s Directional Movement System. It quantifies the fraction of recent true range attributable to downward price extension. The computation smooths both -DM (minus directional movement) and TR (true range) with Wilder's RMA ($\alpha = 1/N$), then divides: $-DI = 100 \times \text{Smooth}(-DM) / \text{Smooth}(TR)$. When -DI rises, downward price pressure is increasing. When -DI crosses above +DI, it signals a potential bearish trend. The -DI line is commonly plotted alongside +DI to visualize directional balance.
Where:
- -DM (Minus Directional Movement) = max(PrevLow - Low, 0) when PrevLow - Low > High - PrevHigh, else 0
- TR (True Range) = max(High - Low, |High - PrevClose|, |Low - PrevClose|)
- Smoothing uses Wilder's method: Smooth = Smooth - Smooth/N + Input
## Historical Context
## Parameters
| Parameter | Default | Range | Description |
| :--- | :--- | :--- | :--- |
| Period | 14 | 2-∞ | Wilder smoothing period |
J. Welles Wilder Jr. introduced the Directional Movement System in *New Concepts in Technical Trading Systems* (1978). The system decomposes price range into directional components. +DI and -DI are the normalized indicators from which DX and ADX are derived. While most traders focus on ADX for trend strength, +DI and -DI remain essential for determining trend *direction* — a bearish signal occurs when -DI crosses above +DI, bullish when +DI crosses above -DI.
## Interpretation
- **Rising -DI:** Strengthening downward movement
- **-DI > +DI:** Bears dominate; potential downtrend
- **-DI crossover above +DI:** Bearish signal
- **High -DI (>40):** Strong downward momentum
## Architecture & Physics
## References
- Wilder, J. Welles Jr. "New Concepts in Technical Trading Systems" (1978)
### 1. Minus Directional Movement
$$\text{UpMove} = H_t - H_{t-1}, \quad \text{DownMove} = L_{t-1} - L_t$$
$$-DM = \begin{cases} \text{DownMove} & \text{if DownMove} > \text{UpMove and DownMove} > 0 \\ 0 & \text{otherwise} \end{cases}$$
### 2. True Range
$$TR = \max(H_t - L_t,\; |H_t - C_{t-1}|,\; |L_t - C_{t-1}|)$$
### 3. Wilder Smoothing (RMA)
$$-DM_{\text{smooth}} = \text{RMA}(-DM, N), \quad TR_{\text{smooth}} = \text{RMA}(TR, N)$$
### 4. Minus Directional Indicator
$$-DI = 100 \times \frac{-DM_{\text{smooth}}}{TR_{\text{smooth}}}$$
When $TR_{\text{smooth}} = 0$ (no price movement), -DI = 0.
### 5. Complexity
- **Time:** $O(1)$ per bar — all RMA updates are recursive
- **Space:** $O(1)$ — scalar state only (delegates to Dx)
- **Warmup:** $N$ bars
## Mathematical Foundation
### Parameters
| Symbol | Parameter | Default | Constraint |
|--------|-----------|---------|------------|
| $N$ | period | 14 | $N \geq 2$ |
### Interpretation
| -DI Value | Signal |
|-----------|--------|
| Rising -DI | Strengthening downward movement |
| -DI > +DI | Bears dominate; potential downtrend |
| -DI crossover above +DI | Bearish signal |
| High -DI (>40) | Strong downward momentum |
-DI measures directional *strength*, not absolute direction. Compare +DI vs -DI for directional bias: if $-DI > +DI$, the trend is down.
## Performance Profile
### Operation Count (Streaming Mode)
-DI is a thin wrapper around Dx. The per-bar cost is identical to Dx (one property extraction after Dx completes its update).
**Post-warmup steady state (per bar):**
| Operation | Count | Cost (cycles) | Subtotal |
| :--- | :---: | :---: | :---: |
| Dx.Update (full pipeline) | 1 | 75 | 75 |
| Property extraction | 1 | 1 | 1 |
| **Total** | **2** | — | **~76 cycles** |
### Quality Metrics
| Metric | Score | Notes |
| :--- | :---: | :--- |
| **Accuracy** | 9/10 | Exact Dx delegation; FMA-precise RMA smoothing |
| **Timeliness** | 7/10 | N-bar warmup; responds to bar-level changes |
| **Smoothness** | 7/10 | Single RMA layer; moderate noise suppression |
| **Noise Rejection** | 7/10 | Wilder smoothing filters transient spikes |
## Resources
- Wilder, J.W. — *New Concepts in Technical Trading Systems* (Trend Research, 1978)
- PineScript reference: `minusdi.pine` in indicator directory
+55
View File
@@ -0,0 +1,55 @@
// Licensed under the Apache License, Version 2.0
// © mihakralj
//@version=6
indicator("Minus Directional Indicator (-DI)", "-DI", overlay=false)
//@function Calculates -DI using Wilder's smoothing with compensated RMA
//@param period Number of bars used in the calculation
//@returns -DI value (0-100)
//@optimized Uses Wilder's smoothing (RMA) with warmup compensation for accurate values from bar 1
minusdi(simple int period) =>
if period <= 0
runtime.error("Period must be greater than 0")
float alpha = 1.0 / period
float beta = 1.0 - alpha
float tr = 0.0
float minus_dm = 0.0
if na(close[1])
tr := high - low
else
tr := math.max(high - low, math.max(math.abs(high - close[1]), math.abs(low - close[1])))
float upMove = high - high[1]
float downMove = low[1] - low
if downMove > upMove and downMove > 0
minus_dm := downMove
var bool warmup = true
var float e = 1.0
var float tr_ema = 0.0
var float tr_result = tr
var float minus_dm_ema = 0.0
var float minus_dm_result = minus_dm
tr_ema := alpha * (tr - tr_ema) + tr_ema
minus_dm_ema := alpha * (minus_dm - minus_dm_ema) + minus_dm_ema
if warmup
e *= beta
float c = 1.0 / (1.0 - e)
tr_result := c * tr_ema
minus_dm_result := c * minus_dm_ema
warmup := e > 1e-10
else
tr_result := tr_ema
minus_dm_result := minus_dm_ema
float minus_di = tr_result != 0.0 ? 100.0 * minus_dm_result / tr_result : 0.0
minus_di
// ---------- Main loop ----------
// Inputs
i_period = input.int(14, "Period", minval=1, tooltip="Number of bars used in the calculation")
// Calculation
minus_di = minusdi(i_period)
// Plot
plot(minus_di, "-DI", color=color.red, linewidth=2)
hline(25, "Threshold", color=color.gray, linestyle=hline.style_dashed)