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, Eq)]
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}
60
61impl Default for MarketCycle {
62    fn default() -> Self {
63        Self::new(MarketCycleParams::default())
64    }
65}
66
67impl Indicator for MarketCycle {
68    fn name(&self) -> &'static str {
69        "MarketCycle"
70    }
71    fn required_len(&self) -> usize {
72        self.params.momentum_period + 1
73    }
74    fn required_columns(&self) -> &[&'static str] {
75        &["close"]
76    }
77
78    /// TODO: port Python momentum-based phase assignment with transition rules.
79    fn calculate(&self, candles: &[Candle]) -> Result<IndicatorOutput, IndicatorError> {
80        self.check_len(candles)?;
81
82        let close: Vec<f64> = candles.iter().map(|c| c.close).collect();
83        let mp = self.params.momentum_period;
84        let n = close.len();
85
86        // Step 1: assign base phases from momentum.
87        let mut phases = vec![CyclePhase::Plateau; n];
88        for i in mp..n {
89            let momentum = close[i] - close[i - mp];
90            phases[i] = if momentum > 0.0 {
91                CyclePhase::Markup
92            } else if momentum < 0.0 {
93                CyclePhase::Markdown
94            } else {
95                CyclePhase::Plateau
96            };
97        }
98
99        // Step 2: apply transition rules (mirrors Python cycle.loc[...] assignments).
100        // TODO: port Python shift-based rule application.
101        let mut result = phases.clone();
102        for i in 1..n {
103            match (phases[i - 1], phases[i]) {
104                (CyclePhase::Markdown, p) if p != CyclePhase::Markdown => {
105                    result[i] = CyclePhase::Accumulation;
106                }
107                (CyclePhase::Markup, p) if p != CyclePhase::Markup => {
108                    result[i] = CyclePhase::Distribution;
109                }
110                _ => {}
111            }
112        }
113
114        let values: Vec<f64> = result.iter().map(|p| p.as_f64()).collect();
115
116        Ok(IndicatorOutput::from_pairs([(
117            "MarketCycle".to_string(),
118            values,
119        )]))
120    }
121}
122
123pub fn factory<S: ::std::hash::BuildHasher>(params: &HashMap<String, String, S>) -> Result<Box<dyn Indicator>, IndicatorError> {
124    Ok(Box::new(MarketCycle::new(MarketCycleParams {
125        momentum_period: param_usize(params, "momentum_period", 1)?,
126    })))
127}
128
129#[cfg(test)]
130mod tests {
131    use super::*;
132
133    fn candles(closes: &[f64]) -> Vec<Candle> {
134        closes
135            .iter()
136            .enumerate()
137            .map(|(i, &c)| Candle {
138                time: i64::try_from(i).expect("time index fits i64"),
139                open: c,
140                high: c,
141                low: c,
142                close: c,
143                volume: 1.0,
144            })
145            .collect()
146    }
147
148    #[test]
149    fn market_cycle_output_column() {
150        let out = MarketCycle::default()
151            .calculate(&candles(&[1.0, 2.0, 3.0]))
152            .unwrap();
153        assert!(out.get("MarketCycle").is_some());
154    }
155
156    #[test]
157    fn rising_prices_give_markup() {
158        let closes = vec![1.0, 2.0, 3.0, 4.0, 5.0];
159        let out = MarketCycle::default().calculate(&candles(&closes)).unwrap();
160        let vals = out.get("MarketCycle").unwrap();
161        // Index 1+ should reflect Markup (1.0) except where transition rules fire.
162        assert_eq!(vals[1], CyclePhase::Markup.as_f64());
163    }
164
165    #[test]
166    fn falling_after_rising_gives_distribution() {
167        // Rise then fall → distribution transition.
168        let closes = vec![1.0, 2.0, 3.0, 2.0];
169        let out = MarketCycle::default().calculate(&candles(&closes)).unwrap();
170        let vals = out.get("MarketCycle").unwrap();
171        assert_eq!(vals[3], CyclePhase::Distribution.as_f64());
172    }
173
174    #[test]
175    fn factory_creates_market_cycle() {
176        assert_eq!(factory(&HashMap::new()).unwrap().name(), "MarketCycle");
177    }
178}