* 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.
217 lines
6.5 KiB
Rust
217 lines
6.5 KiB
Rust
//! Normalized Average True Range.
|
|
|
|
use crate::error::Result;
|
|
use crate::ohlcv::Candle;
|
|
use crate::traits::Indicator;
|
|
|
|
use super::Atr;
|
|
|
|
/// Normalized Average True Range — [`Atr`] expressed as a percentage of price.
|
|
///
|
|
/// `Atr` reports volatility in raw price units, which makes its readings
|
|
/// impossible to compare across instruments at different price levels. NATR
|
|
/// fixes that by dividing by the current close:
|
|
///
|
|
/// ```text
|
|
/// NATR = 100 · ATR / close
|
|
/// ```
|
|
///
|
|
/// A NATR of `2.0` always means "the average true range is 2 % of price",
|
|
/// whether the instrument trades at $10 or $10 000 — so NATR values are
|
|
/// directly comparable, and stop distances or position sizes expressed as a
|
|
/// NATR multiple behave consistently across a portfolio.
|
|
///
|
|
/// # Example
|
|
///
|
|
/// ```
|
|
/// use wickra_core::{Candle, Indicator, Natr};
|
|
///
|
|
/// let mut indicator = Natr::new(14).unwrap();
|
|
/// let mut last = None;
|
|
/// for i in 0..80 {
|
|
/// let base = 100.0 + f64::from(i);
|
|
/// let candle =
|
|
/// Candle::new(base, base + 2.0, base - 2.0, base, 10.0, i64::from(i)).unwrap();
|
|
/// last = indicator.update(candle);
|
|
/// }
|
|
/// assert!(last.is_some());
|
|
/// ```
|
|
#[derive(Debug, Clone)]
|
|
pub struct Natr {
|
|
atr: Atr,
|
|
last: Option<f64>,
|
|
}
|
|
|
|
impl Natr {
|
|
/// Construct a new NATR with the given ATR period.
|
|
///
|
|
/// # Errors
|
|
///
|
|
/// Returns [`crate::Error::PeriodZero`] if `period == 0`.
|
|
pub fn new(period: usize) -> Result<Self> {
|
|
Ok(Self {
|
|
atr: Atr::new(period)?,
|
|
last: None,
|
|
})
|
|
}
|
|
|
|
/// Configured period.
|
|
pub const fn period(&self) -> usize {
|
|
self.atr.period()
|
|
}
|
|
|
|
/// Current value if available.
|
|
pub const fn value(&self) -> Option<f64> {
|
|
self.last
|
|
}
|
|
}
|
|
|
|
impl Indicator for Natr {
|
|
type Input = Candle;
|
|
type Output = f64;
|
|
|
|
fn update(&mut self, candle: Candle) -> Option<f64> {
|
|
let atr = self.atr.update(candle)?;
|
|
let natr = if candle.close == 0.0 {
|
|
// NATR is undefined against a zero close.
|
|
0.0
|
|
} else {
|
|
100.0 * atr / candle.close
|
|
};
|
|
self.last = Some(natr);
|
|
Some(natr)
|
|
}
|
|
|
|
fn reset(&mut self) {
|
|
self.atr.reset();
|
|
self.last = None;
|
|
}
|
|
|
|
fn warmup_period(&self) -> usize {
|
|
self.atr.warmup_period()
|
|
}
|
|
|
|
fn is_ready(&self) -> bool {
|
|
self.last.is_some()
|
|
}
|
|
|
|
fn name(&self) -> &'static str {
|
|
"NATR"
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use crate::traits::BatchExt;
|
|
use approx::assert_relative_eq;
|
|
|
|
fn candle(open: f64, high: f64, low: f64, close: f64, ts: i64) -> Candle {
|
|
Candle::new(open, high, low, close, 1.0, ts).unwrap()
|
|
}
|
|
|
|
#[test]
|
|
fn new_rejects_zero_period() {
|
|
assert!(Natr::new(0).is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn warmup_period_matches_atr() {
|
|
let natr = Natr::new(14).unwrap();
|
|
assert_eq!(natr.warmup_period(), 14);
|
|
}
|
|
|
|
/// Cover the const accessors `period` / `value` (lines 59-66) and the
|
|
/// Indicator-impl `name` body (98-100). `warmup_period` is covered
|
|
/// already by `warmup_period_matches_atr`.
|
|
#[test]
|
|
fn accessors_and_metadata() {
|
|
let mut natr = Natr::new(14).unwrap();
|
|
assert_eq!(natr.period(), 14);
|
|
assert_eq!(natr.name(), "NATR");
|
|
assert_eq!(natr.value(), None);
|
|
let candles: Vec<Candle> = (0..14)
|
|
.map(|i| candle(100.0, 102.0, 98.0, 101.0, i))
|
|
.collect();
|
|
for c in &candles {
|
|
natr.update(*c);
|
|
}
|
|
assert!(natr.value().is_some());
|
|
}
|
|
|
|
/// Cover the `candle.close == 0.0` defensive branch (line 77). All
|
|
/// other tests feed candles with close ≈ 100, so the zero-close
|
|
/// fallback never fired. Feed an all-zero candle series — the Candle
|
|
/// validator accepts open == high == low == close == 0 with positive
|
|
/// volume, and ATR is 0 each bar, so the indicator must emit exactly
|
|
/// 0.0 rather than computing 100 * 0 / 0 = NaN.
|
|
#[test]
|
|
fn zero_close_yields_zero_natr() {
|
|
let candles: Vec<Candle> = (0..15).map(|i| candle(0.0, 0.0, 0.0, 0.0, i)).collect();
|
|
let mut natr = Natr::new(5).unwrap();
|
|
let out = natr.batch(&candles);
|
|
let last = out.into_iter().flatten().last().expect("emits");
|
|
assert_eq!(last, 0.0);
|
|
}
|
|
|
|
#[test]
|
|
fn natr_is_atr_over_close_as_percent() {
|
|
// NATR must equal 100 * ATR / close, bar for bar.
|
|
let candles: Vec<Candle> = (0..60)
|
|
.map(|i| {
|
|
let mid = 100.0 + (i as f64 * 0.3).sin() * 10.0;
|
|
candle(mid, mid + 3.0, mid - 3.0, mid + 1.0, i)
|
|
})
|
|
.collect();
|
|
let natr_out = Natr::new(14).unwrap().batch(&candles);
|
|
let atr_out = Atr::new(14).unwrap().batch(&candles);
|
|
for (i, (n, a)) in natr_out.iter().zip(atr_out.iter()).enumerate() {
|
|
// Same warmup period — emission shape must agree at every index.
|
|
assert_eq!(n.is_some(), a.is_some(), "warmup mismatch at index {i}");
|
|
if let (Some(nv), Some(av)) = (n, a) {
|
|
let want = 100.0 * av / candles[i].close;
|
|
assert_relative_eq!(*nv, want, epsilon = 1e-9);
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn flat_market_yields_zero() {
|
|
// No range -> ATR is 0 -> NATR is 0.
|
|
let mut natr = Natr::new(5).unwrap();
|
|
let candles: Vec<Candle> = (0..30)
|
|
.map(|i| candle(100.0, 100.0, 100.0, 100.0, i))
|
|
.collect();
|
|
for v in natr.batch(&candles).into_iter().flatten() {
|
|
assert_relative_eq!(v, 0.0, epsilon = 1e-12);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn reset_clears_state() {
|
|
let mut natr = Natr::new(5).unwrap();
|
|
let candles: Vec<Candle> = (0..20)
|
|
.map(|i| candle(100.0, 102.0, 98.0, 101.0, i))
|
|
.collect();
|
|
natr.batch(&candles);
|
|
assert!(natr.is_ready());
|
|
natr.reset();
|
|
assert!(!natr.is_ready());
|
|
assert_eq!(natr.update(candles[0]), None);
|
|
}
|
|
|
|
#[test]
|
|
fn batch_equals_streaming() {
|
|
let candles: Vec<Candle> = (0..80)
|
|
.map(|i| {
|
|
let mid = 100.0 + (i as f64 * 0.35).sin() * 9.0;
|
|
candle(mid, mid + 2.5, mid - 2.5, mid + 0.5, i)
|
|
})
|
|
.collect();
|
|
let batch = Natr::new(14).unwrap().batch(&candles);
|
|
let mut b = Natr::new(14).unwrap();
|
|
let streamed: Vec<_> = candles.iter().map(|c| b.update(*c)).collect();
|
|
assert_eq!(batch, streamed);
|
|
}
|
|
}
|