F13b: add True Range, Chaikin Volatility, Z-Score and Linear Regression Angle

Second half of the eight indicators that fill out the new family taxonomy.

- Rust core: true_range.rs (TrueRange — the raw single-bar volatility ATR
  averages), chaikin_volatility.rs (ChaikinVolatility — rate of change of a
  smoothed high-low spread), z_score.rs (ZScore — price normalised against
  its rolling mean and standard deviation) and linreg_angle.rs (LinRegAngle
  — the rolling regression slope as a degree angle). Each with a full
  Indicator impl, runnable doctest and reference / property / warmup /
  reset / batch==streaming tests.
- Python / Node / WASM: classes wired through all three bindings (ZScore
  and LinRegAngle ride the scalar macros where possible) plus .pyi stubs
  and __init__.py / __all__ entries.
- Wiki: four new Indicator-*.md pages.

The eight-family taxonomy restructure (Overview / Home / README / folder
layout) lands next in F13c.

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:06:36 +02:00
parent e452d35a27
commit 6643f7a81d
16 changed files with 1837 additions and 7 deletions
@@ -0,0 +1,143 @@
# LinRegAngle
> Linear Regression Angle — the slope of the rolling least-squares fit,
> expressed as an angle in degrees.
## Quick reference
| Field | Value |
|-------|-------|
| Family | Price Statistics |
| Input type | `f64` (price) |
| Output type | `f64` |
| Output range | `(90°, +90°)` |
| Default parameters | `period = 14` (Python) |
| Warmup period | `period` |
| Interpretation | Steepness of the trend; sign is direction, magnitude is pitch. |
## Formula
```
LinRegAngle = atan(LinRegSlope) · 180 / π
```
The angle carries exactly the same information as
[`LinRegSlope`](Indicator-LinRegSlope.md) — positive while price trends up,
negative while it trends down — but maps the unbounded slope through `atan`
onto `(90°, +90°)`. That bounded, price-unit-free scale makes "how steep is
the trend" comparable at a glance and across instruments. This is TA-Lib's
`LINEARREG_ANGLE`.
## Parameters
`period` — the regression window. Must be at least `2` (a line needs two
points). The Python binding defaults it to `14`; the Rust and Node
constructors require it explicitly.
## Inputs / Outputs
From `crates/wickra-core/src/indicators/linreg_angle.rs`:
```rust
impl Indicator for LinRegAngle {
type Input = f64;
type Output = f64;
// update(&mut self, input: f64) -> Option<f64>
}
```
`LinRegAngle` is a **scalar** indicator: it consumes one `f64` price per step.
Because `Input = f64` it can sit inside a [`Chain`](../../Indicator-Chaining.md).
## Warmup
`LinRegAngle::new(14).warmup_period() == 14`. The first value lands once the
window holds a full `period` prices.
## Edge cases
- **`period < 2`.** Rejected at construction — a regression line is undefined
for fewer than two points.
- **Unit slope.** A series rising by exactly `1` per step has slope `1`, and
`atan(1) = 45°`.
- **Flat series.** A constant input has slope `0` and therefore angle `0`.
- **Reset.** `angle.reset()` clears the rolling regression window.
## Examples
### Rust
```rust
use wickra::{BatchExt, Indicator, LinRegAngle};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut angle = LinRegAngle::new(5)?;
// Closes rising by 1 per step -> slope 1 -> atan(1) = 45 degrees.
let out = angle.batch(&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
println!("{:?}", out);
Ok(())
}
```
Output:
```
[None, None, None, None, Some(45.0), Some(45.0)]
```
### Python
```python
import numpy as np
import wickra as ta
angle = ta.LinRegAngle(5)
print(angle.batch(np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0])))
```
Output:
```
[ nan nan nan nan 45. 45.]
```
### Node
```javascript
const ta = require('wickra');
const angle = new ta.LinRegAngle(5);
console.log(angle.batch([1, 2, 3, 4, 5, 6]));
```
Output:
```
[ NaN, NaN, NaN, NaN, 45, 45 ]
```
## Interpretation
The angle is read like a slope: sign gives trend direction, magnitude gives
how steeply price is pitched. Because it is bounded to `±90°` it is convenient
for thresholds — e.g. "only trade with the trend while the angle exceeds
`30°`" — and for comparing trend pitch across instruments with different price
scales, which the raw [`LinRegSlope`](Indicator-LinRegSlope.md) cannot do.
## Common pitfalls
- **Reading degrees as a price quantity.** The angle depends on the chart's
implicit scaling; treat it as a relative steepness gauge, not an absolute.
- **Tiny periods.** `period = 2` reduces the fit to the last difference.
## References
The angle of an ordinary least-squares fit to a rolling price window; matches
TA-Lib's `LINEARREG_ANGLE`.
## See also
- [Indicator-LinRegSlope.md](Indicator-LinRegSlope.md) — the same fit's slope,
in raw price-per-bar units.
- [Indicator-LinearRegression.md](Indicator-LinearRegression.md) — the
endpoint of the same rolling fit.
- [Indicators-Overview.md](../../Indicators-Overview.md) — the full taxonomy.
@@ -0,0 +1,139 @@
# ZScore
> Z-Score — how many standard deviations the latest price sits from its
> rolling mean.
## Quick reference
| Field | Value |
|-------|-------|
| Family | Price Statistics |
| Input type | `f64` (price) |
| Output type | `f64` |
| Output range | unbounded around zero (standard deviations) |
| Default parameters | `period = 20` (Python) |
| Warmup period | `period` |
| Interpretation | Large magnitude = stretched; a return toward `0` = reversion. |
## Formula
```
ZScore = (price SMA(price, n)) / population_stddev(price, n)
```
The Z-Score normalises price against its own recent behaviour: it subtracts
the rolling mean and divides by the rolling population standard deviation. A
reading of `+2` means price is two standard deviations above its `n`-bar
average — statistically stretched to the upside; `2` is the mirror. It is the
standard input to mean-reversion strategies.
## Parameters
`period` — the rolling window for the mean and standard deviation. The Python
binding defaults it to `20`; the Rust and Node constructors require it.
## Inputs / Outputs
From `crates/wickra-core/src/indicators/z_score.rs`:
```rust
impl Indicator for ZScore {
type Input = f64;
type Output = f64;
// update(&mut self, input: f64) -> Option<f64>
}
```
`ZScore` is a **scalar** indicator: it consumes one `f64` price per step.
Because `Input = f64` it can sit inside a [`Chain`](../../Indicator-Chaining.md).
## Warmup
`ZScore::new(20).warmup_period() == 20`. The first value lands once the window
holds a full `period` prices.
## Edge cases
- **Zero dispersion.** A flat window has a zero standard deviation; `ZScore`
is defined as `0` rather than dividing by zero.
- **Rising series.** A monotonically rising price always scores above its
trailing mean (positive).
- **Reset.** `z.reset()` clears the rolling window.
## Examples
### Rust
```rust
use wickra::{BatchExt, Indicator, ZScore};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut z = ZScore::new(2)?;
// Window [1, 3]: mean 2, population stddev 1; latest 3 -> (3 - 2) / 1.
println!("{:?}", z.batch(&[1.0, 3.0]));
Ok(())
}
```
Output:
```
[None, Some(1.0)]
```
### Python
```python
import numpy as np
import wickra as ta
z = ta.ZScore(2)
print(z.batch(np.array([1.0, 3.0])))
```
Output:
```
[nan 1.]
```
### Node
```javascript
const ta = require('wickra');
const z = new ta.ZScore(2);
console.log(z.batch([1, 3]));
```
Output:
```
[ NaN, 1 ]
```
## Interpretation
Z-Score is the workhorse of mean-reversion: a common rule enters against the
move when `|ZScore| > 2` and exits as it crosses back through `0`. Read
together with a trend filter — a high Z-Score in a strong trend is often
continuation, not exhaustion, so the reversion edge is best in ranging
regimes.
## Common pitfalls
- **Trading extremes blindly.** A trending market can hold a high Z-Score for
a long time; pair it with a regime filter.
- **Tiny periods.** A short window makes the mean and stddev jumpy.
## References
The standard statistical Z-Score (standard score) applied to a rolling price
window.
## See also
- [Indicator-StdDev.md](../volatility/Indicator-StdDev.md) — the rolling
standard deviation in the denominator.
- [Indicator-LinearRegression.md](Indicator-LinearRegression.md) — another
rolling statistical fit.
- [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`](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](Indicator-Atr.md) — the level of per-bar volatility.
- [Indicator-TrueRange.md](Indicator-TrueRange.md) — raw single-bar range.
- [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`](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`](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](Indicator-Atr.md) — the Wilder-smoothed average of the
True Range.
- [Indicator-ChaikinVolatility.md](Indicator-ChaikinVolatility.md) — a
rate-of-change volatility measure.
- [Indicators-Overview.md](../../Indicators-Overview.md) — the full taxonomy.