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
+136 -77
View File
@@ -1,67 +1,64 @@
# STARCHANNEL: Stoller Average Range Channel
## Overview and Purpose
> "Volatility is the market's pulse—STARC channels let you feel it."
The Stoller Average Range Channel (STARCHANNEL) is a volatility-based channel indicator that creates an adaptive price envelope using the Average True Range (ATR) to determine the band width around a simple moving average centerline. Developed by Manning Stoller, this indicator provides dynamic support and resistance levels that automatically adjust to changing market volatility conditions. Unlike fixed percentage envelopes, STARCHANNEL expands during volatile periods and contracts during calmer markets, offering more relevant and responsive trading signals.
The Stoller Average Range Channel (STARCHANNEL) creates a volatility-adaptive price envelope using the Average True Range (ATR) to determine band width around a simple moving average centerline. Developed by Manning Stoller, this indicator provides dynamic support and resistance levels that automatically expand during volatile periods and contract during calmer marketsoffering more relevant and responsive trading signals than fixed percentage envelopes.
The implementation uses efficient circular buffer calculations for both the simple moving average and ATR, ensuring optimal performance while properly handling data gaps and initialization. By combining the stability of a simple moving average with the adaptive nature of ATR-based width calculations, STARCHANNEL creates a volatility-normalized trading framework that adapts to each security's specific volatility characteristics.
## Historical Context
## Core Concepts
Manning Stoller developed the STARC Bands in the early 1980s as a volatility-adaptive alternative to fixed percentage envelopes. His insight was simple: channels should widen during high volatility and contract during low volatility, reflecting actual market conditions rather than arbitrary percentages.
* **Volatility-adaptive envelope:** Channel automatically widens during volatile periods and narrows during calm markets, providing dynamic support/resistance levels
* **SMA-centered structure:** Uses a simple moving average of the price as the middle line, providing a stable reference point for mean reversion analysis
* **ATR-based width:** Calculates channel width using ATR multiplied by a configurable factor, making the bands proportional to actual market volatility
* **Customizable sensitivity:** Adjustable multiplier allows traders to fine-tune the channel to different trading styles, timeframes, and market conditions
The indicator combines two established concepts: the simple moving average (for trend direction) and Average True Range (for volatility measurement). J. Welles Wilder had already popularized ATR in his 1978 book "New Concepts in Technical Trading Systems." Stoller's contribution was recognizing that ATR-based bands would naturally adapt to each security's volatility characteristics.
STARCHANNEL improves upon traditional percentage-based channels by incorporating the ATR, which measures volatility based on a security's true range (accounting for gaps and limit moves). This approach ensures that the channel expands precisely when it should—during periods of high volatility—creating a more responsive and market-adaptive trading framework that reflects actual price movement characteristics.
STARC Bands gained popularity among futures traders in the 1980s and remain widely used today. The approach influenced many subsequent indicators that combine trend-following centerlines with volatility-based band widths.
## Common Settings and Parameters
## Architecture & Physics
| Parameter | Default | Function | When to Adjust |
| ------ | ------ | ------ | ------ |
| Period | 20 | Lookback period for both SMA and ATR calculations | Shorter (10-15) for more responsiveness to recent volatility; longer (30-50) for more stable channel and filtered signals |
| ATR Multiplier | 2.0 | Determines channel width as a multiple of ATR | Higher (2.5-3.0) for wider channel and fewer signals; lower (1.0-1.5) for tighter channel and more frequent signals |
| Source | source | Data source for centerline calculation | Can be modified to use typical price (hlc3) for a more balanced view of price action |
STARCHANNEL consists of three components: a simple moving average centerline and upper/lower bands at a configurable ATR multiple.
**Pro Tip:** For a comprehensive trading framework, try using multiple STARCHANNEL settings simultaneously. A narrower channel (1.0-1.5× ATR) can help identify minor retracements and short-term entry points, while a wider channel (2.5-3.0× ATR) can be used for major support/resistance zones and stop placement.
### 1. Simple Moving Average (Middle Band)
## Calculation and Mathematical Foundation
The centerline is a standard SMA of the close price:
**Simplified explanation:**
STARCHANNEL first calculates a middle line using a simple moving average of the source price. It then creates upper and lower channel boundaries by adding or subtracting the ATR (multiplied by a factor) from this middle line.
$$
\text{Middle}_t = \frac{1}{n} \sum_{i=0}^{n-1} C_{t-i}
$$
**Technical formula:**
where $C$ is the close price and $n$ is the period.
Middle Line = SMA(Source, Period)
Upper Channel = Middle Line + ATR(Period) × Multiplier
Lower Channel = Middle Line - ATR(Period) × Multiplier
### 2. True Range Calculation
Where:
* SMA = Simple Moving Average
* ATR = Average True Range calculated using Wilder's smoothing
* Period = Lookback period for calculations
* Multiplier = Factor for channel width
True Range captures the full extent of price movement including gaps:
> 🔍 **Technical Note:** The implementation uses optimized circular buffers to maintain rolling sums for SMA calculations and Wilder's smoothing method for ATR, ensuring O(1) computational complexity regardless of the lookback period. The ATR calculation includes proper initialization handling for early bars, with bias correction that prevents the common "warm-up effect" seen in many ATR implementations.
$$
TR_t = \max(H_t - L_t, |H_t - C_{t-1}|, |L_t - C_{t-1}|)
$$
## Interpretation Details
### 3. Average True Range (ATR)
STARCHANNEL provides several analytical frameworks for trading decisions:
ATR uses Wilder's smoothing (RMA) with warmup compensation:
* **Mean reversion opportunities:** Price touching or briefly exceeding a channel boundary often suggests a potential reversal toward the middle line, especially in range-bound markets
* **Trend strength assessment:** In strong trends, price will regularly touch or slightly exceed the channel in the trend direction while respecting the opposite boundary
* **Breakout confirmation:** Sustained price movement beyond a channel boundary after a period of contraction often signals a genuine breakout rather than a false move
* **Volatility shifts:** Sudden expansion of channel width indicates increasing volatility that may precede significant price moves
* **Support and resistance framework:** The middle line often acts as the first support/resistance level, while the outer boundaries represent more significant levels
* **Stop placement guide:** The channel boundaries provide logical stop-loss placement points based on a security's actual volatility
* **Timeframe alignment:** Comparing STARCHANNEL across multiple timeframes can identify high-probability setups where support/resistance aligns
* **Channel position analysis:** Price position within the channel (upper third, middle third, lower third) can indicate potential reversal zones
$$
ATR_t = \frac{ATR_{t-1} \times (n-1) + TR_t}{n}
$$
### 4. Channel Bands
Upper and lower bands are placed at a configurable ATR multiple:
$$
\text{Upper}_t = \text{Middle}_t + k \times ATR_t
$$
$$
\text{Lower}_t = \text{Middle}_t - k \times ATR_t
$$
where $k$ is the multiplier (default 2.0).
## Performance Profile
### Operation Count (Streaming Mode, per Bar)
STARCHANNEL combines SMA (centerline) with ATR (band width):
### Operation Count (Streaming Mode, Scalar)
| Operation | Count | Cost (cycles) | Subtotal |
| :--- | :---: | :---: | :---: |
@@ -71,28 +68,16 @@ STARCHANNEL combines SMA (centerline) with ATR (band width):
| CMP/ABS/MAX | 3 | 1 | 3 |
| **Total** | **14** | — | **~48 cycles** |
**Breakdown:**
- SMA update (running sum): 2 ADD + 1 DIV = 17 cycles
- True Range (3-way max): 2 SUB + 3 CMP = 5 cycles
- ATR (Wilder smoothing): 1 ADD + 1 MUL + 1 DIV = 19 cycles
- Band calculation: 1 ADD + 1 SUB + 2 MUL = 8 cycles
**Complexity:** O(1) per bar for streaming updates using running sums.
### Complexity Analysis
### Batch Mode (SIMD)
| Mode | Complexity | Notes |
| :--- | :---: | :--- |
| Streaming | O(1) | Running sums for SMA, EMA for ATR |
| Batch | O(n) | Linear scan |
**Memory**: ~32 bytes (SMA sum, ATR state, previous close)
### SIMD Analysis
| Optimization | Applicable | Notes |
| :--- | :---: | :--- |
| AVX2 vectorization | Partial | True Range calculation vectorizable |
| FMA | ✅ | Wilder smoothing: `prev + alpha * (tr - prev)` |
| Batch parallelism | ❌ | ATR recursive dependency |
| Operation | Scalar Ops | SIMD Benefit | Notes |
| :--- | :---: | :---: | :--- |
| True Range | 3N | 8× | Vectorizable |
| ATR (Wilder) | N | 1× | Sequential dependency |
| SMA running sum | N | 1× | Sequential |
| Band calculation | 4N | 8× | Vectorizable |
### Quality Metrics
@@ -103,22 +88,96 @@ STARCHANNEL combines SMA (centerline) with ATR (band width):
| **Overshoot** | 7/10 | Bands lag during volatility spikes |
| **Smoothness** | 8/10 | SMA centerline provides smooth reference |
## Limitations and Considerations
## Validation
* **Lagging nature:** As a moving average-based indicator incorporating ATR, the channel reacts to volatility changes with some delay
* **Parameter sensitivity:** Performance varies significantly based on period and multiplier settings, requiring optimization for specific securities
* **False signals in trending markets:** Channel touches may not indicate reversals during strong trends, potentially leading to premature position exits
* **Complementary tool requirement:** Most effective when combined with trend identification and momentum indicators
* **Volatility regime changes:** During sudden extreme volatility spikes, channel may widen with a delay, potentially after the optimal entry/exit point
* **Lookback period trade-offs:** Shorter periods increase responsiveness but also noise; longer periods provide stability but increase lag
* **Mean reversion assumption:** Implicitly assumes prices will revert to the mean (middle line), which doesn't always hold in strongly trending markets
* **Gap handling:** While ATR accounts for gaps, sudden large gaps can temporarily distort channel calculations
| Library | Status | Notes |
| :--- | :---: | :--- |
| **TA-Lib** | N/A | Not directly available |
| **Skender** | N/A | Not directly available |
| **Tulip** | N/A | Not directly available |
| **TradingView** | ✅ | Matches PineScript implementation |
| **Manual** | ✅ | Verified against hand calculations |
## Usage & Pitfalls
- **Lagging nature:** As a moving average-based indicator incorporating ATR, the channel reacts to volatility changes with some delay.
- **Parameter sensitivity:** Performance varies significantly based on period and multiplier settings, requiring optimization for specific securities.
- **False signals in trending markets:** Channel touches may not indicate reversals during strong trends, potentially leading to premature position exits.
- **Complementary tool requirement:** Most effective when combined with trend identification and momentum indicators.
- **Volatility regime changes:** During sudden extreme volatility spikes, channel may widen with a delay.
- **Lookback period trade-offs:** Shorter periods increase responsiveness but also noise; longer periods provide stability but increase lag.
- **Gap handling:** While ATR accounts for gaps, sudden large gaps can temporarily distort channel calculations.
## API
```mermaid
classDiagram
class Starchannel {
+string Name
+int WarmupPeriod
+TValue Last
+TValue Upper
+TValue Lower
+bool IsHot
+Starchannel(int period, double multiplier)
+Starchannel(TBarSeries source, int period, double multiplier)
+TValue Update(TBar input, bool isNew)
+Tuple~TSeries,TSeries,TSeries~ Update(TBarSeries source)
+void Prime(TBarSeries source)
+void Reset()
+static void Batch(ReadOnlySpan~double~ high, ReadOnlySpan~double~ low, ReadOnlySpan~double~ close, Span~double~ middle, Span~double~ upper, Span~double~ lower, int period, double multiplier)
+static Tuple~TSeries,TSeries,TSeries~ Batch(TBarSeries source, int period, double multiplier)
+static Tuple~Tuple~TSeries,TSeries,TSeries~,Starchannel~ Calculate(TBarSeries source, int period, double multiplier)
}
```
### Class: `Starchannel`
| Parameter | Type | Default | Range | Description |
| :--- | :--- | :--- | :--- | :--- |
| `period` | `int` | `20` | `≥1` | Lookback period for both SMA and ATR calculations. |
| `multiplier` | `double` | `2.0` | `>0` | ATR multiplier for band width. |
### Properties
- `Last` (`TValue`): The current SMA value (middle line).
- `Upper` (`TValue`): The upper band (SMA + multiplier × ATR).
- `Lower` (`TValue`): The lower band (SMA - multiplier × ATR).
- `IsHot` (`bool`): Returns `true` when warmup period is complete.
### Methods
- `Update(TBar input, bool isNew)`: Updates the indicator with a new bar and returns the result.
- `Update(TBarSeries source)`: Processes an entire bar series and returns (Middle, Upper, Lower) tuple of TSeries.
- `Prime(TBarSeries source)`: Initializes internal state from historical data.
- `Reset()`: Resets the indicator to its initial state.
- `Batch(...)`: Static method for zero-allocation span-based batch processing.
- `Calculate(TBarSeries source, int period, double multiplier)`: Static factory that returns results and indicator instance.
## C# Example
```csharp
using QuanTAlib;
// Initialize
var starchannel = new Starchannel(period: 20, multiplier: 2.0);
// Update Loop
foreach (var bar in quotes)
{
starchannel.Update(bar, isNew: true);
// Use valid results
if (starchannel.IsHot)
{
Console.WriteLine($"{bar.Time}: Mid={starchannel.Last.Value:F2}, Upper={starchannel.Upper.Value:F2}, Lower={starchannel.Lower.Value:F2}");
}
}
```
## References
* Stoller, M. (1980s). Development of the Stoller Average Range Channel concept
* Wilder, J. W. (1978). New Concepts in Technical Trading Systems. Trend Research.
* Kaufman, P. J. (2013). Trading Systems and Methods (5th ed.). John Wiley & Sons.
* Murphy, J. J. (1999). Technical Analysis of the Financial Markets. New York Institute of Finance.
* Brooks, A. (2006). Reading Price Charts Bar by Bar. John Wiley & Sons.
* Elder, A. (2014). The New Trading for a Living. John Wiley & Sons.
- Stoller, M. (1980s). Development of the Stoller Average Range Channel concept.
- Wilder, J. W. (1978). *New Concepts in Technical Trading Systems*. Trend Research.
- Kaufman, P. J. (2013). *Trading Systems and Methods*, 5th ed. John Wiley & Sons.
- Murphy, J. J. (1999). *Technical Analysis of the Financial Markets*. New York Institute of Finance.