Skip to main content

indicators/volatility/
market_cycle.rs

1//! Market Cycle Indicator.
2//!
3//! Python source: `indicators/other/market_cycle.py :: class MarketCycleIndicator`
4//!
5//! Detects market cycle phases from price momentum:
6//! - `Markup`       — momentum > 0
7//! - `Markdown`     — momentum < 0
8//! - `Plateau`      — momentum == 0
9//! - `Accumulation` — previous phase was Markdown, current changed
10//! - `Distribution` — previous phase was Markup, current changed
11//!
12//! Output column: `"MarketCycle"` — encoded as `f64`:
13//! - 1.0 = Markup, -1.0 = Markdown, 0.0 = Plateau,
14//!   0.5 = Accumulation, -0.5 = Distribution.
15
16use std::collections::HashMap;
17
18use crate::error::IndicatorError;
19use crate::indicator::{Indicator, IndicatorOutput};
20use crate::registry::param_usize;
21use crate::types::Candle;
22
23/// Numeric encoding for cycle phases (avoids `String` in `IndicatorOutput`).
24#[derive(Debug, Clone, Copy, PartialEq)]
25pub enum CyclePhase {
26    Markup = 1,
27    Markdown = -1,
28    Plateau = 0,
29    Accumulation = 2, // using 2/-2 to distinguish from Markup/Markdown
30    Distribution = -2,
31}
32
33impl CyclePhase {
34    pub fn as_f64(self) -> f64 {
35        self as i32 as f64
36    }
37}
38
39#[derive(Debug, Clone)]
40pub struct MarketCycleParams {
41    /// Momentum diff period.  Python default: 1.
42    pub momentum_period: usize,
43}
44impl Default for MarketCycleParams {
45    fn default() -> Self {
46        Self { momentum_period: 1 }
47    }
48}
49
50#[derive(Debug, Clone)]
51pub struct MarketCycle {
52    pub params: MarketCycleParams,
53}
54
55impl MarketCycle {
56    pub fn new(params: MarketCycleParams) -> Self {
57        Self { params }
58    }
59    pub fn default() -> Self {
60        Self::new(MarketCycleParams::default())
61    }
62}
63
64impl Indicator for MarketCycle {
65    fn name(&self) -> &str {
66        "MarketCycle"
67    }
68    fn required_len(&self) -> usize {
69        self.params.momentum_period + 1
70    }
71    fn required_columns(&self) -> &[&'static str] {
72        &["close"]
73    }
74
75    /// TODO: port Python momentum-based phase assignment with transition rules.
76    fn calculate(&self, candles: &[Candle]) -> Result<IndicatorOutput, IndicatorError> {
77        self.check_len(candles)?;
78
79        let close: Vec<f64> = candles.iter().map(|c| c.close).collect();
80        let mp = self.params.momentum_period;
81        let n = close.len();
82
83        // Step 1: assign base phases from momentum.
84        let mut phases = vec![CyclePhase::Plateau; n];
85        for i in mp..n {
86            let momentum = close[i] - close[i - mp];
87            phases[i] = if momentum > 0.0 {
88                CyclePhase::Markup
89            } else if momentum < 0.0 {
90                CyclePhase::Markdown
91            } else {
92                CyclePhase::Plateau
93            };
94        }
95
96        // Step 2: apply transition rules (mirrors Python cycle.loc[...] assignments).
97        // TODO: port Python shift-based rule application.
98        let mut result = phases.clone();
99        for i in 1..n {
100            match (phases[i - 1], phases[i]) {
101                (CyclePhase::Markdown, p) if p != CyclePhase::Markdown => {
102                    result[i] = CyclePhase::Accumulation
103                }
104                (CyclePhase::Markup, p) if p != CyclePhase::Markup => {
105                    result[i] = CyclePhase::Distribution
106                }
107                _ => {}
108            }
109        }
110
111        let values: Vec<f64> = result.iter().map(|p| p.as_f64()).collect();
112
113        Ok(IndicatorOutput::from_pairs([(
114            "MarketCycle".to_string(),
115            values,
116        )]))
117    }
118}
119
120pub fn factory(params: &HashMap<String, String>) -> Result<Box<dyn Indicator>, IndicatorError> {
121    Ok(Box::new(MarketCycle::new(MarketCycleParams {
122        momentum_period: param_usize(params, "momentum_period", 1)?,
123    })))
124}
125
126#[cfg(test)]
127mod tests {
128    use super::*;
129
130    fn candles(closes: &[f64]) -> Vec<Candle> {
131        closes.iter().enumerate().map(|(i, &c)| Candle {
132            time: i as i64, open: c, high: c, low: c, close: c, volume: 1.0,
133        }).collect()
134    }
135
136    #[test]
137    fn market_cycle_output_column() {
138        let out = MarketCycle::default().calculate(&candles(&[1.0, 2.0, 3.0])).unwrap();
139        assert!(out.get("MarketCycle").is_some());
140    }
141
142    #[test]
143    fn rising_prices_give_markup() {
144        let closes = vec![1.0, 2.0, 3.0, 4.0, 5.0];
145        let out = MarketCycle::default().calculate(&candles(&closes)).unwrap();
146        let vals = out.get("MarketCycle").unwrap();
147        // Index 1+ should reflect Markup (1.0) except where transition rules fire.
148        assert_eq!(vals[1], CyclePhase::Markup.as_f64());
149    }
150
151    #[test]
152    fn falling_after_rising_gives_distribution() {
153        // Rise then fall → distribution transition.
154        let closes = vec![1.0, 2.0, 3.0, 2.0];
155        let out = MarketCycle::default().calculate(&candles(&closes)).unwrap();
156        let vals = out.get("MarketCycle").unwrap();
157        assert_eq!(vals[3], CyclePhase::Distribution.as_f64());
158    }
159
160    #[test]
161    fn factory_creates_market_cycle() {
162        assert_eq!(factory(&HashMap::new()).unwrap().name(), "MarketCycle");
163    }
164}