F5: add PPO, DPO and Coppock Curve price oscillators
Completes the F5 family (Price oscillators) end to end: - Rust core: ppo.rs (Percentage Price Oscillator — MACD as a percentage of the slow EMA), dpo.rs (Detrended Price Oscillator — shifted price minus its SMA), coppock.rs (Coppock Curve — WMA of two summed ROCs). Each with a full Indicator impl, runnable doctest and reference / constant-series / warmup / reset / batch==streaming / non-finite tests. - Python: PyPpo / PyDpo / PyCoppock PyO3 classes + module registration + .pyi stubs (defaults PPO=(12,26), DPO=20, Coppock=(14,11,10)). - Node: DpoNode via the scalar macro, explicit PpoNode and CoppockNode; index.d.ts and index.js updated. - WASM: WasmDpo / WasmPpo / WasmCoppock via the scalar macro. - Wiki: Indicator-Ppo/Dpo/Coppock.md plus rows in Indicators-Overview.md and entries in Home.md. cargo fmt + clippy (core/wickra/data/wasm/node) clean; 300 core tests, 25 data tests and 42 doctests green.
This commit is contained in:
@@ -0,0 +1,198 @@
|
||||
//! Coppock Curve.
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::traits::Indicator;
|
||||
|
||||
use super::{Roc, Wma};
|
||||
|
||||
/// Coppock Curve — Edwin Coppock's long-term momentum indicator.
|
||||
///
|
||||
/// The Coppock Curve is a weighted moving average of the sum of two rates of
|
||||
/// change:
|
||||
///
|
||||
/// ```text
|
||||
/// Coppock = WMA( ROC(long) + ROC(short), wma_period )
|
||||
/// ```
|
||||
///
|
||||
/// Coppock designed it (1962) as a long-horizon buy signal for stock indices:
|
||||
/// on a monthly chart with the conventional `(long = 14, short = 11,
|
||||
/// wma_period = 10)`, a turn upward from below zero has historically marked
|
||||
/// the start of a new bull phase. The two ROCs blend a slightly longer and a
|
||||
/// slightly shorter momentum horizon; the WMA smooths the result.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use wickra_core::{Indicator, Coppock};
|
||||
///
|
||||
/// let mut indicator = Coppock::new(14, 11, 10).unwrap();
|
||||
/// let mut last = None;
|
||||
/// for i in 0..120 {
|
||||
/// last = indicator.update(100.0 + f64::from(i));
|
||||
/// }
|
||||
/// assert!(last.is_some());
|
||||
/// ```
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Coppock {
|
||||
roc_long_period: usize,
|
||||
roc_short_period: usize,
|
||||
wma_period: usize,
|
||||
roc_long: Roc,
|
||||
roc_short: Roc,
|
||||
wma: Wma,
|
||||
current: Option<f64>,
|
||||
}
|
||||
|
||||
impl Coppock {
|
||||
/// Construct a new Coppock Curve with the two ROC periods and the WMA period.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`Error::PeriodZero`] if any period is `0`.
|
||||
pub fn new(roc_long_period: usize, roc_short_period: usize, wma_period: usize) -> Result<Self> {
|
||||
if roc_long_period == 0 || roc_short_period == 0 || wma_period == 0 {
|
||||
return Err(Error::PeriodZero);
|
||||
}
|
||||
Ok(Self {
|
||||
roc_long_period,
|
||||
roc_short_period,
|
||||
wma_period,
|
||||
roc_long: Roc::new(roc_long_period)?,
|
||||
roc_short: Roc::new(roc_short_period)?,
|
||||
wma: Wma::new(wma_period)?,
|
||||
current: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The `(roc_long, roc_short, wma)` periods.
|
||||
pub const fn periods(&self) -> (usize, usize, usize) {
|
||||
(self.roc_long_period, self.roc_short_period, self.wma_period)
|
||||
}
|
||||
|
||||
/// Current value if available.
|
||||
pub const fn value(&self) -> Option<f64> {
|
||||
self.current
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for Coppock {
|
||||
type Input = f64;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, input: f64) -> Option<f64> {
|
||||
if !input.is_finite() {
|
||||
// Non-finite input is ignored; no component is advanced.
|
||||
return self.current;
|
||||
}
|
||||
let long = self.roc_long.update(input);
|
||||
let short = self.roc_short.update(input);
|
||||
let result = match (long, short) {
|
||||
(Some(l), Some(s)) => self.wma.update(l + s),
|
||||
_ => None,
|
||||
};
|
||||
if result.is_some() {
|
||||
self.current = result;
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.roc_long.reset();
|
||||
self.roc_short.reset();
|
||||
self.wma.reset();
|
||||
self.current = None;
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
// Both ROCs must be ready (the longer one is `period + 1`), then the
|
||||
// WMA needs `wma_period` of their summed values.
|
||||
self.roc_long_period.max(self.roc_short_period) + self.wma_period
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.current.is_some()
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"Coppock"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
#[test]
|
||||
fn new_rejects_zero_period() {
|
||||
assert!(matches!(Coppock::new(0, 11, 10), Err(Error::PeriodZero)));
|
||||
assert!(matches!(Coppock::new(14, 0, 10), Err(Error::PeriodZero)));
|
||||
assert!(matches!(Coppock::new(14, 11, 0), Err(Error::PeriodZero)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_emission_at_warmup_period() {
|
||||
let mut c = Coppock::new(6, 4, 3).unwrap();
|
||||
assert_eq!(c.warmup_period(), 9);
|
||||
let out = c.batch(&(1..=40).map(f64::from).collect::<Vec<_>>());
|
||||
for v in out.iter().take(8) {
|
||||
assert!(v.is_none());
|
||||
}
|
||||
assert!(out[8].is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_series_yields_zero() {
|
||||
// Both ROCs are 0 on a flat series, so the WMA of zeros is 0.
|
||||
let mut c = Coppock::new(6, 4, 3).unwrap();
|
||||
let out = c.batch(&[100.0; 40]);
|
||||
for v in out.iter().skip(c.warmup_period() - 1).flatten() {
|
||||
assert_relative_eq!(*v, 0.0, epsilon = 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uptrend_is_positive() {
|
||||
// A steady uptrend has positive ROCs, so the Coppock Curve is positive.
|
||||
let mut c = Coppock::new(14, 11, 10).unwrap();
|
||||
let prices: Vec<f64> = (1..=120).map(|i| 100.0 * 1.01_f64.powi(i)).collect();
|
||||
let out = c.batch(&prices);
|
||||
let last = out.iter().rev().flatten().next().unwrap();
|
||||
assert!(
|
||||
*last > 0.0,
|
||||
"uptrend Coppock should be positive, got {last}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_non_finite_input() {
|
||||
let mut c = Coppock::new(6, 4, 3).unwrap();
|
||||
let out = c.batch(&(1..=40).map(f64::from).collect::<Vec<_>>());
|
||||
let last = *out.last().unwrap();
|
||||
assert!(last.is_some());
|
||||
assert_eq!(c.update(f64::NAN), last);
|
||||
assert_eq!(c.update(f64::INFINITY), last);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut c = Coppock::new(6, 4, 3).unwrap();
|
||||
c.batch(&(1..=40).map(f64::from).collect::<Vec<_>>());
|
||||
assert!(c.is_ready());
|
||||
c.reset();
|
||||
assert!(!c.is_ready());
|
||||
assert_eq!(c.update(1.0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let prices: Vec<f64> = (1..=120)
|
||||
.map(|i| 100.0 + (f64::from(i) * 0.2).sin() * 10.0)
|
||||
.collect();
|
||||
let batch = Coppock::new(14, 11, 10).unwrap().batch(&prices);
|
||||
let mut b = Coppock::new(14, 11, 10).unwrap();
|
||||
let streamed: Vec<_> = prices.iter().map(|p| b.update(*p)).collect();
|
||||
assert_eq!(batch, streamed);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
//! Detrended Price Oscillator.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Detrended Price Oscillator — strips the trend out of price to expose its
|
||||
/// shorter cycles.
|
||||
///
|
||||
/// Instead of comparing price to a *current* moving average, DPO compares a
|
||||
/// **past** price — shifted back by `period / 2 + 1` bars — to the moving
|
||||
/// average of the window:
|
||||
///
|
||||
/// ```text
|
||||
/// shift = period / 2 + 1
|
||||
/// DPO_t = price_{t − shift} − SMA(period)_t
|
||||
/// ```
|
||||
///
|
||||
/// Because the price is taken from roughly half a cycle back, the dominant
|
||||
/// trend cancels out and what remains oscillates around zero — making the
|
||||
/// peak-to-peak cycle length easy to read. DPO is **not** a momentum
|
||||
/// indicator and is not meant to track the latest bar.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use wickra_core::{Indicator, Dpo};
|
||||
///
|
||||
/// let mut indicator = Dpo::new(20).unwrap();
|
||||
/// let mut last = None;
|
||||
/// for i in 0..80 {
|
||||
/// last = indicator.update(100.0 + (f64::from(i) * 0.3).sin() * 10.0);
|
||||
/// }
|
||||
/// assert!(last.is_some());
|
||||
/// ```
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Dpo {
|
||||
period: usize,
|
||||
shift: usize,
|
||||
/// Window of the most recent `capacity` prices, oldest at the front.
|
||||
capacity: usize,
|
||||
window: VecDeque<f64>,
|
||||
sum: f64,
|
||||
last: Option<f64>,
|
||||
}
|
||||
|
||||
impl Dpo {
|
||||
/// Construct a new DPO with the given period.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`Error::PeriodZero`] if `period == 0`.
|
||||
pub fn new(period: usize) -> Result<Self> {
|
||||
if period == 0 {
|
||||
return Err(Error::PeriodZero);
|
||||
}
|
||||
let shift = period / 2 + 1;
|
||||
// The window must cover both the SMA (`period` prices) and the
|
||||
// look-back (`shift + 1` prices: the current bar plus `shift` history).
|
||||
let capacity = period.max(shift + 1);
|
||||
Ok(Self {
|
||||
period,
|
||||
shift,
|
||||
capacity,
|
||||
window: VecDeque::with_capacity(capacity),
|
||||
sum: 0.0,
|
||||
last: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Configured period.
|
||||
pub const fn period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
|
||||
/// The look-back shift `period / 2 + 1`.
|
||||
pub const fn shift(&self) -> usize {
|
||||
self.shift
|
||||
}
|
||||
|
||||
/// Current value if available.
|
||||
pub const fn value(&self) -> Option<f64> {
|
||||
self.last
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for Dpo {
|
||||
type Input = f64;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, input: f64) -> Option<f64> {
|
||||
if !input.is_finite() {
|
||||
// Non-finite input is ignored; the window is left untouched.
|
||||
return self.last;
|
||||
}
|
||||
self.window.push_back(input);
|
||||
self.sum += input;
|
||||
let len = self.window.len();
|
||||
if len > self.period {
|
||||
// The price that just left the SMA window.
|
||||
self.sum -= self.window[len - 1 - self.period];
|
||||
}
|
||||
if self.window.len() > self.capacity {
|
||||
self.window.pop_front();
|
||||
}
|
||||
if self.window.len() < self.capacity {
|
||||
return None;
|
||||
}
|
||||
let sma = self.sum / self.period as f64;
|
||||
// `price_{t - shift}` — index counts back from the newest bar.
|
||||
let shifted = self.window[self.window.len() - 1 - self.shift];
|
||||
let dpo = shifted - sma;
|
||||
self.last = Some(dpo);
|
||||
Some(dpo)
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.window.clear();
|
||||
self.sum = 0.0;
|
||||
self.last = None;
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
self.capacity
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.last.is_some()
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"DPO"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
#[test]
|
||||
fn new_rejects_zero_period() {
|
||||
assert!(matches!(Dpo::new(0), Err(Error::PeriodZero)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_is_half_period_plus_one() {
|
||||
assert_eq!(Dpo::new(20).unwrap().shift(), 11);
|
||||
assert_eq!(Dpo::new(4).unwrap().shift(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reference_values() {
|
||||
// DPO(4): shift = 3, capacity = max(4, 4) = 4.
|
||||
// At input 4: window [1,2,3,4], SMA = 2.5, price[t-3] = 1 -> 1 - 2.5 = -1.5.
|
||||
let mut dpo = Dpo::new(4).unwrap();
|
||||
let out = dpo.batch(&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
|
||||
assert_eq!(dpo.warmup_period(), 4);
|
||||
assert_eq!(out[0], None);
|
||||
assert_eq!(out[2], None);
|
||||
assert_relative_eq!(out[3].unwrap(), -1.5, epsilon = 1e-12);
|
||||
assert_relative_eq!(out[4].unwrap(), -1.5, epsilon = 1e-12);
|
||||
assert_relative_eq!(out[5].unwrap(), -1.5, epsilon = 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_series_yields_zero() {
|
||||
// A flat series: the shifted price equals the SMA, so DPO is 0.
|
||||
let mut dpo = Dpo::new(10).unwrap();
|
||||
let out = dpo.batch(&[50.0; 40]);
|
||||
for v in out.iter().skip(dpo.warmup_period() - 1).flatten() {
|
||||
assert_relative_eq!(*v, 0.0, epsilon = 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_non_finite_input() {
|
||||
let mut dpo = Dpo::new(4).unwrap();
|
||||
let out = dpo.batch(&[1.0, 2.0, 3.0, 4.0, 5.0]);
|
||||
let last = *out.last().unwrap();
|
||||
assert!(last.is_some());
|
||||
assert_eq!(dpo.update(f64::NAN), last);
|
||||
assert_eq!(dpo.update(f64::INFINITY), last);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut dpo = Dpo::new(4).unwrap();
|
||||
dpo.batch(&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
|
||||
assert!(dpo.is_ready());
|
||||
dpo.reset();
|
||||
assert!(!dpo.is_ready());
|
||||
assert_eq!(dpo.update(1.0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let prices: Vec<f64> = (1..=80)
|
||||
.map(|i| 100.0 + (f64::from(i) * 0.4).sin() * 7.0)
|
||||
.collect();
|
||||
let batch = Dpo::new(20).unwrap().batch(&prices);
|
||||
let mut b = Dpo::new(20).unwrap();
|
||||
let streamed: Vec<_> = prices.iter().map(|p| b.update(*p)).collect();
|
||||
assert_eq!(batch, streamed);
|
||||
}
|
||||
}
|
||||
@@ -11,8 +11,10 @@ mod awesome_oscillator;
|
||||
mod bollinger;
|
||||
mod cci;
|
||||
mod cmo;
|
||||
mod coppock;
|
||||
mod dema;
|
||||
mod donchian;
|
||||
mod dpo;
|
||||
mod ema;
|
||||
mod hma;
|
||||
mod kama;
|
||||
@@ -22,6 +24,7 @@ mod mfi;
|
||||
mod mom;
|
||||
mod obv;
|
||||
mod pmo;
|
||||
mod ppo;
|
||||
mod psar;
|
||||
mod roc;
|
||||
mod rsi;
|
||||
@@ -48,8 +51,10 @@ pub use awesome_oscillator::AwesomeOscillator;
|
||||
pub use bollinger::{BollingerBands, BollingerOutput};
|
||||
pub use cci::Cci;
|
||||
pub use cmo::Cmo;
|
||||
pub use coppock::Coppock;
|
||||
pub use dema::Dema;
|
||||
pub use donchian::{Donchian, DonchianOutput};
|
||||
pub use dpo::Dpo;
|
||||
pub use ema::Ema;
|
||||
pub use hma::Hma;
|
||||
pub use kama::Kama;
|
||||
@@ -59,6 +64,7 @@ pub use mfi::Mfi;
|
||||
pub use mom::Mom;
|
||||
pub use obv::Obv;
|
||||
pub use pmo::Pmo;
|
||||
pub use ppo::Ppo;
|
||||
pub use psar::Psar;
|
||||
pub use roc::Roc;
|
||||
pub use rsi::Rsi;
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
//! Percentage Price Oscillator.
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::traits::Indicator;
|
||||
|
||||
use super::Ema;
|
||||
|
||||
/// Percentage Price Oscillator — MACD expressed as a percentage.
|
||||
///
|
||||
/// PPO is the gap between a fast and a slow EMA, divided by the slow EMA and
|
||||
/// scaled to a percentage:
|
||||
///
|
||||
/// ```text
|
||||
/// PPO = 100 · (EMA_fast − EMA_slow) / EMA_slow
|
||||
/// ```
|
||||
///
|
||||
/// Dividing by the slow EMA makes PPO **scale-free**: a `PPO` of `1.5` means
|
||||
/// "the fast EMA is 1.5 % above the slow EMA" on any instrument, so PPO
|
||||
/// readings *are* comparable across assets — unlike the raw price-unit
|
||||
/// [`MacdIndicator`](crate::MacdIndicator). The classic PPO **signal line** is
|
||||
/// a 9-period EMA of this PPO line; compose it with [`Chain`](crate::Chain)
|
||||
/// and an [`Ema`] if you need it.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use wickra_core::{Indicator, Ppo};
|
||||
///
|
||||
/// let mut indicator = Ppo::new(12, 26).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 Ppo {
|
||||
fast: usize,
|
||||
slow: usize,
|
||||
ema_fast: Ema,
|
||||
ema_slow: Ema,
|
||||
current: Option<f64>,
|
||||
}
|
||||
|
||||
impl Ppo {
|
||||
/// Construct a new PPO with the `fast` and `slow` EMA periods.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`Error::PeriodZero`] if either period is `0`, or
|
||||
/// [`Error::InvalidPeriod`] if `fast >= slow`.
|
||||
pub fn new(fast: usize, slow: usize) -> Result<Self> {
|
||||
if fast == 0 || slow == 0 {
|
||||
return Err(Error::PeriodZero);
|
||||
}
|
||||
if fast >= slow {
|
||||
return Err(Error::InvalidPeriod {
|
||||
message: "PPO fast period must be < slow period",
|
||||
});
|
||||
}
|
||||
Ok(Self {
|
||||
fast,
|
||||
slow,
|
||||
ema_fast: Ema::new(fast)?,
|
||||
ema_slow: Ema::new(slow)?,
|
||||
current: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The `(fast, slow)` periods.
|
||||
pub const fn periods(&self) -> (usize, usize) {
|
||||
(self.fast, self.slow)
|
||||
}
|
||||
|
||||
/// Current value if available.
|
||||
pub const fn value(&self) -> Option<f64> {
|
||||
self.current
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for Ppo {
|
||||
type Input = f64;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, input: f64) -> Option<f64> {
|
||||
if !input.is_finite() {
|
||||
// Non-finite input is ignored; the EMAs are not advanced.
|
||||
return self.current;
|
||||
}
|
||||
let fast = self.ema_fast.update(input);
|
||||
let slow = self.ema_slow.update(input);
|
||||
match (fast, slow) {
|
||||
(Some(f), Some(s)) => {
|
||||
let ppo = if s == 0.0 {
|
||||
// Undefined ratio against a zero slow EMA: report flat.
|
||||
0.0
|
||||
} else {
|
||||
100.0 * (f - s) / s
|
||||
};
|
||||
self.current = Some(ppo);
|
||||
Some(ppo)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.ema_fast.reset();
|
||||
self.ema_slow.reset();
|
||||
self.current = None;
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
// The slow EMA is the last to seed.
|
||||
self.slow
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.current.is_some()
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"PPO"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
#[test]
|
||||
fn new_rejects_zero_period() {
|
||||
assert!(matches!(Ppo::new(0, 26), Err(Error::PeriodZero)));
|
||||
assert!(matches!(Ppo::new(12, 0), Err(Error::PeriodZero)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_rejects_fast_not_less_than_slow() {
|
||||
assert!(matches!(Ppo::new(26, 12), Err(Error::InvalidPeriod { .. })));
|
||||
assert!(matches!(Ppo::new(12, 12), Err(Error::InvalidPeriod { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_emission_at_warmup_period() {
|
||||
let mut ppo = Ppo::new(3, 6).unwrap();
|
||||
assert_eq!(ppo.warmup_period(), 6);
|
||||
let out = ppo.batch(&(1..=30).map(f64::from).collect::<Vec<_>>());
|
||||
for v in out.iter().take(5) {
|
||||
assert!(v.is_none());
|
||||
}
|
||||
assert!(out[5].is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_series_yields_zero() {
|
||||
// Both EMAs converge to the constant, so their gap is zero.
|
||||
let mut ppo = Ppo::new(3, 6).unwrap();
|
||||
let out = ppo.batch(&[100.0; 60]);
|
||||
for v in out.iter().skip(5).flatten() {
|
||||
assert_relative_eq!(*v, 0.0, epsilon = 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uptrend_is_positive() {
|
||||
// In a rising series the fast EMA leads the slow EMA, so PPO > 0.
|
||||
let mut ppo = Ppo::new(5, 12).unwrap();
|
||||
let out = ppo.batch(&(1..=80).map(f64::from).collect::<Vec<_>>());
|
||||
let last = out.iter().rev().flatten().next().unwrap();
|
||||
assert!(*last > 0.0, "uptrend PPO should be positive, got {last}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_non_finite_input() {
|
||||
let mut ppo = Ppo::new(3, 6).unwrap();
|
||||
let out = ppo.batch(&(1..=30).map(f64::from).collect::<Vec<_>>());
|
||||
let last = *out.last().unwrap();
|
||||
assert!(last.is_some());
|
||||
assert_eq!(ppo.update(f64::NAN), last);
|
||||
assert_eq!(ppo.update(f64::INFINITY), last);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut ppo = Ppo::new(3, 6).unwrap();
|
||||
ppo.batch(&(1..=30).map(f64::from).collect::<Vec<_>>());
|
||||
assert!(ppo.is_ready());
|
||||
ppo.reset();
|
||||
assert!(!ppo.is_ready());
|
||||
assert_eq!(ppo.update(1.0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let prices: Vec<f64> = (1..=120)
|
||||
.map(|i| 100.0 + (f64::from(i) * 0.25).sin() * 9.0)
|
||||
.collect();
|
||||
let batch = Ppo::new(12, 26).unwrap().batch(&prices);
|
||||
let mut b = Ppo::new(12, 26).unwrap();
|
||||
let streamed: Vec<_> = prices.iter().map(|p| b.update(*p)).collect();
|
||||
assert_eq!(batch, streamed);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user