Add Choppiness Index (CHOP) implementation and tests

- Implemented ChopIndicator for Quantower with configurable period and cold value display.
- Created Chop class for calculating the Choppiness Index with detailed documentation.
- Added comprehensive unit tests for Chop functionality, covering various market conditions and edge cases.
- Developed markdown documentation for CHOP, detailing its historical context, mathematical foundation, and usage examples.
- Established a remediation plan for channel indicators documentation, identifying gaps and prioritizing updates.
This commit is contained in:
Miha Kralj
2026-02-05 19:42:49 -08:00
parent 95838a6435
commit 26280ce80b
73 changed files with 8485 additions and 5254 deletions
+84
View File
@@ -0,0 +1,84 @@
using TradingPlatform.BusinessLayer;
namespace QuanTAlib.Tests;
public class ChopIndicatorTests
{
[Fact]
public void ChopIndicator_Constructor_SetsDefaults()
{
var indicator = new ChopIndicator();
Assert.Equal(14, indicator.Period);
Assert.True(indicator.ShowColdValues);
Assert.Equal("Choppiness Index", indicator.Name);
Assert.True(indicator.SeparateWindow);
Assert.True(indicator.OnBackGround);
}
[Fact]
public void ChopIndicator_MinHistoryDepths_EqualsZero()
{
var indicator = new ChopIndicator { Period = 20 };
Assert.Equal(0, ChopIndicator.MinHistoryDepths);
IWatchlistIndicator watchlistIndicator = indicator;
Assert.Equal(0, watchlistIndicator.MinHistoryDepths);
}
[Fact]
public void ChopIndicator_ShortName_IncludesParameters()
{
var indicator = new ChopIndicator { Period = 20 };
indicator.Initialize();
Assert.Contains("CHOP", indicator.ShortName, StringComparison.Ordinal);
Assert.Contains("20", indicator.ShortName, StringComparison.Ordinal);
}
[Fact]
public void ChopIndicator_SourceCodeLink_IsValid()
{
var indicator = new ChopIndicator();
Assert.Contains("github.com", indicator.SourceCodeLink, StringComparison.Ordinal);
Assert.Contains("Chop.Quantower.cs", indicator.SourceCodeLink, StringComparison.Ordinal);
}
[Fact]
public void ChopIndicator_Initialize_CreatesInternalChop()
{
var indicator = new ChopIndicator { Period = 14 };
// Initialize should not throw
indicator.Initialize();
// After init, line series should exist (single CHOP line)
Assert.Single(indicator.LinesSeries);
}
[Fact]
public void ChopIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
{
var indicator = new ChopIndicator { Period = 5 };
indicator.Initialize();
// Add historical data
var now = DateTime.UtcNow;
// Need enough bars for Period
for (int i = 0; i < 20; i++)
{
indicator.HistoricalData.AddBar(now.AddMinutes(i), 100 + i, 110 + i, 90 + i, 105 + i);
// Process update for each bar to simulate history loading
var args = new UpdateArgs(UpdateReason.HistoricalBar);
indicator.ProcessUpdate(args);
}
// Line series should have a value
double chop = indicator.LinesSeries[0].GetValue(0);
Assert.True(double.IsFinite(chop));
Assert.InRange(chop, 0.0, 100.0);
}
}
+51
View File
@@ -0,0 +1,51 @@
using System.Drawing;
using System.Runtime.CompilerServices;
using TradingPlatform.BusinessLayer;
namespace QuanTAlib;
[SkipLocalsInit]
public sealed class ChopIndicator : Indicator, IWatchlistIndicator
{
[InputParameter("Period", sortIndex: 1, 2, 1000, 1, 0)]
public int Period { get; set; } = 14;
[InputParameter("Show cold values", sortIndex: 21)]
public bool ShowColdValues { get; set; } = true;
private Chop _chop = null!;
private readonly LineSeries _chopSeries;
public static int MinHistoryDepths => 0;
int IWatchlistIndicator.MinHistoryDepths => MinHistoryDepths;
public override string ShortName => $"CHOP {Period}";
public override string SourceCodeLink => "https://github.com/mihakralj/QuanTAlib/blob/main/lib/dynamics/chop/Chop.Quantower.cs";
public ChopIndicator()
{
OnBackGround = true;
SeparateWindow = true;
Name = "Choppiness Index";
Description = "Measures market trendiness (E.W. Dreiss)";
_chopSeries = new LineSeries(name: "CHOP", color: Color.Yellow, width: 2, style: LineStyle.Solid);
AddLineSeries(_chopSeries);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override void OnInit()
{
_chop = new Chop(Period);
base.OnInit();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override void OnUpdate(UpdateArgs args)
{
TValue result = _chop.Update(this.GetInputBar(args), args.IsNewBar());
_chopSeries.SetValue(result.Value, _chop.IsHot, ShowColdValues);
}
}
+312
View File
@@ -0,0 +1,312 @@
namespace QuanTAlib;
public class ChopTests
{
[Fact]
public void BasicCalculation_ProducesValidResults()
{
var chop = new Chop(14);
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 42);
var bars = gbm.Fetch(50, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
for (int i = 0; i < bars.Count; i++)
{
var result = chop.Update(bars[i]);
if (i >= 13) // WarmupPeriod = 14
{
// CHOP should be between 0 and 100
Assert.True(result.Value >= 0.0 && result.Value <= 100.0,
$"CHOP value {result.Value} at index {i} out of range [0, 100]");
}
}
Assert.True(chop.IsHot);
}
[Fact]
public void StrongTrend_ProducesLowChop()
{
// Create a strong trending market (steadily rising prices)
var chop = new Chop(14);
var bars = new TBarSeries();
// Generate trending bars: each bar higher than the last
for (int i = 0; i < 50; i++)
{
double basePrice = 100 + i * 2; // Strong uptrend
bars.Add(new TBar(
time: DateTime.UtcNow.AddMinutes(i),
open: basePrice - 0.5,
high: basePrice + 0.5,
low: basePrice - 0.5,
close: basePrice + 0.3,
volume: 1000
));
}
TValue result = default;
for (int i = 0; i < bars.Count; i++)
{
result = chop.Update(bars[i]);
}
// Strong trend should have low CHOP (< 50, ideally < 38.2)
Assert.True(result.Value < 50.0,
$"Strong trend should have low CHOP, got {result.Value}");
}
[Fact]
public void SidewaysMarket_ProducesHighChop()
{
// Create a choppy/sideways market (oscillating prices)
var chop = new Chop(14);
var bars = new TBarSeries();
// Generate choppy bars: prices oscillate in a range
for (int i = 0; i < 50; i++)
{
double oscillation = Math.Sin(i * 0.5) * 2; // Small oscillations
double basePrice = 100 + oscillation;
bars.Add(new TBar(
time: DateTime.UtcNow.AddMinutes(i),
open: basePrice - 1,
high: basePrice + 2,
low: basePrice - 2,
close: basePrice + 0.5,
volume: 1000
));
}
TValue result = default;
for (int i = 0; i < bars.Count; i++)
{
result = chop.Update(bars[i]);
}
// Sideways market should have high CHOP (> 50, ideally > 61.8)
Assert.True(result.Value > 50.0,
$"Choppy market should have high CHOP, got {result.Value}");
}
[Fact]
public void BarCorrection_RestoresState()
{
var chop = new Chop(14);
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 42);
var bars = gbm.Fetch(20, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
// Feed initial bars
for (int i = 0; i < 15; i++)
{
chop.Update(bars[i], isNew: true);
}
// Bar 15 processed, state is saved
// Process bar 16 as new
chop.Update(bars[15], isNew: true);
double valueAfter16New = chop.Last.Value;
// Now correct bar 16 (isNew=false) with a different bar
var modifiedBar = new TBar(
bars[15].Time,
bars[15].Open * 1.1,
bars[15].High * 1.2,
bars[15].Low * 0.9,
bars[15].Close * 1.15,
bars[15].Volume
);
chop.Update(modifiedBar, isNew: false);
double valueAfter16Corrected = chop.Last.Value;
// Corrected value should be different from the original bar 16 value
Assert.NotEqual(valueAfter16New, valueAfter16Corrected);
}
[Fact]
public void Reset_ClearsState()
{
var chop = new Chop(14);
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 42);
var bars = gbm.Fetch(20, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
// Feed bars to warm up
for (int i = 0; i < 15; i++)
{
chop.Update(bars[i]);
}
Assert.True(chop.IsHot);
// Reset
chop.Reset();
Assert.False(chop.IsHot);
Assert.Equal(0.0, chop.Last.Value);
}
[Fact]
public void Constructor_ThrowsForInvalidPeriod()
{
Assert.Throws<ArgumentException>(() => new Chop(1));
Assert.Throws<ArgumentException>(() => new Chop(0));
Assert.Throws<ArgumentException>(() => new Chop(-1));
}
[Fact]
public void NaN_Input_KeepsLastValidValue()
{
var chop = new Chop(14);
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 42);
var bars = gbm.Fetch(20, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
// Feed some valid bars first
for (int i = 0; i < 15; i++)
{
chop.Update(bars[i]);
}
double lastValidValue = chop.Last.Value;
// Create a bar with NaN values
var nanBar = new TBar(DateTime.UtcNow, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN);
var result = chop.Update(nanBar);
// Should keep last valid value
Assert.Equal(lastValidValue, result.Value);
}
[Fact]
public void Infinity_Input_KeepsLastValidValue()
{
var chop = new Chop(14);
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 42);
var bars = gbm.Fetch(20, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
// Feed some valid bars first
for (int i = 0; i < 15; i++)
{
chop.Update(bars[i]);
}
double lastValidValue = chop.Last.Value;
// Create a bar with Infinity values
var infBar = new TBar(DateTime.UtcNow, double.PositiveInfinity, double.PositiveInfinity, double.NegativeInfinity, double.PositiveInfinity, double.PositiveInfinity);
var result = chop.Update(infBar);
// Should keep last valid value
Assert.Equal(lastValidValue, result.Value);
}
[Fact]
public void BatchMode_ProducesValidResults()
{
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 42);
var bars = gbm.Fetch(50, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
var result = Chop.Batch(bars);
Assert.Equal(50, result.Count);
// Check that warmed-up values are in valid range
for (int i = 13; i < result.Count; i++)
{
Assert.True(result[i].Value >= 0.0 && result[i].Value <= 100.0,
$"CHOP value {result[i].Value} at index {i} out of range [0, 100]");
}
}
[Fact]
public void BatchModeWithPeriod_MatchesStreamingMode()
{
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.2, seed: 42);
var bars = gbm.Fetch(50, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
// Batch mode
var batchResult = Chop.Batch(bars, period: 10);
// Streaming mode
var streamingChop = new Chop(10);
for (int i = 0; i < bars.Count; i++)
{
streamingChop.Update(bars[i]);
}
// Results should match
Assert.Equal(batchResult.Last.Value, streamingChop.Last.Value, precision: 10);
}
[Fact]
public void Name_ReflectsPeriod()
{
var chop14 = new Chop(14);
var chop20 = new Chop(20);
Assert.Equal("CHOP(14)", chop14.Name);
Assert.Equal("CHOP(20)", chop20.Name);
}
[Fact]
public void Period_Property_ReturnsCorrectValue()
{
var chop = new Chop(21);
Assert.Equal(21, chop.Period);
}
[Fact]
public void WarmupPeriod_EqualsToPeriod()
{
var chop = new Chop(14);
Assert.Equal(14, chop.WarmupPeriod);
}
[Fact]
public void EventPublishing_Works()
{
var chop = new Chop(14);
var gbm = new GBM();
int eventCount = 0;
TValue lastPublishedValue = default;
bool lastIsNew = false;
chop.Pub += (object? sender, in TValueEventArgs args) =>
{
eventCount++;
lastPublishedValue = args.Value;
lastIsNew = args.IsNew;
};
var bar = gbm.Next(isNew: true);
chop.Update(bar, isNew: true);
Assert.Equal(1, eventCount);
Assert.True(lastIsNew);
Assert.Equal(chop.Last.Value, lastPublishedValue.Value);
// Update with isNew=false
chop.Update(bar, isNew: false);
Assert.Equal(2, eventCount);
Assert.False(lastIsNew);
}
[Fact]
public void ZeroPriceRange_ReturnsNaN()
{
// When all prices are the same, CHOP should return NaN (or handle gracefully)
var chop = new Chop(5);
// Create bars with identical high and low
for (int i = 0; i < 10; i++)
{
var bar = new TBar(DateTime.UtcNow.AddMinutes(i), 100, 100, 100, 100, 1000);
chop.Update(bar);
}
// Zero price range should result in NaN or clamped value
Assert.True(double.IsNaN(chop.Last.Value) || chop.Last.Value >= 0);
}
}
+259
View File
@@ -0,0 +1,259 @@
using System.Runtime.CompilerServices;
namespace QuanTAlib;
/// <summary>
/// CHOP: Choppiness Index
/// </summary>
/// <remarks>
/// Non-directional indicator measuring market trendiness (E.W. Dreiss).
/// Range [0-100]: Low values indicate trending, high values indicate choppy/sideways markets.
///
/// Calculation: <c>CHOP = 100 × LOG10(SUM(TR, n) / (MaxHigh - MinLow)) / LOG10(n)</c>.
///
/// Key Levels:
/// - Above 61.8: Market is consolidating (choppy)
/// - Below 38.2: Market is trending
/// - 50: Neutral midpoint
/// </remarks>
/// <seealso href="Chop.md">Detailed documentation</seealso>
[SkipLocalsInit]
public sealed class Chop : ITValuePublisher
{
private readonly int _period;
private readonly RingBuffer _trValues;
private readonly RingBuffer _highs;
private readonly RingBuffer _lows;
// Bar correction state
private double _trSum;
private double _savedTrSum;
private double _prevClose;
private double _savedPrevClose;
/// <summary>
/// Display name for the indicator.
/// </summary>
public string Name { get; }
public event TValuePublishedHandler? Pub;
/// <summary>
/// Current CHOP value.
/// </summary>
public TValue Last { get; private set; }
/// <summary>
/// True if the indicator has enough data for a full period calculation.
/// </summary>
public bool IsHot => _trValues.IsFull;
/// <summary>
/// The period parameter.
/// </summary>
public int Period => _period;
/// <summary>
/// The number of bars required for the indicator to warm up.
/// </summary>
public int WarmupPeriod { get; }
/// <summary>
/// Creates CHOP indicator with specified period.
/// </summary>
/// <param name="period">Lookback period (must be >= 2)</param>
public Chop(int period = 14)
{
if (period < 2)
{
throw new ArgumentException("Period must be at least 2", nameof(period));
}
_period = period;
Name = $"CHOP({period})";
WarmupPeriod = period;
_trValues = new RingBuffer(period);
_highs = new RingBuffer(period);
_lows = new RingBuffer(period);
_trSum = 0.0;
_savedTrSum = 0.0;
_prevClose = double.NaN;
_savedPrevClose = double.NaN;
}
/// <summary>
/// Resets the indicator state.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Reset()
{
_trValues.Clear();
_highs.Clear();
_lows.Clear();
_trSum = 0.0;
_savedTrSum = 0.0;
_prevClose = double.NaN;
_savedPrevClose = double.NaN;
Last = default;
}
/// <summary>
/// Updates the CHOP indicator with a new bar.
/// </summary>
/// <param name="input">The price bar (High, Low, Close required)</param>
/// <param name="isNew">True for new bar, false for update of current bar</param>
/// <returns>The current CHOP value</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TValue Update(TBar input, bool isNew = true)
{
double high = input.High;
double low = input.Low;
double close = input.Close;
// Handle NaN/Infinity inputs
if (!double.IsFinite(high) || !double.IsFinite(low) || !double.IsFinite(close))
{
Pub?.Invoke(this, new TValueEventArgs { Value = Last, IsNew = isNew });
return Last;
}
if (isNew)
{
// Save state for potential correction
_savedTrSum = _trSum;
_savedPrevClose = _prevClose;
}
else
{
// Restore state for correction
_trSum = _savedTrSum;
_prevClose = _savedPrevClose;
}
// Calculate True Range
double pc = double.IsNaN(_prevClose) ? close : _prevClose;
double tr = Math.Max(high - low, Math.Max(Math.Abs(high - pc), Math.Abs(low - pc)));
// Update rolling sum: subtract old value if buffer is full
if (_trValues.IsFull)
{
_trSum -= _trValues[0];
}
// Add new values to buffers
_trValues.Add(tr, isNew);
_highs.Add(high, isNew);
_lows.Add(low, isNew);
_trSum += tr;
// Update previous close for next bar
if (isNew)
{
_prevClose = close;
}
// Calculate CHOP if we have enough data
double chop = ComputeChop();
Last = new TValue(input.Time, chop);
Pub?.Invoke(this, new TValueEventArgs { Value = Last, IsNew = isNew });
return Last;
}
/// <summary>
/// Updates with a bar series.
/// </summary>
public TSeries Update(TBarSeries source)
{
if (source.Count == 0)
{
return new TSeries([], []);
}
int len = source.Count;
var tList = new List<long>(len);
var vList = new List<double>(len);
var times = source.Open.Times;
for (int i = 0; i < len; i++)
{
var result = Update(source[i], isNew: true);
tList.Add(times[i]);
vList.Add(result.Value);
}
return new TSeries(tList, vList);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private double ComputeChop()
{
int count = _trValues.Count;
if (count < 2)
{
return double.NaN;
}
// Find max high and min low in the period
double maxHigh = double.MinValue;
double minLow = double.MaxValue;
var highsBuffer = _highs.InternalBuffer;
var lowsBuffer = _lows.InternalBuffer;
int capacity = _highs.Capacity;
int start = _highs.StartIndex;
for (int i = 0; i < count; i++)
{
int idx = (start + i) % capacity;
double h = highsBuffer[idx];
double l = lowsBuffer[idx];
if (h > maxHigh)
{
maxHigh = h;
}
if (l < minLow)
{
minLow = l;
}
}
double priceRange = maxHigh - minLow;
// Avoid division by zero
if (priceRange <= 0.0)
{
return double.NaN;
}
// CHOP = 100 * LOG10(SUM_TR / RANGE) / LOG10(n)
double logRatio = Math.Log10(_trSum / priceRange);
double logN = Math.Log10(count);
double chop = 100.0 * logRatio / logN;
// Clamp to [0, 100]
return Math.Clamp(chop, 0.0, 100.0);
}
/// <summary>
/// Batch calculation with default parameters.
/// </summary>
public static TSeries Batch(TBarSeries source)
{
return Batch(source, period: 14);
}
/// <summary>
/// Batch calculation with specified parameters.
/// </summary>
public static TSeries Batch(TBarSeries source, int period)
{
var indicator = new Chop(period);
return indicator.Update(source);
}
}
+128
View File
@@ -0,0 +1,128 @@
# Choppiness Index (CHOP)
The **Choppiness Index** is a non-directional volatility indicator developed by Australian commodity trader **E.W. Dreiss**. It measures whether the market is trending or trading sideways (choppy), helping traders identify optimal conditions for trend-following or range-trading strategies.
## Historical Context
E.W. Dreiss created the Choppiness Index to help traders avoid whipsaw losses by identifying market conditions unsuitable for trend-following strategies. The indicator uses a logarithmic relationship between True Range sums and price channel width to quantify market "trendiness."
## Architecture & Physics
### The Physics of Market Trendiness
The Choppiness Index compares the sum of True Range values (total price movement) to the overall price channel (net movement). In a perfect trend, these would be nearly equal—price moves efficiently in one direction. In a choppy market, True Range accumulates rapidly while net movement (price channel) remains small.
```
Trending: Sum(TR) ≈ Price Channel → Low CHOP
Choppy: Sum(TR) >> Price Channel → High CHOP
```
### Logarithmic Scaling
The use of LOG10 normalizes the indicator to a 0-100 scale regardless of price level or volatility magnitude:
$$\text{CHOP} = 100 \times \frac{\log_{10}\left(\frac{\sum_{i=1}^{n} TR_i}{\text{MaxHigh}_n - \text{MinLow}_n}\right)}{\log_{10}(n)}$$
## Mathematical Foundation
**True Range (TR):**
$$TR = \max(H - L, |H - C_{prev}|, |L - C_{prev}|)$$
**Choppiness Index:**
$$CHOP = 100 \times \frac{\log_{10}\left(\frac{\sum TR_n}{H_{\max} - L_{\min}}\right)}{\log_{10}(n)}$$
Where:
- $n$ = Lookback period
- $\sum TR_n$ = Sum of True Range over n bars
- $H_{\max}$ = Highest high over n bars
- $L_{\min}$ = Lowest low over n bars
## Performance Profile
| Metric | Value |
|--------|-------|
| Time Complexity | O(n) per update |
| Space Complexity | O(n) ring buffers |
| Memory per Instance | ~24n bytes |
| Allocations | Zero in hot path |
### Zero-Allocation Design
The implementation uses three ring buffers for TR values, highs, and lows. Rolling sum for TR values avoids recalculation. Min/max search is O(n) but cache-friendly due to sequential memory access.
## Interpretation
| Level | Meaning | Strategy |
|-------|---------|----------|
| > 61.8 | High choppiness | Avoid trend strategies, use range trading |
| 38.2 - 61.8 | Neutral | Mixed conditions |
| < 38.2 | Low choppiness | Market trending, use trend-following |
**Key Insight:** CHOP does not indicate direction—only whether the market is trending or consolidating.
## Usage
### Streaming (Bar-by-Bar)
```csharp
var chop = new Chop(14);
foreach (var bar in bars)
{
TValue result = chop.Update(bar);
if (chop.IsHot)
{
if (result.Value < 38.2)
Console.WriteLine("Trending market - look for trend entries");
else if (result.Value > 61.8)
Console.WriteLine("Choppy market - avoid trend trades");
}
}
```
### Batch Processing
```csharp
var bars = dataSource.GetBars(100);
var chopSeries = Chop.Batch(bars, period: 14);
// Access results
foreach (var value in chopSeries)
{
Console.WriteLine($"CHOP: {value.Value:F2}");
}
```
### Bar Correction
```csharp
var chop = new Chop(14);
// New bar arrives
chop.Update(bar, isNew: true);
// Bar updates (same bar, corrected values)
chop.Update(correctedBar, isNew: false);
```
## Validation
| Reference | Match | Notes |
|-----------|-------|-------|
| TradingView | ✓ | Standard implementation |
| PineScript | ✓ | Matches chop.pine reference |
## Common Pitfalls
1. **Directional Bias**: CHOP does not indicate trend direction—use with directional indicators.
2. **Lag**: Like all indicators, CHOP lags price action; trend may start before CHOP confirms.
3. **Threshold Sensitivity**: 38.2 and 61.8 are guidelines; optimal levels vary by market.
## Related Indicators
- **ADX**: Another trend strength indicator (directional)
- **ATR**: True Range smoothed (volatility)
- **Aroon**: Trend timing based on high/low recency
## References
- Dreiss, E.W. - Original Choppiness Index development
- [TradingView CHOP Documentation](https://www.tradingview.com/support/solutions/43000501980)