quantwave_core/indicators/
volume.rs1use crate::indicators::metadata::{IndicatorMetadata, ParamDef};
2#[allow(unused_imports)]
3use crate::traits::Next;
4
5talib_4_in_1_out!(AD, talib_rs::volume::ad);
6impl Default for AD {
7 fn default() -> Self {
8 Self::new()
9 }
10}
11talib_4_in_1_out!(ADOSC, talib_rs::volume::adosc, fastperiod: usize, slowperiod: usize);
12talib_2_in_1_out!(OBV, talib_rs::volume::obv);
13impl Default for OBV {
14 fn default() -> Self {
15 Self::new()
16 }
17}
18
19pub const AD_METADATA: IndicatorMetadata = IndicatorMetadata {
20 name: "Accumulation/Distribution Line (AD)",
21 description: "A volume-based indicator designed to measure the cumulative flow of money into and out of a security.",
22 usage: "Use to confirm price trends or identify potential reversals through divergences. Rising AD confirms an uptrend; falling AD confirms a downtrend.",
23 keywords: &["volume", "momentum", "classic", "accumulation", "distribution"],
24 ehlers_summary: "Developed by Marc Chaikin, the AD line uses the relationship between price and volume to determine whether a security is being accumulated or distributed. It is calculated by multiplying the Money Flow Multiplier by the period's volume and adding it to a cumulative total. — StockCharts ChartSchool",
25 params: &[],
26 formula_source: "https://www.investopedia.com/terms/a/accumulationdistributioncurve.asp",
27 formula_latex: r#"
28\[
29\text{MFM} = \frac{(Close - Low) - (High - Close)}{High - Low} \\ \text{MFV} = \text{MFM} \times Volume \\ AD_t = AD_{t-1} + \text{MFV}
30\]
31"#,
32 gold_standard_file: "ad.json",
33 category: "Classic",
34};
35
36pub const ADOSC_METADATA: IndicatorMetadata = IndicatorMetadata {
37 name: "Chaikin Oscillator (ADOSC)",
38 description: "An indicator that measures the momentum of the Accumulation/Distribution Line using the difference between two exponential moving averages.",
39 usage: "Use to anticipate changes in the AD Line. Positive values indicate increasing buying pressure, while negative values indicate increasing selling pressure.",
40 keywords: &["volume", "oscillator", "momentum", "classic"],
41 ehlers_summary: "Marc Chaikin developed this oscillator to identify momentum shifts in the AD Line. By applying EMAs of different lengths to the AD Line, it highlights changes in money flow before they become apparent in the cumulative total, providing an early warning system for trend exhaustion. — StockCharts ChartSchool",
42 params: &[
43 ParamDef { name: "fastperiod", default: "3", description: "Fast EMA period" },
44 ParamDef { name: "slowperiod", default: "10", description: "Slow EMA period" },
45 ],
46 formula_source: "https://www.investopedia.com/terms/c/chaikinoscillator.asp",
47 formula_latex: r#"
48\[
49ADOSC = EMA(AD, 3) - EMA(AD, 10)
50\]
51"#,
52 gold_standard_file: "adosc.json",
53 category: "Classic",
54};
55
56pub const OBV_METADATA: IndicatorMetadata = IndicatorMetadata {
57 name: "On-Balance Volume (OBV)",
58 description: "A momentum indicator that uses volume flow to predict changes in stock price.",
59 usage: "Use to identify accumulation by institutions. When price is flat but OBV is rising, a breakout to the upside is likely. Conversely, when price is flat but OBV is falling, a breakdown is likely.",
60 keywords: &["volume", "momentum", "classic", "accumulation", "distribution"],
61 ehlers_summary: "Introduced by Joe Granville in his 1963 book 'Granville's New Key to Stock Market Profits', OBV is one of the oldest and most respected volume indicators. It operates on the principle that volume precedes price, and that institutional money flow leaves a detectable trail in the volume data before the price move occurs. — StockCharts ChartSchool",
62 params: &[],
63 formula_source: "https://www.investopedia.com/terms/o/onbalancevolume.asp",
64 formula_latex: r#"
65\[
66OBV_t = OBV_{t-1} + \begin{cases} Volume & \text{if } Close_t > Close_{t-1} \\ 0 & \text{if } Close_t = Close_{t-1} \\ -Volume & \text{if } Close_t < Close_{t-1} \end{cases}
67\]
68"#,
69 gold_standard_file: "obv.json",
70 category: "Classic",
71};
72
73#[cfg(test)]
74mod tests {
75 use super::*;
76 use crate::traits::Next;
77 use proptest::prelude::*;
78
79 proptest! {
80 #[test]
81 fn test_ad_parity(
82 h in prop::collection::vec(10.0..100.0, 1..100),
83 l in prop::collection::vec(10.0..100.0, 1..100),
84 c in prop::collection::vec(10.0..100.0, 1..100),
85 v in prop::collection::vec(1.0..1000.0, 1..100)
86 ) {
87 let len = h.len().min(l.len()).min(c.len()).min(v.len());
88 if len == 0 { return Ok(()); }
89 let mut high = Vec::with_capacity(len);
90 let mut low = Vec::with_capacity(len);
91 let mut close = Vec::with_capacity(len);
92 let mut volume = Vec::with_capacity(len);
93 for i in 0..len {
94 let v_h: f64 = h[i];
95 let v_l: f64 = l[i];
96 let v_c: f64 = c[i];
97 let v_v: f64 = v[i];
98 high.push(v_h.max(v_l).max(v_c));
99 low.push(v_h.min(v_l).min(v_c));
100 close.push(v_c);
101 volume.push(v_v);
102 }
103
104 let mut ad = AD::new();
105 let streaming_results: Vec<f64> = (0..len).map(|i| ad.next((high[i], low[i], close[i], volume[i]))).collect();
106 let batch_results = talib_rs::volume::ad(&high, &low, &close, &volume).unwrap_or_else(|_| vec![f64::NAN; len]);
107
108 for (s, b) in streaming_results.iter().zip(batch_results.iter()) {
109 if s.is_nan() {
110 assert!(b.is_nan());
111 } else {
112 approx::assert_relative_eq!(s, b, epsilon = 1e-6);
113 }
114 }
115 }
116
117 #[test]
118 fn test_obv_parity(
119 c in prop::collection::vec(10.0..100.0, 1..100),
120 v in prop::collection::vec(1.0..1000.0, 1..100)
121 ) {
122 let len = c.len().min(v.len());
123 if len == 0 { return Ok(()); }
124 let close = c[..len].to_vec();
125 let volume = v[..len].to_vec();
126
127 let mut obv = OBV::new();
128 let streaming_results: Vec<f64> = (0..len).map(|i| obv.next((close[i], volume[i]))).collect();
129 let batch_results = talib_rs::volume::obv(&close, &volume).unwrap_or_else(|_| vec![f64::NAN; len]);
130
131 for (s, b) in streaming_results.iter().zip(batch_results.iter()) {
132 if s.is_nan() {
133 assert!(b.is_nan());
134 } else {
135 approx::assert_relative_eq!(s, b, epsilon = 1e-6);
136 }
137 }
138 }
139 }
140}