1use std::collections::HashMap;
19
20use crate::error::IndicatorError;
21use crate::functions::{self};
22use crate::indicator::{Indicator, IndicatorOutput, PriceColumn};
23use crate::types::Candle;
24
25#[derive(Debug, Clone)]
28pub struct MacdParams {
29 pub fast_period: usize,
31 pub slow_period: usize,
33 pub signal_period: usize,
35 pub column: PriceColumn,
37}
38
39impl Default for MacdParams {
40 fn default() -> Self {
41 Self {
42 fast_period: 12,
43 slow_period: 26,
44 signal_period: 9,
45 column: PriceColumn::Close,
46 }
47 }
48}
49
50#[derive(Debug, Clone)]
53pub struct Macd {
54 pub params: MacdParams,
55}
56
57impl Macd {
58 pub fn new(params: MacdParams) -> Self {
59 Self { params }
60 }
61
62}
63
64impl Default for Macd {
65 fn default() -> Self {
66 Self::new(MacdParams::default())
67 }
68}
69
70impl Indicator for Macd {
71 fn name(&self) -> &'static str {
72 "MACD"
73 }
74
75 fn required_len(&self) -> usize {
76 self.params.slow_period + self.params.signal_period
78 }
79
80 fn required_columns(&self) -> &[&'static str] {
81 &["close"]
82 }
83
84 fn calculate(&self, candles: &[Candle]) -> Result<IndicatorOutput, IndicatorError> {
88 self.check_len(candles)?;
89
90 let prices = self.params.column.extract(candles);
91 let (macd_line, signal_line, histogram) = functions::macd(
92 &prices,
93 self.params.fast_period,
94 self.params.slow_period,
95 self.params.signal_period,
96 )?;
97
98 Ok(IndicatorOutput::from_pairs([
99 ("MACD_line".to_string(), macd_line),
100 ("MACD_signal".to_string(), signal_line),
101 ("MACD_histogram".to_string(), histogram),
102 ]))
103 }
104}
105
106pub fn factory<S: ::std::hash::BuildHasher>(params: &HashMap<String, String, S>) -> Result<Box<dyn Indicator>, IndicatorError> {
109 Ok(Box::new(Macd::new(MacdParams {
110 fast_period: crate::registry::param_usize(params, "fast_period", 12)?,
111 slow_period: crate::registry::param_usize(params, "slow_period", 26)?,
112 signal_period: crate::registry::param_usize(params, "signal_period", 9)?,
113 column: PriceColumn::Close,
114 })))
115}
116
117#[cfg(test)]
120mod tests {
121 use super::*;
122
123 fn candles(closes: &[f64]) -> Vec<Candle> {
124 closes
125 .iter()
126 .enumerate()
127 .map(|(i, &c)| Candle {
128 time: i64::try_from(i).expect("time index fits i64"),
129 open: c,
130 high: c,
131 low: c,
132 close: c,
133 volume: 1.0,
134 })
135 .collect()
136 }
137
138 #[test]
139 fn macd_insufficient_data() {
140 let macd = Macd::default();
141 assert!(macd.calculate(&candles(&[1.0; 10])).is_err());
142 }
143
144 #[test]
145 fn macd_output_has_three_columns() {
146 let macd = Macd::default();
147 let closes: Vec<f64> = (1..=50).map(|x| x as f64).collect();
148 let out = macd.calculate(&candles(&closes)).unwrap();
149 assert!(out.get("MACD_line").is_some(), "missing MACD_line");
150 assert!(out.get("MACD_signal").is_some(), "missing MACD_signal");
151 assert!(
152 out.get("MACD_histogram").is_some(),
153 "missing MACD_histogram"
154 );
155 }
156
157 #[test]
158 fn macd_histogram_is_line_minus_signal() {
159 let macd = Macd::default();
160 let closes: Vec<f64> = (1..=50).map(|x| x as f64).collect();
161 let out = macd.calculate(&candles(&closes)).unwrap();
162 let line = out.get("MACD_line").unwrap();
163 let signal = out.get("MACD_signal").unwrap();
164 let hist = out.get("MACD_histogram").unwrap();
165 for i in 0..line.len() {
166 if !line[i].is_nan() && !signal[i].is_nan() {
167 assert!((hist[i] - (line[i] - signal[i])).abs() < 1e-9);
168 }
169 }
170 }
171
172 #[test]
173 fn factory_creates_macd() {
174 let params = HashMap::new();
175 let ind = factory(¶ms).unwrap();
176 assert_eq!(ind.name(), "MACD");
177 }
178}