quantwave_core/indicators/
volume.rs1use crate::indicators::metadata::{IndicatorMetadata, ParamDef};
2use crate::traits::Next;
3
4talib_4_in_1_out!(AD, talib_rs::volume::ad);
5impl Default for AD {
6 fn default() -> Self {
7 Self::new()
8 }
9}
10talib_4_in_1_out!(ADOSC, talib_rs::volume::adosc, fastperiod: usize, slowperiod: usize);
11talib_2_in_1_out!(OBV, talib_rs::volume::obv);
12impl Default for OBV {
13 fn default() -> Self {
14 Self::new()
15 }
16}
17
18pub const AD_METADATA: IndicatorMetadata = IndicatorMetadata {
19 name: "Accumulation/Distribution Line (AD)",
20 description: "A volume-based indicator designed to measure the cumulative flow of money into and out of a security.",
21 usage: "Use to confirm price trends or identify potential reversals through divergences. Rising AD confirms an uptrend; falling AD confirms a downtrend.",
22 keywords: &["volume", "momentum", "classic", "accumulation", "distribution"],
23 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",
24 params: &[],
25 formula_source: "https://www.investopedia.com/terms/a/accumulationdistributioncurve.asp",
26 formula_latex: r#"
27\[
28\text{MFM} = \frac{(Close - Low) - (High - Close)}{High - Low} \\ \text{MFV} = \text{MFM} \times Volume \\ AD_t = AD_{t-1} + \text{MFV}
29\]
30"#,
31 gold_standard_file: "ad.json",
32 category: "Classic",
33};
34
35pub const ADOSC_METADATA: IndicatorMetadata = IndicatorMetadata {
36 name: "Chaikin Oscillator (ADOSC)",
37 description: "An indicator that measures the momentum of the Accumulation/Distribution Line using the difference between two exponential moving averages.",
38 usage: "Use to anticipate changes in the AD Line. Positive values indicate increasing buying pressure, while negative values indicate increasing selling pressure.",
39 keywords: &["volume", "oscillator", "momentum", "classic"],
40 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",
41 params: &[
42 ParamDef { name: "fastperiod", default: "3", description: "Fast EMA period" },
43 ParamDef { name: "slowperiod", default: "10", description: "Slow EMA period" },
44 ],
45 formula_source: "https://www.investopedia.com/terms/c/chaikinoscillator.asp",
46 formula_latex: r#"
47\[
48ADOSC = EMA(AD, 3) - EMA(AD, 10)
49\]
50"#,
51 gold_standard_file: "adosc.json",
52 category: "Classic",
53};
54
55pub const OBV_METADATA: IndicatorMetadata = IndicatorMetadata {
56 name: "On-Balance Volume (OBV)",
57 description: "A momentum indicator that uses volume flow to predict changes in stock price.",
58 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.",
59 keywords: &["volume", "momentum", "classic", "accumulation", "distribution"],
60 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",
61 params: &[],
62 formula_source: "https://www.investopedia.com/terms/o/onbalancevolume.asp",
63 formula_latex: r#"
64\[
65OBV_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}
66\]
67"#,
68 gold_standard_file: "obv.json",
69 category: "Classic",
70};
71
72#[cfg(test)]
73mod tests {
74 use super::*;
75 use crate::traits::Next;
76 use proptest::prelude::*;
77
78 proptest! {
79 #[test]
80 fn test_ad_parity(
81 h in prop::collection::vec(10.0..100.0, 1..100),
82 l in prop::collection::vec(10.0..100.0, 1..100),
83 c in prop::collection::vec(10.0..100.0, 1..100),
84 v in prop::collection::vec(1.0..1000.0, 1..100)
85 ) {
86 let len = h.len().min(l.len()).min(c.len()).min(v.len());
87 if len == 0 { return Ok(()); }
88 let mut high = Vec::with_capacity(len);
89 let mut low = Vec::with_capacity(len);
90 let mut close = Vec::with_capacity(len);
91 let mut volume = Vec::with_capacity(len);
92 for i in 0..len {
93 let v_h: f64 = h[i];
94 let v_l: f64 = l[i];
95 let v_c: f64 = c[i];
96 let v_v: f64 = v[i];
97 high.push(v_h.max(v_l).max(v_c));
98 low.push(v_h.min(v_l).min(v_c));
99 close.push(v_c);
100 volume.push(v_v);
101 }
102
103 let mut ad = AD::new();
104 let streaming_results: Vec<f64> = (0..len).map(|i| ad.next((high[i], low[i], close[i], volume[i]))).collect();
105 let batch_results = talib_rs::volume::ad(&high, &low, &close, &volume).unwrap_or_else(|_| vec![f64::NAN; len]);
106
107 for (s, b) in streaming_results.iter().zip(batch_results.iter()) {
108 if s.is_nan() {
109 assert!(b.is_nan());
110 } else {
111 approx::assert_relative_eq!(s, b, epsilon = 1e-6);
112 }
113 }
114 }
115
116 #[test]
117 fn test_obv_parity(
118 c in prop::collection::vec(10.0..100.0, 1..100),
119 v in prop::collection::vec(1.0..1000.0, 1..100)
120 ) {
121 let len = c.len().min(v.len());
122 if len == 0 { return Ok(()); }
123 let close = c[..len].to_vec();
124 let volume = v[..len].to_vec();
125
126 let mut obv = OBV::new();
127 let streaming_results: Vec<f64> = (0..len).map(|i| obv.next((close[i], volume[i]))).collect();
128 let batch_results = talib_rs::volume::obv(&close, &volume).unwrap_or_else(|_| vec![f64::NAN; len]);
129
130 for (s, b) in streaming_results.iter().zip(batch_results.iter()) {
131 if s.is_nan() {
132 assert!(b.is_nan());
133 } else {
134 approx::assert_relative_eq!(s, b, epsilon = 1e-6);
135 }
136 }
137 }
138 }
139}