* feat(apo): add Absolute Price Oscillator EMA(close, fast) - EMA(close, slow). Like MACD without the signal EMA. Defaults to (fast = 12, slow = 26); fast must be strictly less than slow. Touchpoints: apo.rs + mod.rs + lib.rs re-export, PyApo + __init__.py + test_new_indicators SCALAR + test_known_values flat reference, ApoNode + index.d.ts/index.js + indicators.test.js factory + reference, WasmApo via scalar macro, scalar-fuzz target, README + CHANGELOG. * fix(apo): add PyApo + ApoNode + WasmApo bindings missed fromec269d8The previous APO commit (ec269d8) only registered APO in the Python __init__.py / Node index.js / Node index.d.ts / fuzz / tests / docs. The actual PyApo pyclass, ApoNode napi class, and WasmApo wasm class edits silently no-op'd because the underlying lib.rs files had been touched by a branch switch between Read and Edit. The bindings were therefore advertising APO from the Python module / Node package / WASM module but not actually exposing it. Fix: insert PyApo block + add_class call in bindings/python/src/lib.rs, ApoNode block in bindings/node/src/lib.rs, WasmApo macro line in bindings/wasm/src/lib.rs. cargo test workspace stays at 615 (no new tests added; the existing test_known_values + indicators.test.js references would have failed at import once the bindings rebuilt without these classes). * feat(ao-histogram): add Awesome Oscillator Histogram AO - SMA(AO, sma_period). A configurable variant of the existing AcceleratorOscillator (which fixes fast=5, slow=34, sma=5). Three parameters; defaults match Bill Williams' Accelerator. Touchpoints: awesome_oscillator_histogram.rs + mod.rs + lib.rs re-export, PyAoHist + __init__.py + test_new_indicators CANDLE_SCALAR + test_known_values flat reference, AwesomeOscillatorHistogramNode + index.d.ts/index.js + indicators.test.js factory + reference, WasmAoHist, candle-fuzz target, README + CHANGELOG. * feat(cfo): add Chande Forecast Oscillator 100 * (close - LinReg(close, period)) / close. Positive when close overshoots the linear forecast, negative when it undershoots. Holds the previous value if the close is zero (percentage form undefined). Single param period (default 14). Touchpoints: cfo.rs + mod.rs + lib.rs re-export, PyCfo + __init__.py + test_new_indicators SCALAR + test_known_values linear reference, CfoNode + index.d.ts/index.js + indicators.test.js factory + reference, WasmCfo via scalar macro, scalar-fuzz target, README + CHANGELOG. * fix(cfo): add WasmCfo binding missed from733afd9* feat(zero-lag-macd): add Zero-Lag MACD Classic MACD topology with ZLEMA substituted for EMA everywhere: faster reaction to trend changes at the cost of slightly noisier readings. Multi-output ZeroLagMacdOutput { macd, signal, histogram }. Three parameters (fast = 12, slow = 26, signal = 9); fast must be strictly less than slow. Touchpoints: zero_lag_macd.rs + mod.rs + lib.rs re-export, PyZeroLagMacd + __init__.py + test_new_indicators MULTI + test_known_values flat reference, ZeroLagMacdNode + ZeroLagMacdValue + index.d.ts/index.js + indicators.test.js multi factory + reference, WasmZeroLagMacd, scalar fuzz with hand-rolled drive (multi-output bypasses the f64-only helper), README + CHANGELOG. * feat(elder-impulse): add Alexander Elder Impulse System Tri-state momentum gauge: +1 (green/buy) when EMA trend and MACD histogram both rise, -1 (red/sell) when both fall, 0 (blue/neutral) on disagreement. Four parameters (ema_period, macd_fast, macd_slow, macd_signal); defaults (13, 12, 26, 9) match Elder. Internally feeds both branches on every input so they warm in parallel; needs one bar past the slowest branch to seed direction state. Touchpoints: elder_impulse.rs + mod.rs + lib.rs re-export, PyElderImpulse + __init__.py + test_new_indicators SCALAR + test_known_values neutral reference, ElderImpulseNode + index.d.ts/index.js + indicators.test.js factory + reference, WasmElderImpulse via scalar macro, scalar-fuzz target, README + CHANGELOG. * feat(stc): add Schaff Trend Cycle Doug Schaff's doubly-Stochastic-smoothed MACD. Bounded [0, 100] reading that reacts faster than MACD by extracting the percentile of MACD within a recent window, half-EMA-smoothing it, and re-stochasing the smoothed series. Four parameters (fast = 23, slow = 50, schaff_period = 10, factor = 0.5); fast must be strictly less than slow and factor must lie in (0, 1]. Output clamped to [0, 100] to absorb floating-point rounding. The stochastic stages clamp to 0 when their rolling range collapses (flat input or perfectly monotone trend), so a flat series settles deterministically at 0 after warmup. Touchpoints: stc.rs + mod.rs + lib.rs re-export, PyStc + __init__.py + test_new_indicators SCALAR + test_known_values flat reference, StcNode + index.d.ts/index.js + indicators.test.js factory + reference, WasmStc via scalar macro, scalar-fuzz target, README + CHANGELOG. * fix(stc): rename last_stc -> last_value to satisfy clippy * ci: Retry setup-node and setup-python on CDN flakes Setup-node on Windows runners and setup-python across all OSes occasionally fail with a silent hang or 5xx mid-download ("Attempting to download 18..." → fail in <1s) — pure upstream CDN flake. The fix ran on this branch's previous merge commit (24e723f) had to be re-triggered manually via `gh run rerun --failed`. Wrap both setup actions with continue-on-error and a follow-up retry step that waits 30s and re-runs the same setup. The retry only fires when the first attempt failed (steps.<id>.outcome == 'failure'), so a green setup costs nothing extra. The retry uses the identical pinned SHA so we still get supply-chain verification on both attempts. Applied to ci.yml (Python matrix and Node matrix). release.yml has the same setup-node / setup-python steps but is rarely re-run, so the existing manual rerun pattern stays sufficient for now. * test(zero-lag-macd): Fix MULTI dict shape mismatch + cover warmup_period ZeroLagMACD was registered in the Python MULTI dict (which asserts a (n, 2) batch shape) but actually emits (n, 3) — macd, signal, histogram — like MACD. Moved out into its own standalone test test_zero_lag_macd_streaming_matches_batch (3-tuple shape), and included in the lifecycle sweep. Mirrors the existing Alligator pattern for 3-output candle indicators. Also adds a unit test for ZeroLagMacd::warmup_period that pins both the (12, 26, 9) classic case and a small-period config — these four lines were the codecov/patch miss on PR 41.
174 lines
4.6 KiB
Rust
174 lines
4.6 KiB
Rust
//! Chande Forecast Oscillator (CFO).
|
||
|
||
use crate::error::{Error, Result};
|
||
use crate::indicators::linreg::LinearRegression;
|
||
use crate::traits::Indicator;
|
||
|
||
/// Tushar Chande's Forecast Oscillator — the percentage difference between
|
||
/// the close and the endpoint of an `n`-bar linear-regression forecast of the
|
||
/// close.
|
||
///
|
||
/// ```text
|
||
/// CFO_t = 100 · (close_t − LinearRegression(close, period)_t) / close_t
|
||
/// ```
|
||
///
|
||
/// Positive readings mean the close is *above* the linear forecast (price has
|
||
/// overshot trend); negative readings mean it sits below. Wraps the existing
|
||
/// `LinearRegression` so the warmup matches.
|
||
///
|
||
/// # Example
|
||
///
|
||
/// ```
|
||
/// use wickra_core::{Cfo, Indicator};
|
||
///
|
||
/// let mut cfo = Cfo::new(14).unwrap();
|
||
/// let mut last = None;
|
||
/// for i in 0..40 {
|
||
/// last = cfo.update(100.0 + f64::from(i));
|
||
/// }
|
||
/// assert!(last.is_some());
|
||
/// ```
|
||
#[derive(Debug, Clone)]
|
||
pub struct Cfo {
|
||
period: usize,
|
||
linreg: LinearRegression,
|
||
current: Option<f64>,
|
||
}
|
||
|
||
impl Cfo {
|
||
/// # Errors
|
||
/// Returns [`Error::PeriodZero`] if `period == 0`.
|
||
pub fn new(period: usize) -> Result<Self> {
|
||
if period == 0 {
|
||
return Err(Error::PeriodZero);
|
||
}
|
||
Ok(Self {
|
||
period,
|
||
linreg: LinearRegression::new(period)?,
|
||
current: None,
|
||
})
|
||
}
|
||
|
||
/// Configured period.
|
||
pub const fn period(&self) -> usize {
|
||
self.period
|
||
}
|
||
}
|
||
|
||
impl Indicator for Cfo {
|
||
type Input = f64;
|
||
type Output = f64;
|
||
|
||
fn update(&mut self, input: f64) -> Option<f64> {
|
||
let forecast = self.linreg.update(input)?;
|
||
// Hold the previous value if the close is zero — the percentage form
|
||
// is undefined and a return of inf would propagate badly.
|
||
if input == 0.0 {
|
||
return self.current;
|
||
}
|
||
let value = 100.0 * (input - forecast) / input;
|
||
self.current = Some(value);
|
||
Some(value)
|
||
}
|
||
|
||
fn reset(&mut self) {
|
||
self.linreg.reset();
|
||
self.current = None;
|
||
}
|
||
|
||
fn warmup_period(&self) -> usize {
|
||
self.period
|
||
}
|
||
|
||
fn is_ready(&self) -> bool {
|
||
self.current.is_some()
|
||
}
|
||
|
||
fn name(&self) -> &'static str {
|
||
"CFO"
|
||
}
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
use crate::traits::BatchExt;
|
||
use approx::assert_relative_eq;
|
||
|
||
#[test]
|
||
fn rejects_zero_period() {
|
||
assert!(matches!(Cfo::new(0), Err(Error::PeriodZero)));
|
||
}
|
||
|
||
#[test]
|
||
fn accessors_and_metadata() {
|
||
let cfo = Cfo::new(14).unwrap();
|
||
assert_eq!(cfo.period(), 14);
|
||
assert_eq!(cfo.warmup_period(), 14);
|
||
assert_eq!(cfo.name(), "CFO");
|
||
}
|
||
|
||
#[test]
|
||
fn constant_series_yields_zero() {
|
||
// LinReg of a constant series equals the constant, so close − forecast
|
||
// is 0 and CFO is 0.
|
||
let mut cfo = Cfo::new(5).unwrap();
|
||
let out = cfo.batch(&[42.0_f64; 30]);
|
||
for v in out.iter().skip(4).flatten() {
|
||
assert_relative_eq!(*v, 0.0, epsilon = 1e-12);
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn perfect_linear_series_yields_zero() {
|
||
// LinReg of a perfectly linear input fits the line exactly, so the
|
||
// close lands on the forecast and CFO = 0.
|
||
let mut cfo = Cfo::new(5).unwrap();
|
||
let prices: Vec<f64> = (1..=20).map(|i| f64::from(i) * 2.0).collect();
|
||
let out = cfo.batch(&prices);
|
||
for v in out.iter().skip(4).flatten() {
|
||
assert_relative_eq!(*v, 0.0, epsilon = 1e-9);
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn warmup_emits_first_value_at_period() {
|
||
let mut cfo = Cfo::new(3).unwrap();
|
||
for i in 1..=2 {
|
||
assert_eq!(cfo.update(f64::from(i)), None);
|
||
}
|
||
assert!(cfo.update(3.0).is_some());
|
||
}
|
||
|
||
#[test]
|
||
fn batch_equals_streaming() {
|
||
let prices: Vec<f64> = (1..=80)
|
||
.map(|i| 100.0 + (f64::from(i) * 0.3).sin() * 5.0)
|
||
.collect();
|
||
let mut a = Cfo::new(14).unwrap();
|
||
let mut b = Cfo::new(14).unwrap();
|
||
assert_eq!(
|
||
a.batch(&prices),
|
||
prices.iter().map(|p| b.update(*p)).collect::<Vec<_>>()
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn reset_clears_state() {
|
||
let mut cfo = Cfo::new(5).unwrap();
|
||
cfo.batch(&(1..=20).map(f64::from).collect::<Vec<_>>());
|
||
assert!(cfo.is_ready());
|
||
cfo.reset();
|
||
assert!(!cfo.is_ready());
|
||
assert_eq!(cfo.update(1.0), None);
|
||
}
|
||
|
||
#[test]
|
||
fn zero_close_holds_value() {
|
||
let mut cfo = Cfo::new(3).unwrap();
|
||
cfo.batch(&[1.0_f64, 2.0, 3.0]);
|
||
let before = cfo.current;
|
||
assert_eq!(cfo.update(0.0), before);
|
||
}
|
||
}
|