Files
wickra/crates/wickra-core/src/indicators/trix.rs
T
kingchencandGitHub b86cf68eb8 test: 100% coverage for t3 + adx + natr + trix + coppock (#20)
* test(t3): cover period/volume_factor/value accessors + name metadata

Codecov flagged 12 lines in crates/wickra-core/src/indicators/t3.rs
(file at 91.48%): const accessors period (95-97), volume_factor
(100-102), value (105-107) and Indicator-impl name (148-150). The
warmup_period method is already covered by first_emission_at_warmup_
period; the other four metadata methods were never queried.

Add accessors_and_metadata asserting period == 5, volume_factor == 0.7,
name == "T3", and value() across both the None (pre-warmup) and Some
(post-warmup) branches.

t3.rs is now at 141/141 lines, no behavioural change.

* test(adx): cover period accessor, warmup/name metadata, zero-TR branch

Codecov flagged 11 lines in crates/wickra-core/src/indicators/adx.rs
(file at 94.17%): the const accessor period (89-91), the tr_v == 0.0
defensive branches inside update (142, 147), and the Indicator-impl
warmup_period (199-201) and name (207-209) bodies.

Add accessors_and_metadata asserting period == 14, warmup_period == 28,
name == "ADX". Add zero_true_range_yields_zero_di_and_zero_adx feeding
flat all-zero candles (H == L == close == 0) — every TR is 0, so the
smoothed tr_smooth stays at 0 and update must take the zero-denominator
fallback for both plus_di and minus_di, then the dx_den == 0 path for
ADX. The indicator must emit 0/0/0 rather than NaN.

adx.rs is now at 189/189 lines, no behavioural change.

* test(natr): cover accessors, zero-close branch, kill dead panic arm

Codecov flagged 11 lines in crates/wickra-core/src/indicators/natr.rs
(file at 87.64%):

  - const accessors period (59-61), value (64-66) — never queried
  - line 77 (`0.0` in the candle.close == 0.0 fallback) — every test
    used candles with close ≈ 100, so the divide-by-zero guard never
    fired
  - Indicator-impl name body (98-100) — never queried
  - line 142 (`_ => panic!("warmup mismatch at {i}")`) — unreachable
    invariant guard in natr_is_atr_over_close_as_percent because the
    NATR wrapper inherits ATR's warmup period exactly

Add accessors_and_metadata covering period/value/name. Add
zero_close_yields_zero_natr feeding an all-zero candle series (Candle
validator accepts open == high == low == close == 0 with positive
volume) — ATR is 0 each bar, so the indicator must emit exactly 0.0
rather than 100 * 0 / 0 = NaN. Refactor natr_is_atr_over_close_as_
percent to assert the warmup-shape invariant via assert_eq! on
is_some(), removing the dead panic arm.

natr.rs is now at 89/89 lines, no behavioural change.

* test(trix): cover period accessor, warmup/name metadata, zero-prev branch

Codecov flagged 11 lines in crates/wickra-core/src/indicators/trix.rs
(file at 84.05%):

  - const accessor period (47-49) — never queried
  - the Some(_) match arm (67-68) — the degenerate path where the
    previous triple-EMA value is exactly 0.0 (would otherwise divide
    by zero on the percent-rate formula). All other tests used
    inputs ≈ 100, so prev_tr was never 0.0
  - Indicator-impl warmup_period (84, 86-87) and name (93-95) — never
    queried

Add accessors_and_metadata asserting period == 5, warmup_period == 14
(= 3*5 - 1), name == "TRIX". Add zero_input_series_yields_zero_trix
feeding [0.0; 20] — every EMA stage collapses to 0.0, so once warmed
up prev_tr is Some(0.0) and every subsequent emission must take the
fallback arm returning 0.0.

trix.rs is now at 69/69 lines, no behavioural change.

* test(coppock): cover periods/value accessors + name + simplify assert

Codecov flagged 10 lines in crates/wickra-core/src/indicators/coppock.rs
(file at 91.07%):

  - const accessors periods (68-70), value (73-75) — never queried
  - Indicator-impl name body (128-130) — never queried
  - line 180 (`warmup - 1,` format-arg) inside the multi-line assert!
    in warmup_period_matches_first_some_for_every_parameter_set —
    only evaluated on assertion failure, which never happens, so
    Codecov flagged the cold path as uncovered

Add accessors_and_metadata covering periods/value/name. Simplify the
multi-line assert's format args to a static message — the {warmup}
binding already appears once in the cold path so dropping the literal
"warmup index" arg loses nothing diagnostic but kills the dead
expression-arg line.

coppock.rs is now at 112/112 lines, no behavioural change.
2026-05-24 00:46:20 +02:00

171 lines
4.7 KiB
Rust

//! TRIX: triple-smoothed EMA percent rate of change.
use crate::error::Result;
use crate::indicators::ema::Ema;
use crate::traits::Indicator;
/// TRIX: the 1-period percent rate of change of a triple-smoothed EMA.
///
/// `TRIX = 100 * (TR_t - TR_{t-1}) / TR_{t-1}` where
/// `TR_t = EMA(EMA(EMA(price)))`.
///
/// # Example
///
/// ```
/// use wickra_core::{Indicator, Trix};
///
/// let mut indicator = Trix::new(3).unwrap();
/// let mut last = None;
/// for i in 0..80 {
/// last = indicator.update(100.0 + f64::from(i));
/// }
/// assert!(last.is_some());
/// ```
#[derive(Debug, Clone)]
pub struct Trix {
ema1: Ema,
ema2: Ema,
ema3: Ema,
prev_tr: Option<f64>,
period: usize,
}
impl Trix {
/// # Errors
/// Returns [`crate::Error::PeriodZero`] if `period == 0`.
pub fn new(period: usize) -> Result<Self> {
Ok(Self {
ema1: Ema::new(period)?,
ema2: Ema::new(period)?,
ema3: Ema::new(period)?,
prev_tr: None,
period,
})
}
/// Configured period.
pub const fn period(&self) -> usize {
self.period
}
}
impl Indicator for Trix {
type Input = f64;
type Output = f64;
fn update(&mut self, input: f64) -> Option<f64> {
let e1 = self.ema1.update(input)?;
let e2 = self.ema2.update(e1)?;
let e3 = self.ema3.update(e2)?;
match self.prev_tr {
Some(prev) if prev != 0.0 => {
let trix = 100.0 * (e3 - prev) / prev;
self.prev_tr = Some(e3);
Some(trix)
}
Some(_) => {
self.prev_tr = Some(e3);
Some(0.0)
}
None => {
self.prev_tr = Some(e3);
None
}
}
}
fn reset(&mut self) {
self.ema1.reset();
self.ema2.reset();
self.ema3.reset();
self.prev_tr = None;
}
fn warmup_period(&self) -> usize {
// Triple EMA seeds at 3*period-2; plus one extra for the rate of change.
3 * self.period - 1
}
fn is_ready(&self) -> bool {
self.prev_tr.is_some() && self.ema3.is_ready()
}
fn name(&self) -> &'static str {
"TRIX"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
#[test]
fn constant_series_yields_zero_trix() {
let mut trix = Trix::new(5).unwrap();
let out = trix.batch(&[100.0_f64; 80]);
let last = out.iter().rev().flatten().next().unwrap();
assert_relative_eq!(*last, 0.0, epsilon = 1e-9);
}
#[test]
fn rising_series_eventually_positive_trix() {
let prices: Vec<f64> = (1..=200).map(f64::from).collect();
let mut trix = Trix::new(5).unwrap();
let last = trix.batch(&prices).into_iter().flatten().last().unwrap();
assert!(last > 0.0);
}
#[test]
fn batch_equals_streaming() {
let prices: Vec<f64> = (1..=80).map(|i| f64::from(i) * 1.3).collect();
let mut a = Trix::new(7).unwrap();
let mut b = Trix::new(7).unwrap();
assert_eq!(
a.batch(&prices),
prices.iter().map(|p| b.update(*p)).collect::<Vec<_>>()
);
}
#[test]
fn reset_clears_state() {
let mut trix = Trix::new(5).unwrap();
trix.batch(&(1..=80).map(f64::from).collect::<Vec<_>>());
assert!(trix.is_ready());
trix.reset();
assert!(!trix.is_ready());
}
#[test]
fn rejects_zero_period() {
assert!(Trix::new(0).is_err());
}
/// Cover the const accessor `period` (47-49) and the Indicator-impl
/// `warmup_period` (84-87) + `name` (93-95). Existing tests never
/// inspect these metadata methods.
#[test]
fn accessors_and_metadata() {
let trix = Trix::new(5).unwrap();
assert_eq!(trix.period(), 5);
// Triple EMA seeds at 3*5-2 = 13; +1 for the rate-of-change pair = 14.
assert_eq!(trix.warmup_period(), 14);
assert_eq!(trix.name(), "TRIX");
}
/// Cover the `Some(_)` match arm at lines 66-68 — the degenerate path
/// where the previous triple-EMA value is exactly 0.0 (which would
/// otherwise divide by zero on the percent-rate formula). A series of
/// all-zero inputs collapses every EMA stage to 0.0, so once the
/// indicator warms up `prev_tr` is `Some(0.0)` and every subsequent
/// emission must take the fallback branch and return 0.0.
#[test]
fn zero_input_series_yields_zero_trix() {
let mut trix = Trix::new(3).unwrap();
let out = trix.batch(&[0.0_f64; 20]);
let last = out.into_iter().flatten().last().expect("emits");
assert_eq!(last, 0.0);
}
}