F8: add Bollinger Bandwidth and %b

Completes the F8 family (Bands & channels) end to end:

- Rust core: bollinger_bandwidth.rs ((upper - lower) / middle — the
  squeeze gauge) and percent_b.rs ((price - lower) / (upper - lower) —
  price position within the bands, unclamped). Both wrap BollingerBands
  and carry a full Indicator impl, runnable doctest and reference /
  constant-series / definition-consistency / warmup / reset /
  batch==streaming tests.
- Python: PyBollingerBandwidth / PyPercentB PyO3 classes + module
  registration + .pyi stubs (defaults (20, 2.0)).
- Node: explicit BollingerBandwidthNode and PercentBNode; index.d.ts
  and index.js updated.
- WASM: WasmBollingerBandwidth / WasmPercentB via the scalar macro.
- Wiki: Indicator-BollingerBandwidth.md and Indicator-PercentB.md plus
  rows in Indicators-Overview.md and entries in Home.md.

cargo fmt + clippy (core/wickra/data/wasm/node) clean; 362 core tests,
25 data tests and 51 doctests green.
This commit is contained in:
kingchenc
2026-05-22 18:30:49 +02:00
parent 6c58d3827c
commit 99dd144576
13 changed files with 907 additions and 7 deletions
+3 -1
View File
@@ -310,7 +310,7 @@ if (!nativeBinding) {
throw new Error(`Failed to load native binding`) throw new Error(`Failed to load native binding`)
} }
const { version, SMA, EMA, WMA, RSI, DEMA, TEMA, HMA, ROC, TRIX, SMMA, TRIMA, ZLEMA, T3, VWMA, MOM, CMO, TSI, PMO, StochRSI, UltimateOscillator, PPO, DPO, Coppock, AroonOscillator, Vortex, MassIndex, NATR, StdDev, UlcerIndex, HistoricalVolatility, MACD, BollingerBands, ATR, Stochastic, OBV, ADX, CCI, WilliamsR, MFI, PSAR, Keltner, Donchian, VWAP, AwesomeOscillator, Aroon, KAMA } = nativeBinding const { version, SMA, EMA, WMA, RSI, DEMA, TEMA, HMA, ROC, TRIX, SMMA, TRIMA, ZLEMA, T3, VWMA, MOM, CMO, TSI, PMO, StochRSI, UltimateOscillator, PPO, DPO, Coppock, AroonOscillator, Vortex, MassIndex, NATR, StdDev, UlcerIndex, HistoricalVolatility, BollingerBandwidth, PercentB, MACD, BollingerBands, ATR, Stochastic, OBV, ADX, CCI, WilliamsR, MFI, PSAR, Keltner, Donchian, VWAP, AwesomeOscillator, Aroon, KAMA } = nativeBinding
module.exports.version = version module.exports.version = version
module.exports.SMA = SMA module.exports.SMA = SMA
@@ -343,6 +343,8 @@ module.exports.NATR = NATR
module.exports.StdDev = StdDev module.exports.StdDev = StdDev
module.exports.UlcerIndex = UlcerIndex module.exports.UlcerIndex = UlcerIndex
module.exports.HistoricalVolatility = HistoricalVolatility module.exports.HistoricalVolatility = HistoricalVolatility
module.exports.BollingerBandwidth = BollingerBandwidth
module.exports.PercentB = PercentB
module.exports.MACD = MACD module.exports.MACD = MACD
module.exports.BollingerBands = BollingerBands module.exports.BollingerBands = BollingerBands
module.exports.ATR = ATR module.exports.ATR = ATR
+74
View File
@@ -1147,6 +1147,80 @@ impl PmoNode {
// ============================== VWMA ============================== // ============================== VWMA ==============================
// ============================== Bollinger Bandwidth ==============================
#[napi(js_name = "BollingerBandwidth")]
pub struct BollingerBandwidthNode {
inner: wc::BollingerBandwidth,
}
#[napi]
impl BollingerBandwidthNode {
#[napi(constructor)]
pub fn new(period: u32, multiplier: f64) -> napi::Result<Self> {
Ok(Self {
inner: wc::BollingerBandwidth::new(period as usize, multiplier).map_err(map_err)?,
})
}
#[napi]
pub fn update(&mut self, value: f64) -> Option<f64> {
self.inner.update(value)
}
#[napi]
pub fn batch(&mut self, prices: Vec<f64>) -> Vec<f64> {
flatten(self.inner.batch(&prices))
}
#[napi]
pub fn reset(&mut self) {
self.inner.reset();
}
#[napi(js_name = "isReady")]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[napi(js_name = "warmupPeriod")]
pub fn warmup_period(&self) -> u32 {
self.inner.warmup_period() as u32
}
}
// ============================== Percent B ==============================
#[napi(js_name = "PercentB")]
pub struct PercentBNode {
inner: wc::PercentB,
}
#[napi]
impl PercentBNode {
#[napi(constructor)]
pub fn new(period: u32, multiplier: f64) -> napi::Result<Self> {
Ok(Self {
inner: wc::PercentB::new(period as usize, multiplier).map_err(map_err)?,
})
}
#[napi]
pub fn update(&mut self, value: f64) -> Option<f64> {
self.inner.update(value)
}
#[napi]
pub fn batch(&mut self, prices: Vec<f64>) -> Vec<f64> {
flatten(self.inner.batch(&prices))
}
#[napi]
pub fn reset(&mut self) {
self.inner.reset();
}
#[napi(js_name = "isReady")]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[napi(js_name = "warmupPeriod")]
pub fn warmup_period(&self) -> u32 {
self.inner.warmup_period() as u32
}
}
// ============================== NATR ============================== // ============================== NATR ==============================
#[napi(js_name = "NATR")] #[napi(js_name = "NATR")]
@@ -76,6 +76,34 @@ class TRIMA:
@property @property
def value(self) -> Optional[float]: ... def value(self) -> Optional[float]: ...
class BollingerBandwidth:
def __init__(self, period: int = 20, multiplier: float = 2.0) -> None: ...
def update(self, value: float) -> Optional[float]: ...
def batch(self, prices: NDArray[np.float64]) -> NDArray[np.float64]: ...
def reset(self) -> None: ...
def is_ready(self) -> bool: ...
def warmup_period(self) -> int: ...
@property
def period(self) -> int: ...
@property
def multiplier(self) -> float: ...
@property
def value(self) -> Optional[float]: ...
class PercentB:
def __init__(self, period: int = 20, multiplier: float = 2.0) -> None: ...
def update(self, value: float) -> Optional[float]: ...
def batch(self, prices: NDArray[np.float64]) -> NDArray[np.float64]: ...
def reset(self) -> None: ...
def is_ready(self) -> bool: ...
def warmup_period(self) -> int: ...
@property
def period(self) -> int: ...
@property
def multiplier(self) -> float: ...
@property
def value(self) -> Optional[float]: ...
class NATR: class NATR:
def __init__(self, period: int = 14) -> None: ... def __init__(self, period: int = 14) -> None: ...
def update(self, candle: CandleLike) -> Optional[float]: ... def update(self, candle: CandleLike) -> Optional[float]: ...
+122
View File
@@ -1519,6 +1519,126 @@ impl PyAroon {
} }
} }
// ============================== Bollinger Bandwidth ==============================
#[pyclass(name = "BollingerBandwidth", module = "wickra._wickra")]
#[derive(Clone)]
struct PyBollingerBandwidth {
inner: wc::BollingerBandwidth,
}
#[pymethods]
impl PyBollingerBandwidth {
#[new]
#[pyo3(signature = (period=20, multiplier=2.0))]
fn new(period: usize, multiplier: f64) -> PyResult<Self> {
Ok(Self {
inner: wc::BollingerBandwidth::new(period, multiplier).map_err(map_err)?,
})
}
fn update(&mut self, value: f64) -> Option<f64> {
self.inner.update(value)
}
fn batch<'py>(
&mut self,
py: Python<'py>,
prices: PyReadonlyArray1<'py, f64>,
) -> PyResult<Bound<'py, PyArray1<f64>>> {
let slice = prices
.as_slice()
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
Ok(flatten(self.inner.batch(slice)).into_pyarray_bound(py))
}
#[getter]
fn period(&self) -> usize {
self.inner.period()
}
#[getter]
fn multiplier(&self) -> f64 {
self.inner.multiplier()
}
#[getter]
fn value(&self) -> Option<f64> {
self.inner.value()
}
fn reset(&mut self) {
self.inner.reset();
}
fn is_ready(&self) -> bool {
self.inner.is_ready()
}
fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
fn __repr__(&self) -> String {
format!(
"BollingerBandwidth(period={}, multiplier={})",
self.inner.period(),
self.inner.multiplier()
)
}
}
// ============================== Percent B ==============================
#[pyclass(name = "PercentB", module = "wickra._wickra")]
#[derive(Clone)]
struct PyPercentB {
inner: wc::PercentB,
}
#[pymethods]
impl PyPercentB {
#[new]
#[pyo3(signature = (period=20, multiplier=2.0))]
fn new(period: usize, multiplier: f64) -> PyResult<Self> {
Ok(Self {
inner: wc::PercentB::new(period, multiplier).map_err(map_err)?,
})
}
fn update(&mut self, value: f64) -> Option<f64> {
self.inner.update(value)
}
fn batch<'py>(
&mut self,
py: Python<'py>,
prices: PyReadonlyArray1<'py, f64>,
) -> PyResult<Bound<'py, PyArray1<f64>>> {
let slice = prices
.as_slice()
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
Ok(flatten(self.inner.batch(slice)).into_pyarray_bound(py))
}
#[getter]
fn period(&self) -> usize {
self.inner.period()
}
#[getter]
fn multiplier(&self) -> f64 {
self.inner.multiplier()
}
#[getter]
fn value(&self) -> Option<f64> {
self.inner.value()
}
fn reset(&mut self) {
self.inner.reset();
}
fn is_ready(&self) -> bool {
self.inner.is_ready()
}
fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
fn __repr__(&self) -> String {
format!(
"PercentB(period={}, multiplier={})",
self.inner.period(),
self.inner.multiplier()
)
}
}
// ============================== NATR ============================== // ============================== NATR ==============================
#[pyclass(name = "NATR", module = "wickra._wickra")] #[pyclass(name = "NATR", module = "wickra._wickra")]
@@ -2789,5 +2909,7 @@ fn _wickra(_py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<PyStdDev>()?; m.add_class::<PyStdDev>()?;
m.add_class::<PyUlcerIndex>()?; m.add_class::<PyUlcerIndex>()?;
m.add_class::<PyHistoricalVolatility>()?; m.add_class::<PyHistoricalVolatility>()?;
m.add_class::<PyBollingerBandwidth>()?;
m.add_class::<PyPercentB>()?;
Ok(()) Ok(())
} }
+2
View File
@@ -90,6 +90,8 @@ wasm_scalar_indicator!(WasmCoppock, "Coppock", wc::Coppock, roc_long: usize, roc
wasm_scalar_indicator!(WasmStdDev, "StdDev", wc::StdDev, period: usize); wasm_scalar_indicator!(WasmStdDev, "StdDev", wc::StdDev, period: usize);
wasm_scalar_indicator!(WasmUlcerIndex, "UlcerIndex", wc::UlcerIndex, period: usize); wasm_scalar_indicator!(WasmUlcerIndex, "UlcerIndex", wc::UlcerIndex, period: usize);
wasm_scalar_indicator!(WasmHistoricalVolatility, "HistoricalVolatility", wc::HistoricalVolatility, period: usize, trading_periods: usize); wasm_scalar_indicator!(WasmHistoricalVolatility, "HistoricalVolatility", wc::HistoricalVolatility, period: usize, trading_periods: usize);
wasm_scalar_indicator!(WasmBollingerBandwidth, "BollingerBandwidth", wc::BollingerBandwidth, period: usize, multiplier: f64);
wasm_scalar_indicator!(WasmPercentB, "PercentB", wc::PercentB, period: usize, multiplier: f64);
// ---------- KAMA (three params) ---------- // ---------- KAMA (three params) ----------
@@ -0,0 +1,176 @@
//! Bollinger Bandwidth.
use crate::error::Result;
use crate::traits::Indicator;
use super::BollingerBands;
/// Bollinger Bandwidth — the width of the Bollinger Bands relative to the
/// middle band.
///
/// ```text
/// Bandwidth = (upper lower) / middle
/// ```
///
/// Because the bands are `middle ± multiplier · stddev`, the bandwidth is
/// `2 · multiplier · stddev / middle` — a normalised volatility reading. Its
/// value is the basis of two classic patterns: the **squeeze** (bandwidth at a
/// multi-month low, signalling a coiled, low-volatility market about to
/// expand) and the **bulge** (bandwidth at an extreme high).
///
/// # Example
///
/// ```
/// use wickra_core::{Indicator, BollingerBandwidth};
///
/// let mut indicator = BollingerBandwidth::new(20, 2.0).unwrap();
/// let mut last = None;
/// for i in 0..80 {
/// last = indicator.update(100.0 + (f64::from(i) * 0.3).sin() * 6.0);
/// }
/// assert!(last.is_some());
/// ```
#[derive(Debug, Clone)]
pub struct BollingerBandwidth {
bands: BollingerBands,
last: Option<f64>,
}
impl BollingerBandwidth {
/// Construct a new Bollinger Bandwidth indicator.
///
/// # Errors
///
/// Returns [`crate::Error::PeriodZero`] for `period == 0` and
/// [`crate::Error::NonPositiveMultiplier`] for `multiplier <= 0`.
pub fn new(period: usize, multiplier: f64) -> Result<Self> {
Ok(Self {
bands: BollingerBands::new(period, multiplier)?,
last: None,
})
}
/// Configured period.
pub const fn period(&self) -> usize {
self.bands.period()
}
/// Configured multiplier.
pub const fn multiplier(&self) -> f64 {
self.bands.multiplier()
}
/// Current value if available.
pub const fn value(&self) -> Option<f64> {
self.last
}
}
impl Indicator for BollingerBandwidth {
type Input = f64;
type Output = f64;
fn update(&mut self, input: f64) -> Option<f64> {
let o = self.bands.update(input)?;
let bandwidth = if o.middle == 0.0 {
// Undefined against a zero middle band.
0.0
} else {
(o.upper - o.lower) / o.middle
};
self.last = Some(bandwidth);
Some(bandwidth)
}
fn reset(&mut self) {
self.bands.reset();
self.last = None;
}
fn warmup_period(&self) -> usize {
self.bands.warmup_period()
}
fn is_ready(&self) -> bool {
self.last.is_some()
}
fn name(&self) -> &'static str {
"BollingerBandwidth"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
#[test]
fn new_rejects_invalid_parameters() {
assert!(BollingerBandwidth::new(0, 2.0).is_err());
assert!(BollingerBandwidth::new(20, 0.0).is_err());
assert!(BollingerBandwidth::new(20, -1.0).is_err());
}
#[test]
fn constant_series_yields_zero() {
// Flat prices: the bands collapse onto the middle, so width is 0.
let mut bbw = BollingerBandwidth::new(5, 2.0).unwrap();
let out = bbw.batch(&[100.0; 20]);
for v in out.iter().skip(4).flatten() {
assert_relative_eq!(*v, 0.0, epsilon = 1e-12);
}
}
#[test]
fn matches_bands_definition() {
// Bandwidth must equal (upper - lower) / middle from BollingerBands.
let prices: Vec<f64> = (1..=60)
.map(|i| 100.0 + (f64::from(i) * 0.3).sin() * 8.0)
.collect();
let bbw_out = BollingerBandwidth::new(20, 2.0).unwrap().batch(&prices);
let bands_out = BollingerBands::new(20, 2.0).unwrap().batch(&prices);
for (w, b) in bbw_out.iter().zip(bands_out.iter()) {
match (w, b) {
(Some(wv), Some(bv)) => {
assert_relative_eq!(*wv, (bv.upper - bv.lower) / bv.middle, epsilon = 1e-12);
}
(None, None) => {}
_ => panic!("warmup mismatch"),
}
}
}
#[test]
fn output_is_non_negative() {
let mut bbw = BollingerBandwidth::new(20, 2.0).unwrap();
let prices: Vec<f64> = (1..=120)
.map(|i| 100.0 + (f64::from(i) * 0.25).sin() * 12.0)
.collect();
for v in bbw.batch(&prices).into_iter().flatten() {
assert!(v >= 0.0, "bandwidth must be non-negative, got {v}");
}
}
#[test]
fn reset_clears_state() {
let mut bbw = BollingerBandwidth::new(5, 2.0).unwrap();
bbw.batch(&(1..=20).map(f64::from).collect::<Vec<_>>());
assert!(bbw.is_ready());
bbw.reset();
assert!(!bbw.is_ready());
assert_eq!(bbw.update(1.0), None);
}
#[test]
fn batch_equals_streaming() {
let prices: Vec<f64> = (1..=80)
.map(|i| 100.0 + (f64::from(i) * 0.3).cos() * 7.0)
.collect();
let batch = BollingerBandwidth::new(20, 2.0).unwrap().batch(&prices);
let mut b = BollingerBandwidth::new(20, 2.0).unwrap();
let streamed: Vec<_> = prices.iter().map(|p| b.update(*p)).collect();
assert_eq!(batch, streamed);
}
}
+4
View File
@@ -10,6 +10,7 @@ mod aroon_oscillator;
mod atr; mod atr;
mod awesome_oscillator; mod awesome_oscillator;
mod bollinger; mod bollinger;
mod bollinger_bandwidth;
mod cci; mod cci;
mod cmo; mod cmo;
mod coppock; mod coppock;
@@ -27,6 +28,7 @@ mod mfi;
mod mom; mod mom;
mod natr; mod natr;
mod obv; mod obv;
mod percent_b;
mod pmo; mod pmo;
mod ppo; mod ppo;
mod psar; mod psar;
@@ -57,6 +59,7 @@ pub use aroon_oscillator::AroonOscillator;
pub use atr::Atr; pub use atr::Atr;
pub use awesome_oscillator::AwesomeOscillator; pub use awesome_oscillator::AwesomeOscillator;
pub use bollinger::{BollingerBands, BollingerOutput}; pub use bollinger::{BollingerBands, BollingerOutput};
pub use bollinger_bandwidth::BollingerBandwidth;
pub use cci::Cci; pub use cci::Cci;
pub use cmo::Cmo; pub use cmo::Cmo;
pub use coppock::Coppock; pub use coppock::Coppock;
@@ -74,6 +77,7 @@ pub use mfi::Mfi;
pub use mom::Mom; pub use mom::Mom;
pub use natr::Natr; pub use natr::Natr;
pub use obv::Obv; pub use obv::Obv;
pub use percent_b::PercentB;
pub use pmo::Pmo; pub use pmo::Pmo;
pub use ppo::Ppo; pub use ppo::Ppo;
pub use psar::Psar; pub use psar::Psar;
@@ -0,0 +1,184 @@
//! Bollinger %b.
use crate::error::Result;
use crate::traits::Indicator;
use super::BollingerBands;
/// Bollinger %b — where price sits within the Bollinger Bands.
///
/// ```text
/// %b = (price lower) / (upper lower)
/// ```
///
/// `%b = 1` means price is exactly on the upper band, `%b = 0` on the lower
/// band, `%b = 0.5` on the middle band. The value is **not** clamped: price
/// breaking above the upper band gives `%b > 1`, breaking below the lower band
/// gives `%b < 0`. That makes %b a clean, scale-free way to compare a price's
/// band position across instruments and to spot band overshoots.
///
/// # Example
///
/// ```
/// use wickra_core::{Indicator, PercentB};
///
/// let mut indicator = PercentB::new(20, 2.0).unwrap();
/// let mut last = None;
/// for i in 0..80 {
/// last = indicator.update(100.0 + (f64::from(i) * 0.3).sin() * 6.0);
/// }
/// assert!(last.is_some());
/// ```
#[derive(Debug, Clone)]
pub struct PercentB {
bands: BollingerBands,
last: Option<f64>,
}
impl PercentB {
/// Construct a new %b indicator.
///
/// # Errors
///
/// Returns [`crate::Error::PeriodZero`] for `period == 0` and
/// [`crate::Error::NonPositiveMultiplier`] for `multiplier <= 0`.
pub fn new(period: usize, multiplier: f64) -> Result<Self> {
Ok(Self {
bands: BollingerBands::new(period, multiplier)?,
last: None,
})
}
/// Configured period.
pub const fn period(&self) -> usize {
self.bands.period()
}
/// Configured multiplier.
pub const fn multiplier(&self) -> f64 {
self.bands.multiplier()
}
/// Current value if available.
pub const fn value(&self) -> Option<f64> {
self.last
}
}
impl Indicator for PercentB {
type Input = f64;
type Output = f64;
fn update(&mut self, input: f64) -> Option<f64> {
let o = self.bands.update(input)?;
let width = o.upper - o.lower;
let percent_b = if width == 0.0 {
// Bands collapsed onto the middle: price is exactly mid-band.
0.5
} else {
(input - o.lower) / width
};
self.last = Some(percent_b);
Some(percent_b)
}
fn reset(&mut self) {
self.bands.reset();
self.last = None;
}
fn warmup_period(&self) -> usize {
self.bands.warmup_period()
}
fn is_ready(&self) -> bool {
self.last.is_some()
}
fn name(&self) -> &'static str {
"PercentB"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
#[test]
fn new_rejects_invalid_parameters() {
assert!(PercentB::new(0, 2.0).is_err());
assert!(PercentB::new(20, 0.0).is_err());
assert!(PercentB::new(20, -1.0).is_err());
}
#[test]
fn constant_series_yields_midpoint() {
// Flat prices: bands collapse, price is exactly mid-band -> 0.5.
let mut pb = PercentB::new(5, 2.0).unwrap();
let out = pb.batch(&[100.0; 20]);
for v in out.iter().skip(4).flatten() {
assert_relative_eq!(*v, 0.5, epsilon = 1e-12);
}
}
#[test]
fn matches_bands_definition() {
// %b must equal (price - lower) / (upper - lower) from BollingerBands.
let prices: Vec<f64> = (1..=60)
.map(|i| 100.0 + (f64::from(i) * 0.3).sin() * 8.0)
.collect();
let pb_out = PercentB::new(20, 2.0).unwrap().batch(&prices);
let bands_out = BollingerBands::new(20, 2.0).unwrap().batch(&prices);
for (i, (p, b)) in pb_out.iter().zip(bands_out.iter()).enumerate() {
match (p, b) {
(Some(pv), Some(bv)) => {
let want = (prices[i] - bv.lower) / (bv.upper - bv.lower);
assert_relative_eq!(*pv, want, epsilon = 1e-12);
}
(None, None) => {}
_ => panic!("warmup mismatch at {i}"),
}
}
}
#[test]
fn price_at_middle_is_half() {
// A symmetric oscillation keeps the SMA centred; when price crosses
// the SMA, %b passes through 0.5. Verified via the bands definition.
let prices: Vec<f64> = (1..=60)
.map(|i| 100.0 + (f64::from(i) * 0.5).sin() * 5.0)
.collect();
let pb_out = PercentB::new(20, 2.0).unwrap().batch(&prices);
let bands_out = BollingerBands::new(20, 2.0).unwrap().batch(&prices);
for (i, (p, b)) in pb_out.iter().zip(bands_out.iter()).enumerate() {
if let (Some(pv), Some(bv)) = (p, b) {
if (prices[i] - bv.middle).abs() < 1e-9 {
assert_relative_eq!(*pv, 0.5, epsilon = 1e-6);
}
}
}
}
#[test]
fn reset_clears_state() {
let mut pb = PercentB::new(5, 2.0).unwrap();
pb.batch(&(1..=20).map(f64::from).collect::<Vec<_>>());
assert!(pb.is_ready());
pb.reset();
assert!(!pb.is_ready());
assert_eq!(pb.update(1.0), None);
}
#[test]
fn batch_equals_streaming() {
let prices: Vec<f64> = (1..=80)
.map(|i| 100.0 + (f64::from(i) * 0.3).cos() * 7.0)
.collect();
let batch = PercentB::new(20, 2.0).unwrap().batch(&prices);
let mut b = PercentB::new(20, 2.0).unwrap();
let streamed: Vec<_> = prices.iter().map(|p| b.update(*p)).collect();
assert_eq!(batch, streamed);
}
}
+5 -5
View File
@@ -45,11 +45,11 @@ pub mod indicators;
pub use error::{Error, Result}; pub use error::{Error, Result};
pub use indicators::{ pub use indicators::{
Adx, AdxOutput, Aroon, AroonOscillator, AroonOutput, Atr, AwesomeOscillator, BollingerBands, Adx, AdxOutput, Aroon, AroonOscillator, AroonOutput, Atr, AwesomeOscillator, BollingerBands,
BollingerOutput, Cci, Cmo, Coppock, Dema, Donchian, DonchianOutput, Dpo, Ema, BollingerBandwidth, BollingerOutput, Cci, Cmo, Coppock, Dema, Donchian, DonchianOutput, Dpo,
HistoricalVolatility, Hma, Kama, Keltner, KeltnerOutput, MacdIndicator, MacdOutput, MassIndex, Ema, HistoricalVolatility, Hma, Kama, Keltner, KeltnerOutput, MacdIndicator, MacdOutput,
Mfi, Mom, Natr, Obv, Pmo, Ppo, Psar, Roc, RollingVwap, Rsi, Sma, Smma, StdDev, StochRsi, MassIndex, Mfi, Mom, Natr, Obv, PercentB, Pmo, Ppo, Psar, Roc, RollingVwap, Rsi, Sma, Smma,
Stochastic, StochasticOutput, Tema, Trima, Trix, Tsi, UlcerIndex, UltimateOscillator, Vortex, StdDev, StochRsi, Stochastic, StochasticOutput, Tema, Trima, Trix, Tsi, UlcerIndex,
VortexOutput, Vwap, Vwma, WilliamsR, Wma, Zlema, T3, UltimateOscillator, Vortex, VortexOutput, Vwap, Vwma, WilliamsR, Wma, Zlema, T3,
}; };
pub use ohlcv::{Candle, Tick}; pub use ohlcv::{Candle, Tick};
pub use traits::{BatchExt, Chain, Indicator}; pub use traits::{BatchExt, Chain, Indicator};
+2
View File
@@ -122,6 +122,8 @@ Rust / Python / Node examples. They are grouped by family, mirroring the
- [Indicator-StdDev.md](indicators/volatility/Indicator-StdDev.md) - [Indicator-StdDev.md](indicators/volatility/Indicator-StdDev.md)
- [Indicator-UlcerIndex.md](indicators/volatility/Indicator-UlcerIndex.md) - [Indicator-UlcerIndex.md](indicators/volatility/Indicator-UlcerIndex.md)
- [Indicator-HistoricalVolatility.md](indicators/volatility/Indicator-HistoricalVolatility.md) - [Indicator-HistoricalVolatility.md](indicators/volatility/Indicator-HistoricalVolatility.md)
- [Indicator-BollingerBandwidth.md](indicators/volatility/Indicator-BollingerBandwidth.md)
- [Indicator-PercentB.md](indicators/volatility/Indicator-PercentB.md)
**Volume** — price moves weighted or confirmed by traded volume. **Volume** — price moves weighted or confirmed by traded volume.
+3 -1
View File
@@ -1,6 +1,6 @@
# Indicators Overview # Indicators Overview
Wickra ships 46 indicators, organised in source under the four classical Wickra ships 48 indicators, organised in source under the four classical
families — trend, momentum, volatility, volume — that map directly to the families — trend, momentum, volatility, volume — that map directly to the
directory structure of `crates/wickra-core/src/indicators/`. The same family directory structure of `crates/wickra-core/src/indicators/`. The same family
labels are used here, plus a second-level grouping that reflects how the labels are used here, plus a second-level grouping that reflects how the
@@ -130,6 +130,8 @@ measure — that lives in the volatility module by source convention.
| `BollingerBands` | SMA middle band with `±multiplier × population_stddev` upper/lower bands. | `f64` | `(upper, middle, lower, stddev)` | unbounded (price scale) | `(period=20, multiplier=2.0)` (Python) | `period` | [Indicator-BollingerBands.md](indicators/volatility/Indicator-BollingerBands.md) | | `BollingerBands` | SMA middle band with `±multiplier × population_stddev` upper/lower bands. | `f64` | `(upper, middle, lower, stddev)` | unbounded (price scale) | `(period=20, multiplier=2.0)` (Python) | `period` | [Indicator-BollingerBands.md](indicators/volatility/Indicator-BollingerBands.md) |
| `Keltner` | EMA middle band with `±multiplier × ATR` upper/lower bands. | `Candle` | `(upper, middle, lower)` | unbounded (price scale) | `(ema_period=20, atr_period=10, multiplier=2.0)` (Python) | `max(ema_period, atr_period)` | [Indicator-Keltner.md](indicators/volatility/Indicator-Keltner.md) | | `Keltner` | EMA middle band with `±multiplier × ATR` upper/lower bands. | `Candle` | `(upper, middle, lower)` | unbounded (price scale) | `(ema_period=20, atr_period=10, multiplier=2.0)` (Python) | `max(ema_period, atr_period)` | [Indicator-Keltner.md](indicators/volatility/Indicator-Keltner.md) |
| `Donchian` | Highest high and lowest low over `period` bars; middle = mean of the two. | `Candle` | `(upper, middle, lower)` | unbounded (price scale) | `period = 20` (Python) | `period` | [Indicator-Donchian.md](indicators/volatility/Indicator-Donchian.md) | | `Donchian` | Highest high and lowest low over `period` bars; middle = mean of the two. | `Candle` | `(upper, middle, lower)` | unbounded (price scale) | `period = 20` (Python) | `period` | [Indicator-Donchian.md](indicators/volatility/Indicator-Donchian.md) |
| `BollingerBandwidth` | `(upper lower) / middle` of the Bollinger Bands; the "squeeze" gauge. | `f64` | `f64` | `[0, ∞)` | `(period=20, multiplier=2.0)` (Python) | `period` | [Indicator-BollingerBandwidth.md](indicators/volatility/Indicator-BollingerBandwidth.md) |
| `PercentB` | `(price lower) / (upper lower)`; price position within the bands. | `f64` | `f64` | unbounded (`0``1` inside the bands) | `(period=20, multiplier=2.0)` (Python) | `period` | [Indicator-PercentB.md](indicators/volatility/Indicator-PercentB.md) |
### Range-average ### Range-average
@@ -0,0 +1,156 @@
# BollingerBandwidth
> Bollinger Bandwidth — the width of the Bollinger Bands relative to the
> middle band: a normalised volatility reading.
## Quick reference
| Field | Value |
|-------|-------|
| Family | Volatility |
| Sub-category | Envelopes (derived) |
| Input type | `f64` (single close) |
| Output type | `f64` |
| Output range | `[0, ∞)` |
| Default parameters | `(period = 20, multiplier = 2.0)` (Python) |
| Warmup period | `period` |
| Interpretation | Band width as a fraction of price; lows flag a "squeeze". |
## Formula
```
Bandwidth = (upper lower) / middle
```
where `upper`, `middle` and `lower` come from
[`BollingerBands`](Indicator-BollingerBands.md). Since the bands are
`middle ± multiplier · stddev`, the bandwidth simplifies to
`2 · multiplier · stddev / middle` — volatility normalised by price level.
Its extremes name two classic patterns: the **squeeze** (bandwidth at a
multi-month low — a coiled, quiet market that often precedes a sharp
move) and the **bulge** (bandwidth at an extreme high — an exhausted,
over-extended move).
## Parameters
| Name | Type | Default | Valid range | Description |
|--------------|---------|----------------|-------------|-------------|
| `period` | `usize` | `20` (Python) | `>= 1` | Bollinger Bands period. `0` errors with `Error::PeriodZero`. |
| `multiplier` | `f64` | `2.0` (Python) | `> 0` | Band standard-deviation multiplier. `<= 0` errors with `Error::NonPositiveMultiplier`. |
The Python binding defaults the pair to `(20, 2.0)`.
## Inputs / Outputs
From `crates/wickra-core/src/indicators/bollinger_bandwidth.rs`:
```rust
impl Indicator for BollingerBandwidth {
type Input = f64;
type Output = f64;
// update(&mut self, input: f64) -> Option<f64>
}
```
A single `f64` close in, an `Option<f64>` out. Python maps this to
`float | None` / `numpy.ndarray` (NaN warmup); Node to `number | null` /
`Array<number>` (NaN warmup).
## Warmup
`warmup_period() == period` — identical to the underlying `BollingerBands`.
## Edge cases
- **Constant series.** Flat prices collapse the bands onto the middle, so
the width — and bandwidth — is `0.0` (`constant_series_yields_zero`
pins this).
- **Zero middle band.** Bandwidth is undefined against a `0.0` middle
band; the indicator reports `0.0` for that bar.
- **Non-negative.** Bandwidth is `(upper lower) / middle` with
`upper >= lower` and a positive middle band, so it is never negative
(`output_is_non_negative` pins this).
- **Reset.** `bbw.reset()` clears the underlying bands.
## Examples
### Rust
```rust
use wickra::{BatchExt, Indicator, BollingerBandwidth};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut bbw = BollingerBandwidth::new(20, 2.0)?;
// A flat stretch then a volatile stretch: bandwidth rises.
let mut prices: Vec<f64> = vec![100.0; 30];
prices.extend((0..30).map(|i| 100.0 + (f64::from(i)).sin() * 10.0));
let out = bbw.batch(&prices);
println!("flat-window bandwidth: {:?}", out[25]);
Ok(())
}
```
Output:
```
flat-window bandwidth: Some(0.0)
```
While prices are flat the bands sit on top of each other, so bandwidth is
`0`; once volatility arrives it climbs.
### Python
```python
import numpy as np
import wickra as ta
bbw = ta.BollingerBandwidth(20, 2.0)
prices = np.full(40, 100.0) # flat series
print(bbw.batch(prices)[-1]) # 0.0
```
Output:
```
0.0
```
### Node
```javascript
const ta = require('wickra');
const bbw = new ta.BollingerBandwidth(20, 2.0);
const prices = Array.from({ length: 60 }, (_, i) => 100 + Math.sin(i * 0.3) * 6);
console.log('warmupPeriod:', bbw.warmupPeriod());
```
## Interpretation
`BollingerBandwidth` is the standard way to quantify the Bollinger
"squeeze". Volatility is mean-reverting and cyclical: extended periods of
low bandwidth tend to be followed by expansion, and vice versa. Traders
watch for bandwidth dropping to a multi-month low (the squeeze) as a
heads-up that a directional move is loading — then take the direction
from price breaking the band, or from a separate trend indicator.
## Common pitfalls
- **Treating the squeeze as directional.** Low bandwidth says a move is
*coming*, not which way. Confirm direction separately.
- **Comparing raw bandwidth across instruments without context.** It is
normalised by price, which helps, but "low" is relative to each
instrument's own history — compare against its own range.
## References
John Bollinger, *Bollinger on Bollinger Bands* (2001). Bandwidth is one
of Bollinger's two derived indicators (with %b).
## See also
- [Indicator-BollingerBands.md](Indicator-BollingerBands.md) — the bands
this measures.
- [Indicator-PercentB.md](Indicator-PercentB.md) — the companion derived
indicator: price *position* within the bands.
- [Indicators-Overview.md](../../Indicators-Overview.md) — the full taxonomy.
@@ -0,0 +1,148 @@
# PercentB
> Bollinger %b — where price sits within the Bollinger Bands, scaled so
> `0` is the lower band and `1` is the upper band.
## Quick reference
| Field | Value |
|-------|-------|
| Family | Volatility |
| Sub-category | Envelopes (derived) |
| Input type | `f64` (single close) |
| Output type | `f64` |
| Output range | unbounded (`0` = lower band, `1` = upper band) |
| Default parameters | `(period = 20, multiplier = 2.0)` (Python) |
| Warmup period | `period` |
| Interpretation | Price position in the band; `> 1` / `< 0` = band overshoot. |
## Formula
```
%b = (price lower) / (upper lower)
```
where `upper` and `lower` come from
[`BollingerBands`](Indicator-BollingerBands.md). `%b = 1` is price exactly
on the upper band, `%b = 0` on the lower band, `%b = 0.5` on the middle
band. The value is **deliberately not clamped**: a close above the upper
band gives `%b > 1`, a close below the lower band gives `%b < 0` — so %b
shows band overshoots directly.
## Parameters
| Name | Type | Default | Valid range | Description |
|--------------|---------|----------------|-------------|-------------|
| `period` | `usize` | `20` (Python) | `>= 1` | Bollinger Bands period. `0` errors with `Error::PeriodZero`. |
| `multiplier` | `f64` | `2.0` (Python) | `> 0` | Band standard-deviation multiplier. `<= 0` errors with `Error::NonPositiveMultiplier`. |
The Python binding defaults the pair to `(20, 2.0)`.
## Inputs / Outputs
From `crates/wickra-core/src/indicators/percent_b.rs`:
```rust
impl Indicator for PercentB {
type Input = f64;
type Output = f64;
// update(&mut self, input: f64) -> Option<f64>
}
```
A single `f64` close in, an `Option<f64>` out. Python maps this to
`float | None` / `numpy.ndarray` (NaN warmup); Node to `number | null` /
`Array<number>` (NaN warmup).
## Warmup
`warmup_period() == period` — identical to the underlying `BollingerBands`.
## Edge cases
- **Constant series.** Flat prices collapse the bands onto the middle;
with zero band width the price is exactly mid-band and %b is reported
as `0.5` (`constant_series_yields_midpoint` pins this).
- **Band overshoot.** %b is not clamped — values outside `[0, 1]` are
expected and meaningful.
- **NaN / infinity inputs.** Passed straight to the underlying
`BollingerBands`, which drops them.
- **Reset.** `pb.reset()` clears the underlying bands.
## Examples
### Rust
```rust
use wickra::{BatchExt, Indicator, PercentB};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut pb = PercentB::new(5, 2.0)?;
// A flat series: price is exactly mid-band, so %b is 0.5.
let out = pb.batch(&[100.0; 20]);
println!("{:?}", out[10]);
Ok(())
}
```
Output:
```
Some(0.5)
```
### Python
```python
import numpy as np
import wickra as ta
pb = ta.PercentB(20, 2.0)
prices = np.full(40, 100.0) # flat series -> mid-band
print(pb.batch(prices)[-1]) # 0.5
```
Output:
```
0.5
```
### Node
```javascript
const ta = require('wickra');
const pb = new ta.PercentB(20, 2.0);
const prices = Array.from({ length: 60 }, (_, i) => 100 + Math.sin(i * 0.3) * 6);
console.log('warmupPeriod:', pb.warmupPeriod());
```
## Interpretation
`PercentB` turns "is price near a band?" into a single number. The
canonical reads: `%b > 1` is a close above the upper band (strong, often
overbought); `%b < 0` is a close below the lower band (weak, often
oversold); `%b` crossing `0.5` is price crossing the middle SMA. Because
it is normalised, %b is the right input when you want to *compare* band
position across instruments, or feed band position into another rule —
for example "buy when %b crosses back above 0 from below".
## Common pitfalls
- **Expecting `[0, 1]` bounds.** %b is intentionally unclamped; values
outside `[0, 1]` are the band-overshoot signal, not an error.
- **Confusing it with bandwidth.** %b is price *position*;
[`BollingerBandwidth`](Indicator-BollingerBandwidth.md) is band *width*.
## References
John Bollinger, *Bollinger on Bollinger Bands* (2001). %b is one of
Bollinger's two derived indicators (with bandwidth).
## See also
- [Indicator-BollingerBands.md](Indicator-BollingerBands.md) — the bands
this locates price within.
- [Indicator-BollingerBandwidth.md](Indicator-BollingerBandwidth.md) — the
companion derived indicator: band *width*.
- [Indicators-Overview.md](../../Indicators-Overview.md) — the full taxonomy.