F7: add NATR, StdDev, Ulcer Index and Historical Volatility
Completes the F7 family (Volatility) end to end: - Rust core: natr.rs (ATR as a percentage of close), std_dev.rs (rolling population standard deviation), ulcer_index.rs (RMS of trailing-high drawdowns — downside-only risk), historical_volatility.rs (annualised sample stddev of log returns). Each with a full Indicator impl, runnable doctest and reference / constant-series / warmup / reset / batch==streaming tests. - Python: PyNatr / PyStdDev / PyUlcerIndex / PyHistoricalVolatility PyO3 classes + module registration + .pyi stubs. - Node: StdDevNode / UlcerIndexNode via the scalar macro, explicit NatrNode and HistoricalVolatilityNode; index.d.ts and index.js updated. - WASM: WasmStdDev / WasmUlcerIndex / WasmHistoricalVolatility via the scalar macro, explicit WasmNatr. - Wiki: Indicator-Natr/StdDev/UlcerIndex/HistoricalVolatility.md plus rows in Indicators-Overview.md and entries in Home.md. cargo fmt + clippy (core/wickra/data/wasm/node) clean; 350 core tests, 25 data tests and 49 doctests green.
This commit is contained in:
@@ -118,6 +118,10 @@ Rust / Python / Node examples. They are grouped by family, mirroring the
|
||||
- [Indicator-Keltner.md](indicators/volatility/Indicator-Keltner.md)
|
||||
- [Indicator-Donchian.md](indicators/volatility/Indicator-Donchian.md)
|
||||
- [Indicator-Psar.md](indicators/volatility/Indicator-Psar.md)
|
||||
- [Indicator-Natr.md](indicators/volatility/Indicator-Natr.md)
|
||||
- [Indicator-StdDev.md](indicators/volatility/Indicator-StdDev.md)
|
||||
- [Indicator-UlcerIndex.md](indicators/volatility/Indicator-UlcerIndex.md)
|
||||
- [Indicator-HistoricalVolatility.md](indicators/volatility/Indicator-HistoricalVolatility.md)
|
||||
|
||||
**Volume** — price moves weighted or confirmed by traded volume.
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Indicators Overview
|
||||
|
||||
Wickra ships 42 indicators, organised in source under the four classical
|
||||
Wickra ships 46 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
|
||||
@@ -136,6 +136,10 @@ measure — that lives in the volatility module by source convention.
|
||||
| Indicator | One-liner | Input | Output | Range | Defaults | Warmup | Deep dive |
|
||||
|-----------|-----------|-------|--------|-------|----------|--------|-----------|
|
||||
| `Atr` | Wilder-smoothed True Range; per-bar absolute volatility. | `Candle` | `f64` | `[0, ∞)` (price scale) | `period = 14` (Python) | `period` | [Indicator-Atr.md](indicators/volatility/Indicator-Atr.md) |
|
||||
| `Natr` | `100·ATR/close`; ATR as a percentage, comparable across instruments. | `Candle` | `f64` | `[0, ∞)` (percent) | `period = 14` (Python) | `period` | [Indicator-Natr.md](indicators/volatility/Indicator-Natr.md) |
|
||||
| `StdDev` | Rolling population standard deviation of price. | `f64` | `f64` | `[0, ∞)` (price scale) | `period = 20` (Python) | `period` | [Indicator-StdDev.md](indicators/volatility/Indicator-StdDev.md) |
|
||||
| `UlcerIndex` | RMS of trailing-high drawdowns; downside-only risk. | `f64` | `f64` | `[0, ∞)` (percent) | `period = 14` (Python) | `2·period − 1` | [Indicator-UlcerIndex.md](indicators/volatility/Indicator-UlcerIndex.md) |
|
||||
| `HistoricalVolatility` | Annualised sample stddev of log returns. | `f64` | `f64` | `[0, ∞)` (annualised percent) | `(period=20, trading_periods=252)` (Python) | `period + 1` | [Indicator-HistoricalVolatility.md](indicators/volatility/Indicator-HistoricalVolatility.md) |
|
||||
|
||||
### Trailing stop
|
||||
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
# 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 |
|
||||
| Sub-category | Return-based |
|
||||
| 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_{t−1})
|
||||
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](Indicator-StdDev.md) — population dispersion of
|
||||
raw prices.
|
||||
- [Indicator-Natr.md](Indicator-Natr.md) — range-based volatility as a
|
||||
percentage.
|
||||
- [Indicators-Overview.md](../../Indicators-Overview.md) — the full taxonomy.
|
||||
@@ -0,0 +1,144 @@
|
||||
# NATR
|
||||
|
||||
> Normalized Average True Range — ATR expressed as a percentage of price, so
|
||||
> volatility is comparable across instruments.
|
||||
|
||||
## Quick reference
|
||||
|
||||
| Field | Value |
|
||||
|-------|-------|
|
||||
| Family | Volatility |
|
||||
| Sub-category | Range-average |
|
||||
| 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`](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`](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](Indicator-Atr.md) — the price-unit original.
|
||||
- [Indicator-HistoricalVolatility.md](Indicator-HistoricalVolatility.md) —
|
||||
return-based annualised volatility.
|
||||
- [Indicators-Overview.md](../../Indicators-Overview.md) — the full taxonomy.
|
||||
@@ -0,0 +1,156 @@
|
||||
# StdDev
|
||||
|
||||
> Rolling population standard deviation — the dispersion of the last
|
||||
> `period` prices around their mean.
|
||||
|
||||
## Quick reference
|
||||
|
||||
| Field | Value |
|
||||
|-------|-------|
|
||||
| Family | Volatility |
|
||||
| Sub-category | Dispersion |
|
||||
| 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`](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`](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](Indicator-BollingerBands.md) — bands built
|
||||
from this dispersion measure.
|
||||
- [Indicator-HistoricalVolatility.md](Indicator-HistoricalVolatility.md) —
|
||||
annualised volatility of log returns.
|
||||
- [Indicators-Overview.md](../../Indicators-Overview.md) — the full taxonomy.
|
||||
@@ -0,0 +1,161 @@
|
||||
# UlcerIndex
|
||||
|
||||
> Ulcer Index — Peter Martin's downside-only risk measure: the
|
||||
> root-mean-square of recent drawdowns.
|
||||
|
||||
## Quick reference
|
||||
|
||||
| Field | Value |
|
||||
|-------|-------|
|
||||
| Family | Volatility |
|
||||
| Sub-category | Downside risk |
|
||||
| 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`](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](Indicator-StdDev.md) — two-sided dispersion.
|
||||
- [Indicator-Atr.md](Indicator-Atr.md) — per-bar range volatility.
|
||||
- [Indicators-Overview.md](../../Indicators-Overview.md) — the full taxonomy.
|
||||
Reference in New Issue
Block a user