F2: add ZLEMA, T3 and VWMA advanced moving averages

Completes the F2 family (Advanced MAs) end to end:

- Rust core: zlema.rs (Zero-Lag EMA over the de-lagged series
  2·price − price[lag]), t3.rs (Tillson's six-EMA cascade with the
  volume-factor polynomial), vwma.rs (volume-weighted rolling mean with
  a zero-volume fallback to the unweighted mean). Each with a full
  Indicator impl, runnable doctest and reference-value / warmup /
  reset / batch==streaming / non-finite tests.
- Python: PyZlema / PyT3 / PyVwma PyO3 classes + module registration
  + .pyi stubs (T3 defaults v=0.7).
- Node: ZlemaNode via the scalar macro, explicit T3Node and VwmaNode
  classes; index.d.ts and index.js updated.
- WASM: WasmZlema / WasmT3 via the scalar macro, explicit WasmVwma.
- Wiki: Indicator-Zlema.md, Indicator-T3.md, Indicator-Vwma.md plus
  rows in Indicators-Overview.md and entries in Home.md.

cargo fmt + clippy (core/wickra/data/wasm/node) clean; 232 core tests,
25 data tests and 33 doctests green.
This commit is contained in:
kingchenc
2026-05-22 17:45:02 +02:00
parent ed7324115c
commit 780a176072
15 changed files with 1573 additions and 3 deletions
+3
View File
@@ -81,6 +81,9 @@ Rust / Python / Node examples. They are grouped by family, mirroring the
- [Indicator-Kama.md](indicators/trend/Indicator-Kama.md)
- [Indicator-Smma.md](indicators/trend/Indicator-Smma.md)
- [Indicator-Trima.md](indicators/trend/Indicator-Trima.md)
- [Indicator-Zlema.md](indicators/trend/Indicator-Zlema.md)
- [Indicator-T3.md](indicators/trend/Indicator-T3.md)
- [Indicator-Vwma.md](indicators/trend/Indicator-Vwma.md)
**Momentum** — measure the rate of price change rather than the level.
+4 -1
View File
@@ -1,6 +1,6 @@
# Indicators Overview
Wickra ships 27 indicators, organised in source under the four classical
Wickra ships 30 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
@@ -36,6 +36,7 @@ benchmarks against fancier averages.
| `Sma` | Equal-weighted rolling mean over `period` closes. | `f64` | `f64` | unbounded (price scale) | `period` (no default in core; Python defaults vary by binding) | `period` | [Indicator-Sma.md](indicators/trend/Indicator-Sma.md) |
| `Wma` | Linear weights `1, 2, …, period` so the newest bar matters most. | `f64` | `f64` | unbounded (price scale) | `period` | `period` | [Indicator-Wma.md](indicators/trend/Indicator-Wma.md) |
| `Trima` | A `period`-window SMA applied twice; triangular weights centred on the middle bar. | `f64` | `f64` | unbounded (price scale) | `period` | `period` | [Indicator-Trima.md](indicators/trend/Indicator-Trima.md) |
| `Vwma` | Rolling mean of closes weighted by each bar's volume. | `Candle` | `f64` | unbounded (price scale) | `period` | `period` | [Indicator-Vwma.md](indicators/trend/Indicator-Vwma.md) |
### Exponential family
@@ -48,6 +49,8 @@ you stack more EMAs, but so does responsiveness to noise.
| `Dema` | Mulloy's `2·EMA EMA(EMA)`; removes first-order EMA lag. | `f64` | `f64` | unbounded (price scale) | `period` | `2·period 1` | [Indicator-Dema.md](indicators/trend/Indicator-Dema.md) |
| `Tema` | Mulloy's `3·EMA 3·EMA(EMA) + EMA(EMA(EMA))`; removes more lag than DEMA. | `f64` | `f64` | unbounded (price scale) | `period` | `3·period 2` | [Indicator-Tema.md](indicators/trend/Indicator-Tema.md) |
| `Smma` | Wilder's RMA: an SMA-seeded exponential average with the slow `1/period` factor. | `f64` | `f64` | unbounded (price scale) | `period` | `period` | [Indicator-Smma.md](indicators/trend/Indicator-Smma.md) |
| `Zlema` | EMA of the de-lagged series `2·price price[lag]`; near-zero group delay. | `f64` | `f64` | unbounded (price scale) | `period` | `lag + period` | [Indicator-Zlema.md](indicators/trend/Indicator-Zlema.md) |
| `T3` | Tillson's six-EMA cascade recombined with a volume factor `v`. | `f64` | `f64` | unbounded (price scale) | `(period, v=0.7)` (Python) | `6·period 5` | [Indicator-T3.md](indicators/trend/Indicator-T3.md) |
`Trix` is also built from a triple-smoothed EMA, but it is a *momentum
oscillator* — it emits the rate of change of that EMA, not a price-scale
+172
View File
@@ -0,0 +1,172 @@
# T3
> Tillson T3 — a six-fold cascaded EMA recombined with a volume factor `v`
> to give a smooth, low-lag trend line.
## Quick reference
| Field | Value |
|-------|-------|
| Family | Trend |
| Sub-category | Exponential family |
| Input type | `f64` (single close) |
| Output type | `f64` |
| Output range | unbounded; tracks the input price scale |
| Default parameters | `period` required; `v = 0.7` (Python default) |
| Warmup period | `6·period 5` |
| Interpretation | Smooth trend line with less lag than a same-period EMA. |
## Formula
T3 is the *generalised DEMA* (`GD`) applied three times. Tim Tillson's
expansion of `GD(GD(GD(price)))` over six chained EMAs — `e1 … e6`, each
of the same `period`, where `e2 = EMA(e1)`, `e3 = EMA(e2)`, … — is:
```
v2 = v², v3 = v³
c1 = v3
c2 = 3·v2 + 3·v3
c3 = 6·v2 3·v 3·v3
c4 = 1 + 3·v + v3 + 3·v2
T3 = c1·e6 + c2·e5 + c3·e4 + c4·e3
```
The four coefficients always sum to `1`, so a constant price series maps
to itself. The volume factor `v` controls the lag/overshoot trade-off:
`v = 0` collapses T3 to the plain triple-cascaded EMA `e3`; the
conventional `v = 0.7` adds a corrective hump that sharpens turns.
## Parameters
| Name | Type | Default | Valid range | Description |
|----------|---------|----------------|-------------|-------------|
| `period` | `usize` | none | `>= 1` | Length of every EMA in the cascade. `period = 0` errors with `Error::PeriodZero`. |
| `v` | `f64` | `0.7` (Python) | `[0.0, 1.0]`| Volume factor. Non-finite or out-of-range values error with `Error::InvalidPeriod`. |
The Python binding defaults `v` to `0.7` via `#[pyo3(signature = (period, v=0.7))]`;
`period` is always explicit. The Node and WASM constructors take both
arguments explicitly.
## Inputs / Outputs
From `crates/wickra-core/src/indicators/t3.rs`:
```rust
impl Indicator for T3 {
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
`T3::new(period, v).warmup_period() == 6·period 5`. Each stage of the
SMA-seeded EMA cascade adds `period 1` bars of delay: `e1` seeds at
input `period`, `e2` at `2·period 1`, …, `e6` at `6·period 5`. T3
emits its first value once `e6` is ready, since the output formula needs
`e3` through `e6`.
## Edge cases
- **Constant series.** Because `c1 + c2 + c3 + c4 = 1` for any `v`, a flat
input series produces a flat output equal to the constant
(`coefficients_sum_to_one` and `constant_series_yields_the_constant`
pin this).
- **`v = 0`.** The coefficients become `c1 = c2 = c3 = 0`, `c4 = 1`, so
`T3` is exactly the third stage of the EMA cascade
(`zero_volume_factor_collapses_to_triple_cascaded_ema` pins this).
- **NaN / infinity inputs.** Non-finite inputs are silently dropped — the
cascade is not advanced — and the previous valid value is returned.
- **Reset.** `t3.reset()` clears all six EMAs and the cached value.
## Examples
### Rust
```rust
use wickra::{BatchExt, Indicator, T3};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let prices: Vec<f64> = (1..=40).map(f64::from).collect();
let mut t3 = T3::new(3, 0.7)?;
let out = t3.batch(&prices);
println!("warmup_period = {}", t3.warmup_period());
println!("first ready index = {:?}", out.iter().position(Option::is_some));
Ok(())
}
```
Output:
```
warmup_period = 13
first ready index = Some(12)
```
`T3(3, 0.7)` warms up after `6·3 5 = 13` inputs, so the first non-`None`
output sits at index `12`. On a pure ramp the output then tracks the input
trend with a smooth, near-constant offset.
### Python
```python
import numpy as np
import wickra as ta
t3 = ta.T3(5) # v defaults to 0.7
prices = np.linspace(100.0, 140.0, 60)
out = t3.batch(prices)
print("warmup_period =", t3.warmup_period())
print("ready values:", np.count_nonzero(~np.isnan(out)))
```
Output:
```
warmup_period = 25
ready values: 36
```
### Node
```javascript
const ta = require('wickra');
const t3 = new ta.T3(5, 0.7);
const prices = Array.from({ length: 60 }, (_, i) => 100 + i);
console.log('warmupPeriod:', t3.warmupPeriod());
console.log('last:', t3.batch(prices).at(-1));
```
## Interpretation
`T3` is a "best of both" trend line — close to `Tema` in lag reduction but
visibly smoother, because the six-EMA cascade filters noise the
three-EMA `Tema` lets through. Use it as a single trend filter or as the
slow leg of a crossover where you want a clean line. Raise `v` toward `1`
for sharper turns (more overshoot), lower it toward `0` for maximum
smoothness (`v = 0` is just a triple EMA).
## Common pitfalls
- **Treating `v` as optional outside Python.** Only the Python binding
defaults `v` to `0.7`; the Rust, Node and WASM constructors require it.
- **Underestimating warmup.** `6·period 5` grows fast — a `T3(20)` needs
`115` bars before its first value.
## References
Tim Tillson, "Better Moving Averages", *Technical Analysis of Stocks &
Commodities* (1998). The six-EMA expansion and coefficient formulas here
match Tillson's published derivation and TA-Lib's `T3`.
## See also
- [Indicator-Tema.md](Indicator-Tema.md) — the three-EMA relative.
- [Indicator-Dema.md](Indicator-Dema.md) — the two-EMA relative.
- [Indicator-Zlema.md](Indicator-Zlema.md) — low-lag average via de-lagging.
- [Indicators-Overview.md](../../Indicators-Overview.md) — the full taxonomy.
@@ -0,0 +1,176 @@
# VWMA
> Volume-Weighted Moving Average — a rolling mean of closes where each bar
> is weighted by its own traded volume.
## Quick reference
| Field | Value |
|-------|-------|
| Family | Trend |
| Sub-category | Volume-weighted averages |
| Input type | `Candle` (uses `close` and `volume`) |
| Output type | `f64` |
| Output range | unbounded; tracks the input price scale |
| Default parameters | `period` is required (no default in either binding) |
| Warmup period | `period` |
| Interpretation | Trend line that leans toward high-conviction (high-volume) bars. |
## Formula
```
VWMA_t = Σ(close_i · volume_i) / Σ(volume_i) over the last `period` bars
```
A heavy bar pulls the average toward its close; a thin bar barely moves
it. Both the numerator (`Σ price·volume`) and denominator (`Σ volume`)
are maintained as O(1) rolling sums, so `update` is O(1) regardless of
`period`.
If **every** bar in the window has zero volume the weighted mean is
undefined (`0 / 0`). VWMA then falls back to the plain unweighted mean of
the `period` closes, so the output is always finite and defined.
## Parameters
| Name | Type | Default | Valid range | Description |
|----------|---------|---------|-------------|-------------|
| `period` | `usize` | none | `>= 1` | Rolling window length in bars. `period = 0` errors with `Error::PeriodZero`. |
There is no Python `#[pyo3(signature = …)]` default for `VWMA`, so
`wickra.VWMA(period)` requires the period explicitly.
## Inputs / Outputs
From `crates/wickra-core/src/indicators/vwma.rs`:
```rust
impl Indicator for Vwma {
type Input = Candle;
type Output = f64;
// update(&mut self, input: Candle) -> Option<f64>
}
```
`VWMA` is a **candle-input** indicator: it reads `close` and `volume` from
each `Candle`. In Python the streaming `update` accepts a 6-tuple or a
dict; the batch helper takes `close` and `volume` numpy arrays. Node and
WASM expose `update(close, volume)` and `batch(close, volume)`.
## Warmup
`Vwma::new(period).warmup_period() == period`. The first `period 1`
candles fill the rolling window; the `period`-th `update()` produces the
first weighted mean.
## Edge cases
- **Constant closes.** Closes all equal to `c` give `VWMA = c` regardless
of the volumes (`Σ c·v / Σ v = c`), and the zero-volume fallback also
yields `c` (`constant_series_yields_the_constant` pins this).
- **Zero-volume window.** If every bar in the window has `volume = 0`,
VWMA returns the unweighted mean of the `period` closes
(`zero_volume_window_falls_back_to_unweighted_mean` pins this).
- **Candle validation.** `Candle::new` already rejects NaN/infinite fields
and negative volume, so `update` never sees an invalid bar — there is no
separate non-finite guard.
- **Reset.** `vwma.reset()` clears the window and all three rolling sums.
## Examples
### Rust
```rust
use wickra::{Candle, Indicator, Vwma};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut vwma = Vwma::new(2)?;
// (close, volume): (10, 1) then (20, 3).
let a = Candle::new(10.0, 10.0, 10.0, 10.0, 1.0, 0)?;
let b = Candle::new(20.0, 20.0, 20.0, 20.0, 3.0, 1)?;
println!("{:?}", vwma.update(a));
println!("{:?}", vwma.update(b));
Ok(())
}
```
Output:
```
None
Some(17.5)
```
The window holds two bars: `(10·1 + 20·3) / (1 + 3) = 70 / 4 = 17.5`. The
heavier bar at `20` dominates, so the result sits well above the simple
mean of `15`. This matches the `reference_value` test in
`crates/wickra-core/src/indicators/vwma.rs`.
### Python
```python
import numpy as np
import wickra as ta
vwma = ta.VWMA(2)
close = np.array([10.0, 20.0, 30.0])
volume = np.array([1.0, 3.0, 1.0])
print(vwma.batch(close, volume))
print("warmup_period =", vwma.warmup_period())
```
Output:
```
[ nan 17.5 22.5]
warmup_period = 2
```
### Node
```javascript
const ta = require('wickra');
const vwma = new ta.VWMA(2);
console.log(vwma.batch([10, 20, 30], [1, 3, 1]));
console.log('warmupPeriod:', vwma.warmupPeriod());
```
Output:
```
[ NaN, 17.5, 22.5 ]
warmupPeriod: 2
```
## Interpretation
`Vwma` is a trend line that respects participation. Compared with an
equal-weighted `Sma` of the same period, it reacts faster to moves backed
by heavy volume and lags moves on thin volume. The classic read is the
`Vwma`-vs-`Sma` relationship: `Vwma` above `Sma` means recent strength was
volume-backed (more trustworthy); `Vwma` below `Sma` means the up-moves
came on light volume. It is a session-independent cousin of
[`Vwap`](../volume/Indicator-Vwap.md) — VWAP weights by volume since the
start of the stream, VWMA over a fixed rolling window.
## Common pitfalls
- **Feeding it scalar prices.** `VWMA` needs volume; it takes a `Candle`,
not an `f64`. Use `Sma`/`Wma` for a pure price series.
- **Assuming a zero-volume window is an error.** It is not — VWMA falls
back to the unweighted mean. If that fallback matters to you, screen the
window's total volume yourself.
## References
The volume-weighted moving average is a standard volume-weighted rolling
mean; the rolling-sum formulation here matches the common pandas
implementation `(close*volume).rolling(n).sum() / volume.rolling(n).sum()`,
with an explicit zero-volume fallback added for robustness.
## See also
- [Indicator-Sma.md](Indicator-Sma.md) — the equal-weighted counterpart.
- [Indicator-Vwap.md](../volume/Indicator-Vwap.md) — volume-weighted price
since the start of the stream.
- [Indicators-Overview.md](../../Indicators-Overview.md) — the full taxonomy.
@@ -0,0 +1,167 @@
# ZLEMA
> Zero-Lag Exponential Moving Average — an EMA fed a de-lagged price series
> so it tracks turns with almost no group delay.
## Quick reference
| Field | Value |
|-------|-------|
| Family | Trend |
| Sub-category | Exponential family |
| Input type | `f64` (single close) |
| Output type | `f64` |
| Output range | unbounded; tracks the input price scale |
| Default parameters | `period` is required (no default in either binding) |
| Warmup period | `lag + period` where `lag = (period 1) / 2` |
| Interpretation | Low-lag trend line; crossings of price react far sooner than a plain EMA. |
## Formula
```
lag = (period 1) / 2 (integer division)
de_lagged_t = 2·price_t price_{tlag}
ZLEMA_t = EMA_period(de_lagged)_t
```
The trick (Ehlers & Way, 2010): `price_t price_{tlag}` is a momentum
term. Adding it to the current price *over-shoots* in the direction of the
recent move by exactly enough to cancel the EMA's lag. The inner EMA then
smooths that de-lagged series with the usual `α = 2 / (period + 1)`.
## Parameters
| Name | Type | Default | Valid range | Description |
|----------|---------|---------|-------------|-------------|
| `period` | `usize` | none | `>= 1` | EMA length. `period = 0` errors with `Error::PeriodZero`. The lag offset is derived as `(period 1) / 2`. |
There is no Python `#[pyo3(signature = …)]` default for `ZLEMA`, so
`wickra.ZLEMA(period)` requires the period explicitly. The derived `lag`
is exposed as a read-only property.
## Inputs / Outputs
From `crates/wickra-core/src/indicators/zlema.rs`:
```rust
impl Indicator for Zlema {
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
`Zlema::new(period).warmup_period() == lag + period`. The de-lagged series
is undefined until `lag` prior inputs exist, so it produces its first
value on input `lag + 1`; the inner EMA then needs `period` de-lagged
values to seed. The first non-`None` output therefore lands on input
`lag + period`.
## Edge cases
- **Constant series.** De-lagging a constant gives the same constant
(`2c c = c`), so `ZLEMA` of a flat series is flat
(`constant_series_yields_the_constant` pins this).
- **NaN / infinity inputs.** Non-finite inputs are silently dropped: the
rolling lag buffer is not advanced and the inner EMA is not fed, so the
previous valid value (if any) is returned.
- **`period = 1`.** `lag = 0`, the de-lagged series equals the raw price,
and `ZLEMA(1)` degenerates to a pass-through.
- **Reset.** `zlema.reset()` clears the lag buffer and the inner EMA.
## Examples
### Rust
```rust
use wickra::{BatchExt, Indicator, Zlema};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut zlema = Zlema::new(3)?;
let out: Vec<Option<f64>> = zlema.batch(&[1.0, 2.0, 3.0, 4.0, 5.0]);
println!("{:?}", out);
println!("lag = {}, warmup_period = {}", zlema.lag(), zlema.warmup_period());
Ok(())
}
```
Output:
```
[None, None, None, Some(4.0), Some(5.0)]
lag = 1, warmup_period = 4
```
`ZLEMA(3)` has `lag = 1`. The de-lagged series of `[1,2,3,4,5]` is
`[_, 3, 4, 5, 6]`; `EMA(3)` of that seeds at `mean(3,4,5) = 4.0`, then
`0.5·6 + 0.5·4 = 5.0`. This matches the `reference_values` test in
`crates/wickra-core/src/indicators/zlema.rs`.
### Python
```python
import numpy as np
import wickra as ta
zlema = ta.ZLEMA(3)
print(zlema.batch(np.array([1.0, 2.0, 3.0, 4.0, 5.0])))
print("lag =", zlema.lag, "warmup_period =", zlema.warmup_period())
```
Output:
```
[nan nan nan 4. 5.]
lag = 1 warmup_period = 4
```
### Node
```javascript
const ta = require('wickra');
const zlema = new ta.ZLEMA(3);
console.log(zlema.batch([1, 2, 3, 4, 5]));
console.log('warmupPeriod:', zlema.warmupPeriod());
```
Output:
```
[ NaN, NaN, NaN, 4, 5 ]
warmupPeriod: 4
```
## Interpretation
`Zlema` is a low-lag trend line. Use it where an `Ema` would lag too much
into a reversal — for example as the fast leg of a crossover system, or
as a trailing reference that should react quickly. The momentum injection
that removes the lag also makes `Zlema` overshoot on sharp spikes, so it
is noisier than the `Ema` it is built on; pair it with a slower filter if
whipsaws are a concern.
## Common pitfalls
- **Expecting `Ema`-identical values.** `Zlema` is deliberately *not* an
`Ema` — it leads price. The two only coincide for `period = 1`.
- **Forgetting the extra warmup.** Warmup is `lag + period`, not `period`;
budget `(period 1) / 2` extra bars before the first output.
## References
John Ehlers and Ric Way, "Zero Lag (Well, Almost)", *Technical Analysis
of Stocks & Commodities* (2010). The implementation here uses the standard
`lag = (period 1) / 2` and an SMA-seeded inner EMA.
## See also
- [Indicator-Ema.md](Indicator-Ema.md) — the inner average ZLEMA de-lags.
- [Indicator-Hma.md](Indicator-Hma.md) — another low-lag average, via WMAs.
- [Indicator-T3.md](Indicator-T3.md) — low-lag average via a six-EMA cascade.
- [Indicators-Overview.md](../../Indicators-Overview.md) — the full taxonomy.