Skip to main content

indicators/signal/
vol_regime.rs

1//! Volume-regime helpers: rolling percentile tracker, volatility regime classifier,
2//! and a simple MA-slope market regime classifier.
3//!
4//! These are ported from the Python `VolatilityPercentile`, `PercentileTracker`,
5//! and `MarketRegime` classes in `indicators.py`.
6//!
7//! Note: `MarketRegimeTracker` is distinct from the statistical `MarketRegime` enum
8//! in `types.rs` — it is a simpler slope-based classifier used by the signal engine.
9
10use std::collections::{HashMap, VecDeque};
11
12use crate::error::IndicatorError;
13use crate::indicator::{Indicator, IndicatorOutput};
14use crate::registry::param_usize;
15use crate::types::Candle;
16
17// ── Params ────────────────────────────────────────────────────────────────────
18
19#[derive(Debug, Clone)]
20pub struct VolumeRegimeParams {
21    /// ATR period for computing true-range inputs to the percentile tracker.
22    pub atr_period: usize,
23    /// Rolling window for the [`PercentileTracker`].
24    pub pct_window: usize,
25}
26
27impl Default for VolumeRegimeParams {
28    fn default() -> Self {
29        Self {
30            atr_period: 14,
31            pct_window: 100,
32        }
33    }
34}
35
36// ── Indicator struct ──────────────────────────────────────────────────────────
37
38/// Batch `Indicator` wrapping [`VolatilityPercentile`].
39///
40/// Computes a rolling ATR, feeds it into the percentile tracker, and outputs
41/// `vol_pct` (0–1) and `vol_regime` (encoded as 0=VERY_LOW … 4=VERY_HIGH).
42#[derive(Debug, Clone)]
43pub struct VolumeRegime {
44    pub params: VolumeRegimeParams,
45}
46
47impl VolumeRegime {
48    pub fn new(params: VolumeRegimeParams) -> Self {
49        Self { params }
50    }
51    pub fn with_defaults() -> Self {
52        Self::new(VolumeRegimeParams::default())
53    }
54}
55
56impl Indicator for VolumeRegime {
57    fn name(&self) -> &'static str {
58        "VolumeRegime"
59    }
60    fn required_len(&self) -> usize {
61        self.params.atr_period + 1
62    }
63    fn required_columns(&self) -> &[&'static str] {
64        &["high", "low", "close"]
65    }
66
67    fn calculate(&self, candles: &[Candle]) -> Result<IndicatorOutput, IndicatorError> {
68        self.check_len(candles)?;
69        let p = &self.params;
70        let mut tracker = VolatilityPercentile::new(p.pct_window);
71
72        // Incremental ATR (RMA / Wilder smoothing).
73        let mut prev_close: Option<f64> = None;
74        let mut atr_rma: Option<f64> = None;
75        let alpha = 1.0 / p.atr_period as f64;
76
77        let n = candles.len();
78        let mut vol_pct = vec![f64::NAN; n];
79        let mut vol_regime = vec![f64::NAN; n];
80
81        for (i, c) in candles.iter().enumerate() {
82            let tr = match prev_close {
83                None => c.high - c.low,
84                Some(pc) => (c.high - c.low)
85                    .max((c.high - pc).abs())
86                    .max((c.low - pc).abs()),
87            };
88            atr_rma = Some(match atr_rma {
89                None => tr,
90                Some(a) => alpha * tr + (1.0 - alpha) * a,
91            });
92            prev_close = Some(c.close);
93
94            tracker.update(atr_rma);
95            vol_pct[i] = tracker.vol_pct;
96            vol_regime[i] = match tracker.vol_regime {
97                "VERY LOW" => 0.0,
98                "LOW" => 1.0,
99                "HIGH" => 3.0,
100                "VERY HIGH" => 4.0,
101                _ => 2.0, // MED
102            };
103        }
104
105        Ok(IndicatorOutput::from_pairs([
106            ("vol_pct", vol_pct),
107            ("vol_regime", vol_regime),
108        ]))
109    }
110}
111
112// ── Registry factory ──────────────────────────────────────────────────────────
113
114pub fn factory<S: ::std::hash::BuildHasher>(params: &HashMap<String, String, S>) -> Result<Box<dyn Indicator>, IndicatorError> {
115    let atr_period = param_usize(params, "atr_period", 14)?;
116    let pct_window = param_usize(params, "pct_window", 100)?;
117    Ok(Box::new(VolumeRegime::new(VolumeRegimeParams {
118        atr_period,
119        pct_window,
120    })))
121}
122
123// ── PercentileTracker ─────────────────────────────────────────────────────────
124
125/// Rolling percentile calculator over a fixed-size window.
126pub struct PercentileTracker {
127    buf: VecDeque<f64>,
128}
129
130impl PercentileTracker {
131    pub fn new(maxlen: usize) -> Self {
132        Self {
133            buf: VecDeque::with_capacity(maxlen),
134        }
135    }
136
137    /// Seed the buffer with alternating `lo` / `hi` values so it is never empty.
138    pub fn seeded(maxlen: usize, seed_lo: f64, seed_hi: f64) -> Self {
139        let mut t = Self::new(maxlen);
140        for i in 0..(maxlen / 2) {
141            t.buf.push_back(if i % 2 == 0 { seed_lo } else { seed_hi });
142        }
143        t
144    }
145
146    pub fn push(&mut self, val: f64) {
147        if self.buf.len() == self.buf.capacity() {
148            self.buf.pop_front();
149        }
150        self.buf.push_back(val);
151    }
152
153    /// Fraction of buffered values strictly less than `val`.
154    pub fn pct(&self, val: f64) -> f64 {
155        let n = self.buf.len();
156        if n == 0 {
157            return 0.5;
158        }
159        self.buf.iter().filter(|&&v| v < val).count() as f64 / n as f64
160    }
161}
162
163// ── VolatilityPercentile ──────────────────────────────────────────────────────
164
165/// Classifies ATR into a volatility regime by comparing the current ATR to its
166/// own rolling percentile history.
167pub struct VolatilityPercentile {
168    tracker: PercentileTracker,
169    pub vol_pct: f64,
170    pub vol_regime: &'static str,
171    pub vol_mult: f64,
172    /// Confidence score adjustment applied to `conf_min_score`.
173    pub conf_adj: f64,
174}
175
176impl VolatilityPercentile {
177    pub fn new(maxlen: usize) -> Self {
178        let tracker = PercentileTracker::seeded(maxlen, 20.0, 200.0);
179        Self {
180            tracker,
181            vol_pct: 0.5,
182            vol_regime: "MED",
183            vol_mult: 1.2,
184            conf_adj: 1.0,
185        }
186    }
187
188    pub fn update(&mut self, atr: Option<f64>) {
189        let Some(v) = atr else { return };
190        if v <= 0.0 {
191            return;
192        }
193        self.tracker.push(v);
194        let p = self.tracker.pct(v);
195        self.vol_pct = p;
196        (self.vol_regime, self.vol_mult, self.conf_adj) = if p >= 0.8 {
197            ("VERY HIGH", 1.8, 1.15)
198        } else if p >= 0.6 {
199            ("HIGH", 1.5, 1.05)
200        } else if p <= 0.2 {
201            ("VERY LOW", 0.8, 0.9)
202        } else if p <= 0.4 {
203            ("LOW", 1.0, 0.95)
204        } else {
205            ("MED", 1.2, 1.0)
206        };
207    }
208}
209
210// ── MarketRegimeTracker ───────────────────────────────────────────────────────
211
212/// Simple slope + volatility regime tracker (ported from Python `MarketRegime` class).
213///
214/// Uses a 200-bar MA slope and return volatility to classify as:
215/// `"TRENDING↑"`, `"TRENDING↓"`, `"VOLATILE"`, `"RANGING"`, or `"NEUTRAL"`.
216pub struct MarketRegimeTracker {
217    closes: VecDeque<f64>,
218    ma200_hist: VecDeque<f64>,
219    ret_hist: VecDeque<f64>,
220
221    pub regime: &'static str,
222    pub is_trending_u: bool,
223    pub is_trending_d: bool,
224    pub is_ranging: bool,
225    pub is_volatile: bool,
226}
227
228impl MarketRegimeTracker {
229    pub fn new() -> Self {
230        Self {
231            closes: VecDeque::with_capacity(220),
232            ma200_hist: VecDeque::with_capacity(120),
233            ret_hist: VecDeque::with_capacity(110),
234            regime: "NEUTRAL",
235            is_trending_u: false,
236            is_trending_d: false,
237            is_ranging: false,
238            is_volatile: false,
239        }
240    }
241
242    pub fn update(&mut self, close: f64) {
243        let prev_cl = self.closes.back().copied().unwrap_or(close);
244
245        if self.closes.len() == 220 {
246            self.closes.pop_front();
247        }
248        self.closes.push_back(close);
249
250        if self.closes.len() < 200 {
251            return;
252        }
253
254        // 200-bar SMA
255        let ma200: f64 = self.closes.iter().rev().take(200).sum::<f64>() / 200.0;
256
257        if self.ma200_hist.len() == 120 {
258            self.ma200_hist.pop_front();
259        }
260        self.ma200_hist.push_back(ma200);
261
262        let ret = if prev_cl != 0.0 {
263            (close - prev_cl) / prev_cl
264        } else {
265            0.0
266        };
267        if self.ret_hist.len() == 110 {
268            self.ret_hist.pop_front();
269        }
270        self.ret_hist.push_back(ret);
271
272        if self.ma200_hist.len() < 21 || self.ret_hist.len() < 51 {
273            return;
274        }
275
276        // Slope of MA200 over last 20 bars, normalised by average MA change
277        let ma_arr: Vec<f64> = self.ma200_hist.iter().copied().collect();
278        let diffs: Vec<f64> = ma_arr.windows(2).map(|w| (w[1] - w[0]).abs()).collect();
279        let avg_chg = if diffs.is_empty() {
280            1e-9
281        } else {
282            let tail: Vec<f64> = diffs.iter().rev().take(100).copied().collect();
283            tail.iter().sum::<f64>() / tail.len() as f64
284        };
285        let slope_n = if avg_chg > 0.0 {
286            (ma200 - ma_arr[ma_arr.len() - 21]) / (avg_chg * 20.0)
287        } else {
288            0.0
289        };
290
291        // Return volatility
292        let ret_arr: Vec<f64> = self.ret_hist.iter().copied().collect();
293        let tail100: Vec<f64> = ret_arr.iter().rev().take(100).copied().collect();
294        let ret_s = std_dev(&tail100);
295        let tail50: Vec<f64> = ret_arr.iter().rev().take(50).map(|r| r.abs()).collect();
296        let ret_sma = if tail50.is_empty() {
297            ret_s.max(1e-9)
298        } else {
299            (tail50.iter().sum::<f64>() / tail50.len() as f64).max(1e-9)
300        };
301        let vol_n = ret_s / ret_sma;
302
303        self.regime = if slope_n > 1.0 {
304            "TRENDING↑"
305        } else if slope_n < -1.0 {
306            "TRENDING↓"
307        } else if vol_n > 1.5 {
308            "VOLATILE"
309        } else if vol_n < 0.8 {
310            "RANGING"
311        } else {
312            "NEUTRAL"
313        };
314
315        self.is_trending_u = self.regime == "TRENDING↑";
316        self.is_trending_d = self.regime == "TRENDING↓";
317        self.is_ranging = self.regime == "RANGING";
318        self.is_volatile = self.regime == "VOLATILE";
319    }
320}
321
322impl Default for MarketRegimeTracker {
323    fn default() -> Self {
324        Self::new()
325    }
326}
327
328// ── helpers ───────────────────────────────────────────────────────────────────
329
330fn std_dev(data: &[f64]) -> f64 {
331    if data.len() < 2 {
332        return 0.0;
333    }
334    let mean = data.iter().sum::<f64>() / data.len() as f64;
335    let var = data.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / data.len() as f64;
336    var.sqrt()
337}