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
+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-UlcerIndex.md](indicators/volatility/Indicator-UlcerIndex.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.
+3 -1
View File
@@ -1,6 +1,6 @@
# 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
directory structure of `crates/wickra-core/src/indicators/`. The same family
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) |
| `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) |
| `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
@@ -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.