Skip to main content

quantwave_core/indicators/
conventions.rs

1//! Machine-readable convention notes for indicators whose name does not fully
2//! determine their formula (quantwave-xnaf / quantwave-l2n4).
3//!
4//! Some indicator slugs are ambiguous in the wild: "ATR" can mean Wilder's RMA
5//! (TA-Lib, TradingView, Wilder 1978) or a plain EMA of true range; "stddev" can
6//! be population (`ddof=0`) or sample (`ddof=1`); "roc" can be a percentage or a
7//! plain ratio. Prose in a docs page is easy to miss, so the convention actually
8//! implemented is recorded here as data and surfaced through the Python
9//! `metadata()` / `boundary_info()` discovery API.
10//!
11//! PROCESS RULE (AGENTS.md): the *source* of every calculation must be recorded
12//! and never assumed. `source` below is the recorded provenance for the
13//! convention that is actually implemented. Where no authoritative source has
14//! been found for the implemented variant, `source` says so explicitly rather
15//! than naming a plausible-looking one.
16
17/// One convention that a caller could plausibly get wrong.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
19pub struct ConventionNote {
20    /// Indicator slug this note applies to (matches `metadata_registry`).
21    pub slug: &'static str,
22    /// What aspect of the calculation is ambiguous, e.g. "smoothing", "scaling".
23    pub aspect: &'static str,
24    /// The convention this implementation actually follows.
25    pub convention: &'static str,
26    /// Widely used conventions this implementation does *not* follow.
27    pub differs_from: &'static str,
28    /// Recorded provenance for the implemented convention, or an explicit
29    /// statement that no source has been established.
30    pub source: &'static str,
31    /// What a caller should do about it.
32    pub guidance: &'static str,
33}
34
35/// Slugs whose implemented convention differs from what the bare name implies.
36///
37/// Keep this sorted by slug. Mirrored on the Python side in
38/// `quantwave/_metadata.py::_CONVENTION_NOTES`.
39pub const CONVENTION_NOTES: &[ConventionNote] = &[
40    ConventionNote {
41        slug: "alma",
42        aspect: "warmup",
43        convention: "During the initial warmup window (< period bars), ALMA normalizes a partial slice of Gaussian weights over available bars, returning finite values immediately from bar 0.",
44        differs_from: "Implementations that emit NaN until the full period of bars has accumulated.",
45        source: "ProRealTime Arnaud Legoux Moving Average specification.",
46        guidance: "To match NaN-warmup implementations, use WarmupPolicy::Nan or mask the first period-1 bars.",
47    },
48    ConventionNote {
49        slug: "atr",
50        aspect: "smoothing",
51        convention: "Wilder's RMA (alpha = 1/period, SMA-seeded over the first `period` \
52                     true ranges, NaN during warmup) by default across all layers (`atr()`, \
53                     `Atr` streaming, and Polars `pl.col().ta.atr()`). Both layers support \
54                     `smoothing='ema'` for exponential smoothing (alpha = 2/(period+1)).",
55        differs_from: "EMA-smoothed ATR variants (alpha = 2/(period+1)) without NaN warmup \
56                       when using default smoothing='wilder'.",
57        source: "Wilder, J. W. (1978). New Concepts in Technical Trading Systems.",
58        guidance: "Default `atr()` matches TA-Lib and TradingView bit for bit across plain and \
59                   Polars APIs. Use `smoothing='ema'` if EMA smoothing is explicitly desired.",
60    },
61    ConventionNote {
62        slug: "atr_ts",
63        aspect: "smoothing",
64        convention: "ATR trailing stop built on the EMA-smoothed `Atr` (alpha = 2/(period+1)).",
65        differs_from: "TradingView ATR trailing stops, which use Wilder's RMA.",
66        source: "NONE RECORDED for the EMA smoothing. Metadata `formula_source` points at \
67                 TradingView's ATR page, which specifies Wilder. Inherited from `atr`.",
68        guidance: "Stop distances differ from a TradingView-equivalent ATR trailing stop. \
69                   See quantwave-xnaf before using for live risk sizing.",
70    },
71    ConventionNote {
72        slug: "keltner",
73        aspect: "smoothing",
74        convention: "Channel width uses the EMA-smoothed `Atr` (alpha = 2/(period+1)); \
75                     the basis is a plain EMA of close.",
76        differs_from: "The Investopedia / Chester Keltner formulation and most charting \
77                       platforms, which use Wilder-smoothed ATR for the band width.",
78        source: "NONE RECORDED for the EMA smoothing. Inherited from `atr`.",
79        guidance: "Band widths differ from a Wilder-ATR Keltner channel.",
80    },
81    ConventionNote {
82        slug: "roc",
83        aspect: "scaling",
84        convention: "Percentage: (price / price[-period] - 1) * 100, matching TA-Lib `ROC`.",
85        differs_from: "pandas `pct_change(period)` and TA-Lib `ROCP`, which return the \
86                       plain ratio (no x100).",
87        source: "TA-Lib ROC/ROCP definitions.",
88        guidance: "Use `rocp` for the unscaled ratio. Mixing the two is a silent 100x error.",
89    },
90    ConventionNote {
91        slug: "stddev",
92        aspect: "degrees of freedom",
93        convention: "Population standard deviation, ddof = 0, matching TA-Lib `STDDEV`.",
94        differs_from: "pandas `Series.std()` and numpy `ndarray.std(ddof=1)` defaults, \
95                       which use the sample estimator ddof = 1.",
96        source: "TA-Lib STDDEV definition.",
97        guidance: "Values differ by a factor of sqrt(N / (N - 1)); rescale if you are \
98                   reconciling against pandas.",
99    },
100    ConventionNote {
101        slug: "supertrend",
102        aspect: "smoothing",
103        convention: "Bands are built on the EMA-smoothed `Atr` (alpha = 2/(period+1)).",
104        differs_from: "TradingView's SuperTrend, which uses Pine `ta.atr` — Wilder's RMA.",
105        source: "NONE RECORDED for the EMA smoothing. Metadata `formula_source` points at \
106                 a TradingView SuperTrend script, which uses Wilder. Inherited from `atr`.",
107        guidance: "Flip points can differ from a TradingView SuperTrend on the same inputs.",
108    },
109    ConventionNote {
110        slug: "ttm_squeeze",
111        aspect: "smoothing",
112        convention: "The Keltner leg of the squeeze test uses the EMA-smoothed `Atr`.",
113        differs_from: "Implementations that use Wilder-smoothed ATR for the Keltner leg.",
114        source: "NONE RECORDED for the EMA smoothing. Inherited from `atr`.",
115        guidance: "Squeeze on/off transitions can differ near the threshold.",
116    },
117    ConventionNote {
118        slug: "vpn",
119        aspect: "smoothing",
120        convention: "The volume-positive-negative threshold uses the EMA-smoothed `Atr`.",
121        differs_from: "Implementations that use Wilder-smoothed ATR for the threshold.",
122        source: "NONE RECORDED for the EMA smoothing. Inherited from `atr`.",
123        guidance: "Threshold crossings can differ from a Wilder-ATR VPN.",
124    },
125];
126
127/// Convention notes recorded for `slug`, if any.
128///
129/// ```
130/// use quantwave_core::indicators::conventions::convention_notes;
131/// let notes = convention_notes("atr");
132/// assert_eq!(notes.len(), 1);
133/// assert_eq!(notes[0].aspect, "smoothing");
134/// ```
135pub fn convention_notes(slug: &str) -> Vec<&'static ConventionNote> {
136    CONVENTION_NOTES.iter().filter(|n| n.slug == slug).collect()
137}
138
139/// Every slug that carries at least one convention note, sorted and deduplicated.
140pub fn slugs_with_conventions() -> Vec<&'static str> {
141    let mut slugs: Vec<&'static str> = CONVENTION_NOTES.iter().map(|n| n.slug).collect();
142    slugs.sort_unstable();
143    slugs.dedup();
144    slugs
145}
146
147#[cfg(test)]
148mod tests {
149    use super::*;
150    use crate::indicators::metadata_registry::ALL_REGISTERED;
151
152    #[test]
153    fn notes_are_sorted_by_slug() {
154        let slugs: Vec<&str> = CONVENTION_NOTES.iter().map(|n| n.slug).collect();
155        let mut sorted = slugs.clone();
156        sorted.sort_unstable();
157        assert_eq!(slugs, sorted, "CONVENTION_NOTES must be sorted by slug");
158    }
159
160    #[test]
161    fn every_note_targets_a_registered_slug() {
162        for note in CONVENTION_NOTES {
163            assert!(
164                ALL_REGISTERED.iter().any(|r| r.slug == note.slug),
165                "convention note for unregistered slug {:?}",
166                note.slug
167            );
168        }
169    }
170
171    #[test]
172    fn every_note_is_fully_populated() {
173        for note in CONVENTION_NOTES {
174            for (field, value) in [
175                ("aspect", note.aspect),
176                ("convention", note.convention),
177                ("differs_from", note.differs_from),
178                ("source", note.source),
179                ("guidance", note.guidance),
180            ] {
181                assert!(
182                    !value.trim().is_empty(),
183                    "convention note {:?} has empty {field}",
184                    note.slug
185                );
186            }
187        }
188    }
189
190    #[test]
191    fn atr_family_divergence_is_recorded() {
192        // The ATR-composed indicators all inherit the EMA smoothing; if one of
193        // them is ever switched to Wilder, this test forces the note to be updated.
194        for slug in [
195            "atr",
196            "atr_ts",
197            "keltner",
198            "supertrend",
199            "ttm_squeeze",
200            "vpn",
201        ] {
202            let notes = convention_notes(slug);
203            assert_eq!(notes.len(), 1, "expected exactly one note for {slug}");
204            assert_eq!(notes[0].aspect, "smoothing");
205        }
206    }
207
208    #[test]
209    fn lookup_of_unknown_slug_is_empty() {
210        assert!(convention_notes("rsi").is_empty());
211        assert!(convention_notes("not_a_real_slug").is_empty());
212    }
213}