F13c: restructure the indicator catalogue into eight families

The original taxonomy was four classical families plus a statistics group,
with the F1-F12 expansion slotted in as sub-categories. This regroups the
whole 71-indicator catalogue into eight top-level families, each with at
least five members:

  Moving Averages (12), Momentum Oscillators (13), Trend & Directional (9),
  Price Oscillators (5), Volatility & Bands (12), Trailing Stops (5),
  Volume (9), Price Statistics (7).

- Wiki: docs/wiki/indicators/ reorganised into eight family folders; all 71
  indicator pages moved with `git mv`. Every internal cross-link is
  normalised to `../<family>/Indicator-X.md`, each page's `Family` field is
  set to its new family, and two pre-existing `../Indicator-Chaining.md`
  links (should have been `../../`) are corrected. A link check confirms
  every relative wiki link resolves.
- Indicators-Overview.md fully rewritten around the eight families;
  Home.md indicator reference and the README family table follow suit.
- Warmup-Periods.md gains the eight F13 indicators; CHANGELOG records the
  46-indicator expansion (25 -> 71) and the eight-family taxonomy.
- Tests: Node indicators.test.js and Python test_new_indicators.py cover
  all eight new indicators (Node 91/91, Python 117/117 green).

cargo fmt + clippy (core/wickra/data/wasm/node) clean; 508 core tests,
25 data tests and 74 doctests green.
This commit is contained in:
kingchenc
2026-05-22 21:21:56 +02:00
parent 6643f7a81d
commit d2f99efd78
78 changed files with 612 additions and 616 deletions
@@ -0,0 +1,225 @@
# ATR (Average True Range)
> Wilder's volatility benchmark: an exponentially-smoothed average of the
> per-bar true range that absorbs overnight gaps and is dimensioned in price
> units.
## Quick reference
| Item | Value |
|---------------------|--------------------------------------------------------------------------------------|
| Family | Volatility & Bands |
| Input type | `Candle` (uses `high`, `low`, `close`) |
| Output type | `f64` |
| Output range | unbounded `≥ 0` |
| Default parameters | `period = 14` (Wilder) |
| Warmup period | `period` (14 for defaults) |
| Interpretation | dollar-denominated volatility scale; rises in chop and expansion |
## Formula
For each candle, the **true range** is
`TR_t = max(H_t - L_t, |H_t - C_{t-1}|, |L_t - C_{t-1}|)` when a previous
close is available, otherwise `TR_t = H_t - L_t` (see `Candle::true_range`
in `crates/wickra-core/src/ohlcv.rs`).
ATR is then Wilder-smoothed:
```
seed_ATR_period = (TR_1 + TR_2 + … + TR_period) / period
ATR_t = ((period - 1) * ATR_{t-1} + TR_t) / period for t > period
```
This is mathematically the same recursion as an EMA with `alpha = 1/period`
(Wilder smoothing), seeded with a simple mean of the first `period` true
ranges (`crates/wickra-core/src/indicators/atr.rs:58-69`).
## Parameters
| Name | Type | Default | Constraint | Source |
|----------|---------|---------|------------|-------------------------------------|
| `period` | `usize` | `14` | `> 0` | `Atr::new` (`atr.rs:26`) |
Python default from `#[pyo3(signature = (period=14))]` in
`bindings/python/src/lib.rs`. `period == 0` returns `Error::PeriodZero`.
## Inputs / Outputs
```rust
impl Indicator for Atr {
type Input = Candle;
type Output = f64;
fn update(&mut self, candle: Candle) -> Option<f64>;
fn warmup_period(&self) -> usize { self.period }
}
```
- **Rust input.** A full `Candle` struct; only `high`, `low`, and `close`
are read (`prev_close` is cached internally between calls).
- **Python streaming.** Accepts either a 6-tuple
`(open, high, low, close, volume, timestamp)` or a dict with keys
`open`, `high`, `low`, `close`, `volume`, and optional `timestamp`.
- **Python batch.** `ATR.batch(high, low, close)` takes three equal-length
`numpy.ndarray` columns and returns a 1-D `np.ndarray` with `NaN` for
every warmup row.
- **Node streaming.** `atr.update(high, low, close)` returns `number | null`.
- **Node batch.** `atr.batch(high, low, close)` returns `Array<number>` of
the same length, `NaN` during warmup.
## Warmup
`warmup_period() == period`. The first `period - 1` candles return `None`
(or `NaN`/`null` in batch); the `period`-th candle returns the seed value
`(TR_1 + … + TR_period) / period`. Each subsequent candle applies the
Wilder recursion.
Verified for `period = 3`: the first non-`None` output is at index `2`
(the 3rd candle).
## Edge cases
- **First candle.** `Candle::true_range(None)` falls back to `high - low`
because there is no previous close yet. The first TR is the bar range.
- **Gaps.** With a previous close at `5.0` and a candle of `H=10, L=9`,
`TR = max(1, 5, 4) = 5` — i.e. `|H - prev_close|` dominates. The
pinned test `gap_up_uses_high_minus_prev_close` covers exactly this.
- **Constant input.** A series of identical candles (no gaps, fixed range)
yields a constant ATR equal to the bar range, even before the seed is
complete — the smoothing has nothing to smooth.
- **Non-negativity.** ATR is always `≥ 0`. The Rust test `never_negative`
pins this property across a sinusoidal price series.
- **NaN / infinity.** `Candle::new` rejects non-finite `open`/`high`/
`low`/`close`/`volume`; constructing the candle returns
`Error::InvalidCandle` before it can ever reach ATR.
- **Reset.** `reset()` clears `prev_close`, the seed buffer, and the
running average; the next call behaves as if the indicator were
freshly constructed.
## Examples
### Rust
```rust
use wickra::{Atr, BatchExt, Candle, Indicator};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let candles = vec![
Candle::new(10.0, 11.0, 9.0, 10.5, 1.0, 0)?,
Candle::new(10.5, 12.0, 10.0, 11.5, 1.0, 0)?,
Candle::new(11.5, 13.0, 11.0, 12.5, 1.0, 0)?,
Candle::new(12.5, 14.0, 12.0, 13.5, 1.0, 0)?,
Candle::new(13.5, 15.0, 13.0, 14.5, 1.0, 0)?,
];
let mut atr = Atr::new(3)?;
println!("{:?}", atr.batch(&candles));
Ok(())
}
```
Output:
```
[None, None, Some(2.0), Some(2.0), Some(2.0)]
```
Every bar has range `2.0` and no gap-driven TR component, so both the
seed `(2 + 2 + 2) / 3 = 2.0` and every subsequent Wilder update stay at
`2.0`.
### Python
```python
import numpy as np
import wickra as ta
atr = ta.ATR(3)
high = np.array([11.0, 12.0, 13.0, 14.0, 15.0])
low = np.array([ 9.0, 10.0, 11.0, 12.0, 13.0])
close = np.array([10.5, 11.5, 12.5, 13.5, 14.5])
print(atr.batch(high, low, close))
```
Output:
```
[nan nan 2. 2. 2.]
```
### Node
```js
const w = require('wickra');
const atr = new w.ATR(3);
console.log(atr.batch(
[11, 12, 13, 14, 15],
[ 9, 10, 11, 12, 13],
[10.5, 11.5, 12.5, 13.5, 14.5],
));
```
Output:
```
[ NaN, NaN, 2, 2, 2 ]
```
Streaming form (`atr.update(high, low, close)`):
```js
const w = require('wickra');
const atr = new w.ATR(3);
console.log(atr.update(11, 9, 10.5));
console.log(atr.update(12, 10, 11.5));
console.log(atr.update(13, 11, 12.5));
console.log(atr.update(14, 12, 13.5));
```
Output:
```
null
null
2
2
```
## Interpretation
- **Stop sizing.** A common pattern is "place a stop `k * ATR` away from
entry," with `k` typically in `[1.5, 3.0]` depending on the timeframe.
ATR's units are price, so the stop distance is directly tradable.
- **Position sizing.** `risk_per_trade / ATR` gives a quantity that
normalises risk across assets of very different price levels.
- **Regime detection.** Persistently rising ATR signals an expansion
regime; persistently low ATR signals consolidation, often preceding
expansion (the volatility-of-volatility argument).
## Common pitfalls
- **Wilder smoothing vs EMA.** Wilder's smoothing factor is `1/period`,
not the EMA's `2/(period+1)`. They look similar but produce different
numbers; a 14-period Wilder ATR is **not** the same as a 14-period
EMA of true range. Wickra uses the Wilder recursion explicitly.
- **Off-by-one seeding.** ATR(14) emits its first value on the 14th
candle, not the 15th — unlike RSI(14) which needs 15 candles for 14
diffs. The difference is that ATR's seed uses `period` true ranges
directly (and `TR_1` is well-defined even without a previous close),
while RSI(14) needs 14 *differences* between consecutive closes.
## References
- J. Welles Wilder Jr., *New Concepts in Technical Trading Systems*,
Trend Research, 1978. Chapter on the Average True Range and the
Wilder smoothing constant.
## See also
- [Bollinger Bands](../volatility-bands/Indicator-BollingerBands.md) — stddev-based volatility
envelope around an SMA.
- [Keltner Channels](../volatility-bands/Indicator-Keltner.md) — directly composes EMA + ATR.
- [Donchian Channels](../volatility-bands/Indicator-Donchian.md) — rolling high/low without
any smoothing.
- [PSAR](../trailing-stops/Indicator-Psar.md) — uses ATR-like volatility tracking implicitly
through its acceleration factor.
@@ -0,0 +1,257 @@
# Bollinger Bands
> An SMA centerline wrapped in symmetric standard-deviation envelopes; the
> classical reading is that price persistently outside a band signals a
> volatility-driven trend, not a reversal.
## Quick reference
| Item | Value |
|---------------------|--------------------------------------------------------------------------------|
| Family | Volatility & Bands |
| Input type | `f64` (typically the close price) |
| Output type | `BollingerOutput { upper: f64, middle: f64, lower: f64, stddev: f64 }` |
| Output range | unbounded; `lower ≤ middle ≤ upper`, `stddev ≥ 0` |
| Default parameters | `period = 20`, `multiplier = 2.0` |
| Warmup period | `period` (20 for defaults) |
| Interpretation | width tracks recent volatility; price tags band on momentum |
## Formula
Each step uses the trailing window of the last `period` inputs:
```
mean = (1/n) * Σ x_i
var = (1/n) * Σ (x_i - mean)^2 (population variance, denominator = n)
stddev = sqrt(var)
upper = mean + multiplier * stddev
middle = mean
lower = mean - multiplier * stddev
```
Wickra computes `var` from the streaming sums `Σ x` and `Σ x²` as
`Σx²/n - (Σx/n)²` and clamps to `0.0` to absorb catastrophic cancellation on
near-constant inputs (`crates/wickra-core/src/indicators/bollinger.rs:82`).
## Parameters
| Name | Type | Default | Constraint | Source |
|--------------|---------|---------|----------------------|----------------------------------------------------------|
| `period` | `usize` | `20` | `> 0` | `BollingerBands::new` (`bollinger.rs:43`) |
| `multiplier` | `f64` | `2.0` | finite and `> 0.0` | `BollingerBands::new` (`bollinger.rs:47`) |
Python defaults come from `#[pyo3(signature = (period=20, multiplier=2.0))]`
in `bindings/python/src/lib.rs`. Invalid inputs raise `ValueError` in Python
and return `Error::PeriodZero` / `Error::NonPositiveMultiplier` in Rust.
## Inputs / Outputs
Rust signature:
```rust
impl Indicator for BollingerBands {
type Input = f64;
type Output = BollingerOutput;
fn update(&mut self, input: f64) -> Option<BollingerOutput>;
fn warmup_period(&self) -> usize { self.period }
}
```
`BollingerOutput` fields: `upper`, `middle`, `lower`, `stddev`.
- **Python streaming** (`update`) returns the 4-tuple `(upper, middle, lower, stddev)`
or `None` during warmup.
- **Python batch** (`batch`) returns a 2-D `numpy.ndarray` of shape `(n, 4)` with
columns `[upper, middle, lower, stddev]`; warmup rows are entirely `NaN`.
- **Node streaming** (`update`) returns a `{ upper, middle, lower, stddev }`
object or `null` during warmup.
- **Node batch** (`batch`) returns a flat `Array<number>` of length `n * 4`
interleaved per row: `[u0, m0, l0, s0, u1, m1, l1, s1, …]`. Warmup rows
are four consecutive `NaN`s.
## Warmup
`warmup_period() == period`. The first `period - 1` inputs return `None`; the
`period`-th input emits the first `BollingerOutput`. Verified for `period = 5`:
the first non-`None` value appears on the 5th input (index 4).
## Edge cases
- **Constant input.** With a flat series the population stddev collapses to
exactly `0.0`, so `upper == middle == lower == mean`. The library guards
against tiny negative floating-point values from catastrophic cancellation
by clamping the variance with `.max(0.0)`.
- **Flat range / squeeze.** Real markets never give exactly `0.0`, but very
low-volatility windows produce visibly narrow bands; the upper and lower
bands collapse onto the middle band (the "Bollinger squeeze").
- **NaN / infinity input.** The implementation skips non-finite inputs:
`if !input.is_finite() { return self.current(); }`. The window is not
advanced and the previous `BollingerOutput` (or `None`) is returned.
- **Multiplier validation.** `multiplier <= 0` or non-finite returns
`Error::NonPositiveMultiplier`. `period == 0` returns `Error::PeriodZero`.
- **Reset.** `reset()` clears the window and both running sums, returning the
indicator to a freshly-constructed state.
## Examples
### Rust
```rust
use wickra::{BatchExt, BollingerBands, Indicator};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut bb = BollingerBands::new(5, 2.0)?;
let out = bb.batch(&[2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0]);
for (i, v) in out.into_iter().enumerate() {
println!("i={i} -> {:?}", v);
}
Ok(())
}
```
Output:
```
i=0 -> None
i=1 -> None
i=2 -> None
i=3 -> None
i=4 -> Some(BollingerOutput { upper: 5.759591794226543, middle: 3.8, lower: 1.8404082057734565, stddev: 0.9797958971132716 })
i=5 -> Some(BollingerOutput { upper: 5.379795897113269, middle: 4.4, lower: 3.420204102886732, stddev: 0.48989794855663404 })
i=6 -> Some(BollingerOutput { upper: 7.190890230020663, middle: 5.0, lower: 2.809109769979336, stddev: 1.095445115010332 })
i=7 -> Some(BollingerOutput { upper: 9.577708763999665, middle: 6.0, lower: 2.422291236000335, stddev: 1.7888543819998326 })
```
The first emission at `i=4` uses the window `[2, 4, 4, 4, 5]` with mean
`3.8` and population stddev `sqrt(0.96) ≈ 0.9797959`.
### Python
```python
import numpy as np
import wickra as ta
bb = ta.BollingerBands(5, 2.0)
prices = np.array([2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0], dtype=float)
out = bb.batch(prices)
print("shape:", out.shape)
print("row 4:", out[4])
print("row 7:", out[7])
```
Output:
```
shape: (8, 4)
row 4: [5.75959179 3.8 1.84040821 0.9797959 ]
row 7: [9.57770876 6. 2.42229124 1.78885438]
```
Streaming variant returns a 4-tuple `(upper, middle, lower, stddev)` per
tick or `None` during warmup:
```python
import wickra as ta
bb = ta.BollingerBands(5, 2.0)
for p in [2.0, 4.0, 4.0, 4.0, 5.0, 9.0]:
print(p, "->", bb.update(p))
```
Output:
```
2.0 -> None
4.0 -> None
4.0 -> None
4.0 -> None
5.0 -> (5.759591794226543, 3.8, 1.8404082057734565, 0.9797958971132716)
9.0 -> (9.078143885933063, 5.2, 1.321856114066938, 1.939071942966531)
```
### Node
```js
const w = require('wickra');
const bb = new w.BollingerBands(5, 2.0);
const flat = bb.batch([2, 4, 4, 4, 5, 5, 7, 9]);
console.log('length:', flat.length);
console.log('row 4 [upper, middle, lower, stddev]:', flat.slice(16, 20));
console.log('row 7 [upper, middle, lower, stddev]:', flat.slice(28, 32));
```
Output:
```
length: 32
row 4 [upper, middle, lower, stddev]: [ 5.759591794226543, 3.8, 1.8404082057734565, 0.9797958971132716 ]
row 7 [upper, middle, lower, stddev]: [ 9.577708763999665, 6, 2.422291236000335, 1.7888543819998326 ]
```
Streaming returns the named object `{ upper, middle, lower, stddev }`:
```js
const w = require('wickra');
const bb = new w.BollingerBands(5, 2.0);
[2, 4, 4, 4, 5].forEach(p => console.log(p, '->', bb.update(p)));
```
Output:
```
2 -> null
4 -> null
4 -> null
4 -> null
5 -> {
upper: 5.759591794226543,
middle: 3.8,
lower: 1.8404082057734565,
stddev: 0.9797958971132716
}
```
## Interpretation
- **Bandwidth as volatility.** `(upper - lower) / middle` is the Bollinger
bandwidth; a multi-month low in bandwidth is the classic "squeeze" that
often precedes an expansion move.
- **Tags vs breakouts.** A single touch of the upper band is not a sell
signal in Bollinger's own framework; persistent closes outside the band
("walking the band") signal trend continuation, not exhaustion.
- **%b position.** `(price - lower) / (upper - lower)` normalises position
inside the channel and is useful as a feature for cross-asset comparison.
## Common pitfalls
- **Stddev convention.** Wickra uses **population** standard deviation
(denominator `n`, not `n - 1`). This matches Bollinger's original
formulation and every reference implementation (TA-Lib, pandas-ta);
switching to the sample variant would mis-align bands by a factor of
`sqrt(n / (n - 1))` and break parity with other tools.
- **Partial rows.** In the Python 2-D batch result, do not slice an
individual column out and use it for analysis without checking for
`NaN` — every warmup row is `NaN` across all four columns. Filter with
`mask = ~np.isnan(out[:, 0])` before reading any single column.
- **Flat batch length in Node.** The Node `batch` returns `n * 4` numbers
interleaved per row, not four parallel arrays. Reshape with
`Array.from({ length: n }, (_, i) => flat.slice(i * 4, i * 4 + 4))`
if you want per-row records.
## References
- John Bollinger, *Bollinger on Bollinger Bands*, McGraw-Hill, 2001 (the
original publication of the indicator dates to the early 1980s).
- Wilder's *New Concepts in Technical Trading Systems* (1978) for the
surrounding family of volatility envelopes.
## See also
- [Keltner Channels](../volatility-bands/Indicator-Keltner.md) — same envelope shape but band
width is driven by ATR instead of stddev.
- [Donchian Channels](../volatility-bands/Indicator-Donchian.md) — rolling high/low envelope
with no smoothing.
- [ATR](../volatility-bands/Indicator-Atr.md) — the volatility scale most commonly used to
size Bollinger-style stops.
@@ -0,0 +1,155 @@
# BollingerBandwidth
> Bollinger Bandwidth — the width of the Bollinger Bands relative to the
> middle band: a normalised volatility reading.
## Quick reference
| Field | Value |
|-------|-------|
| Family | Volatility & Bands |
| 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`](../volatility-bands/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](../volatility-bands/Indicator-BollingerBands.md) — the bands
this measures.
- [Indicator-PercentB.md](../volatility-bands/Indicator-PercentB.md) — the companion derived
indicator: price *position* within the bands.
- [Indicators-Overview.md](../../Indicators-Overview.md) — the full taxonomy.
@@ -0,0 +1,154 @@
# ChaikinVolatility
> Chaikin Volatility — the rate of change of a smoothed high-low spread;
> is the trading range widening or narrowing?
## Quick reference
| Field | Value |
|-------|-------|
| Family | Volatility & Bands |
| Input type | `Candle` (uses `high`, `low`) |
| Output type | `f64` |
| Output range | unbounded around zero (percent) |
| Default parameters | `ema_period = 10`, `roc_period = 10` (Python) |
| Warmup period | `ema_period + roc_period` |
| Interpretation | Positive = ranges expanding, negative = ranges contracting. |
## Formula
```
spread_t = high_t low_t
smoothed_t = EMA(spread, ema_period)_t
ChaikinVol = 100 · (smoothed_t smoothed_{troc_period}) / smoothed_{troc_period}
```
Marc Chaikin's volatility measure tracks not the *level* of the trading range
but how fast it is *widening or narrowing*. The bar's high-low spread is
EMA-smoothed, then run through a rate-of-change: a rising value means ranges
are expanding (often near a market top, as fear spikes), a falling value means
they are contracting (a quiet, complacent market). The classic configuration
smooths the spread with a `10`-period EMA and takes its `10`-period rate of
change.
## Parameters
- `ema_period` — the EMA that smooths the high-low spread (`10`).
- `roc_period` — the rate-of-change lookback over the smoothed spread (`10`).
`ChaikinVolatility::classic()` returns the `(10, 10)` configuration.
## Inputs / Outputs
From `crates/wickra-core/src/indicators/chaikin_volatility.rs`:
```rust
impl Indicator for ChaikinVolatility {
type Input = Candle;
type Output = f64;
// update(&mut self, input: Candle) -> Option<f64>
}
```
`ChaikinVolatility` is a **candle-input** indicator that reads `high` and
`low`. Python's streaming `update` accepts a 6-tuple or a dict; the batch
helper takes `high`, `low` numpy arrays. Node and WASM expose
`update(high, low)` and the matching `batch`.
## Warmup
`ChaikinVolatility::classic().warmup_period() == 20`. The EMA emits at candle
`ema_period`; the rate-of-change then needs `roc_period` more smoothed values.
## Edge cases
- **Constant range.** A constant high-low spread smooths to a constant EMA,
whose rate of change is `0`.
- **Expanding range.** A monotonically widening range reads positive.
- **Reset.** `cv.reset()` clears the inner EMA and ROC.
## Examples
### Rust
```rust
use wickra::{BatchExt, Candle, Indicator, ChaikinVolatility};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut cv = ChaikinVolatility::new(10, 10)?;
// A constant 2-wide range -> constant EMA -> zero rate of change.
let candles: Vec<Candle> = (0..40)
.map(|i| {
let base = 100.0 + f64::from(i);
Candle::new(base, base + 1.0, base - 1.0, base, 1.0, i).unwrap()
})
.collect();
println!("{:?}", cv.batch(&candles).last().unwrap());
Ok(())
}
```
Output:
```
Some(0.0)
```
### Python
```python
import numpy as np
import wickra as ta
cv = ta.ChaikinVolatility(10, 10)
n = 40
base = np.arange(n, dtype=float) + 100.0
print(cv.batch(base + 1.0, base - 1.0)[-1])
```
Output:
```
0.0
```
### Node
```javascript
const ta = require('wickra');
const cv = new ta.ChaikinVolatility(10, 10);
const base = Array.from({ length: 40 }, (_, i) => 100 + i);
const out = cv.batch(base.map((b) => b + 1), base.map((b) => b - 1));
console.log(out[out.length - 1]);
```
Output:
```
0
```
## Interpretation
A rising Chaikin Volatility warns that ranges are expanding fast — Chaikin
associated sharp rises with market tops, where panic widens bars. A low or
falling reading is the calm, range-contracting market that often precedes a
move. It complements [`Atr`](../volatility-bands/Indicator-Atr.md): ATR gives the level of
volatility, Chaikin Volatility gives its momentum.
## Common pitfalls
- **Reading it as a volatility level.** It is a *rate of change* — zero means
steady ranges, not zero volatility.
- **Feeding it scalar prices.** It needs the `high`/`low` bar.
## References
Marc Chaikin's Chaikin Volatility; the EMA-of-spread rate-of-change definition
here is the standard one.
## See also
- [Indicator-Atr.md](../volatility-bands/Indicator-Atr.md) — the level of per-bar volatility.
- [Indicator-TrueRange.md](../volatility-bands/Indicator-TrueRange.md) — raw single-bar range.
- [Indicators-Overview.md](../../Indicators-Overview.md) — the full taxonomy.
@@ -0,0 +1,213 @@
# Donchian Channels
> The unsmoothed price-extreme envelope: highest high and lowest low over a
> rolling window, with the mid-band defined as their average. Breakouts of
> the Donchian channel are the foundation of the Turtle trading rules.
## Quick reference
| Item | Value |
|---------------------|--------------------------------------------------------------------|
| Family | Volatility & Bands |
| Input type | `Candle` (uses `high` and `low`) |
| Output type | `DonchianOutput { upper: f64, middle: f64, lower: f64 }` |
| Output range | unbounded; `lower ≤ middle ≤ upper` |
| Default parameters | `period = 20` |
| Warmup period | `period` (20 for defaults) |
| Interpretation | breakout boundary; channel touches are tradable events |
## Formula
For a lookback of `period` candles:
```
upper_t = max( high_t, high_{t-1}, …, high_{t-period+1} )
lower_t = min( low_t, low_{t-1}, …, low_{t-period+1} )
middle_t = (upper_t + lower_t) / 2
```
`crates/wickra-core/src/indicators/donchian.rs:58-72` computes both
extrema by folding over the in-window candles each tick; this is O(n)
per update in the period size and O(1) in the data length.
## Parameters
| Name | Type | Default | Constraint | Source |
|----------|---------|---------|------------|-----------------------------------------|
| `period` | `usize` | `20` | `> 0` | `Donchian::new` (`donchian.rs:30`) |
Python default from `#[pyo3(signature = (period=20))]` in
`bindings/python/src/lib.rs`. `period == 0` returns `Error::PeriodZero`.
## Inputs / Outputs
```rust
impl Indicator for Donchian {
type Input = Candle;
type Output = DonchianOutput;
fn update(&mut self, candle: Candle) -> Option<DonchianOutput>;
}
pub struct DonchianOutput { pub upper: f64, pub middle: f64, pub lower: f64 }
```
- **Python streaming.** Returns `(upper, middle, lower)` tuple or `None`.
- **Python batch.** `Donchian.batch(high, low)` returns a 2-D
`np.ndarray` of shape `(n, 3)` with columns `[upper, middle, lower]`;
warmup rows are `NaN` across all three columns. (`close` is not
required.)
- **Node streaming.** Not exposed — the Node binding ships only the
`batch` form for `Donchian`.
- **Node batch.** `donchian.batch(high, low)` returns a flat
`Array<number>` of length `n * 3` interleaved per row:
`[u0, m0, l0, u1, m1, l1, …]`.
## Warmup
`warmup_period() == period`. The first `period - 1` candles return
`None`; the `period`-th candle emits the first envelope. Verified for
`period = 3`: the first non-`None` output is at index `2` (the 3rd
candle).
## Edge cases
- **Flat market (HH == LL).** When every candle in the window has
identical highs and identical lows, `upper == lower` (and therefore
`middle == upper == lower`). The pinned test
`flat_market_yields_equal_bands` covers this.
- **Single extreme candle.** A lone wick at the edge of the window sets
the boundary until it scrolls out. Donchian therefore reacts in
step-functions, not smoothly — a new all-time high inside the window
immediately moves the upper band; a single bar later, that high
remains the boundary unless an even higher print occurs.
- **NaN / infinity.** `Candle::new` rejects non-finite OHLC values
before they can reach Donchian.
- **Reset.** `reset()` clears the candle window; the configured
`period` is preserved.
## Examples
### Rust
```rust
use wickra::{BatchExt, Candle, Donchian, Indicator};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let candles = vec![
Candle::new(10.0, 11.0, 9.0, 10.5, 1.0, 0)?,
Candle::new(10.5, 12.0, 10.0, 11.5, 1.0, 0)?,
Candle::new(11.5, 13.0, 11.0, 12.5, 1.0, 0)?,
Candle::new(12.5, 14.0, 12.0, 13.5, 1.0, 0)?,
Candle::new(13.5, 15.0, 13.0, 14.5, 1.0, 0)?,
];
let mut d = Donchian::new(3)?;
for (i, v) in d.batch(&candles).into_iter().enumerate() {
println!("i={i} -> {:?}", v);
}
Ok(())
}
```
Output:
```
i=0 -> None
i=1 -> None
i=2 -> Some(DonchianOutput { upper: 13.0, middle: 11.0, lower: 9.0 })
i=3 -> Some(DonchianOutput { upper: 14.0, middle: 12.0, lower: 10.0 })
i=4 -> Some(DonchianOutput { upper: 15.0, middle: 13.0, lower: 11.0 })
```
At `i = 2` the window contains highs `[11, 12, 13]` and lows `[9, 10, 11]`,
so `upper = 13`, `lower = 9`, `middle = 11`.
### Python
```python
import numpy as np
import wickra as ta
d = ta.Donchian(3)
h = np.array([11.0, 12.0, 13.0, 14.0, 15.0])
l = np.array([ 9.0, 10.0, 11.0, 12.0, 13.0])
print(d.batch(h, l))
```
Output:
```
[[nan nan nan]
[nan nan nan]
[13. 11. 9.]
[14. 12. 10.]
[15. 13. 11.]]
```
### Node
```js
const w = require('wickra');
const d = new w.Donchian(3);
const flat = d.batch(
[11, 12, 13, 14, 15],
[ 9, 10, 11, 12, 13],
);
console.log('length:', flat.length);
console.log('row 2 [upper, middle, lower]:', flat.slice(6, 9));
console.log('row 4 [upper, middle, lower]:', flat.slice(12, 15));
```
Output:
```
length: 15
row 2 [upper, middle, lower]: [ 13, 11, 9 ]
row 4 [upper, middle, lower]: [ 15, 13, 11 ]
```
## Interpretation
- **Breakouts.** The original Turtle Trading rules (Dennis / Eckhardt,
early 1980s) buy on a 20-day Donchian upper-band breach and sell on
a 10-day lower-band breach. The modern descendant is the "channel
breakout" family of trend-following systems.
- **Mean reversion.** A small minority of systems take the bands as
fade levels; this works on range-bound assets and fails dramatically
in trends — the inverse of breakout systems.
- **Volatility proxy.** Channel width `upper - lower` is a simple
volatility proxy that requires no smoothing and no parameter tuning
beyond the lookback length.
## Common pitfalls
- **Stale extreme.** A single shock high from `period` candles ago
keeps the upper band elevated even when current prices have fallen
back to normal. Watch for the "channel drop" event when that high
scrolls out of the window — the upper band will step down sharply
in a single bar.
- **No close required.** Donchian only uses high/low. Feeding it a
close-only series (with high = low = close) collapses it into an
envelope of close extremes, which is a much noisier signal than
the canonical high/low form. The Python `batch` accepts only
`(high, low)` for exactly this reason.
- **Flat range collapse.** On a truly flat instrument the channel
collapses to a line (`upper == middle == lower`); downstream code
that divides by `upper - lower` (e.g. computing channel position)
must handle this division-by-zero case explicitly.
## References
- Richard Donchian published the 4-week channel rule in the early
1960s as part of his broader trend-following work.
- Curtis Faith, *Way of the Turtle*, McGraw-Hill, 2007, documents
the 20/10-day Donchian variant that defined the Turtle program.
## See also
- [Bollinger Bands](../volatility-bands/Indicator-BollingerBands.md) — envelope shaped by
stddev rather than rolling extrema.
- [Keltner Channels](../volatility-bands/Indicator-Keltner.md) — envelope shaped by ATR
around an EMA centerline.
- [PSAR](../trailing-stops/Indicator-Psar.md) — alternative trailing-stop construction
for breakout systems.
@@ -0,0 +1,165 @@
# HistoricalVolatility
> Historical Volatility — the annualised standard deviation of log returns,
> the realised volatility used to price options and size risk.
## Quick reference
| Field | Value |
|-------|-------|
| Family | Volatility & Bands |
| Input type | `f64` (single close) |
| Output type | `f64` |
| Output range | `[0, ∞)` (annualised percent) |
| Default parameters | `(period = 20, trading_periods = 252)` (Python) |
| Warmup period | `period + 1` |
| Interpretation | Annualised volatility of returns, in percent. |
## Formula
```
r_t = ln(price_t / price_{t1})
HV = stddev_sample(r over period) · √trading_periods · 100
```
The log returns over the window are measured with the **sample** standard
deviation (divisor `n 1`, Bessel's correction — the unbiased volatility
estimator), then annualised by `√trading_periods` and expressed as a
percentage. `trading_periods` is the number of bars in a year for the
data's frequency: `252` for daily bars, `52` for weekly, `12` for
monthly.
## Parameters
| Name | Type | Default | Valid range | Description |
|-------------------|---------|----------------|-------------|-------------|
| `period` | `usize` | `20` (Python) | `>= 2` | Number of log returns in the window. `0` errors with `Error::PeriodZero`; `1` with `Error::InvalidPeriod` (the sample stddev needs two returns). |
| `trading_periods` | `usize` | `252` (Python) | `>= 1` | Annualisation factor. `0` errors with `Error::PeriodZero`. |
The Python binding defaults the pair to `(20, 252)`. The `periods`
property returns `(period, trading_periods)`.
## Inputs / Outputs
From `crates/wickra-core/src/indicators/historical_volatility.rs`:
```rust
impl Indicator for HistoricalVolatility {
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 + 1`. The first log return needs a previous
price, and the window must then hold `period` returns — so the first
non-`None` output lands on input `period + 1`.
## Edge cases
- **Constant series.** A flat price series has all log returns equal to
`0`, so volatility is `0.0` (`constant_series_yields_zero` pins this).
- **Geometric series.** A constant growth factor produces a *constant*
log return; its standard deviation — and so HV — is `0`
(`geometric_series_yields_zero` pins this).
- **Non-positive prices.** A log return is undefined when either price is
`<= 0`; that return is treated as `0`.
- **Non-negative.** Volatility is a standard deviation and is never
negative (`output_is_non_negative` pins this).
- **NaN / infinity inputs.** Non-finite inputs are silently dropped.
- **Reset.** `hv.reset()` clears the previous price, the window and the
running sums.
## Examples
### Rust
```rust
use wickra::{BatchExt, Indicator, HistoricalVolatility};
fn main() -> Result<(), Box<dyn std::error::Error>> {
// 20-bar window, 252 trading days per year.
let mut hv = HistoricalVolatility::new(20, 252)?;
let prices: Vec<f64> = (0..40).map(|i| 100.0 * 1.01_f64.powi(i)).collect();
let out = hv.batch(&prices);
println!("warmup_period = {}", hv.warmup_period());
// A perfectly geometric series has constant returns -> zero volatility.
println!("last = {:?}", out.last().unwrap());
Ok(())
}
```
Output:
```
warmup_period = 21
last = Some(0.0)
```
### Python
```python
import numpy as np
import wickra as ta
hv = ta.HistoricalVolatility() # (period=20, trading_periods=252)
prices = np.full(40, 100.0) # flat series
print(hv.batch(prices)[-1]) # no return variation -> 0
```
Output:
```
0.0
```
### Node
```javascript
const ta = require('wickra');
// 52 trading periods per year for weekly bars.
const hv = new ta.HistoricalVolatility(20, 52);
const prices = Array.from({ length: 60 }, (_, i) => 100 + Math.sin(i * 0.3) * 5);
console.log('warmupPeriod:', hv.warmupPeriod());
```
## Interpretation
`HistoricalVolatility` is the realised-volatility number quoted in
options and risk work — "this stock has been running at 30 % annualised
vol". Compare it against an option's *implied* volatility to judge whether
options are cheap or rich, feed it into position-sizing (smaller size as
HV rises), or track its own trend: volatility clusters, so a rising HV
tends to keep rising.
Always match `trading_periods` to your bar frequency — annualising daily
bars with `252`, weekly with `52`, monthly with `12`. Using the wrong
factor rescales every reading.
## Common pitfalls
- **Mismatched `trading_periods`.** Annualising weekly data with `252`
inflates HV by `√(252/52) ≈ 2.2×`.
- **Confusing it with `StdDev`.** `StdDev` is the population dispersion of
*prices*; `HistoricalVolatility` is the sample (`n 1`) dispersion of
*log returns*, annualised.
## References
Historical (realised) volatility is the standard `√252`-annualised
standard deviation of log returns; the unbiased `n 1` estimator is the
conventional choice for volatility estimation.
## See also
- [Indicator-StdDev.md](../volatility-bands/Indicator-StdDev.md) — population dispersion of
raw prices.
- [Indicator-Natr.md](../volatility-bands/Indicator-Natr.md) — range-based volatility as a
percentage.
- [Indicators-Overview.md](../../Indicators-Overview.md) — the full taxonomy.
@@ -0,0 +1,214 @@
# Keltner Channels
> A pure composition of [EMA](../moving-averages/Indicator-Ema.md) on typical price plus
> ATR-scaled envelopes. The middle line is the trend filter, the bands are
> the volatility cone.
## Quick reference
| Item | Value |
|---------------------|------------------------------------------------------------------------------------|
| Family | Volatility & Bands |
| Input type | `Candle` (uses `high`, `low`, `close`) |
| Output type | `KeltnerOutput { upper: f64, middle: f64, lower: f64 }` |
| Output range | unbounded; `lower ≤ middle ≤ upper` |
| Default parameters | `ema_period = 20`, `atr_period = 10`, `multiplier = 2.0` |
| Warmup period | `max(ema_period, atr_period)` (`20` for defaults) — exact first-emission index |
| Interpretation | trend-following envelope; tags signal momentum, not exhaustion |
## Formula
```
middle_t = EMA_{ema_period}( typical_price_t ) // tp = (H+L+C)/3
upper_t = middle_t + multiplier * ATR_{atr_period}_t
lower_t = middle_t - multiplier * ATR_{atr_period}_t
```
The middle line is an EMA of **typical price**, not of close
(`crates/wickra-core/src/indicators/keltner.rs:62`,
`candle.typical_price()`).
## Parameters
| Name | Type | Default | Constraint | Source |
|--------------|---------|---------|-------------------------|----------------------------------------------|
| `ema_period` | `usize` | `20` | `> 0` | `Keltner::new` (`keltner.rs:33`) |
| `atr_period` | `usize` | `10` | `> 0` | `Keltner::new` (`keltner.rs:33`) |
| `multiplier` | `f64` | `2.0` | finite and `> 0.0` | `Keltner::new` (`keltner.rs:34-36`) |
Python defaults from
`#[pyo3(signature = (ema_period=20, atr_period=10, multiplier=2.0))]` in
`bindings/python/src/lib.rs`. `Keltner::classic()` returns the same
configuration.
## Inputs / Outputs
```rust
impl Indicator for Keltner {
type Input = Candle;
type Output = KeltnerOutput;
fn update(&mut self, candle: Candle) -> Option<KeltnerOutput>;
}
pub struct KeltnerOutput { pub upper: f64, pub middle: f64, pub lower: f64 }
```
- **Python streaming.** Returns `(upper, middle, lower)` tuple or `None`.
- **Python batch.** `Keltner.batch(high, low, close)` returns a 2-D
`np.ndarray` of shape `(n, 3)` with columns `[upper, middle, lower]`;
warmup rows are `NaN` across all three columns.
- **Node streaming.** Returns a `{ upper, middle, lower }` object or
`null`.
- **Node batch.** `keltner.batch(high, low, close)` returns a flat
`Array<number>` of length `n * 3` interleaved per row:
`[u0, m0, l0, u1, m1, l1, …]`.
## Warmup
`warmup_period()` reports `max(ema_period, atr_period)` — for the
default `(20, 10, 2.0)` that is `20` — and that figure is **exact**: the
first non-`None` output lands on candle `warmup_period()` (index
`warmup_period() - 1`).
`Keltner::update` feeds the EMA and ATR sub-indicators *unconditionally*
on every candle, then emits once both are ready. The two sub-indicators
warm up in parallel over the same candle window, so the slower of the
two (`max(ema_period, atr_period)`) governs the first emission. With the
classic `(20, 10, 2.0)` configuration the first valid `KeltnerOutput` is
the 20th candle (index `19`). This is pinned by the
`first_emission_matches_warmup_period` test in `keltner.rs`.
## Edge cases
- **Flat market.** A constant-OHLC series produces `upper == middle == lower`
because ATR collapses to `0`. The pinned test
`flat_market_collapses_bands` covers this.
- **Trending market.** When ATR rises, both bands widen symmetrically
around the EMA centerline.
- **Reset.** `reset()` resets both the underlying EMA and ATR; the
configured periods/multiplier are preserved.
- **NaN / infinity.** `Candle::new` rejects non-finite OHLC values up
front; the indicator never receives them.
- **Invalid params.** `ema_period == 0`, `atr_period == 0`, or non-positive
`multiplier` returns an error from `Keltner::new`.
## Examples
### Rust
```rust
use wickra::{BatchExt, Candle, Indicator, Keltner};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let candles = vec![
Candle::new(10.0, 11.0, 9.0, 10.5, 1.0, 0)?,
Candle::new(10.5, 12.0, 10.0, 11.5, 1.0, 0)?,
Candle::new(11.5, 13.0, 11.0, 12.5, 1.0, 0)?,
Candle::new(12.5, 14.0, 12.0, 13.5, 1.0, 0)?,
Candle::new(13.5, 15.0, 13.0, 14.5, 1.0, 0)?,
];
let mut k = Keltner::new(3, 3, 2.0)?;
for (i, v) in k.batch(&candles).into_iter().enumerate() {
println!("i={i} -> {:?}", v);
}
Ok(())
}
```
Output:
```
i=0 -> None
i=1 -> None
i=2 -> Some(KeltnerOutput { upper: 15.166666666666666, middle: 11.166666666666666, lower: 7.166666666666666 })
i=3 -> Some(KeltnerOutput { upper: 16.166666666666664, middle: 12.166666666666666, lower: 8.166666666666666 })
i=4 -> Some(KeltnerOutput { upper: 17.166666666666664, middle: 13.166666666666666, lower: 9.166666666666666 })
```
The first emission is at `i = 2` (the 3rd candle), exactly
`max(ema=3, atr=3) = 3` — the value `warmup_period()` reports. The EMA
and ATR sub-indicators are fed in parallel, so neither delays the
other.
### Python
```python
import numpy as np
import wickra as ta
k = ta.Keltner(3, 3, 2.0)
h = np.array([11.0, 12.0, 13.0, 14.0, 15.0])
l = np.array([ 9.0, 10.0, 11.0, 12.0, 13.0])
c = np.array([10.5, 11.5, 12.5, 13.5, 14.5])
print(k.batch(h, l, c))
```
Output:
```
[[ nan nan nan]
[ nan nan nan]
[ nan nan nan]
[ nan nan nan]
[17.16666667 13.16666667 9.16666667]]
```
### Node
```js
const w = require('wickra');
const k = new w.Keltner(3, 3, 2.0);
const flat = k.batch(
[11, 12, 13, 14, 15],
[ 9, 10, 11, 12, 13],
[10.5, 11.5, 12.5, 13.5, 14.5],
);
console.log('length:', flat.length);
console.log('row 4 [upper, middle, lower]:', flat.slice(12, 15));
```
Output:
```
length: 15
row 4 [upper, middle, lower]: [ 17.166666666666664, 13.166666666666666, 9.166666666666666 ]
```
## Interpretation
- **Trend filter.** Persistent closes above the upper band signal
trend continuation, much like Bollinger's "walking the band" pattern;
Keltner is generally tighter than Bollinger on noisy series because
ATR responds more smoothly than a rolling stddev.
- **Squeeze cross-over.** A common "squeeze" setup compares Bollinger
bandwidth to Keltner channel width: when Bollinger fits *inside*
Keltner, a volatility expansion is statistically more likely.
- **Pullback entries.** In a defined uptrend, pullbacks to the middle
EMA line are a classic continuation entry; the lower band acts as
the disaster stop.
## Common pitfalls
- **Typical price ≠ close.** The middle EMA runs on
`(H + L + C) / 3`, not on close. A pre-computed "EMA of close"
panel will not equal the Keltner middle line and trying to align
them at floating-point precision will fail.
## References
- Chester W. Keltner, *How to Make Money in Commodities*, 1960. The
original construction used a 10-day SMA of typical price with an
envelope sized by the 10-day average range. The modern variant
(EMA centerline + ATR envelope) is the form Wickra implements.
- Linda Bradford Raschke popularised the EMA + ATR rephrasing in the
1990s; this is the version most TA libraries ship today.
## See also
- [EMA](../moving-averages/Indicator-Ema.md) — the centerline component.
- [ATR](../volatility-bands/Indicator-Atr.md) — the envelope width component.
- [Bollinger Bands](../volatility-bands/Indicator-BollingerBands.md) — envelope using stddev
rather than ATR; useful side-by-side comparison.
- [Donchian Channels](../volatility-bands/Indicator-Donchian.md) — envelope using rolling
extrema with no smoothing.
@@ -0,0 +1,143 @@
# NATR
> Normalized Average True Range — ATR expressed as a percentage of price, so
> volatility is comparable across instruments.
## Quick reference
| Field | Value |
|-------|-------|
| Family | Volatility & Bands |
| Input type | `Candle` (uses `high`, `low`, `close`) |
| Output type | `f64` |
| Output range | `[0, ∞)` (percent) |
| Default parameters | `period = 14` (Python) |
| Warmup period | `period` |
| Interpretation | Average true range as a percent of the close. |
## Formula
```
NATR = 100 · ATR(period) / close
```
[`Atr`](../volatility-bands/Indicator-Atr.md) measures volatility in raw price units — a `2.0`
ATR is large on a $10 stock and tiny on a $5000 index. Dividing by the
current close converts it to a percentage, so a NATR of `2.0` always
means "the average true range is 2 % of price". That makes NATR readings
comparable across a portfolio, and stop or position-size rules expressed
as a NATR multiple behave consistently regardless of price level.
## Parameters
| Name | Type | Default | Valid range | Description |
|----------|---------|---------------|-------------|-------------|
| `period` | `usize` | `14` (Python) | `>= 1` | Wilder smoothing period of the underlying ATR. `0` errors with `Error::PeriodZero`. |
The Python binding defaults `period` to `14`.
## Inputs / Outputs
From `crates/wickra-core/src/indicators/natr.rs`:
```rust
impl Indicator for Natr {
type Input = Candle;
type Output = f64;
// update(&mut self, input: Candle) -> Option<f64>
}
```
`NATR` is a **candle-input** indicator: it reads `high`, `low` and
`close`. In Python the streaming `update` accepts a 6-tuple or a dict; the
batch helper takes `high`, `low`, `close` numpy arrays. Node and WASM
expose `update(high, low, close)` and `batch(high, low, close)`.
## Warmup
`Natr::new(period).warmup_period() == period` — identical to the
underlying `Atr`, which is Wilder-seeded over `period` true ranges.
## Edge cases
- **Flat market.** A market with no range has `ATR = 0`, so `NATR = 0`
(`flat_market_yields_zero` pins this).
- **Zero close.** NATR is undefined against a `0.0` close; the indicator
reports `0.0` for that bar.
- **Identity.** NATR equals `100 · ATR / close` bar for bar
(`natr_is_atr_over_close_as_percent` pins this).
- **Reset.** `natr.reset()` clears the underlying ATR.
## Examples
### Rust
```rust
use wickra::{BatchExt, Candle, Indicator, Natr};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut natr = Natr::new(14)?;
let candles: Vec<Candle> = (0..40)
.map(|i| {
let p = 100.0 + f64::from(i);
Candle::new(p, p + 2.0, p - 2.0, p, 10.0, i64::from(i)).unwrap()
})
.collect();
let out = natr.batch(&candles);
println!("warmup_period = {}", natr.warmup_period());
println!("last = {:?}", out.last().unwrap());
Ok(())
}
```
### Python
```python
import numpy as np
import wickra as ta
natr = ta.NATR(14)
high = np.arange(102.0, 142.0)
low = high - 4.0
close = high - 2.0
print(natr.batch(high, low, close)[-1])
```
### Node
```javascript
const ta = require('wickra');
const natr = new ta.NATR(14);
const high = Array.from({ length: 40 }, (_, i) => 102 + i);
const low = high.map((h) => h - 4);
const close = high.map((h) => h - 2);
console.log(natr.batch(high, low, close).at(-1));
```
## Interpretation
`Natr` is the tool of choice whenever an ATR-based rule must work across
instruments or across long stretches of time where the price level
drifts. A volatility filter like "skip entries when NATR > 5" or a stop
at "entry 3 × NATR %" stays meaningful on any symbol. Use raw
[`Atr`](../volatility-bands/Indicator-Atr.md) only when you specifically want the answer in
price units (e.g. to place a stop a fixed number of points away).
## Common pitfalls
- **Feeding it scalar prices.** It needs `high`/`low`/`close`.
- **Confusing it with ATR.** NATR is a percentage; an ATR-multiple stop
and a NATR-multiple stop are different distances.
## References
NATR is the percentage-normalised ATR as implemented by TA-Lib (`NATR`);
the underlying ATR is Wilder's from *New Concepts in Technical Trading
Systems* (1978).
## See also
- [Indicator-Atr.md](../volatility-bands/Indicator-Atr.md) — the price-unit original.
- [Indicator-HistoricalVolatility.md](../volatility-bands/Indicator-HistoricalVolatility.md) —
return-based annualised volatility.
- [Indicators-Overview.md](../../Indicators-Overview.md) — the full taxonomy.
@@ -0,0 +1,147 @@
# 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 & Bands |
| 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`](../volatility-bands/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`](../volatility-bands/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](../volatility-bands/Indicator-BollingerBands.md) — the bands
this locates price within.
- [Indicator-BollingerBandwidth.md](../volatility-bands/Indicator-BollingerBandwidth.md) — the
companion derived indicator: band *width*.
- [Indicators-Overview.md](../../Indicators-Overview.md) — the full taxonomy.
@@ -0,0 +1,155 @@
# StdDev
> Rolling population standard deviation — the dispersion of the last
> `period` prices around their mean.
## Quick reference
| Field | Value |
|-------|-------|
| Family | Volatility & Bands |
| Input type | `f64` (single close) |
| Output type | `f64` |
| Output range | `[0, ∞)` (price-difference scale) |
| Default parameters | `period = 20` (Python) |
| Warmup period | `period` |
| Interpretation | Spread of recent prices; the raw volatility behind Bollinger Bands. |
## Formula
```
mean = (1/n) · Σ price
variance = (1/n) · Σ price² mean²
StdDev = √variance
```
This is the **population** standard deviation (divisor `n`, not `n 1`)
— the exact dispersion measure that drives the band width of
[`BollingerBands`](../volatility-bands/Indicator-BollingerBands.md). It is maintained as an
O(1) state machine: a running sum and a running sum-of-squares, each
updated by one add and one subtract per bar. Floating-point cancellation
can leave the computed variance very slightly negative; it is clamped to
zero before the square root.
## Parameters
| Name | Type | Default | Valid range | Description |
|----------|---------|---------------|-------------|-------------|
| `period` | `usize` | `20` (Python) | `>= 1` | Rolling window length. `0` errors with `Error::PeriodZero`. `period = 1` always yields `0`. |
The Python binding defaults `period` to `20`.
## Inputs / Outputs
From `crates/wickra-core/src/indicators/std_dev.rs`:
```rust
impl Indicator for StdDev {
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
`StdDev::new(period).warmup_period() == period`. The first non-`None`
value is emitted once the window holds `period` prices.
## Edge cases
- **Constant series.** A flat series has zero dispersion, so the output
is `0.0` (`constant_series_yields_zero` pins this).
- **NaN / infinity inputs.** Non-finite inputs are silently dropped; the
window and the running sums are left untouched.
- **Reset.** `sd.reset()` clears the window and both running sums.
## Examples
### Rust
```rust
use wickra::{BatchExt, Indicator, StdDev};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut sd = StdDev::new(3)?;
let out: Vec<Option<f64>> = sd.batch(&[2.0, 4.0, 6.0]);
println!("{:?}", out);
Ok(())
}
```
Output:
```
[None, None, Some(1.6329931618554525)]
```
The window `[2, 4, 6]` has mean `4` and variance `(4 + 0 + 4) / 3 = 8/3`,
so the standard deviation is `√(8/3) ≈ 1.633`. This matches the
`reference_value` test in `crates/wickra-core/src/indicators/std_dev.rs`.
### Python
```python
import numpy as np
import wickra as ta
sd = ta.StdDev(3)
print(sd.batch(np.array([2.0, 4.0, 6.0])))
```
Output:
```
[ nan nan 1.6329932]
```
### Node
```javascript
const ta = require('wickra');
const sd = new ta.StdDev(3);
console.log(sd.batch([2, 4, 6]));
```
Output:
```
[ NaN, NaN, 1.6329931618554525 ]
```
## Interpretation
`StdDev` is the most direct volatility measure in the library: large
values mean prices are scattered widely around their mean, small values
mean a tight, quiet market. Use it on its own as a volatility filter, or
recognise it as the engine inside `BollingerBands` — multiplying `StdDev`
by the band multiplier and adding it to an `Sma` reproduces the bands
exactly.
## Common pitfalls
- **Expecting the sample standard deviation.** `StdDev` divides by `n`,
not `n 1`. For the unbiased return-based estimator use
[`HistoricalVolatility`](../volatility-bands/Indicator-HistoricalVolatility.md).
- **Comparing across instruments.** The output is in price units; a
`StdDev` of `5` is not comparable between a $10 and a $1000 asset.
## References
The population standard deviation is standard statistics; this
implementation matches the dispersion term of John Bollinger's Bollinger
Bands and pandas' `rolling(period).std(ddof=0)`.
## See also
- [Indicator-BollingerBands.md](../volatility-bands/Indicator-BollingerBands.md) — bands built
from this dispersion measure.
- [Indicator-HistoricalVolatility.md](../volatility-bands/Indicator-HistoricalVolatility.md) —
annualised volatility of log returns.
- [Indicators-Overview.md](../../Indicators-Overview.md) — the full taxonomy.
@@ -0,0 +1,147 @@
# TrueRange
> True Range — the single-bar volatility measure that ATR is the average
> of, exposed raw.
## Quick reference
| Field | Value |
|-------|-------|
| Family | Volatility & Bands |
| Input type | `Candle` (uses `high`, `low`, `close`) |
| Output type | `f64` |
| Output range | `[0, ∞)` (price scale) |
| Default parameters | none (no parameters) |
| Warmup period | `1` |
| Interpretation | Per-bar volatility including overnight gaps. |
## Formula
```
TR = max( high low, |high close_prev|, |low close_prev| )
```
True Range is the greatest of the bar's own range and the two gaps to the
previous close, so it captures volatility that opens *between* bars — an
overnight gap — not only the range printed within a bar. The first bar has no
previous close and falls back to `high low`. Where [`Atr`](../volatility-bands/Indicator-Atr.md)
is the Wilder-smoothed average of this series, `TrueRange` exposes it raw, one
value per bar.
## Parameters
`TrueRange` takes **no parameters**`TrueRange::new()` in Rust,
`wickra.TrueRange()` in Python, `new ta.TrueRange()` in Node.
## Inputs / Outputs
From `crates/wickra-core/src/indicators/true_range.rs`:
```rust
impl Indicator for TrueRange {
type Input = Candle;
type Output = f64;
// update(&mut self, input: Candle) -> Option<f64>
}
```
`TrueRange` is a **candle-input** indicator that reads `high`, `low` and
`close` (the close drives the gap terms). Python's streaming `update` accepts
a 6-tuple or a dict; the batch helper takes `high`, `low`, `close` numpy
arrays. Node and WASM expose `update(high, low, close)` and the matching
`batch`.
## Warmup
`TrueRange::new().warmup_period() == 1`. It emits a value from the very first
candle — that bar simply has no previous close and uses `high low`.
## Edge cases
- **First bar.** No previous close: `TR = high low`.
- **Gap.** A bar that opens far from the prior close has a `TR` larger than
its own `high low`.
- **Non-negative.** `TR` is always `>= 0`.
- **Reset.** `tr.reset()` drops the previous close; the next bar restarts.
## Examples
### Rust
```rust
use wickra::{BatchExt, Candle, Indicator, TrueRange};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut tr = TrueRange::new();
let out = tr.batch(&[
Candle::new(11.0, 12.0, 8.0, 11.0, 1.0, 0)?, // no prev close -> 12 - 8
Candle::new(9.5, 10.0, 9.0, 9.5, 1.0, 1)?, // prev close 11 -> max(1, 1, 2)
]);
println!("{:?}", out);
Ok(())
}
```
Output:
```
[Some(4.0), Some(2.0)]
```
### Python
```python
import numpy as np
import wickra as ta
tr = ta.TrueRange()
print(tr.batch(
np.array([12.0, 10.0]), np.array([8.0, 9.0]), np.array([11.0, 9.5])
))
```
Output:
```
[4. 2.]
```
### Node
```javascript
const ta = require('wickra');
const tr = new ta.TrueRange();
console.log(tr.batch([12, 10], [8, 9], [11, 9.5]));
```
Output:
```
[ 4, 2 ]
```
## Interpretation
Read `TrueRange` as raw per-bar volatility. It spikes on wide-range or gapping
bars and shrinks in quiet stretches. Smoothing it with a moving average gives
[`Atr`](../volatility-bands/Indicator-Atr.md); using it directly is useful for volatility-scaled
position sizing or for spotting single outlier bars an average would hide.
## Common pitfalls
- **Confusing it with `high low`.** On a gap bar the True Range is larger —
that is the whole point.
- **Feeding it scalar prices.** It needs the full `high`/`low`/`close` bar.
## References
J. Welles Wilder Jr.'s True Range, from *New Concepts in Technical Trading
Systems* (1978).
## See also
- [Indicator-Atr.md](../volatility-bands/Indicator-Atr.md) — the Wilder-smoothed average of the
True Range.
- [Indicator-ChaikinVolatility.md](../volatility-bands/Indicator-ChaikinVolatility.md) — a
rate-of-change volatility measure.
- [Indicators-Overview.md](../../Indicators-Overview.md) — the full taxonomy.
@@ -0,0 +1,160 @@
# UlcerIndex
> Ulcer Index — Peter Martin's downside-only risk measure: the
> root-mean-square of recent drawdowns.
## Quick reference
| Field | Value |
|-------|-------|
| Family | Volatility & Bands |
| Input type | `f64` (single close) |
| Output type | `f64` |
| Output range | `[0, ∞)` (percent) |
| Default parameters | `period = 14` (Python) |
| Warmup period | `2·period 1` |
| Interpretation | Depth and duration of drawdowns; `0` means no drawdown at all. |
## Formula
```
max_t = highest price over the trailing `period` bars
drawdown_t = 100 · (price_t max_t) / max_t
UlcerIndex = √( mean( drawdown² over period ) )
```
Standard deviation treats an up-move and a down-move as equally
"volatile". The Ulcer Index measures only the **pain of being underwater**:
for each bar it takes the percentage drop from the trailing high, squares
it, and reports the root-mean-square. A market that only rises has no
drawdown and an Ulcer Index of `0`; the deeper and longer the drawdowns,
the higher the reading. It is the volatility term in the Martin ratio
(Ulcer Performance Index).
## Parameters
| Name | Type | Default | Valid range | Description |
|----------|---------|---------------|-------------|-------------|
| `period` | `usize` | `14` (Python) | `>= 1` | Look-back for both the trailing high and the RMS window. `0` errors with `Error::PeriodZero`. |
The Python binding defaults `period` to `14`.
## Inputs / Outputs
From `crates/wickra-core/src/indicators/ulcer_index.rs`:
```rust
impl Indicator for UlcerIndex {
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
`UlcerIndex::new(period).warmup_period() == 2·period 1`. The first
`period` prices fill the trailing-maximum window; the per-bar squared
drawdown then needs another `period 1` bars to fill the RMS window.
## Edge cases
- **Pure up-trend.** Price never trades below its own running high, so
every drawdown — and the Ulcer Index — is `0`
(`pure_uptrend_yields_zero` pins this).
- **Constant series.** A flat series has no drawdown; the output is `0.0`
(`constant_series_yields_zero` pins this).
- **Non-negative.** The Ulcer Index is an RMS of real numbers and is
never negative (`output_is_non_negative` pins this).
- **NaN / infinity inputs.** Non-finite inputs are silently dropped.
- **Reset.** `ui.reset()` clears both rolling windows and the sum.
## Examples
### Rust
```rust
use wickra::{BatchExt, Indicator, UlcerIndex};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut ui = UlcerIndex::new(2)?;
let out: Vec<Option<f64>> = ui.batch(&[10.0, 8.0, 12.0, 9.0]);
println!("{:?}", out);
Ok(())
}
```
Output:
```
[None, None, Some(14.142135623730951), Some(17.67766952966369)]
```
`UlcerIndex(2)` warms up after `3` bars. At bar 3 the squared drawdowns in
the window are `[400, 0]`, so the index is `√(400/2) = √200`. At bar 4
they are `[0, 625]`, giving `√(625/2) = √312.5`. This matches the
`reference_values` test in
`crates/wickra-core/src/indicators/ulcer_index.rs`.
### Python
```python
import numpy as np
import wickra as ta
ui = ta.UlcerIndex(2)
print(ui.batch(np.array([10.0, 8.0, 12.0, 9.0])))
```
Output:
```
[ nan nan 14.1421356 17.6776695]
```
### Node
```javascript
const ta = require('wickra');
const ui = new ta.UlcerIndex(2);
console.log(ui.batch([10, 8, 12, 9]));
```
Output:
```
[ NaN, NaN, 14.142135623730951, 17.67766952966369 ]
```
## Interpretation
`UlcerIndex` answers "how uncomfortable has holding this been?" — a high
reading means deep or prolonged drawdowns, a low reading means a smooth
ride up. It is most useful for *comparing* instruments or strategies on a
downside-risk basis, and as the denominator of the Ulcer Performance
Index (`(return risk-free) / UlcerIndex`), a Sharpe-ratio analogue that
penalises only downside volatility.
## Common pitfalls
- **Reading it as two-sided volatility.** The Ulcer Index ignores upside
entirely — a wildly choppy *up*-trend can still score near `0`. Use
[`StdDev`](../volatility-bands/Indicator-StdDev.md) for two-sided dispersion.
- **Forgetting the doubled warmup.** Warmup is `2·period 1`, not
`period`.
## References
Peter Martin and Byron McCann, *The Investor's Guide to Fidelity Funds*
(1989); the index is also documented at StockCharts. The trailing-high
drawdown RMS here follows that definition.
## See also
- [Indicator-StdDev.md](../volatility-bands/Indicator-StdDev.md) — two-sided dispersion.
- [Indicator-Atr.md](../volatility-bands/Indicator-Atr.md) — per-bar range volatility.
- [Indicators-Overview.md](../../Indicators-Overview.md) — the full taxonomy.