F4: add StochRSI and Ultimate Oscillator

Completes the F4 family (Stochastic oscillators) end to end:

- Rust core: stoch_rsi.rs (Stochastic Oscillator applied to the RSI
  series, bounded [0,100]) and ultimate_oscillator.rs (Larry Williams'
  weighted three-timeframe buying-pressure oscillator). Each with a full
  Indicator impl, runnable doctest and reference / saturation / bounds /
  warmup / reset / batch==streaming tests.
- Python: PyStochRsi / PyUltimateOscillator PyO3 classes + module
  registration + .pyi stubs (defaults StochRSI=(14,14), UO=(7,14,28)).
- Node: explicit StochRsiNode and UltimateOscillatorNode; index.d.ts
  and index.js updated.
- WASM: WasmStochRsi via the scalar macro, explicit
  WasmUltimateOscillator.
- Wiki: Indicator-StochRsi.md and Indicator-UltimateOscillator.md plus
  rows in Indicators-Overview.md and entries in Home.md.

cargo fmt + clippy (core/wickra/data/wasm/node) clean; 278 core tests,
25 data tests and 39 doctests green.
This commit is contained in:
kingchenc
2026-05-22 18:02:44 +02:00
parent 7728151c87
commit e24e7726ce
13 changed files with 1181 additions and 3 deletions
+2
View File
@@ -102,6 +102,8 @@ Rust / Python / Node examples. They are grouped by family, mirroring the
- [Indicator-Cmo.md](indicators/momentum/Indicator-Cmo.md)
- [Indicator-Tsi.md](indicators/momentum/Indicator-Tsi.md)
- [Indicator-Pmo.md](indicators/momentum/Indicator-Pmo.md)
- [Indicator-StochRsi.md](indicators/momentum/Indicator-StochRsi.md)
- [Indicator-UltimateOscillator.md](indicators/momentum/Indicator-UltimateOscillator.md)
**Volatility** — envelope width and per-bar dispersion measures.
+3 -1
View File
@@ -1,6 +1,6 @@
# Indicators Overview
Wickra ships 34 indicators, organised in source under the four classical
Wickra ships 36 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
@@ -84,6 +84,8 @@ mental model, though the exact thresholds differ in the literature.
| `Stochastic` | `%K = (close low_n)/(high_n low_n) × 100`, smoothed into `%D`. | `Candle` | `(k, d)` | each in `[0, 100]` | `(k_period=14, d_period=3)` (Python) | `k_period + d_period 1` | [Indicator-Stochastic.md](indicators/momentum/Indicator-Stochastic.md) |
| `Mfi` | "Volume-weighted RSI": Wilder smoothing of money-flow ratios. | `Candle` | `f64` | `[0, 100]` | `period = 14` (Python) | `period` | [Indicator-Mfi.md](indicators/momentum/Indicator-Mfi.md) |
| `Aroon` | Bars-since-high and bars-since-low scaled to `[0, 100]`. | `Candle` | `(up, down)` | each in `[0, 100]` | `period = 14` (Python) | `period + 1` | [Indicator-Aroon.md](indicators/momentum/Indicator-Aroon.md) |
| `StochRsi` | Stochastic Oscillator applied to the RSI series; sharpens RSI extremes. | `f64` | `f64` | `[0, 100]` | `(rsi_period=14, stoch_period=14)` (Python) | `rsi_period + stoch_period` | [Indicator-StochRsi.md](indicators/momentum/Indicator-StochRsi.md) |
| `UltimateOscillator` | Larry Williams' weighted three-timeframe buying-pressure oscillator. | `Candle` | `f64` | `[0, 100]` | `(short=7, mid=14, long=28)` (Python) | `max(short,mid,long) + 1` | [Indicator-UltimateOscillator.md](indicators/momentum/Indicator-UltimateOscillator.md) |
### Unbounded oscillators
@@ -0,0 +1,165 @@
# StochRSI
> Stochastic RSI — the Stochastic Oscillator formula applied to the RSI
> series, sharpening RSI's overbought/oversold turns.
## Quick reference
| Field | Value |
|-------|-------|
| Family | Momentum |
| Sub-category | Bounded oscillators (0 … 100) |
| Input type | `f64` (single close) |
| Output type | `f64` |
| Output range | `[0, 100]` |
| Default parameters | `(rsi_period = 14, stoch_period = 14)` (Python) |
| Warmup period | `rsi_period + stoch_period` |
| Interpretation | Where RSI sits in its own recent range; near `0`/`100` = extremes. |
## Formula
```
RSI_t = Rsi(rsi_period) of price
StochRSI = 100 · (RSI_t min(RSI, stoch_period)) / (max(RSI, …) min(RSI, …))
```
RSI rarely visits its `0`/`100` extremes — it spends most of its life
bunched around the middle. StochRSI re-normalises it: it asks where the
*current* RSI sits within its own high/low range over the last
`stoch_period` bars. The result swings the full `[0, 100]` width far more
often than raw RSI, so reversals are easier to spot.
## Parameters
| Name | Type | Default | Valid range | Description |
|----------------|---------|---------------|-------------|-------------|
| `rsi_period` | `usize` | `14` (Python) | `>= 1` | Period of the underlying RSI. `0` errors with `Error::PeriodZero`. |
| `stoch_period` | `usize` | `14` (Python) | `>= 1` | Lookback for the high/low range of RSI. `0` errors with `Error::PeriodZero`. |
The Python binding defaults the pair to `(14, 14)` via
`#[pyo3(signature = (rsi_period=14, stoch_period=14))]`. Node and WASM
take both explicitly. The `periods` property returns
`(rsi_period, stoch_period)`.
## Inputs / Outputs
From `crates/wickra-core/src/indicators/stoch_rsi.rs`:
```rust
impl Indicator for StochRsi {
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
`StochRsi::new(rsi_period, stoch_period).warmup_period()
== rsi_period + stoch_period`. The inner RSI emits its first value on
input `rsi_period + 1`; the stochastic window then needs `stoch_period`
RSI values, so the first non-`None` output lands on input
`rsi_period + stoch_period`.
## Edge cases
- **Flat RSI window.** When every RSI value in the window is equal — for
example a constant price (RSI pinned at `50`) or a pure trend (RSI
pinned at `100`) — the range is zero and StochRSI reports the neutral
`50.0` (`flat_rsi_window_yields_50` and `pure_uptrend_yields_50` pin
this).
- **Bounds.** The output is always within `[0, 100]`
(`output_stays_within_0_100` pins this).
- **NaN / infinity inputs.** Non-finite inputs are silently dropped; the
RSI and the window are not advanced.
- **Reset.** `stoch_rsi.reset()` clears the inner RSI and the window.
## Examples
### Rust
```rust
use wickra::{BatchExt, Indicator, StochRsi};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut sr = StochRsi::new(14, 14)?;
let prices: Vec<f64> = (1..=60)
.map(|i| 100.0 + (f64::from(i) * 0.3).sin() * 10.0)
.collect();
let out = sr.batch(&prices);
println!("warmup_period = {}", sr.warmup_period());
println!("ready values: {}", out.iter().flatten().count());
Ok(())
}
```
Output:
```
warmup_period = 28
ready values: 33
```
The first 27 inputs return `None`; from input 28 onward every output is a
defined `[0, 100]` value.
### Python
```python
import numpy as np
import wickra as ta
sr = ta.StochRSI() # (rsi_period=14, stoch_period=14)
prices = np.full(40, 100.0) # constant series
print(sr.batch(prices)[-1]) # flat RSI window -> neutral 50
```
Output:
```
50.0
```
### Node
```javascript
const ta = require('wickra');
const sr = new ta.StochRSI(14, 14);
const prices = Array.from({ length: 60 }, (_, i) => 100 + Math.sin(i * 0.3) * 10);
console.log('warmupPeriod:', sr.warmupPeriod());
```
## Interpretation
`StochRsi` is read like any `[0, 100]` oscillator, but with tighter
thresholds because it saturates so readily: above `80` is overbought,
below `20` oversold, and the `50` line is the midpoint. Because it is two
oscillators deep, it is *fast and noisy* — excellent for spotting
short-term turns, poor as a standalone trend filter. Many traders smooth
it further (an SMA of StochRSI) and trade the crossover.
## Common pitfalls
- **Using it as a trend filter.** `StochRsi` whipsaws; confirm with a
slower indicator before acting on a raw threshold cross.
- **Forgetting the stacked warmup.** Warmup is `rsi_period + stoch_period`
— for the default `(14, 14)` that is 28 bars.
- **Expecting raw-RSI values.** `StochRsi` is a *position within range*,
not RSI itself; the two are not interchangeable.
## References
Tushar Chande and Stanley Kroll, *The New Technical Trader* (1994). The
implementation is the standard Stochastic-of-RSI; the flat-window
convention (`50`) matches this library's [`Stochastic`](Indicator-Stochastic.md).
## See also
- [Indicator-Rsi.md](Indicator-Rsi.md) — the underlying oscillator.
- [Indicator-Stochastic.md](Indicator-Stochastic.md) — the same formula on
price instead of RSI.
- [Indicators-Overview.md](../../Indicators-Overview.md) — the full taxonomy.
@@ -0,0 +1,179 @@
# UltimateOscillator
> Ultimate Oscillator — Larry Williams' momentum oscillator that blends
> three lookback periods into one bounded `[0, 100]` reading.
## Quick reference
| Field | Value |
|-------|-------|
| Family | Momentum |
| Sub-category | Bounded oscillators (0 … 100) |
| Input type | `Candle` (uses `high`, `low`, `close`) |
| Output type | `f64` |
| Output range | `[0, 100]` |
| Default parameters | `(short = 7, mid = 14, long = 28)` (Python) |
| Warmup period | `max(short, mid, long) + 1` |
| Interpretation | Weighted three-timeframe buying pressure; `50` is neutral. |
## Formula
```
true_low_t = min(low_t, close_{t1})
BP_t = close_t true_low_t (buying pressure)
TR_t = max(high_t, close_{t1}) true_low_t (true range)
avg_n = Σ BP over n / Σ TR over n
UO = 100 · (4·avg_short + 2·avg_mid + avg_long) / 7
```
A single-timeframe momentum oscillator can show false divergences when
its lookback does not match the swing being measured. The Ultimate
Oscillator averages buying pressure over *three* windows and weights the
fastest (`4×`) above the medium (`2×`) and slow (`1×`), which damps those
false signals while keeping the response quick.
## Parameters
| Name | Type | Default | Valid range | Description |
|---------|---------|---------------|-------------|-------------|
| `short` | `usize` | `7` (Python) | `>= 1` | Fast lookback (weight `4`). `0` errors with `Error::PeriodZero`. |
| `mid` | `usize` | `14` (Python) | `>= 1` | Medium lookback (weight `2`). |
| `long` | `usize` | `28` (Python) | `>= 1` | Slow lookback (weight `1`). |
The Python binding defaults the trio to `(7, 14, 28)` via
`#[pyo3(signature = (short=7, mid=14, long=28))]`. Node and WASM take all
three explicitly. The `periods` property returns `(short, mid, long)`.
`UltimateOscillator::classic()` is the conventional `(7, 14, 28)`.
## Inputs / Outputs
From `crates/wickra-core/src/indicators/ultimate_oscillator.rs`:
```rust
impl Indicator for UltimateOscillator {
type Input = Candle;
type Output = f64;
// update(&mut self, input: Candle) -> Option<f64>
}
```
`UltimateOscillator` 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
`warmup_period() == max(short, mid, long) + 1`. The first bar has no
previous close, so the first `BP`/`TR` pair forms on bar 2; the longest
window must then fill, so the first non-`None` output lands on input
`max(short, mid, long) + 1`.
## Edge cases
- **Pure uptrend.** Bars that each close higher have `BP == TR`, so every
ratio is `1` and UO saturates at `100`
(`pure_uptrend_saturates_at_100` pins this).
- **Pure downtrend.** Bars that each close lower have `BP == 0`, so UO is
`0` (`pure_downtrend_saturates_at_0` pins this).
- **Flat market.** Identical bars have zero true range; each window
contributes the neutral ratio `0.5`, so UO reads `50`
(`flat_market_reads_50` pins this).
- **Bounds.** The output is always within `[0, 100]`
(`output_stays_within_0_100` pins this).
- **Candle validation.** `Candle::new` rejects NaN/infinite fields, so
`update` never sees an invalid bar.
- **Reset.** `uo.reset()` clears the previous close, the rolling window
and all six running sums.
## Examples
### Rust
```rust
use wickra::{BatchExt, Candle, Indicator, UltimateOscillator};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut uo = UltimateOscillator::classic(); // (7, 14, 28)
// 30 flat candles, each closing one tick higher than the last.
let candles: Vec<Candle> = (0..40)
.map(|i| {
let p = 100.0 + f64::from(i);
Candle::new(p, p, p, p, 1.0, i64::from(i)).unwrap()
})
.collect();
let out = uo.batch(&candles);
println!("warmup_period = {}", uo.warmup_period());
println!("last = {:?}", out.last().unwrap());
Ok(())
}
```
Output:
```
warmup_period = 29
last = Some(100.0)
```
Every bar closes higher with `BP == TR`, so UO saturates at `100`. This
matches the `pure_uptrend_saturates_at_100` test in
`crates/wickra-core/src/indicators/ultimate_oscillator.rs`.
### Python
```python
import numpy as np
import wickra as ta
uo = ta.UltimateOscillator() # (7, 14, 28)
high = np.full(40, 100.0)
low = np.full(40, 100.0)
close = np.full(40, 100.0) # perfectly flat market
print(uo.batch(high, low, close)[-1])
```
Output:
```
50.0
```
### Node
```javascript
const ta = require('wickra');
const uo = new ta.UltimateOscillator(7, 14, 28);
const flat = Array.from({ length: 40 }, () => 100);
console.log(uo.batch(flat, flat, flat).at(-1)); // 50
```
## Interpretation
`UltimateOscillator` is read with the usual overbought/oversold lens —
above `70` is stretched, below `30` is washed out — but Larry Williams'
canonical signal is *divergence with confirmation*: price makes a new
extreme while UO does not, then UO breaks the level of the divergence.
The three-timeframe blend makes those divergences more reliable than a
single-period oscillator.
## Common pitfalls
- **Feeding it scalar prices.** It needs `high`/`low`/`close`; it takes a
`Candle`, not an `f64`.
- **Reordering the periods.** The `4 / 2 / 1` weights assume `short` is
the fastest window — keep `short < mid < long`. Any positive periods
are accepted, but mis-ordering them inverts the intended weighting.
## References
Larry Williams, "The Ultimate Oscillator", *Technical Analysis of Stocks
& Commodities* (1985). The buying-pressure / true-range definition and the
`4 / 2 / 1` weighting follow Williams' original.
## See also
- [Indicator-Stochastic.md](Indicator-Stochastic.md) — single-timeframe
bounded oscillator.
- [Indicator-Rsi.md](Indicator-Rsi.md) — the canonical momentum oscillator.
- [Indicators-Overview.md](../../Indicators-Overview.md) — the full taxonomy.