mirror of
https://github.com/mihakralj/QuanTAlib.git
synced 2026-08-21 20:18:05 +00:00
Add new moving average implementations: LTMA, MCNMA, NLMA, NMA, NYQMA, RAIN, and TRAMA
- LTMA (Linear Trend Moving Average): Introduces a predictive moving average using dual cascaded EMAs for trend estimation. - MCNMA (McNicholl EMA): Implements a zero-lag TEMA using a cascaded EMA structure for enhanced responsiveness. - NLMA (Non-Lag Moving Average): Utilizes a damped cosine kernel to achieve reduced lag in moving averages. - NMA (Natural Moving Average): Adapts smoothing based on volatility profiles using a square-root kernel. - NYQMA (Nyquist Moving Average): Applies the Nyquist-Shannon theorem to prevent aliasing in cascaded moving averages. - RAIN (Rainbow Moving Average): Combines multiple SMA layers with weighted averages for multi-scale smoothing. - TRAMA (Trend Regularity Adaptive Moving Average): Adapts smoothing based on the frequency of new highs and lows in price data.
This commit is contained in:
+86
-38
@@ -1,65 +1,113 @@
|
||||
# SUPER: SuperTrend
|
||||
|
||||
> "It's not an indicator; it's a trailing stop with a marketing budget. Perfect for traders who want to catch the trend but lack the emotional discipline to hold on."
|
||||
> "It's not an indicator; it's a trailing stop with a marketing budget."
|
||||
|
||||
SuperTrend is a trend-following indicator that overlays the price chart. It uses the Average True Range (ATR) to calculate upper and lower volatility bands, switching between them based on the direction of the closing price. It effectively functions as a trailing stop-loss that adapts to market volatility.
|
||||
SuperTrend is a trend-following overlay that uses ATR-scaled bands around the HL2 midpoint, switching between upper and lower bands based on close price breakouts. A ratchet mechanism prevents the active band from moving against the trend, creating a step-like trailing stop that adapts to volatility. The indicator is a two-state machine (bullish/bearish) with O(1) per-bar updates and zero allocations in the hot path.
|
||||
|
||||
## Historical Context
|
||||
|
||||
Created by Olivier Seban. It gained massive popularity in the retail trading community for its visual simplicity: Green line = Buy, Red line = Sell. It combines the volatility measurement of Wilder's ATR with a simple breakout logic.
|
||||
Olivier Seban created SuperTrend, which gained massive popularity in the retail trading community for its visual simplicity: a single line that is green during uptrends and red during downtrends. The construction combines Wilder's ATR volatility measurement (1978) with a breakout/ratchet mechanism. Unlike moving-average crossover systems that produce continuous values, SuperTrend outputs a binary trend state with a concrete stop level, making it directly actionable as a trailing stop-loss. The indicator does not repaint historical values, though the current bar's value can oscillate until the close is finalized.
|
||||
|
||||
## Architecture & Physics
|
||||
|
||||
SuperTrend is a state machine. It maintains two theoretical bands (Upper and Lower) and a boolean state (`IsBullish`).
|
||||
### 1. Basic Bands
|
||||
|
||||
### The Ratchet Mechanism
|
||||
The raw bands center on the HL2 midpoint, offset by ATR times a multiplier:
|
||||
|
||||
The bands act as a ratchet:
|
||||
$$\text{Upper}_{\text{basic}} = \frac{H_t + L_t}{2} + m \cdot \text{ATR}(N)$$
|
||||
|
||||
* **Bullish Mode**: The Lower Band (Stop Loss) can only move up. If the calculated Lower Band drops, the indicator ignores it and keeps the previous value.
|
||||
* **Bearish Mode**: The Upper Band (Stop Loss) can only move down.
|
||||
$$\text{Lower}_{\text{basic}} = \frac{H_t + L_t}{2} - m \cdot \text{ATR}(N)$$
|
||||
|
||||
The trend flips when the Close price crosses the active band.
|
||||
where $m$ is the multiplier (default 3.0) and $N$ is the ATR period (default 10).
|
||||
|
||||
### 2. Ratchet Logic
|
||||
|
||||
The bands act as a one-way ratchet that prevents regression against the trend:
|
||||
|
||||
**Upper band** (bearish stop) can only move down:
|
||||
|
||||
$$\text{Upper}_{\text{final}} = \begin{cases} \min(\text{Upper}_{\text{basic}},\ \text{Upper}_{\text{prev}}) & \text{if } C_{t-1} \leq \text{Upper}_{\text{prev}} \\ \text{Upper}_{\text{basic}} & \text{otherwise} \end{cases}$$
|
||||
|
||||
**Lower band** (bullish stop) can only move up:
|
||||
|
||||
$$\text{Lower}_{\text{final}} = \begin{cases} \max(\text{Lower}_{\text{basic}},\ \text{Lower}_{\text{prev}}) & \text{if } C_{t-1} \geq \text{Lower}_{\text{prev}} \\ \text{Lower}_{\text{basic}} & \text{otherwise} \end{cases}$$
|
||||
|
||||
### 3. Trend State Machine
|
||||
|
||||
$$\text{Trend}_t = \begin{cases} \text{Bullish} & \text{if } C_t > \text{Upper}_{\text{final}} \\ \text{Bearish} & \text{if } C_t < \text{Lower}_{\text{final}} \\ \text{Trend}_{t-1} & \text{otherwise (hysteresis)} \end{cases}$$
|
||||
|
||||
$$\text{SuperTrend} = \begin{cases} \text{Lower}_{\text{final}} & \text{if Bullish} \\ \text{Upper}_{\text{final}} & \text{if Bearish} \end{cases}$$
|
||||
|
||||
The output is the active stop level. Crossing the active band flips the state.
|
||||
|
||||
### 4. Complexity
|
||||
|
||||
| Metric | Value |
|
||||
|:-------|:------|
|
||||
| Time | O(1) per bar |
|
||||
| Space | O(1) (ATR state + 2 band values + 1 trend boolean) |
|
||||
| Allocations | Zero in hot path |
|
||||
| Warmup | N bars (ATR stabilization) |
|
||||
|
||||
## Mathematical Foundation
|
||||
|
||||
### 1. Basic Bands
|
||||
### Parameters
|
||||
|
||||
$$ Upper_{basic} = \frac{High + Low}{2} + (Multiplier \times ATR) $$
|
||||
$$ Lower_{basic} = \frac{High + Low}{2} - (Multiplier \times ATR) $$
|
||||
| Parameter | Type | Default | Constraint | Description |
|
||||
|:----------|:-----|:--------|:-----------|:------------|
|
||||
| atrPeriod | int | 10 | > 0 | ATR lookback period |
|
||||
| multiplier | double | 3.0 | > 0 | ATR multiplier for band width |
|
||||
|
||||
### 2. Ratchet Logic (Bullish Example)
|
||||
### Pseudo-code
|
||||
|
||||
$$ Lower_{final} = \begin{cases} Lower_{basic} & \text{if } Lower_{basic} > Lower_{prev} \text{ or } Close_{prev} < Lower_{prev} \\ Lower_{prev} & \text{otherwise} \end{cases} $$
|
||||
```
|
||||
SUPERTREND(bar, atrPeriod=10, multiplier=3.0):
|
||||
|
||||
### 3. Trend Logic
|
||||
// ATR update (Wilder's smoothing or SMA)
|
||||
atr = ATR.Update(bar, atrPeriod)
|
||||
|
||||
$$ SuperTrend = \begin{cases} Lower_{final} & \text{if Bullish} \\ Upper_{final} & \text{if Bearish} \end{cases} $$
|
||||
// Basic bands
|
||||
hl2 = (bar.High + bar.Low) / 2
|
||||
upper_basic = hl2 + multiplier * atr
|
||||
lower_basic = hl2 - multiplier * atr
|
||||
|
||||
## Performance Profile
|
||||
// Ratchet: upper can only decrease, lower can only increase
|
||||
if prev_close <= prev_upper_final:
|
||||
upper_final = min(upper_basic, prev_upper_final)
|
||||
else:
|
||||
upper_final = upper_basic
|
||||
|
||||
| Metric | Score | Notes |
|
||||
| :--- | :--- | :--- |
|
||||
| **Throughput** | 9 | High; O(1) calculation with minimal overhead. |
|
||||
| **Allocations** | 0 | Zero-allocation in hot paths. |
|
||||
| **Complexity** | O(1) | Constant time regardless of period. |
|
||||
| **Accuracy** | 10 | Matches standard implementations exactly. |
|
||||
| **Timeliness** | 5 | Lag depends on ATR period and multiplier. |
|
||||
| **Overshoot** | 0 | Bands are constrained by price action. |
|
||||
| **Smoothness** | 2 | Step-like behavior; not a smooth curve. |
|
||||
if prev_close >= prev_lower_final:
|
||||
lower_final = max(lower_basic, prev_lower_final)
|
||||
else:
|
||||
lower_final = lower_basic
|
||||
|
||||
## Validation
|
||||
// State machine transition
|
||||
if bar.Close > upper_final:
|
||||
is_bullish = true
|
||||
else if bar.Close < lower_final:
|
||||
is_bullish = false
|
||||
// else: retain previous state (hysteresis)
|
||||
|
||||
| Library | Status | Notes |
|
||||
| :--- | :--- | :--- |
|
||||
| **QuanTAlib** | ✅ | Validated. |
|
||||
| **TA-Lib** | N/A | Not implemented. |
|
||||
| **Skender** | ✅ | Matches `GetSuperTrend` exactly. |
|
||||
| **Tulip** | N/A | Not implemented. |
|
||||
| **Ooples** | ❌ | Diverges significantly due to initialization logic. |
|
||||
// Output active stop level
|
||||
if is_bullish:
|
||||
supertrend = lower_final
|
||||
else:
|
||||
supertrend = upper_final
|
||||
|
||||
### Common Pitfalls
|
||||
return supertrend
|
||||
```
|
||||
|
||||
1. **Repainting**: SuperTrend does not repaint historical values, but the current bar's value can flip back and forth until the Close is finalized.
|
||||
2. **Whipsaws**: In ranging markets, SuperTrend will generate frequent false signals, buying the top and selling the bottom. It requires a trend filter (like ADX).
|
||||
3. **ATR Warmup**: The indicator requires $N$ bars to stabilize the ATR before the bands become accurate.
|
||||
### Band Behavior by State
|
||||
|
||||
| State | Active Band | Ratchet Direction | Flip Condition |
|
||||
|:------|:------------|:------------------|:---------------|
|
||||
| Bullish | Lower (support) | Can only rise | Close < Lower |
|
||||
| Bearish | Upper (resistance) | Can only fall | Close > Upper |
|
||||
|
||||
The step-like output results from the ratchet constraint: the band remains flat until a new extremum pushes it in the trend direction. Whipsaws occur in ranging markets where close repeatedly crosses both bands.
|
||||
|
||||
## Resources
|
||||
|
||||
- Seban, O. SuperTrend indicator documentation.
|
||||
- Wilder, J. W. (1978). *New Concepts in Technical Trading Systems*. Trend Research.
|
||||
|
||||
Reference in New Issue
Block a user