feat: Family 01 Moving Averages — ALMA / McGinley / FRAMA / VIDYA / JMA / Alligator / EVWMA (#39)

* feat(alma): add Arnaud Legoux Moving Average

Gaussian-weighted moving average with configurable centre (offset in
[0, 1]) and kernel width (sigma > 0). Pre-computes normalised weights
at construction so each update is a single rolling window dot product.

Reference: Arnaud Legoux and Dimitrios Kouzis-Loukas, 2009.

Touchpoints:
- crates/wickra-core: alma.rs + mod.rs + lib.rs re-export
- bindings/python: PyAlma + __init__.py + test_new_indicators +
  test_known_values reference
- bindings/node: AlmaNode + index.d.ts/index.js + indicators.test.js
  factory + reference value
- bindings/wasm: wasm_scalar_indicator! macro
- fuzz: indicator_update target covers ALMA(9, 0.85, 6.0)
- crates/wickra/benches: bench_scalar entry
- README + CHANGELOG: Moving Averages row + Unreleased entry

* feat(mcginley): add McGinley Dynamic moving average

John McGinley's self-adjusting moving average with the recurrence
MD + (price - MD) / (0.6 * period * (price / MD)^4). Speeds up when
price falls below the indicator and damps when price runs above the
indicator. Seeded with the simple average of the first period inputs.

Reference: McGinley, Technical Analysis of Stocks & Commodities, 1990.

Touchpoints:
- crates/wickra-core: mcginley_dynamic.rs + mod.rs + lib.rs re-export
- bindings/python: PyMcGinleyDynamic + __init__.py + test_new_indicators
  + test_known_values reference
- bindings/node: McGinleyDynamicNode (scalar macro) + index.d.ts/index.js
  + indicators.test.js factory + reference value
- bindings/wasm: wasm_scalar_indicator! macro
- fuzz: indicator_update target covers McGinleyDynamic(10)
- crates/wickra/benches: bench_scalar entry
- README + CHANGELOG: Moving Averages row + Unreleased entry

* feat(frama): add Fractal Adaptive Moving Average

Ehlers' FRAMA adapts its smoothing constant to the fractal dimension of
the recent window: tight tracking in trends, heavy smoothing in chop.
Uses the close-only variant where max/min over each window half drive
the dimension estimate. Period must be even (default 16).

Reference: Ehlers, Fractal Adaptive Moving Average, 2005.

Touchpoints:
- crates/wickra-core: frama.rs + mod.rs + lib.rs re-export
- bindings/python: PyFrama + __init__.py + test_new_indicators +
  test_known_values reference (constant series + uptrend tracking)
- bindings/node: FramaNode (scalar macro) + index.d.ts/index.js +
  indicators.test.js factory + reference value
- bindings/wasm: wasm_scalar_indicator! macro
- fuzz: indicator_update target covers Frama(16)
- crates/wickra/benches: bench_scalar entry
- README + CHANGELOG: Moving Averages row + Unreleased entry

* feat(vidya): add Variable Index Dynamic Average

Chande's VIDYA — an EMA whose alpha scales with |CMO(cmo_period)| / 100.
Strong directional momentum lifts the smoothing constant toward the
EMA-of-period rate; flat or choppy windows shrink it toward zero so
VIDYA coasts on its previous value. Two parameters: period (14) and
cmo_period (9). Reuses the existing wickra-core Cmo internally.

Reference: Chande, Stocks & Commodities, 1992.

Also fixes a silent gap from d37fbd1 (feat(frama)): the PyFrama Python
class wrapper and its add_class registration were dropped because the
two edits hit "File has not been read yet" errors that scrolled past
in a batch. Adds them here alongside VIDYA's bindings.

Touchpoints (VIDYA): vidya.rs + mod.rs + lib.rs re-export, PyVidya +
__init__.py + test_new_indicators + test_known_values reference,
VidyaNode (manual two-param binding) + index.d.ts/index.js +
indicators.test.js factory + reference, wasm_scalar_indicator! macro,
fuzz target, bench, README + CHANGELOG.

* feat(jma): add Jurik Moving Average

Three-stage filter reconstruction of Mark Jurik's adaptive MA (the
algorithm is proprietary; this is the form used by most open-source
ports since the 1999 TASC article). Parameters: period (14), phase in
[-100, 100] (0), power in 1..=4 (2). State is seeded by setting
e0 = JMA = first input so a constant input stream is reproduced exactly.

Touchpoints: jma.rs + mod.rs + lib.rs re-export, PyJma + __init__.py +
test_new_indicators + test_known_values reference, JmaNode (manual
three-param binding) + index.d.ts/index.js + indicators.test.js factory
+ reference, wasm_scalar_indicator! macro, fuzz target, bench, README +
CHANGELOG.

* feat(alligator): add Bill Williams Alligator

Three SMMA lines (Jaw / Teeth / Lips) over the median price
(high + low) / 2 with default periods 13 / 8 / 5. Multi-output
indicator returning AlligatorOutput { jaw, teeth, lips }. The
original chart variant shifts each line forward for display; we
publish the unshifted SMMA values and leave the visual shift to
the consumer.

Reference: Bill Williams, Trading Chaos, 1995.

Touchpoints: alligator.rs + mod.rs + lib.rs re-export, PyAlligator
(Candle input, returns 3-tuple, ndarray (n, 3) batch) + __init__.py
+ test_new_indicators + test_known_values reference, AlligatorNode +
AlligatorValue + index.d.ts/index.js + indicators.test.js multi
factory + reference, WasmAlligator (manual JsValue object) +
candle-fuzz target + README + CHANGELOG.

* feat(evwma): add Elastic Volume-Weighted Moving Average

Christian P. Fries' elastic recurrence where the smoothing weight is the
bar's volume relative to the running window total:

  V_sum_t = sum of volumes over the last period candles
  EVWMA_t = ((V_sum_t - v_t) * EVWMA_{t-1} + v_t * close_t) / V_sum_t

A bar whose volume is small barely moves the average; a bar that
dominates the window pulls it strongly toward that bar's close. Seeded
with the close of the first full window; holds its previous value if
the entire window has zero volume.

Reference: Fries, Wilmott Magazine, 2001.

Touchpoints: evwma.rs + mod.rs + lib.rs re-export, PyEvwma (close +
volume batch) + __init__.py + test_new_indicators CANDLE_SCALAR +
test_known_values reference, EvwmaNode + index.d.ts/index.js +
indicators.test.js candleScalar factory + reference, WasmEvwma,
candle-fuzz target + README + CHANGELOG.

* ci: Force local wheel install in Python jobs

Use --no-index --no-deps so the Python matrix installs the freshly
built wheel from dist/ and never falls back to PyPI. Previously pip
sometimes picked the released 0.2.x wheel on macOS / Windows when its
platform tag was a wider match than the local build, which made the
job test the released package and miss any new symbols added in the
PR (e.g. AttributeError: module 'wickra' has no attribute 'ALMA').
numpy is already installed by the preceding pip step, so --no-deps
is safe.
This commit is contained in:
kingchenc
2026-05-25 15:01:14 +02:00
committed by GitHub
parent 178fbfd68e
commit 466faddd87
23 changed files with 2765 additions and 21 deletions
+6 -1
View File
@@ -229,7 +229,12 @@ jobs:
- name: Install wheel
shell: bash
working-directory: bindings/python
run: python -m pip install --find-links dist --force-reinstall wickra
# --no-index forces pip to ignore PyPI; --no-deps skips re-resolving
# numpy (already installed in the previous step). Without --no-index
# pip prefers the PyPI 0.2.x wheel over our freshly built one when
# platform tags overlap (e.g. macOS arm64), so tests would run
# against the released package and miss any new symbols the PR adds.
run: python -m pip install --no-index --find-links dist --force-reinstall --no-deps wickra
- name: Run Python tests
working-directory: bindings/python
+37
View File
@@ -7,6 +7,43 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
- **Family 01 — Moving Averages.** `ALMA` (Arnaud Legoux Moving Average):
Gaussian-weighted moving average with configurable centre (`offset` in
`[0, 1]`) and kernel width (`sigma > 0`). Community-standard defaults
`(period = 9, offset = 0.85, sigma = 6.0)` available via `Alma::classic()`.
Exposed in all four bindings (Rust, Python, Node, WASM).
- **Family 01 — Moving Averages.** `EVWMA` (Elastic Volume-Weighted
Moving Average, Fries 2001): an "elastic" recurrence whose smoothing
weight is the bar's volume relative to the running window-volume.
Candle input (uses close + volume), single parameter `period`
(default 20). Holds its previous value if the entire window has zero
volume. Exposed in all four bindings.
- **Family 01 — Moving Averages.** `Alligator` (Bill Williams): three
SMMA lines (Jaw / Teeth / Lips) of the median price `(high + low) / 2`
with default periods 13 / 8 / 5. Multi-output indicator emitting
`AlligatorOutput { jaw, teeth, lips }`. Visual chart shift is left to
the consumer. Exposed in all four bindings.
- **Family 01 — Moving Averages.** `JMA` (Jurik Moving Average):
three-stage filter reconstruction of Mark Jurik's adaptive MA.
Three parameters: `period` (14), `phase` in `[-100, 100]` (0), `power`
in `1..=4` (2). State is seeded to the first input so a constant series
is reproduced exactly. Exposed in all four bindings.
- **Family 01 — Moving Averages.** `VIDYA` (Variable Index Dynamic
Average, Chande 1992): EMA whose smoothing factor is scaled by the
absolute Chande Momentum Oscillator. Two parameters `period` and
`cmo_period` (defaults 14 / 9). Exposed in all four bindings.
- **Family 01 — Moving Averages.** `FRAMA` (Fractal Adaptive Moving
Average, Ehlers 2005): adapts its smoothing constant to the fractal
dimension of the recent window — fast in trends, slow in chop. Single
parameter `period` (must be even, default 16). Exposed in all four
bindings.
- **Family 01 — Moving Averages.** `McGinleyDynamic`: John McGinley's
self-adjusting MA. Single parameter `period`; the recurrence
`MD + (price - MD) / (0.6 * period * (price / MD)^4)` speeds up when price
falls below the indicator and damps when price runs above. Seeded with the
simple average of the first `period` inputs. Exposed in all four bindings.
## [0.2.7] - 2026-05-24
### Added
+2 -2
View File
@@ -109,13 +109,13 @@ python -m benchmarks.compare_libraries
## Indicators
71 streaming-first indicators across eight families. Every one passes the
78 streaming-first indicators across eight families. Every one passes the
`batch == streaming` equivalence test, reference-value tests, and reset
semantics tests.
| Family | Indicators |
|--------|-----------|
| Moving Averages | SMA, EMA, WMA, DEMA, TEMA, HMA, KAMA, SMMA, TRIMA, ZLEMA, T3, VWMA |
| Moving Averages | SMA, EMA, WMA, DEMA, TEMA, HMA, KAMA, SMMA, TRIMA, ZLEMA, T3, VWMA, ALMA, McGinley Dynamic, FRAMA, VIDYA, JMA, Alligator, EVWMA |
| Momentum Oscillators | RSI (Wilder), Stochastic, CCI, ROC, Williams %R, MFI, Awesome Oscillator, MOM, CMO, TSI, PMO, StochRSI, Ultimate Oscillator |
| Trend & Directional | MACD, ADX (+DI/-DI), Aroon, TRIX, Aroon Oscillator, Vortex, Mass Index, Choppiness Index, Vertical Horizontal Filter |
| Price Oscillators | PPO, DPO, Coppock, Accelerator Oscillator, Balance of Power |
@@ -37,6 +37,11 @@ const scalarFactories = {
ROC: () => new wickra.ROC(12),
TRIX: () => new wickra.TRIX(9),
KAMA: () => new wickra.KAMA(10, 2, 30),
ALMA: () => new wickra.ALMA(9, 0.85, 6.0),
McGinleyDynamic: () => new wickra.McGinleyDynamic(10),
FRAMA: () => new wickra.FRAMA(16),
VIDYA: () => new wickra.VIDYA(14, 9),
JMA: () => new wickra.JMA(14, 0, 2),
SMMA: () => new wickra.SMMA(14),
TRIMA: () => new wickra.TRIMA(20),
ZLEMA: () => new wickra.ZLEMA(14),
@@ -86,6 +91,7 @@ const candleScalar = {
AwesomeOscillator: { make: () => new wickra.AwesomeOscillator(5, 34), step: (ind, i) => ind.update(high[i], low[i]), batch: (ind) => ind.batch(high, low) },
OBV: { make: () => new wickra.OBV(), step: (ind, i) => ind.update(close[i], volume[i]), batch: (ind) => ind.batch(close, volume) },
VWMA: { make: () => new wickra.VWMA(20), step: (ind, i) => ind.update(close[i], volume[i]), batch: (ind) => ind.batch(close, volume) },
EVWMA: { make: () => new wickra.EVWMA(20), step: (ind, i) => ind.update(close[i], volume[i]), batch: (ind) => ind.batch(close, volume) },
UltimateOscillator: { make: () => new wickra.UltimateOscillator(7, 14, 28), step: (ind, i) => ind.update(high[i], low[i], close[i]), batch: (ind) => ind.batch(high, low, close) },
AroonOscillator: { make: () => new wickra.AroonOscillator(14), step: (ind, i) => ind.update(high[i], low[i]), batch: (ind) => ind.batch(high, low) },
NATR: { make: () => new wickra.NATR(14), step: (ind, i) => ind.update(high[i], low[i], close[i]), batch: (ind) => ind.batch(high, low, close) },
@@ -122,6 +128,7 @@ for (const [name, d] of Object.entries(candleScalar)) {
// --- Multi-output indicators: object update vs interleaved batch ---
const multi = {
Alligator: { make: () => new wickra.Alligator(13, 8, 5), fields: ['jaw', 'teeth', 'lips'], step: (ind, i) => ind.update(high[i], low[i]), batch: (ind) => ind.batch(high, low) },
MACD: { make: () => new wickra.MACD(12, 26, 9), fields: ['macd', 'signal', 'histogram'], step: (ind, i) => ind.update(close[i]), batch: (ind) => ind.batch(close) },
BollingerBands: { make: () => new wickra.BollingerBands(20, 2), fields: ['upper', 'middle', 'lower', 'stddev'], step: (ind, i) => ind.update(close[i]), batch: (ind) => ind.batch(close) },
Stochastic: { make: () => new wickra.Stochastic(14, 3), fields: ['k', 'd'], step: (ind, i) => ind.update(high[i], low[i], close[i]), batch: (ind) => ind.batch(high, low, close) },
@@ -258,3 +265,59 @@ test('LinRegAngle of a unit-slope series is 45 degrees', () => {
const out = new wickra.LinRegAngle(5).batch([1, 2, 3, 4, 5, 6]);
assert.ok(Math.abs(out[4] - 45) < 1e-9);
});
test('EVWMA(2) reference values on [10, 20, 30] with volumes [1, 3, 1]', () => {
const out = new wickra.EVWMA(2).batch([10, 20, 30], [1, 3, 1]);
assert.ok(Number.isNaN(out[0]));
assert.ok(Math.abs(out[1] - 20) < 1e-12);
assert.ok(Math.abs(out[2] - 22.5) < 1e-12);
});
test('Alligator on a flat median price seeds to that median', () => {
const n = 30;
const out = new wickra.Alligator(13, 8, 5).batch(Array(n).fill(11), Array(n).fill(9));
// All three SMMAs see median (11 + 9) / 2 = 10 every bar.
for (let i = 12; i < n; i++) {
assert.ok(Math.abs(out[i * 3] - 10) < 1e-12, `jaw at ${i}: ${out[i * 3]}`);
assert.ok(Math.abs(out[i * 3 + 1] - 10) < 1e-12);
assert.ok(Math.abs(out[i * 3 + 2] - 10) < 1e-12);
}
});
test('JMA on a flat series reproduces the constant', () => {
const out = new wickra.JMA(14, 0, 2).batch(Array(30).fill(42));
for (let i = 0; i < 30; i++) assert.ok(Math.abs(out[i] - 42) < 1e-12);
});
test('VIDYA on a flat series holds the seed', () => {
const out = new wickra.VIDYA(14, 4).batch(Array(20).fill(42));
for (let i = 0; i < 4; i++) assert.ok(Number.isNaN(out[i]));
for (let i = 4; i < 20; i++) assert.ok(Math.abs(out[i] - 42) < 1e-12);
});
test('FRAMA pure uptrend hugs the latest close', () => {
const out = new wickra.FRAMA(4).batch([1, 2, 3, 4, 5, 6, 7, 8]);
assert.ok(Math.abs(out[out.length - 1] - 8) < 0.05);
});
test('McGinleyDynamic(3) seeds with SMA and recurses on the next price', () => {
// Seed = SMA([10, 20, 30]) = 20. On 40: ratio = 2, divisor = 0.6*3*16 = 28.8.
const out = new wickra.McGinleyDynamic(3).batch([10, 20, 30, 40]);
assert.ok(Number.isNaN(out[0]) && Number.isNaN(out[1]));
assert.ok(Math.abs(out[2] - 20) < 1e-12);
const expected = 20 + 20 / (0.6 * 3 * 16);
assert.ok(Math.abs(out[3] - expected) < 1e-12);
});
test('ALMA(3, 0.85, 6) reference value on [10, 20, 30]', () => {
// m = 0.85 * 2 = 1.7; s = 3 / 6 = 0.5; 2*s^2 = 0.5.
const out = new wickra.ALMA(3, 0.85, 6).batch([10, 20, 30]);
assert.ok(Number.isNaN(out[0]) && Number.isNaN(out[1]));
const w = [0, 1, 2].map((i) => Math.exp(-Math.pow(i - 1.7, 2) / 0.5));
const s = w[0] + w[1] + w[2];
const expected = (10 * w[0] + 20 * w[1] + 30 * w[2]) / s;
assert.ok(Math.abs(out[2] - expected) < 1e-12);
// The heavy offset toward the newest sample lifts the average above the
// simple mean of 20.
assert.ok(out[2] > 20);
});
+8 -1
View File
@@ -310,7 +310,7 @@ if (!nativeBinding) {
throw new Error(`Failed to load native binding`)
}
const { version, SMA, EMA, WMA, RSI, DEMA, TEMA, HMA, ROC, TRIX, SMMA, TRIMA, ZLEMA, MOM, CMO, DPO, StdDev, UlcerIndex, VerticalHorizontalFilter, ZScore, MACD, BollingerBands, ATR, Stochastic, OBV, ADX, CCI, WilliamsR, MFI, PSAR, Keltner, Donchian, VWAP, RollingVWAP, AwesomeOscillator, Aroon, KAMA, T3, TSI, PMO, ADL, VolumePriceTrend, ChaikinMoneyFlow, ChaikinOscillator, ForceIndex, EaseOfMovement, SuperTrend, ChandelierExit, ChandeKrollStop, AtrTrailingStop, TypicalPrice, MedianPrice, WeightedClose, LinearRegression, LinRegSlope, AcceleratorOscillator, BalanceOfPower, ChoppinessIndex, TrueRange, ChaikinVolatility, LinRegAngle, BollingerBandwidth, PercentB, NATR, HistoricalVolatility, AroonOscillator, Vortex, MassIndex, StochRSI, UltimateOscillator, PPO, Coppock, VWMA } = nativeBinding
const { version, SMA, EMA, WMA, RSI, DEMA, TEMA, HMA, ROC, TRIX, SMMA, TRIMA, ZLEMA, MOM, CMO, DPO, StdDev, UlcerIndex, VerticalHorizontalFilter, ZScore, MACD, BollingerBands, ATR, Stochastic, OBV, ADX, CCI, WilliamsR, MFI, PSAR, Keltner, Donchian, VWAP, RollingVWAP, AwesomeOscillator, Aroon, KAMA, ALMA, McGinleyDynamic, FRAMA, VIDYA, JMA, Alligator, EVWMA, T3, TSI, PMO, ADL, VolumePriceTrend, ChaikinMoneyFlow, ChaikinOscillator, ForceIndex, EaseOfMovement, SuperTrend, ChandelierExit, ChandeKrollStop, AtrTrailingStop, TypicalPrice, MedianPrice, WeightedClose, LinearRegression, LinRegSlope, AcceleratorOscillator, BalanceOfPower, ChoppinessIndex, TrueRange, ChaikinVolatility, LinRegAngle, BollingerBandwidth, PercentB, NATR, HistoricalVolatility, AroonOscillator, Vortex, MassIndex, StochRSI, UltimateOscillator, PPO, Coppock, VWMA } = nativeBinding
module.exports.version = version
module.exports.SMA = SMA
@@ -349,6 +349,13 @@ module.exports.RollingVWAP = RollingVWAP
module.exports.AwesomeOscillator = AwesomeOscillator
module.exports.Aroon = Aroon
module.exports.KAMA = KAMA
module.exports.ALMA = ALMA
module.exports.McGinleyDynamic = McGinleyDynamic
module.exports.FRAMA = FRAMA
module.exports.VIDYA = VIDYA
module.exports.JMA = JMA
module.exports.Alligator = Alligator
module.exports.EVWMA = EVWMA
module.exports.T3 = T3
module.exports.TSI = TSI
module.exports.PMO = PMO
+225
View File
@@ -116,6 +116,8 @@ node_scalar_indicator!(
wc::VerticalHorizontalFilter
);
node_scalar_indicator!(ZScoreNode, "ZScore", wc::ZScore);
node_scalar_indicator!(McGinleyDynamicNode, "McGinleyDynamic", wc::McGinleyDynamic);
node_scalar_indicator!(FramaNode, "FRAMA", wc::Frama);
// ============================== MACD ==============================
@@ -1103,6 +1105,229 @@ impl KamaNode {
}
}
// ============================== EVWMA ==============================
#[napi(js_name = "EVWMA")]
pub struct EvwmaNode {
inner: wc::Evwma,
}
#[napi]
impl EvwmaNode {
#[napi(constructor)]
pub fn new(period: u32) -> napi::Result<Self> {
Ok(Self {
inner: wc::Evwma::new(clamp_period(period)).map_err(map_err)?,
})
}
#[napi]
pub fn update(&mut self, close: f64, volume: f64) -> napi::Result<Option<f64>> {
Ok(self.inner.update(cnd(close, close, close, volume)?))
}
#[napi]
pub fn batch(&mut self, close: Vec<f64>, volume: Vec<f64>) -> napi::Result<Vec<f64>> {
if close.len() != volume.len() {
return Err(NapiError::from_reason(
"close and volume must be equal length".to_string(),
));
}
let mut out = Vec::with_capacity(close.len());
for i in 0..close.len() {
out.push(
self.inner
.update(cnd(close[i], close[i], close[i], volume[i])?)
.unwrap_or(f64::NAN),
);
}
Ok(out)
}
#[napi]
pub fn reset(&mut self) {
self.inner.reset();
}
#[napi(js_name = "isReady")]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[napi(js_name = "warmupPeriod")]
pub fn warmup_period(&self) -> u32 {
self.inner.warmup_period() as u32
}
}
// ============================== Alligator ==============================
#[napi(object)]
pub struct AlligatorValue {
pub jaw: f64,
pub teeth: f64,
pub lips: f64,
}
#[napi(js_name = "Alligator")]
pub struct AlligatorNode {
inner: wc::Alligator,
}
#[napi]
impl AlligatorNode {
#[napi(constructor)]
pub fn new(jaw: u32, teeth: u32, lips: u32) -> napi::Result<Self> {
Ok(Self {
inner: wc::Alligator::new(clamp_period(jaw), clamp_period(teeth), clamp_period(lips))
.map_err(map_err)?,
})
}
#[napi]
pub fn reset(&mut self) {
self.inner.reset();
}
#[napi(js_name = "isReady")]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[napi(js_name = "warmupPeriod")]
pub fn warmup_period(&self) -> u32 {
self.inner.warmup_period() as u32
}
#[napi]
pub fn update(&mut self, high: f64, low: f64) -> napi::Result<Option<AlligatorValue>> {
Ok(self
.inner
.update(cnd(high, low, low, 0.0)?)
.map(|o| AlligatorValue {
jaw: o.jaw,
teeth: o.teeth,
lips: o.lips,
}))
}
#[napi]
pub fn batch(&mut self, high: Vec<f64>, low: Vec<f64>) -> napi::Result<Vec<f64>> {
if high.len() != low.len() {
return Err(NapiError::from_reason(
"high and low must be equal length".to_string(),
));
}
let n = high.len();
let mut out = vec![f64::NAN; n * 3];
for i in 0..n {
if let Some(o) = self.inner.update(cnd(high[i], low[i], low[i], 0.0)?) {
out[i * 3] = o.jaw;
out[i * 3 + 1] = o.teeth;
out[i * 3 + 2] = o.lips;
}
}
Ok(out)
}
}
// ============================== JMA ==============================
#[napi(js_name = "JMA")]
pub struct JmaNode {
inner: wc::Jma,
}
#[napi]
impl JmaNode {
#[napi(constructor)]
pub fn new(period: u32, phase: f64, power: u32) -> napi::Result<Self> {
Ok(Self {
inner: wc::Jma::new(clamp_period(period), phase, power).map_err(map_err)?,
})
}
#[napi]
pub fn reset(&mut self) {
self.inner.reset();
}
#[napi(js_name = "isReady")]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[napi(js_name = "warmupPeriod")]
pub fn warmup_period(&self) -> u32 {
self.inner.warmup_period() as u32
}
#[napi]
pub fn update(&mut self, value: f64) -> Option<f64> {
self.inner.update(value)
}
#[napi]
pub fn batch(&mut self, prices: Vec<f64>) -> Vec<f64> {
flatten(self.inner.batch(&prices))
}
}
// ============================== VIDYA ==============================
#[napi(js_name = "VIDYA")]
pub struct VidyaNode {
inner: wc::Vidya,
}
#[napi]
impl VidyaNode {
#[napi(constructor)]
pub fn new(period: u32, cmo_period: u32) -> napi::Result<Self> {
Ok(Self {
inner: wc::Vidya::new(clamp_period(period), clamp_period(cmo_period))
.map_err(map_err)?,
})
}
#[napi]
pub fn reset(&mut self) {
self.inner.reset();
}
#[napi(js_name = "isReady")]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[napi(js_name = "warmupPeriod")]
pub fn warmup_period(&self) -> u32 {
self.inner.warmup_period() as u32
}
#[napi]
pub fn update(&mut self, value: f64) -> Option<f64> {
self.inner.update(value)
}
#[napi]
pub fn batch(&mut self, prices: Vec<f64>) -> Vec<f64> {
flatten(self.inner.batch(&prices))
}
}
// ============================== ALMA ==============================
#[napi(js_name = "ALMA")]
pub struct AlmaNode {
inner: wc::Alma,
}
#[napi]
impl AlmaNode {
#[napi(constructor)]
pub fn new(period: u32, offset: f64, sigma: f64) -> napi::Result<Self> {
Ok(Self {
inner: wc::Alma::new(clamp_period(period), offset, sigma).map_err(map_err)?,
})
}
#[napi]
pub fn reset(&mut self) {
self.inner.reset();
}
#[napi(js_name = "isReady")]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[napi(js_name = "warmupPeriod")]
pub fn warmup_period(&self) -> u32 {
self.inner.warmup_period() as u32
}
#[napi]
pub fn update(&mut self, value: f64) -> Option<f64> {
self.inner.update(value)
}
#[napi]
pub fn batch(&mut self, prices: Vec<f64>) -> Vec<f64> {
flatten(self.inner.batch(&prices))
}
}
// ============================== T3 ==============================
#[napi(js_name = "T3")]
+14
View File
@@ -38,6 +38,13 @@ from ._wickra import (
ZLEMA,
T3,
VWMA,
ALMA,
McGinleyDynamic,
FRAMA,
VIDYA,
JMA,
Alligator,
EVWMA,
# Momentum
RSI,
MACD,
@@ -119,6 +126,13 @@ __all__ = [
"ZLEMA",
"T3",
"VWMA",
"ALMA",
"McGinleyDynamic",
"FRAMA",
"VIDYA",
"JMA",
"Alligator",
"EVWMA",
# Momentum
"RSI",
"MACD",
+386
View File
@@ -812,6 +812,385 @@ impl PyKama {
}
}
// ============================== FRAMA ==============================
#[pyclass(name = "FRAMA", module = "wickra._wickra", skip_from_py_object)]
#[derive(Clone)]
struct PyFrama {
inner: wc::Frama,
}
#[pymethods]
impl PyFrama {
#[new]
#[pyo3(signature = (period=16))]
fn new(period: usize) -> PyResult<Self> {
Ok(Self {
inner: wc::Frama::new(period).map_err(map_err)?,
})
}
fn update(&mut self, value: f64) -> Option<f64> {
self.inner.update(value)
}
fn batch<'py>(
&mut self,
py: Python<'py>,
prices: PyReadonlyArray1<'py, f64>,
) -> PyResult<Bound<'py, PyArray1<f64>>> {
let s = prices
.as_slice()
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
Ok(flatten(self.inner.batch(s)).into_pyarray(py))
}
#[getter]
fn period(&self) -> usize {
self.inner.period()
}
fn reset(&mut self) {
self.inner.reset();
}
fn is_ready(&self) -> bool {
self.inner.is_ready()
}
fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
fn __repr__(&self) -> String {
format!("FRAMA(period={})", self.inner.period())
}
}
// ============================== EVWMA ==============================
#[pyclass(name = "EVWMA", module = "wickra._wickra", skip_from_py_object)]
#[derive(Clone)]
struct PyEvwma {
inner: wc::Evwma,
}
#[pymethods]
impl PyEvwma {
#[new]
#[pyo3(signature = (period=20))]
fn new(period: usize) -> PyResult<Self> {
Ok(Self {
inner: wc::Evwma::new(period).map_err(map_err)?,
})
}
fn update(&mut self, candle: &Bound<'_, PyAny>) -> PyResult<Option<f64>> {
let c = extract_candle(candle)?;
Ok(self.inner.update(c))
}
fn batch<'py>(
&mut self,
py: Python<'py>,
close: PyReadonlyArray1<'py, f64>,
volume: PyReadonlyArray1<'py, f64>,
) -> PyResult<Bound<'py, PyArray1<f64>>> {
let c = close
.as_slice()
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
let v = volume
.as_slice()
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
if c.len() != v.len() {
return Err(PyValueError::new_err(
"close and volume must be equal length",
));
}
let mut out = Vec::with_capacity(c.len());
for i in 0..c.len() {
let candle = wc::Candle::new(c[i], c[i], c[i], c[i], v[i], 0).map_err(map_err)?;
out.push(self.inner.update(candle).unwrap_or(f64::NAN));
}
Ok(out.into_pyarray(py))
}
#[getter]
fn period(&self) -> usize {
self.inner.period()
}
fn reset(&mut self) {
self.inner.reset();
}
fn is_ready(&self) -> bool {
self.inner.is_ready()
}
fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
fn __repr__(&self) -> String {
format!("EVWMA(period={})", self.inner.period())
}
}
// ============================== Alligator ==============================
#[pyclass(name = "Alligator", module = "wickra._wickra", skip_from_py_object)]
#[derive(Clone)]
struct PyAlligator {
inner: wc::Alligator,
}
#[pymethods]
impl PyAlligator {
#[new]
#[pyo3(signature = (jaw=13, teeth=8, lips=5))]
fn new(jaw: usize, teeth: usize, lips: usize) -> PyResult<Self> {
Ok(Self {
inner: wc::Alligator::new(jaw, teeth, lips).map_err(map_err)?,
})
}
fn update(&mut self, candle: &Bound<'_, PyAny>) -> PyResult<Option<(f64, f64, f64)>> {
let c = extract_candle(candle)?;
Ok(self.inner.update(c).map(|o| (o.jaw, o.teeth, o.lips)))
}
fn batch<'py>(
&mut self,
py: Python<'py>,
high: PyReadonlyArray1<'py, f64>,
low: PyReadonlyArray1<'py, f64>,
) -> PyResult<Bound<'py, PyArray2<f64>>> {
let h = high
.as_slice()
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
let l = low
.as_slice()
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
if h.len() != l.len() {
return Err(PyValueError::new_err("high and low must be equal length"));
}
let n = h.len();
let mut out = vec![f64::NAN; n * 3];
for i in 0..n {
let candle = wc::Candle::new(l[i], h[i], l[i], l[i], 0.0, 0).map_err(map_err)?;
if let Some(o) = self.inner.update(candle) {
out[i * 3] = o.jaw;
out[i * 3 + 1] = o.teeth;
out[i * 3 + 2] = o.lips;
}
}
Ok(numpy::ndarray::Array2::from_shape_vec((n, 3), out)
.expect("shape consistent")
.into_pyarray(py))
}
fn reset(&mut self) {
self.inner.reset();
}
fn is_ready(&self) -> bool {
self.inner.is_ready()
}
fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
fn __repr__(&self) -> String {
let (j, t, l) = self.inner.periods();
format!("Alligator(jaw={j}, teeth={t}, lips={l})")
}
}
// ============================== JMA ==============================
#[pyclass(name = "JMA", module = "wickra._wickra", skip_from_py_object)]
#[derive(Clone)]
struct PyJma {
inner: wc::Jma,
}
#[pymethods]
impl PyJma {
#[new]
#[pyo3(signature = (period=14, phase=0.0, power=2))]
fn new(period: usize, phase: f64, power: u32) -> PyResult<Self> {
Ok(Self {
inner: wc::Jma::new(period, phase, power).map_err(map_err)?,
})
}
fn update(&mut self, value: f64) -> Option<f64> {
self.inner.update(value)
}
fn batch<'py>(
&mut self,
py: Python<'py>,
prices: PyReadonlyArray1<'py, f64>,
) -> PyResult<Bound<'py, PyArray1<f64>>> {
let s = prices
.as_slice()
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
Ok(flatten(self.inner.batch(s)).into_pyarray(py))
}
fn reset(&mut self) {
self.inner.reset();
}
fn is_ready(&self) -> bool {
self.inner.is_ready()
}
fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
fn __repr__(&self) -> String {
let (p, ph, pw) = self.inner.params();
format!("JMA(period={p}, phase={ph}, power={pw})")
}
}
// ============================== VIDYA ==============================
#[pyclass(name = "VIDYA", module = "wickra._wickra", skip_from_py_object)]
#[derive(Clone)]
struct PyVidya {
inner: wc::Vidya,
}
#[pymethods]
impl PyVidya {
#[new]
#[pyo3(signature = (period=14, cmo_period=9))]
fn new(period: usize, cmo_period: usize) -> PyResult<Self> {
Ok(Self {
inner: wc::Vidya::new(period, cmo_period).map_err(map_err)?,
})
}
fn update(&mut self, value: f64) -> Option<f64> {
self.inner.update(value)
}
fn batch<'py>(
&mut self,
py: Python<'py>,
prices: PyReadonlyArray1<'py, f64>,
) -> PyResult<Bound<'py, PyArray1<f64>>> {
let s = prices
.as_slice()
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
Ok(flatten(self.inner.batch(s)).into_pyarray(py))
}
fn reset(&mut self) {
self.inner.reset();
}
fn is_ready(&self) -> bool {
self.inner.is_ready()
}
fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
fn __repr__(&self) -> String {
let (p, c) = self.inner.periods();
format!("VIDYA(period={p}, cmo_period={c})")
}
}
// ============================== McGinley Dynamic ==============================
#[pyclass(
name = "McGinleyDynamic",
module = "wickra._wickra",
skip_from_py_object
)]
#[derive(Clone)]
struct PyMcGinleyDynamic {
inner: wc::McGinleyDynamic,
}
#[pymethods]
impl PyMcGinleyDynamic {
#[new]
#[pyo3(signature = (period=10))]
fn new(period: usize) -> PyResult<Self> {
Ok(Self {
inner: wc::McGinleyDynamic::new(period).map_err(map_err)?,
})
}
fn update(&mut self, value: f64) -> Option<f64> {
self.inner.update(value)
}
fn batch<'py>(
&mut self,
py: Python<'py>,
prices: PyReadonlyArray1<'py, f64>,
) -> PyResult<Bound<'py, PyArray1<f64>>> {
let s = prices
.as_slice()
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
Ok(flatten(self.inner.batch(s)).into_pyarray(py))
}
#[getter]
fn period(&self) -> usize {
self.inner.period()
}
fn reset(&mut self) {
self.inner.reset();
}
fn is_ready(&self) -> bool {
self.inner.is_ready()
}
fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
fn __repr__(&self) -> String {
format!("McGinleyDynamic(period={})", self.inner.period())
}
}
// ============================== ALMA ==============================
#[pyclass(name = "ALMA", module = "wickra._wickra", skip_from_py_object)]
#[derive(Clone)]
struct PyAlma {
inner: wc::Alma,
}
#[pymethods]
impl PyAlma {
#[new]
#[pyo3(signature = (period=9, offset=0.85, sigma=6.0))]
fn new(period: usize, offset: f64, sigma: f64) -> PyResult<Self> {
Ok(Self {
inner: wc::Alma::new(period, offset, sigma).map_err(map_err)?,
})
}
fn update(&mut self, value: f64) -> Option<f64> {
self.inner.update(value)
}
fn batch<'py>(
&mut self,
py: Python<'py>,
prices: PyReadonlyArray1<'py, f64>,
) -> PyResult<Bound<'py, PyArray1<f64>>> {
let s = prices
.as_slice()
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
Ok(flatten(self.inner.batch(s)).into_pyarray(py))
}
#[getter]
fn period(&self) -> usize {
self.inner.period()
}
#[getter]
fn offset(&self) -> f64 {
self.inner.offset()
}
#[getter]
fn sigma(&self) -> f64 {
self.inner.sigma()
}
fn reset(&mut self) {
self.inner.reset();
}
fn is_ready(&self) -> bool {
self.inner.is_ready()
}
fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
fn __repr__(&self) -> String {
format!(
"ALMA(period={}, offset={}, sigma={})",
self.inner.period(),
self.inner.offset(),
self.inner.sigma()
)
}
}
// ============================== CCI ==============================
#[pyclass(name = "CCI", module = "wickra._wickra", skip_from_py_object)]
@@ -4494,6 +4873,13 @@ fn _wickra(_py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<PyTema>()?;
m.add_class::<PyHma>()?;
m.add_class::<PyKama>()?;
m.add_class::<PyAlma>()?;
m.add_class::<PyMcGinleyDynamic>()?;
m.add_class::<PyFrama>()?;
m.add_class::<PyVidya>()?;
m.add_class::<PyJma>()?;
m.add_class::<PyAlligator>()?;
m.add_class::<PyEvwma>()?;
m.add_class::<PyCci>()?;
m.add_class::<PyRoc>()?;
m.add_class::<PyWilliamsR>()?;
@@ -66,6 +66,97 @@ def test_rsi_wilder_textbook_first_value():
assert math.isclose(out[14], 70.464, abs_tol=0.05)
def test_alma_constant_series_yields_the_constant():
# ALMA's Gaussian weights are normalised, so any constant series is
# reproduced exactly after warmup.
out = ta.ALMA(9, 0.85, 6.0).batch(np.full(30, 42.0, dtype=np.float64))
assert np.all(np.isnan(out[:8]))
np.testing.assert_allclose(out[8:], 42.0, atol=1e-12)
def test_alma_reference_value_period_3():
# ALMA(period=3, offset=0.85, sigma=6) on [10, 20, 30].
# m = 0.85 * 2 = 1.7; s = 3 / 6 = 0.5; 2*s^2 = 0.5.
out = ta.ALMA(3, 0.85, 6.0).batch(np.array([10.0, 20.0, 30.0]))
assert math.isnan(out[0]) and math.isnan(out[1])
# Independently compute the expected Gaussian-weighted sum.
w = np.exp(-((np.arange(3, dtype=np.float64) - 1.7) ** 2) / 0.5)
expected = float(np.dot([10.0, 20.0, 30.0], w) / w.sum())
assert math.isclose(out[2], expected, abs_tol=1e-12)
# Sanity: heavy offset toward the newest sample lifts the average above
# the simple mean of 20.
assert out[2] > 20.0
def test_mcginley_dynamic_constant_series_yields_the_constant():
# ratio = 1, so the recurrence collapses to MD + 0 / divisor = MD.
out = ta.McGinleyDynamic(5).batch(np.full(30, 42.0, dtype=np.float64))
assert np.all(np.isnan(out[:4]))
np.testing.assert_allclose(out[4:], 42.0, atol=1e-12)
def test_mcginley_dynamic_reference_value():
# Period 3, seed = SMA([10, 20, 30]) = 20.0. Next price 40.0:
# ratio = 2; divisor = 0.6 * 3 * 16 = 28.8; next = 20 + 20/28.8.
out = ta.McGinleyDynamic(3).batch(np.array([10.0, 20.0, 30.0, 40.0]))
assert math.isnan(out[0]) and math.isnan(out[1])
assert math.isclose(out[2], 20.0, abs_tol=1e-12)
expected = 20.0 + 20.0 / (0.6 * 3.0 * 16.0)
assert math.isclose(out[3], expected, abs_tol=1e-12)
def test_frama_constant_series_yields_the_constant():
# Flat input -> degenerate ranges -> alpha clamps to 0.01 and the EMA
# recurrence holds the seed value.
out = ta.FRAMA(4).batch(np.full(20, 42.0, dtype=np.float64))
assert np.all(np.isnan(out[:3]))
np.testing.assert_allclose(out[3:], 42.0, atol=1e-12)
def test_frama_pure_uptrend_hugs_latest():
# Monotonic uptrend -> alpha pushed toward 1.0, FRAMA tracks close.
out = ta.FRAMA(4).batch(np.arange(1.0, 9.0, dtype=np.float64))
assert math.isclose(out[-1], 8.0, abs_tol=0.05)
def test_jma_constant_series_yields_the_constant():
# JMA seeds e0 and the output to the first input, so a constant series
# is reproduced exactly from the first sample.
out = ta.JMA(14, 0.0, 2).batch(np.full(30, 42.0, dtype=np.float64))
np.testing.assert_allclose(out, 42.0, atol=1e-12)
def test_evwma_reference_value_period_2():
# EVWMA(2). Bars: (close, volume) = (10, 1), (20, 3), (30, 1).
# Bar 2: sum_v = 4, seeded prev = 20, EVWMA = (1*20 + 3*20)/4 = 20.
# Bar 3: sum_v = 4 (drops 1, gains 1), EVWMA = (3*20 + 1*30)/4 = 22.5.
out = ta.EVWMA(2).batch(np.array([10.0, 20.0, 30.0]), np.array([1.0, 3.0, 1.0]))
assert math.isnan(out[0])
assert math.isclose(out[1], 20.0, abs_tol=1e-12)
assert math.isclose(out[2], 22.5, abs_tol=1e-12)
def test_alligator_constant_series_holds_at_median_price():
# Median price = (11 + 9) / 2 = 10 on every candle, so all three SMMAs
# seed at 10 and stay there.
n = 30
high = np.full(n, 11.0)
low = np.full(n, 9.0)
out = ta.Alligator(13, 8, 5).batch(high, low)
assert out.shape == (n, 3)
for row in out[12:]:
assert math.isclose(row[0], 10.0, abs_tol=1e-12)
assert math.isclose(row[1], 10.0, abs_tol=1e-12)
assert math.isclose(row[2], 10.0, abs_tol=1e-12)
def test_vidya_constant_series_holds_seed():
# CMO = 0 on a flat series -> alpha = 0 -> VIDYA holds its seed value.
out = ta.VIDYA(14, 4).batch(np.full(20, 42.0, dtype=np.float64))
assert np.all(np.isnan(out[:4]))
np.testing.assert_allclose(out[4:], 42.0, atol=1e-12)
def test_macd_constant_series_converges_to_zero():
out = ta.MACD().batch(np.full(200, 100.0))
# Last row's MACD and signal must be ~0.
@@ -44,6 +44,11 @@ SCALAR = [
(ta.SMMA, (14,)),
(ta.TRIMA, (20,)),
(ta.ZLEMA, (14,)),
(ta.ALMA, (9, 0.85, 6.0)),
(ta.McGinleyDynamic, (10,)),
(ta.FRAMA, (16,)),
(ta.VIDYA, (14, 9)),
(ta.JMA, (14, 0.0, 2)),
(ta.T3, (5, 0.7)),
(ta.MOM, (10,)),
(ta.CMO, (14,)),
@@ -87,6 +92,7 @@ def test_scalar_streaming_matches_batch(cls, args, sine_prices):
CANDLE_SCALAR = {
"VWMA": (lambda: ta.VWMA(20), lambda ind, h, l, c, v: ind.batch(c, v)),
"EVWMA": (lambda: ta.EVWMA(20), lambda ind, h, l, c, v: ind.batch(c, v)),
"UltimateOscillator": (
lambda: ta.UltimateOscillator(7, 14, 28),
lambda ind, h, l, c, v: ind.batch(h, l, c),
@@ -226,6 +232,24 @@ def test_multi_streaming_matches_batch(name, ohlcv):
assert _eq_nan(batch, np.array(rows, dtype=np.float64)), f"{name} mismatch"
# --- Alligator (3-tuple output) -------------------------------------------
def test_alligator_streaming_matches_batch(ohlcv):
high, low, _, _ = ohlcv
alligator = ta.Alligator(13, 8, 5)
batch = alligator.batch(high, low)
assert batch.shape == (high.size, 3)
streamer = ta.Alligator(13, 8, 5)
rows = []
for i in range(high.size):
candle = (float(low[i]), float(high[i]), float(low[i]), float(low[i]), 0.0, i)
v = streamer.update(candle)
rows.append([math.nan, math.nan, math.nan] if v is None else list(v))
assert _eq_nan(batch, np.array(rows, dtype=np.float64)), "Alligator mismatch"
# --- Reference values -----------------------------------------------------
@@ -296,6 +320,7 @@ def test_new_indicators_expose_lifecycle():
instances = [make() for make, _ in CANDLE_SCALAR.values()]
instances += [make() for make, _ in MULTI.values()]
instances += [cls(*args) for cls, args in SCALAR]
instances.append(ta.Alligator(13, 8, 5))
for ind in instances:
assert ind.is_ready() is False
assert ind.warmup_period() >= 1
+103
View File
@@ -79,6 +79,11 @@ wasm_scalar_indicator!(WasmSmma, "SMMA", wc::Smma, period: usize);
wasm_scalar_indicator!(WasmTrima, "TRIMA", wc::Trima, period: usize);
wasm_scalar_indicator!(WasmZlema, "ZLEMA", wc::Zlema, period: usize);
wasm_scalar_indicator!(WasmT3, "T3", wc::T3, period: usize, v: f64);
wasm_scalar_indicator!(WasmAlma, "ALMA", wc::Alma, period: usize, offset: f64, sigma: f64);
wasm_scalar_indicator!(WasmMcGinleyDynamic, "McGinleyDynamic", wc::McGinleyDynamic, period: usize);
wasm_scalar_indicator!(WasmFrama, "FRAMA", wc::Frama, period: usize);
wasm_scalar_indicator!(WasmVidya, "VIDYA", wc::Vidya, period: usize, cmo_period: usize);
wasm_scalar_indicator!(WasmJma, "JMA", wc::Jma, period: usize, phase: f64, power: u32);
wasm_scalar_indicator!(WasmMom, "MOM", wc::Mom, period: usize);
wasm_scalar_indicator!(WasmCmo, "CMO", wc::Cmo, period: usize);
wasm_scalar_indicator!(WasmTsi, "TSI", wc::Tsi, long: usize, short: usize);
@@ -1372,6 +1377,47 @@ impl WasmMassIndex {
}
}
#[wasm_bindgen(js_name = EVWMA)]
pub struct WasmEvwma {
inner: wc::Evwma,
}
#[wasm_bindgen(js_class = EVWMA)]
impl WasmEvwma {
#[wasm_bindgen(constructor)]
pub fn new(period: usize) -> Result<WasmEvwma, JsError> {
Ok(Self {
inner: wc::Evwma::new(period).map_err(map_err)?,
})
}
pub fn update(&mut self, close: f64, volume: f64) -> Result<Option<f64>, JsError> {
let c = make_candle(close, close, close, volume)?;
Ok(self.inner.update(c))
}
pub fn batch(&mut self, close: &[f64], volume: &[f64]) -> Result<Float64Array, JsError> {
if close.len() != volume.len() {
return Err(JsError::new("close and volume must be equal length"));
}
let mut out = Vec::with_capacity(close.len());
for i in 0..close.len() {
let c = make_candle(close[i], close[i], close[i], volume[i])?;
out.push(self.inner.update(c).unwrap_or(f64::NAN));
}
Ok(Float64Array::from(out.as_slice()))
}
pub fn reset(&mut self) {
self.inner.reset();
}
#[wasm_bindgen(js_name = isReady)]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[wasm_bindgen(js_name = warmupPeriod)]
pub fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
}
#[wasm_bindgen(js_name = VWMA)]
pub struct WasmVwma {
inner: wc::Vwma,
@@ -1942,6 +1988,63 @@ impl WasmAo {
}
}
#[wasm_bindgen(js_name = Alligator)]
pub struct WasmAlligator {
inner: wc::Alligator,
}
#[wasm_bindgen(js_class = Alligator)]
impl WasmAlligator {
#[wasm_bindgen(constructor)]
pub fn new(jaw: usize, teeth: usize, lips: usize) -> Result<WasmAlligator, JsError> {
Ok(Self {
inner: wc::Alligator::new(jaw, teeth, lips).map_err(map_err)?,
})
}
/// Returns `[jaw0, teeth0, lips0, jaw1, teeth1, lips1, ...]`, length `3n`.
pub fn batch(&mut self, high: &[f64], low: &[f64]) -> Result<Float64Array, JsError> {
if high.len() != low.len() {
return Err(JsError::new("high and low must be equal length"));
}
let n = high.len();
let mut out = vec![f64::NAN; n * 3];
for i in 0..n {
let c = make_candle(high[i], low[i], low[i], 0.0)?;
if let Some(o) = self.inner.update(c) {
out[i * 3] = o.jaw;
out[i * 3 + 1] = o.teeth;
out[i * 3 + 2] = o.lips;
}
}
Ok(Float64Array::from(out.as_slice()))
}
/// Streaming update. Returns `{ jaw, teeth, lips }` once warm, else `null`.
pub fn update(&mut self, high: f64, low: f64) -> Result<JsValue, JsError> {
let c = make_candle(high, low, low, 0.0)?;
Ok(match self.inner.update(c) {
Some(o) => {
let obj = Object::new();
Reflect::set(&obj, &"jaw".into(), &o.jaw.into()).ok();
Reflect::set(&obj, &"teeth".into(), &o.teeth.into()).ok();
Reflect::set(&obj, &"lips".into(), &o.lips.into()).ok();
obj.into()
}
None => JsValue::NULL,
})
}
pub fn reset(&mut self) {
self.inner.reset();
}
#[wasm_bindgen(js_name = isReady)]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[wasm_bindgen(js_name = warmupPeriod)]
pub fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
}
#[wasm_bindgen(js_name = Aroon)]
pub struct WasmAroon {
inner: wc::Aroon,
@@ -0,0 +1,223 @@
//! Bill Williams' Alligator indicator.
use crate::error::{Error, Result};
use crate::indicators::smma::Smma;
use crate::ohlcv::Candle;
use crate::traits::Indicator;
/// Alligator output: three smoothed moving averages of the median price
/// `(high + low) / 2`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct AlligatorOutput {
/// `Jaw` — the slowest line (default period 13).
pub jaw: f64,
/// `Teeth` — the middle line (default period 8).
pub teeth: f64,
/// `Lips` — the fastest line (default period 5).
pub lips: f64,
}
/// Bill Williams' Alligator: three `SMMA`s of the median price `(high + low) / 2`
/// with different periods. Classic parameters are `(jaw = 13, teeth = 8, lips = 5)`.
///
/// The original chart variant additionally shifts each line forward by a fixed
/// number of bars for display (Jaw +8, Teeth +5, Lips +3). Wickra publishes the
/// *unshifted* `SMMA` values — the consumer can apply the visual shift on the
/// chart side. The indicator emits values once all three `SMMA`s have warmed
/// up, i.e. after `max(jaw, teeth, lips) = jaw` candles.
///
/// Reference: Bill Williams, *Trading Chaos*, 1995.
///
/// # Example
///
/// ```
/// use wickra_core::{Alligator, Candle, Indicator};
///
/// let mut alligator = Alligator::classic();
/// let mut last = None;
/// for i in 0..40 {
/// let base = 100.0 + f64::from(i);
/// let candle =
/// Candle::new(base, base + 1.0, base - 1.0, base, 1.0, i64::from(i)).unwrap();
/// last = alligator.update(candle);
/// }
/// assert!(last.is_some());
/// ```
#[derive(Debug, Clone)]
pub struct Alligator {
jaw_period: usize,
teeth_period: usize,
lips_period: usize,
jaw: Smma,
teeth: Smma,
lips: Smma,
}
impl Alligator {
/// # Errors
/// Returns [`Error::PeriodZero`] if any period is zero.
pub fn new(jaw_period: usize, teeth_period: usize, lips_period: usize) -> Result<Self> {
if jaw_period == 0 || teeth_period == 0 || lips_period == 0 {
return Err(Error::PeriodZero);
}
Ok(Self {
jaw_period,
teeth_period,
lips_period,
jaw: Smma::new(jaw_period)?,
teeth: Smma::new(teeth_period)?,
lips: Smma::new(lips_period)?,
})
}
/// Bill Williams' classic parameters: `(jaw = 13, teeth = 8, lips = 5)`.
pub fn classic() -> Self {
Self::new(13, 8, 5).expect("classic Alligator parameters are valid")
}
/// Configured `(jaw_period, teeth_period, lips_period)`.
pub const fn periods(&self) -> (usize, usize, usize) {
(self.jaw_period, self.teeth_period, self.lips_period)
}
}
impl Indicator for Alligator {
type Input = Candle;
type Output = AlligatorOutput;
fn update(&mut self, candle: Candle) -> Option<AlligatorOutput> {
let median = f64::midpoint(candle.high, candle.low);
// Feed every `SMMA` on every bar so they warm up in parallel; gating
// the longer lines behind the shorter ones would starve them during
// their own warmup.
let lips = self.lips.update(median);
let teeth = self.teeth.update(median);
let jaw = self.jaw.update(median);
Some(AlligatorOutput {
jaw: jaw?,
teeth: teeth?,
lips: lips?,
})
}
fn reset(&mut self) {
self.jaw.reset();
self.teeth.reset();
self.lips.reset();
}
fn warmup_period(&self) -> usize {
// All three SMMAs run on every bar, so readiness is gated by the
// longest period — the Jaw with the default parameters.
self.jaw_period.max(self.teeth_period).max(self.lips_period)
}
fn is_ready(&self) -> bool {
self.jaw.is_ready() && self.teeth.is_ready() && self.lips.is_ready()
}
fn name(&self) -> &'static str {
"Alligator"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
fn candle(high: f64, low: f64, ts: i64) -> Candle {
let close = f64::midpoint(high, low);
Candle::new(close, high, low, close, 1.0, ts).unwrap()
}
#[test]
fn rejects_zero_period() {
assert!(matches!(Alligator::new(0, 8, 5), Err(Error::PeriodZero)));
assert!(matches!(Alligator::new(13, 0, 5), Err(Error::PeriodZero)));
assert!(matches!(Alligator::new(13, 8, 0), Err(Error::PeriodZero)));
}
#[test]
fn accessors_and_metadata() {
let alligator = Alligator::classic();
assert_eq!(alligator.periods(), (13, 8, 5));
assert_eq!(alligator.warmup_period(), 13);
assert_eq!(alligator.name(), "Alligator");
}
#[test]
fn constant_series_yields_the_constant() {
// Median price = 10 for every bar, so each SMMA seeds to 10 and stays.
let mut alligator = Alligator::classic();
let candles: Vec<Candle> = (0..40).map(|i| candle(11.0, 9.0, i)).collect();
let out = alligator.batch(&candles);
for v in out.iter().skip(12).flatten() {
assert_relative_eq!(v.jaw, 10.0, epsilon = 1e-12);
assert_relative_eq!(v.teeth, 10.0, epsilon = 1e-12);
assert_relative_eq!(v.lips, 10.0, epsilon = 1e-12);
}
}
#[test]
fn warmup_emits_first_value_at_longest_period() {
let mut alligator = Alligator::new(5, 3, 2).unwrap();
let candles: Vec<Candle> = (0..6).map(|i| candle(11.0, 9.0, i)).collect();
let out = alligator.batch(&candles);
for v in out.iter().take(4) {
assert!(v.is_none());
}
assert!(out[4].is_some());
}
#[test]
fn pure_uptrend_ordering() {
// On a clean uptrend the fastest line (Lips, smallest SMMA) leads the
// slowest line (Jaw) — lips > teeth > jaw at the latest bar.
let mut alligator = Alligator::classic();
let candles: Vec<Candle> = (0_i64..80)
.map(|i| candle(10.0 + i as f64, 9.0 + i as f64, i))
.collect();
let out = alligator.batch(&candles);
let last = out.last().unwrap().unwrap();
assert!(
last.lips > last.teeth,
"lips {} > teeth {}",
last.lips,
last.teeth
);
assert!(
last.teeth > last.jaw,
"teeth {} > jaw {}",
last.teeth,
last.jaw
);
}
#[test]
fn batch_equals_streaming() {
let candles: Vec<Candle> = (0..80_i64)
.map(|i| {
let base = 100.0 + (i as f64 * 0.2).sin() * 5.0;
candle(base + 1.0, base - 1.0, i)
})
.collect();
let mut a = Alligator::classic();
let mut b = Alligator::classic();
assert_eq!(
a.batch(&candles),
candles.iter().map(|c| b.update(*c)).collect::<Vec<_>>()
);
}
#[test]
fn reset_clears_state() {
let mut alligator = Alligator::classic();
let candles: Vec<Candle> = (0..40).map(|i| candle(11.0, 9.0, i)).collect();
alligator.batch(&candles);
assert!(alligator.is_ready());
alligator.reset();
assert!(!alligator.is_ready());
}
}
+335
View File
@@ -0,0 +1,335 @@
//! Arnaud Legoux Moving Average (ALMA).
use std::collections::VecDeque;
use crate::error::{Error, Result};
use crate::traits::Indicator;
/// Arnaud Legoux Moving Average — a Gaussian-weighted moving average.
///
/// Each output is a weighted sum of the last `period` inputs:
///
/// ```text
/// w[i] = exp(-(i - m)^2 / (2 * s^2)) for i in 0..period
/// m = offset * (period - 1)
/// s = period / sigma
/// ALMA = sum(price[i] * w[i]) / sum(w[i])
/// ```
///
/// The Gaussian is centred on the relative index `offset * (period - 1)`, so
/// `offset = 0.85` puts the peak near the newest sample (responsive), while
/// `offset = 0.5` centres the peak in the middle of the window (smooth).
/// `sigma` controls how concentrated the Gaussian is: larger `sigma` ->
/// narrower kernel, smaller `sigma` -> broader (closer to SMA).
///
/// Reference: Arnaud Legoux and Dimitrios Kouzis-Loukas, 2009.
///
/// # Defaults
///
/// The community-standard parameters are `period = 9`, `offset = 0.85`,
/// `sigma = 6.0`. The first output lands after exactly `period` inputs.
///
/// # Example
///
/// ```
/// use wickra_core::{Alma, Indicator};
///
/// let mut alma = Alma::new(9, 0.85, 6.0).unwrap();
/// let mut last = None;
/// for i in 0..40 {
/// last = alma.update(100.0 + f64::from(i));
/// }
/// assert!(last.is_some());
/// ```
#[derive(Debug, Clone)]
pub struct Alma {
period: usize,
offset: f64,
sigma: f64,
/// Pre-computed, normalised weights (sum to 1). `weights[0]` is the oldest
/// sample in the window, `weights[period - 1]` the newest.
weights: Vec<f64>,
window: VecDeque<f64>,
current: Option<f64>,
}
impl Alma {
/// Construct a new ALMA with the given period, offset and sigma.
///
/// # Errors
///
/// - [`Error::PeriodZero`] if `period == 0`.
/// - [`Error::InvalidPeriod`] if `offset` is outside `[0.0, 1.0]` or
/// `sigma <= 0.0` or either of `offset` / `sigma` is non-finite.
pub fn new(period: usize, offset: f64, sigma: f64) -> Result<Self> {
if period == 0 {
return Err(Error::PeriodZero);
}
if !offset.is_finite() || !(0.0..=1.0).contains(&offset) {
return Err(Error::InvalidPeriod {
message: "ALMA offset must be a finite value in [0, 1]",
});
}
if !sigma.is_finite() || sigma <= 0.0 {
return Err(Error::InvalidPeriod {
message: "ALMA sigma must be a finite positive value",
});
}
let m = offset * (period as f64 - 1.0);
let s = period as f64 / sigma;
let denom = 2.0 * s * s;
// The raw Gaussian weights sum to a strictly positive value because
// every term is `exp(_) > 0`, so the normalisation below cannot divide
// by zero.
let mut raw: Vec<f64> = (0..period)
.map(|i| (-((i as f64 - m).powi(2)) / denom).exp())
.collect();
let sum: f64 = raw.iter().sum();
for w in &mut raw {
*w /= sum;
}
Ok(Self {
period,
offset,
sigma,
weights: raw,
window: VecDeque::with_capacity(period),
current: None,
})
}
/// Construct ALMA with the community-standard parameters
/// `(period = 9, offset = 0.85, sigma = 6.0)`.
pub fn classic() -> Self {
Self::new(9, 0.85, 6.0).expect("classic ALMA parameters are valid")
}
/// Configured period.
pub const fn period(&self) -> usize {
self.period
}
/// Configured offset.
pub const fn offset(&self) -> f64 {
self.offset
}
/// Configured sigma.
pub const fn sigma(&self) -> f64 {
self.sigma
}
}
impl Indicator for Alma {
type Input = f64;
type Output = f64;
fn update(&mut self, input: f64) -> Option<f64> {
if !input.is_finite() {
return self.current;
}
if self.window.len() == self.period {
self.window.pop_front();
}
self.window.push_back(input);
if self.window.len() < self.period {
return None;
}
let mut acc = 0.0;
for (w, p) in self.weights.iter().zip(self.window.iter()) {
acc += w * p;
}
self.current = Some(acc);
Some(acc)
}
fn reset(&mut self) {
self.window.clear();
self.current = None;
}
fn warmup_period(&self) -> usize {
self.period
}
fn is_ready(&self) -> bool {
self.current.is_some()
}
fn name(&self) -> &'static str {
"ALMA"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
#[test]
fn rejects_zero_period() {
assert!(matches!(Alma::new(0, 0.85, 6.0), Err(Error::PeriodZero)));
}
#[test]
fn rejects_invalid_offset() {
assert!(matches!(
Alma::new(9, -0.1, 6.0),
Err(Error::InvalidPeriod { .. })
));
assert!(matches!(
Alma::new(9, 1.1, 6.0),
Err(Error::InvalidPeriod { .. })
));
assert!(matches!(
Alma::new(9, f64::NAN, 6.0),
Err(Error::InvalidPeriod { .. })
));
}
#[test]
fn rejects_invalid_sigma() {
assert!(matches!(
Alma::new(9, 0.85, 0.0),
Err(Error::InvalidPeriod { .. })
));
assert!(matches!(
Alma::new(9, 0.85, -1.0),
Err(Error::InvalidPeriod { .. })
));
assert!(matches!(
Alma::new(9, 0.85, f64::INFINITY),
Err(Error::InvalidPeriod { .. })
));
}
#[test]
fn accessors_and_metadata() {
let alma = Alma::new(9, 0.85, 6.0).unwrap();
assert_eq!(alma.period(), 9);
assert_eq!(alma.warmup_period(), 9);
assert_eq!(alma.name(), "ALMA");
assert!((alma.offset() - 0.85).abs() < 1e-12);
assert!((alma.sigma() - 6.0).abs() < 1e-12);
// Weights are normalised by construction.
let sum: f64 = alma.weights.iter().sum();
assert_relative_eq!(sum, 1.0, epsilon = 1e-12);
}
#[test]
fn classic_factory() {
let a = Alma::classic();
assert_eq!(a.period(), 9);
assert!((a.offset() - 0.85).abs() < 1e-12);
assert!((a.sigma() - 6.0).abs() < 1e-12);
}
#[test]
fn constant_series_yields_the_constant() {
// Normalised weights sum to 1, so any constant is reproduced exactly.
let mut alma = Alma::new(9, 0.85, 6.0).unwrap();
let out = alma.batch(&[42.0_f64; 40]);
for v in out.iter().skip(8).flatten() {
assert_relative_eq!(*v, 42.0, epsilon = 1e-12);
}
}
#[test]
fn warmup_emits_first_value_at_period() {
let mut alma = Alma::new(5, 0.85, 6.0).unwrap();
for i in 0..4 {
assert_eq!(alma.update(f64::from(i)), None);
}
assert!(alma.update(4.0).is_some());
}
#[test]
fn reference_value_period_3() {
// ALMA(period=3, offset=0.85, sigma=6) on [10, 20, 30].
// m = 0.85 * 2 = 1.7; s = 3 / 6 = 0.5; 2*s^2 = 0.5.
// Independently compute the normalised Gaussian weights and the
// expected weighted sum, then check the indicator output matches.
// Computing the expectation here (rather than pinning a printed
// constant) keeps the test stable across libm `exp` implementations.
let mut alma = Alma::new(3, 0.85, 6.0).unwrap();
alma.update(10.0);
alma.update(20.0);
let v = alma.update(30.0).expect("ALMA emits after period");
let w0 = (-((0.0_f64 - 1.7).powi(2)) / 0.5).exp();
let w1 = (-((1.0_f64 - 1.7).powi(2)) / 0.5).exp();
let w2 = (-((2.0_f64 - 1.7).powi(2)) / 0.5).exp();
let s = w0 + w1 + w2;
let expected = (10.0 * w0 + 20.0 * w1 + 30.0 * w2) / s;
// The weighted sum is heavily skewed toward the newest sample so the
// output must sit close to but below the latest input (30).
assert!(v > 25.0 && v < 30.0, "ALMA(3) on [10,20,30] = {v}");
assert_relative_eq!(v, expected, epsilon = 1e-12);
}
#[test]
fn offset_zero_centres_on_oldest_sample() {
// With offset = 0 the Gaussian peaks at index 0, so ALMA leans toward
// the oldest sample in the window and away from the newest.
let mut alma = Alma::new(5, 0.0, 6.0).unwrap();
let series: Vec<f64> = (1..=5).map(f64::from).collect();
let mut last = None;
for p in &series {
last = alma.update(*p);
}
let v = last.unwrap();
let mean = series.iter().sum::<f64>() / series.len() as f64;
// Oldest sample is 1.0, mean is 3.0; an offset-0 ALMA should sit
// strictly below the mean.
assert!(v < mean, "{v} should be less than {mean}");
}
#[test]
fn offset_one_centres_on_newest_sample() {
// Symmetric to the above: offset = 1 leans toward the newest sample.
let mut alma = Alma::new(5, 1.0, 6.0).unwrap();
let series: Vec<f64> = (1..=5).map(f64::from).collect();
let mut last = None;
for p in &series {
last = alma.update(*p);
}
let v = last.unwrap();
let mean = series.iter().sum::<f64>() / series.len() as f64;
assert!(v > mean, "{v} should exceed {mean}");
}
#[test]
fn batch_equals_streaming() {
let prices: Vec<f64> = (1..=100)
.map(|i| (f64::from(i) * 0.2).sin() * 5.0 + f64::from(i) * 0.1)
.collect();
let mut a = Alma::new(9, 0.85, 6.0).unwrap();
let mut b = Alma::new(9, 0.85, 6.0).unwrap();
assert_eq!(
a.batch(&prices),
prices.iter().map(|p| b.update(*p)).collect::<Vec<_>>()
);
}
#[test]
fn reset_clears_state() {
let mut alma = Alma::new(9, 0.85, 6.0).unwrap();
alma.batch(&(1..=40).map(f64::from).collect::<Vec<_>>());
assert!(alma.is_ready());
alma.reset();
assert!(!alma.is_ready());
assert_eq!(alma.update(1.0), None);
}
#[test]
fn ignores_non_finite_input() {
let mut alma = Alma::new(5, 0.85, 6.0).unwrap();
alma.batch(&(1..=5).map(f64::from).collect::<Vec<_>>());
let before = alma.update(6.0).unwrap();
// Non-finite inputs leave the window/current untouched.
assert_eq!(alma.update(f64::NAN), Some(before));
assert_eq!(alma.update(f64::INFINITY), Some(before));
}
}
+238
View File
@@ -0,0 +1,238 @@
//! Elastic Volume-Weighted Moving Average (EVWMA).
use std::collections::VecDeque;
use crate::error::{Error, Result};
use crate::ohlcv::Candle;
use crate::traits::Indicator;
/// Christian P. Fries' Elastic Volume-Weighted Moving Average.
///
/// Unlike `VWMA` which is a per-bar weighted mean, `EVWMA` runs an
/// "elastic" recurrence whose smoothing weight is the bar's volume relative
/// to the running window-volume:
///
/// ```text
/// V_sum_t = Σ volume_i over the last `period` candles
/// EVWMA_t = ((V_sum_t - volume_t) * EVWMA_{t-1} + volume_t * close_t) / V_sum_t
/// ```
///
/// A bar whose volume is small compared to the window total barely moves the
/// average; a bar whose volume dominates the window pulls it strongly toward
/// the bar's close. The series is seeded with the close of the first candle
/// after the volume window has filled (i.e. after `period` candles).
///
/// If `V_sum_t == 0` (every candle in the window has zero volume), the
/// recurrence is undefined; the indicator holds its previous value.
///
/// Reference: Christian P. Fries, *Wilmott Magazine*, 2001.
///
/// # Example
///
/// ```
/// use wickra_core::{Candle, Evwma, Indicator};
///
/// let mut evwma = Evwma::new(20).unwrap();
/// let mut last = None;
/// for i in 0..40 {
/// let p = 100.0 + f64::from(i);
/// let candle = Candle::new(p, p + 1.0, p - 1.0, p, 10.0, i64::from(i)).unwrap();
/// last = evwma.update(candle);
/// }
/// assert!(last.is_some());
/// ```
#[derive(Debug, Clone)]
pub struct Evwma {
period: usize,
/// Rolling window of `(close, volume)` pairs, oldest at the front.
window: VecDeque<(f64, f64)>,
sum_v: f64,
current: Option<f64>,
}
impl Evwma {
/// # Errors
/// Returns [`Error::PeriodZero`] if `period == 0`.
pub fn new(period: usize) -> Result<Self> {
if period == 0 {
return Err(Error::PeriodZero);
}
Ok(Self {
period,
window: VecDeque::with_capacity(period),
sum_v: 0.0,
current: None,
})
}
/// Configured period.
pub const fn period(&self) -> usize {
self.period
}
/// Current value if available.
pub const fn value(&self) -> Option<f64> {
self.current
}
}
impl Indicator for Evwma {
type Input = Candle;
type Output = f64;
fn update(&mut self, candle: Candle) -> Option<f64> {
let close = candle.close;
let volume = candle.volume;
if self.window.len() == self.period {
let (_, old_v) = self.window.pop_front().expect("window is non-empty");
self.sum_v -= old_v;
}
self.window.push_back((close, volume));
self.sum_v += volume;
if self.window.len() < self.period {
return None;
}
// The volume sum may be zero (every bar in the window had zero
// volume); the recurrence is undefined, so seed/hold instead.
if self.sum_v <= 0.0 {
if self.current.is_none() {
self.current = Some(close);
}
return self.current;
}
let prev = self.current.unwrap_or(close);
let next = ((self.sum_v - volume) * prev + volume * close) / self.sum_v;
self.current = Some(next);
Some(next)
}
fn reset(&mut self) {
self.window.clear();
self.sum_v = 0.0;
self.current = None;
}
fn warmup_period(&self) -> usize {
self.period
}
fn is_ready(&self) -> bool {
self.current.is_some()
}
fn name(&self) -> &'static str {
"EVWMA"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
fn candle(close: f64, volume: f64, ts: i64) -> Candle {
Candle::new(close, close, close, close, volume, ts).unwrap()
}
#[test]
fn rejects_zero_period() {
assert!(matches!(Evwma::new(0), Err(Error::PeriodZero)));
}
#[test]
fn accessors_and_metadata() {
let mut e = Evwma::new(5).unwrap();
assert_eq!(e.period(), 5);
assert_eq!(e.warmup_period(), 5);
assert_eq!(e.name(), "EVWMA");
assert_eq!(e.value(), None);
for i in 0..5 {
e.update(candle(10.0, 1.0, i));
}
assert!(e.value().is_some());
}
#[test]
fn constant_series_yields_the_constant() {
// A flat close — every (V_sum - v) * prev + v * close reduces to
// V_sum * close, so the recurrence preserves the constant after the
// first seeded sample.
let mut e = Evwma::new(5).unwrap();
let candles: Vec<Candle> = (0..30).map(|i| candle(42.0, 3.0, i)).collect();
let out = e.batch(&candles);
for v in out.iter().skip(4).flatten() {
assert_relative_eq!(*v, 42.0, epsilon = 1e-12);
}
}
#[test]
fn reference_value_period_2() {
// EVWMA(2). Bars: (close, volume) = (10, 1), (20, 3), (30, 1).
// Bar 1: window not full (size 1) -> None.
// Bar 2: window full, sum_v = 4, prev seeds to 20.
// EVWMA = ((4 - 3) * 20 + 3 * 20) / 4 = 80 / 4 = 20.
// Bar 3: window slides, sum_v = 4 (drops the 1, gains the 1).
// EVWMA = ((4 - 1) * 20 + 1 * 30) / 4 = (60 + 30) / 4 = 22.5.
let mut e = Evwma::new(2).unwrap();
assert_eq!(e.update(candle(10.0, 1.0, 0)), None);
assert_relative_eq!(
e.update(candle(20.0, 3.0, 1)).unwrap(),
20.0,
epsilon = 1e-12
);
assert_relative_eq!(
e.update(candle(30.0, 1.0, 2)).unwrap(),
22.5,
epsilon = 1e-12
);
}
#[test]
fn warmup_emits_first_value_at_period() {
let mut e = Evwma::new(4).unwrap();
for i in 0..3 {
assert_eq!(e.update(candle(10.0, 1.0, i)), None);
}
assert!(e.update(candle(10.0, 1.0, 3)).is_some());
}
#[test]
fn zero_volume_window_holds_value() {
// Every bar has zero volume: no participation, so the recurrence
// can't move and EVWMA simply seeds to the first close.
let mut e = Evwma::new(3).unwrap();
e.update(candle(10.0, 0.0, 0));
e.update(candle(15.0, 0.0, 1));
let v = e.update(candle(20.0, 0.0, 2)).unwrap();
assert_relative_eq!(v, 20.0, epsilon = 1e-12);
// Next bar still flat-zero volume: holds 20.
let v2 = e.update(candle(50.0, 0.0, 3)).unwrap();
assert_relative_eq!(v2, 20.0, epsilon = 1e-12);
}
#[test]
fn batch_equals_streaming() {
let candles: Vec<Candle> = (0..60_i64)
.map(|i| {
let c = 100.0 + (i as f64 * 0.3).sin() * 8.0;
candle(c, 1.0 + (i % 7) as f64, i)
})
.collect();
let batch = Evwma::new(10).unwrap().batch(&candles);
let mut b = Evwma::new(10).unwrap();
let streamed: Vec<_> = candles.iter().map(|c| b.update(*c)).collect();
assert_eq!(batch, streamed);
}
#[test]
fn reset_clears_state() {
let mut e = Evwma::new(3).unwrap();
let candles: Vec<Candle> = (0..10).map(|i| candle(10.0 + i as f64, 2.0, i)).collect();
e.batch(&candles);
assert!(e.is_ready());
e.reset();
assert!(!e.is_ready());
assert_eq!(e.update(candle(10.0, 1.0, 0)), None);
}
}
+259
View File
@@ -0,0 +1,259 @@
//! Fractal Adaptive Moving Average (FRAMA).
use std::collections::VecDeque;
use crate::error::{Error, Result};
use crate::traits::Indicator;
/// Ehlers' Fractal Adaptive Moving Average.
///
/// FRAMA picks its smoothing constant from the fractal dimension `D` of the
/// recent window: in a trending (low-`D`) market it follows price tightly, in
/// a choppy (high-`D`) market it smooths heavily. The window of `period`
/// closes is split into two equal halves; the fractal dimension comes from
/// the price ranges of the halves vs. the whole window:
///
/// ```text
/// N1 = (max(first half) - min(first half)) / (period / 2)
/// N2 = (max(second half) - min(second half)) / (period / 2)
/// N3 = (max(window) - min(window)) / period
/// D = (log(N1 + N2) - log(N3)) / log(2)
/// alpha = exp(-4.6 * (D - 1)) clamped to [0.01, 1.0]
/// ```
///
/// The output is an EMA-like recurrence
/// `FRAMA_t = alpha * close_t + (1 - alpha) * FRAMA_{t - 1}`, seeded with the
/// first close. `period` must be even and at least 2.
///
/// Reference: John F. Ehlers, *Fractal Adaptive Moving Average*, 2005.
///
/// # Example
///
/// ```
/// use wickra_core::{Frama, Indicator};
///
/// let mut frama = Frama::new(16).unwrap();
/// let mut last = None;
/// for i in 0..40 {
/// last = frama.update(100.0 + f64::from(i));
/// }
/// assert!(last.is_some());
/// ```
#[derive(Debug, Clone)]
pub struct Frama {
period: usize,
half: usize,
window: VecDeque<f64>,
current: Option<f64>,
}
impl Frama {
/// # Errors
/// - [`Error::PeriodZero`] if `period == 0`.
/// - [`Error::InvalidPeriod`] if `period` is odd or below 2.
pub fn new(period: usize) -> Result<Self> {
if period == 0 {
return Err(Error::PeriodZero);
}
if period < 2 {
return Err(Error::InvalidPeriod {
message: "FRAMA period must be at least 2",
});
}
if period % 2 != 0 {
return Err(Error::InvalidPeriod {
message: "FRAMA period must be even",
});
}
Ok(Self {
period,
half: period / 2,
window: VecDeque::with_capacity(period),
current: None,
})
}
/// Configured period.
pub const fn period(&self) -> usize {
self.period
}
}
impl Indicator for Frama {
type Input = f64;
type Output = f64;
fn update(&mut self, input: f64) -> Option<f64> {
if !input.is_finite() {
return self.current;
}
if self.window.len() == self.period {
self.window.pop_front();
}
self.window.push_back(input);
if self.window.len() < self.period {
return None;
}
let half = self.half;
let mut h_first = f64::NEG_INFINITY;
let mut l_first = f64::INFINITY;
let mut h_second = f64::NEG_INFINITY;
let mut l_second = f64::INFINITY;
let mut h_whole = f64::NEG_INFINITY;
let mut l_whole = f64::INFINITY;
for (i, &p) in self.window.iter().enumerate() {
if p > h_whole {
h_whole = p;
}
if p < l_whole {
l_whole = p;
}
if i < half {
if p > h_first {
h_first = p;
}
if p < l_first {
l_first = p;
}
} else {
if p > h_second {
h_second = p;
}
if p < l_second {
l_second = p;
}
}
}
let half_f = half as f64;
let period_f = self.period as f64;
let n1 = (h_first - l_first) / half_f;
let n2 = (h_second - l_second) / half_f;
let n3 = (h_whole - l_whole) / period_f;
let alpha = if n1 > 0.0 && n2 > 0.0 && n3 > 0.0 {
let d = ((n1 + n2).ln() - n3.ln()) / 2.0_f64.ln();
(-4.6 * (d - 1.0)).exp().clamp(0.01, 1.0)
} else {
// Degenerate (perfectly flat half or whole window): use the slowest
// smoothing so the indicator coasts on its previous value.
0.01
};
let prev = self.current.unwrap_or(input);
let next = alpha * input + (1.0 - alpha) * prev;
self.current = Some(next);
Some(next)
}
fn reset(&mut self) {
self.window.clear();
self.current = None;
}
fn warmup_period(&self) -> usize {
self.period
}
fn is_ready(&self) -> bool {
self.current.is_some()
}
fn name(&self) -> &'static str {
"FRAMA"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
#[test]
fn rejects_zero_period() {
assert!(matches!(Frama::new(0), Err(Error::PeriodZero)));
}
#[test]
fn rejects_invalid_period() {
assert!(matches!(Frama::new(1), Err(Error::InvalidPeriod { .. })));
assert!(matches!(Frama::new(3), Err(Error::InvalidPeriod { .. })));
assert!(matches!(Frama::new(15), Err(Error::InvalidPeriod { .. })));
}
#[test]
fn accessors_and_metadata() {
let frama = Frama::new(16).unwrap();
assert_eq!(frama.period(), 16);
assert_eq!(frama.warmup_period(), 16);
assert_eq!(frama.name(), "FRAMA");
}
#[test]
fn constant_series_yields_the_constant() {
// Flat input -> alpha clamps to 0.01 (degenerate ranges) and the
// EMA recurrence holds the seed value forever.
let mut frama = Frama::new(4).unwrap();
let out = frama.batch(&[42.0_f64; 30]);
for v in out.iter().skip(3).flatten() {
assert_relative_eq!(*v, 42.0, epsilon = 1e-12);
}
}
#[test]
fn warmup_emits_first_value_at_period() {
let mut frama = Frama::new(4).unwrap();
assert_eq!(frama.update(1.0), None);
assert_eq!(frama.update(2.0), None);
assert_eq!(frama.update(3.0), None);
assert!(frama.update(4.0).is_some());
}
#[test]
fn pure_uptrend_alpha_close_to_one() {
// A strict monotonic uptrend has fractal dimension ~1, so alpha is
// pushed to 1.0 and FRAMA reduces to the latest price.
let mut frama = Frama::new(4).unwrap();
let prices: Vec<f64> = (1..=8).map(f64::from).collect();
let out = frama.batch(&prices);
let last = out.last().unwrap().unwrap();
assert!(
(last - 8.0).abs() < 0.05,
"FRAMA on a clean uptrend should hug the latest close: {last}"
);
}
#[test]
fn batch_equals_streaming() {
let prices: Vec<f64> = (1..=80)
.map(|i| 100.0 + (f64::from(i) * 0.2).sin() * 5.0)
.collect();
let mut a = Frama::new(8).unwrap();
let mut b = Frama::new(8).unwrap();
assert_eq!(
a.batch(&prices),
prices.iter().map(|p| b.update(*p)).collect::<Vec<_>>()
);
}
#[test]
fn reset_clears_state() {
let mut frama = Frama::new(4).unwrap();
frama.batch(&(1..=20).map(f64::from).collect::<Vec<_>>());
assert!(frama.is_ready());
frama.reset();
assert!(!frama.is_ready());
assert_eq!(frama.update(1.0), None);
}
#[test]
fn ignores_non_finite_input() {
let mut frama = Frama::new(4).unwrap();
frama.batch(&[1.0, 2.0, 3.0, 4.0]);
let before = frama.update(5.0).unwrap();
assert_eq!(frama.update(f64::NAN), Some(before));
assert_eq!(frama.update(f64::INFINITY), Some(before));
}
}
+286
View File
@@ -0,0 +1,286 @@
//! Jurik Moving Average (JMA).
use crate::error::{Error, Result};
use crate::traits::Indicator;
/// Mark Jurik's adaptive moving average. The original algorithm is proprietary
/// and Jurik Research has never published the full source. This implementation
/// follows the widely-used three-stage filter reconstruction circulated since
/// the 1999 TASC article on the indicator — the same form used by most
/// open-source ports (`TradingView` Pine, `pandas-ta`, various MQL ports):
///
/// ```text
/// beta = 0.45 * (period - 1) / (0.45 * (period - 1) + 2)
/// alpha = beta ^ power
/// phase_ratio = clamp(phase / 100 + 1.5, 0.5, 2.5)
///
/// e0_t = (1 - alpha) * x_t + alpha * e0_{t-1}
/// e1_t = (x_t - e0_t) * (1 - beta) + beta * e1_{t-1}
/// e2_t = (e0_t + phase_ratio * e1_t - JMA_{t-1}) * (1 - alpha)^2 + alpha^2 * e2_{t-1}
/// JMA_t = JMA_{t-1} + e2_t
/// ```
///
/// The state is seeded by setting `e0 = JMA = first input`, so a constant
/// input stream is reproduced exactly from the first output onward.
///
/// # Parameters
///
/// - `period`: smoothing length (default 14).
/// - `phase`: phase shift in `[-100, 100]`. Values outside this range are
/// clamped to the boundary `phase_ratio` so the constructor never fails on
/// a finite `phase`.
/// - `power`: kernel exponent in `1..=4` (default 2 matches the popular
/// reconstruction).
///
/// # Example
///
/// ```
/// use wickra_core::{Indicator, Jma};
///
/// let mut jma = Jma::new(14, 0.0, 2).unwrap();
/// let mut last = None;
/// for i in 0..40 {
/// last = jma.update(100.0 + f64::from(i));
/// }
/// assert!(last.is_some());
/// ```
#[derive(Debug, Clone)]
pub struct Jma {
period: usize,
phase: f64,
power: u32,
beta: f64,
alpha: f64,
phase_ratio: f64,
e0: f64,
e1: f64,
e2: f64,
output: Option<f64>,
}
impl Jma {
/// # Errors
/// - [`Error::PeriodZero`] if `period == 0`.
/// - [`Error::InvalidPeriod`] if `phase` is non-finite or `power` is
/// outside `1..=4`.
pub fn new(period: usize, phase: f64, power: u32) -> Result<Self> {
if period == 0 {
return Err(Error::PeriodZero);
}
if !phase.is_finite() {
return Err(Error::InvalidPeriod {
message: "JMA phase must be a finite value",
});
}
if !(1..=4).contains(&power) {
return Err(Error::InvalidPeriod {
message: "JMA power must be in 1..=4",
});
}
let len = period as f64 - 1.0;
let beta = 0.45 * len / (0.45 * len + 2.0);
let alpha = beta.powi(i32::try_from(power).expect("power is in 1..=4"));
let phase_ratio = (phase / 100.0 + 1.5).clamp(0.5, 2.5);
Ok(Self {
period,
phase,
power,
beta,
alpha,
phase_ratio,
e0: 0.0,
e1: 0.0,
e2: 0.0,
output: None,
})
}
/// Construct JMA with the popular defaults `(period = 14, phase = 0, power = 2)`.
pub fn classic() -> Self {
Self::new(14, 0.0, 2).expect("classic JMA parameters are valid")
}
/// Configured `(period, phase, power)`.
pub const fn params(&self) -> (usize, f64, u32) {
(self.period, self.phase, self.power)
}
}
impl Indicator for Jma {
type Input = f64;
type Output = f64;
fn update(&mut self, input: f64) -> Option<f64> {
if !input.is_finite() {
return self.output;
}
let Some(prev_jma) = self.output else {
// Seed e0 and JMA to the first input so a flat series is
// reproduced exactly.
self.e0 = input;
self.output = Some(input);
return self.output;
};
self.e0 = (1.0 - self.alpha) * input + self.alpha * self.e0;
self.e1 = (input - self.e0) * (1.0 - self.beta) + self.beta * self.e1;
let one_minus_alpha = 1.0 - self.alpha;
self.e2 =
(self.e0 + self.phase_ratio * self.e1 - prev_jma) * one_minus_alpha * one_minus_alpha
+ self.alpha * self.alpha * self.e2;
let next = prev_jma + self.e2;
self.output = Some(next);
Some(next)
}
fn reset(&mut self) {
self.e0 = 0.0;
self.e1 = 0.0;
self.e2 = 0.0;
self.output = None;
}
fn warmup_period(&self) -> usize {
1
}
fn is_ready(&self) -> bool {
self.output.is_some()
}
fn name(&self) -> &'static str {
"JMA"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
#[test]
fn rejects_zero_period() {
assert!(matches!(Jma::new(0, 0.0, 2), Err(Error::PeriodZero)));
}
#[test]
fn rejects_non_finite_phase() {
assert!(matches!(
Jma::new(14, f64::NAN, 2),
Err(Error::InvalidPeriod { .. })
));
assert!(matches!(
Jma::new(14, f64::INFINITY, 2),
Err(Error::InvalidPeriod { .. })
));
}
#[test]
fn rejects_invalid_power() {
assert!(matches!(
Jma::new(14, 0.0, 0),
Err(Error::InvalidPeriod { .. })
));
assert!(matches!(
Jma::new(14, 0.0, 5),
Err(Error::InvalidPeriod { .. })
));
}
#[test]
fn accessors_and_metadata() {
let jma = Jma::new(14, 0.0, 2).unwrap();
assert_eq!(jma.params(), (14, 0.0, 2));
assert_eq!(jma.warmup_period(), 1);
assert_eq!(jma.name(), "JMA");
}
#[test]
fn classic_factory() {
let jma = Jma::classic();
assert_eq!(jma.params(), (14, 0.0, 2));
}
#[test]
fn constant_series_yields_the_constant() {
// Seeding e0 = JMA = first input means the recurrence stays exactly
// on the constant from the very first sample.
let mut jma = Jma::new(14, 0.0, 2).unwrap();
let out = jma.batch(&[42.0_f64; 60]);
for x in out.iter().flatten() {
assert_relative_eq!(*x, 42.0, epsilon = 1e-12);
}
}
#[test]
fn extreme_phase_is_clamped() {
// phase outside [-100, 100] must produce a finite JMA series (phase
// ratio clamps to [0.5, 2.5]) rather than blow up the recurrence.
let mut a = Jma::new(14, 250.0, 2).unwrap();
let mut b = Jma::new(14, -250.0, 2).unwrap();
let prices: Vec<f64> = (1..=40).map(f64::from).collect();
for &p in &prices {
let va = a.update(p).unwrap();
let vb = b.update(p).unwrap();
assert!(va.is_finite(), "JMA(phase=+250) emitted {va}");
assert!(vb.is_finite(), "JMA(phase=-250) emitted {vb}");
}
}
#[test]
fn pure_uptrend_tracks_close() {
// Monotonic uptrend, period 5, power 2 — after enough samples the
// smoothed JMA sits close to the latest input.
let mut jma = Jma::new(5, 0.0, 2).unwrap();
let prices: Vec<f64> = (1..=80).map(f64::from).collect();
let out = jma.batch(&prices);
let last = out.last().unwrap().unwrap();
let latest = *prices.last().unwrap();
assert!(
(latest - last).abs() < 5.0,
"JMA on a long clean uptrend should track close: {last} vs {latest}"
);
}
#[test]
fn batch_equals_streaming() {
let prices: Vec<f64> = (1..=80)
.map(|i| 100.0 + (f64::from(i) * 0.2).sin() * 5.0)
.collect();
let mut a = Jma::new(14, 0.0, 2).unwrap();
let mut b = Jma::new(14, 0.0, 2).unwrap();
assert_eq!(
a.batch(&prices),
prices.iter().map(|p| b.update(*p)).collect::<Vec<_>>()
);
}
#[test]
fn reset_clears_state() {
let mut jma = Jma::new(14, 0.0, 2).unwrap();
jma.batch(&(1..=30).map(f64::from).collect::<Vec<_>>());
assert!(jma.is_ready());
jma.reset();
assert!(!jma.is_ready());
assert_eq!(jma.e0, 0.0);
}
#[test]
fn ignores_non_finite_input() {
let mut jma = Jma::new(14, 0.0, 2).unwrap();
jma.batch(&(1..=15).map(f64::from).collect::<Vec<_>>());
let before = jma.update(16.0).unwrap();
assert_eq!(jma.update(f64::NAN), Some(before));
assert_eq!(jma.update(f64::INFINITY), Some(before));
}
#[test]
fn period_one_is_pass_through() {
// beta = 0, alpha = 0 -> e2 collapses to (input - prev) and the
// recurrence reduces to JMA_t = input.
let mut jma = Jma::new(1, 0.0, 2).unwrap();
assert_eq!(jma.update(5.0), Some(5.0));
assert_relative_eq!(jma.update(10.0).unwrap(), 10.0, epsilon = 1e-12);
assert_relative_eq!(jma.update(7.0).unwrap(), 7.0, epsilon = 1e-12);
}
}
@@ -0,0 +1,224 @@
//! `McGinley` Dynamic — self-adjusting moving average.
use std::collections::VecDeque;
use crate::error::{Error, Result};
use crate::traits::Indicator;
/// John `McGinley`'s "Dynamic" — a self-adjusting moving average that speeds up
/// in downtrends and slows down in uptrends to track price more closely than
/// a fixed-period MA.
///
/// The recurrence is
///
/// ```text
/// MD_t = MD_{t-1} + (price_t - MD_{t-1}) / (K * period * (price_t / MD_{t-1})^4)
/// ```
///
/// where `K = 0.6` is `McGinley`'s original constant. The fourth-power ratio
/// term shrinks the divisor when price falls below the indicator (faster
/// catch-up) and inflates it when price runs above (more smoothing). The
/// indicator is seeded with the simple average of the first `period` inputs.
///
/// Reference: John R. `McGinley` Jr., *Technical Analysis of Stocks &
/// Commodities*, 1990.
///
/// # Example
///
/// ```
/// use wickra_core::{Indicator, McGinleyDynamic};
///
/// let mut md = McGinleyDynamic::new(10).unwrap();
/// let mut last = None;
/// for i in 0..40 {
/// last = md.update(100.0 + f64::from(i));
/// }
/// assert!(last.is_some());
/// ```
#[derive(Debug, Clone)]
pub struct McGinleyDynamic {
period: usize,
seed: VecDeque<f64>,
seed_sum: f64,
current: Option<f64>,
}
/// `McGinley`'s original constant `K` in the recurrence denominator.
const K: f64 = 0.6;
impl McGinleyDynamic {
/// # Errors
/// Returns [`Error::PeriodZero`] if `period == 0`.
pub fn new(period: usize) -> Result<Self> {
if period == 0 {
return Err(Error::PeriodZero);
}
Ok(Self {
period,
seed: VecDeque::with_capacity(period),
seed_sum: 0.0,
current: None,
})
}
/// Configured period.
pub const fn period(&self) -> usize {
self.period
}
/// Current value if available.
pub const fn value(&self) -> Option<f64> {
self.current
}
}
impl Indicator for McGinleyDynamic {
type Input = f64;
type Output = f64;
fn update(&mut self, input: f64) -> Option<f64> {
if !input.is_finite() {
return self.current;
}
if let Some(prev) = self.current {
// The recurrence divides by `(price / prev)^4`; if either side is
// zero or negative the formula blows up, so we hold the previous
// value as a defensive fallback against degenerate price series.
if prev <= 0.0 || input <= 0.0 {
return self.current;
}
let ratio = input / prev;
let divisor = K * (self.period as f64) * ratio.powi(4);
let next = prev + (input - prev) / divisor;
self.current = Some(next);
} else {
self.seed.push_back(input);
self.seed_sum += input;
if self.seed.len() == self.period {
self.current = Some(self.seed_sum / self.period as f64);
}
}
self.current
}
fn reset(&mut self) {
self.seed.clear();
self.seed_sum = 0.0;
self.current = None;
}
fn warmup_period(&self) -> usize {
self.period
}
fn is_ready(&self) -> bool {
self.current.is_some()
}
fn name(&self) -> &'static str {
"McGinleyDynamic"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
#[test]
fn rejects_zero_period() {
assert!(matches!(McGinleyDynamic::new(0), Err(Error::PeriodZero)));
}
#[test]
fn accessors_and_metadata() {
let mut md = McGinleyDynamic::new(10).unwrap();
assert_eq!(md.period(), 10);
assert_eq!(md.warmup_period(), 10);
assert_eq!(md.name(), "McGinleyDynamic");
assert_eq!(md.value(), None);
for i in 1..=10 {
md.update(f64::from(i));
}
assert!(md.value().is_some());
}
#[test]
fn constant_series_yields_the_constant() {
// ratio = 1, so the recurrence collapses to MD + 0 / divisor = MD.
let mut md = McGinleyDynamic::new(5).unwrap();
let out = md.batch(&[42.0_f64; 30]);
for v in out.iter().skip(4).flatten() {
assert_relative_eq!(*v, 42.0, epsilon = 1e-12);
}
}
#[test]
fn warmup_emits_first_value_at_period() {
let mut md = McGinleyDynamic::new(3).unwrap();
// Seed = SMA([10, 20, 30]) = 20.0.
assert_eq!(md.update(10.0), None);
assert_eq!(md.update(20.0), None);
assert_eq!(md.update(30.0), Some(20.0));
}
#[test]
fn reference_value_recurrence() {
// Period 3, seed = SMA([10, 20, 30]) = 20.0. Then on price = 40.0:
// ratio = 40 / 20 = 2
// divisor = 0.6 * 3 * 2^4 = 0.6 * 3 * 16 = 28.8
// next = 20 + (40 - 20) / 28.8 = 20.694444...
let mut md = McGinleyDynamic::new(3).unwrap();
md.batch(&[10.0_f64, 20.0, 30.0]);
let v = md.update(40.0).unwrap();
let expected = 20.0 + 20.0 / (0.6 * 3.0 * 16.0);
assert_relative_eq!(v, expected, epsilon = 1e-12);
}
#[test]
fn batch_equals_streaming() {
let prices: Vec<f64> = (1..=80)
.map(|i| 100.0 + (f64::from(i) * 0.2).sin() * 5.0)
.collect();
let mut a = McGinleyDynamic::new(10).unwrap();
let mut b = McGinleyDynamic::new(10).unwrap();
assert_eq!(
a.batch(&prices),
prices.iter().map(|p| b.update(*p)).collect::<Vec<_>>()
);
}
#[test]
fn reset_clears_state() {
let mut md = McGinleyDynamic::new(5).unwrap();
md.batch(&(1..=30).map(f64::from).collect::<Vec<_>>());
assert!(md.is_ready());
md.reset();
assert!(!md.is_ready());
assert_eq!(md.update(1.0), None);
}
#[test]
fn ignores_non_finite_input() {
let mut md = McGinleyDynamic::new(3).unwrap();
md.batch(&[10.0_f64, 20.0, 30.0]);
let before = md.value().unwrap();
assert_eq!(md.update(f64::NAN), Some(before));
assert_eq!(md.update(f64::INFINITY), Some(before));
}
#[test]
fn holds_value_when_input_is_non_positive() {
// Defensive: a zero or negative price would make the (price/prev)^4
// divisor zero or otherwise blow up; the recurrence holds steady.
let mut md = McGinleyDynamic::new(3).unwrap();
md.batch(&[10.0_f64, 20.0, 30.0]);
let before = md.value().unwrap();
assert_eq!(md.update(0.0), Some(before));
assert_eq!(md.update(-5.0), Some(before));
// Once a positive price arrives the recurrence resumes normally.
let after = md.update(40.0).unwrap();
assert!(after > before);
}
}
+14
View File
@@ -7,6 +7,8 @@
mod accelerator_oscillator;
mod adl;
mod adx;
mod alligator;
mod alma;
mod aroon;
mod aroon_oscillator;
mod atr;
@@ -29,9 +31,12 @@ mod donchian;
mod dpo;
mod ease_of_movement;
mod ema;
mod evwma;
mod force_index;
mod frama;
mod historical_volatility;
mod hma;
mod jma;
mod kama;
mod keltner;
mod linreg;
@@ -39,6 +44,7 @@ mod linreg_angle;
mod linreg_slope;
mod macd;
mod mass_index;
mod mcginley_dynamic;
mod median_price;
mod mfi;
mod mom;
@@ -66,6 +72,7 @@ mod typical_price;
mod ulcer_index;
mod ultimate_oscillator;
mod vertical_horizontal_filter;
mod vidya;
mod vortex;
mod vpt;
mod vwap;
@@ -79,6 +86,8 @@ mod zlema;
pub use accelerator_oscillator::AcceleratorOscillator;
pub use adl::Adl;
pub use adx::{Adx, AdxOutput};
pub use alligator::{Alligator, AlligatorOutput};
pub use alma::Alma;
pub use aroon::{Aroon, AroonOutput};
pub use aroon_oscillator::AroonOscillator;
pub use atr::Atr;
@@ -101,9 +110,12 @@ pub use donchian::{Donchian, DonchianOutput};
pub use dpo::Dpo;
pub use ease_of_movement::EaseOfMovement;
pub use ema::Ema;
pub use evwma::Evwma;
pub use force_index::ForceIndex;
pub use frama::Frama;
pub use historical_volatility::HistoricalVolatility;
pub use hma::Hma;
pub use jma::Jma;
pub use kama::Kama;
pub use keltner::{Keltner, KeltnerOutput};
pub use linreg::LinearRegression;
@@ -111,6 +123,7 @@ pub use linreg_angle::LinRegAngle;
pub use linreg_slope::LinRegSlope;
pub use macd::{MacdIndicator, MacdOutput};
pub use mass_index::MassIndex;
pub use mcginley_dynamic::McGinleyDynamic;
pub use median_price::MedianPrice;
pub use mfi::Mfi;
pub use mom::Mom;
@@ -138,6 +151,7 @@ pub use typical_price::TypicalPrice;
pub use ulcer_index::UlcerIndex;
pub use ultimate_oscillator::UltimateOscillator;
pub use vertical_horizontal_filter::VerticalHorizontalFilter;
pub use vidya::Vidya;
pub use vortex::{Vortex, VortexOutput};
pub use vpt::VolumePriceTrend;
pub use vwap::{RollingVwap, Vwap};
+193
View File
@@ -0,0 +1,193 @@
//! Variable Index Dynamic Average (VIDYA).
use crate::error::{Error, Result};
use crate::indicators::cmo::Cmo;
use crate::traits::Indicator;
/// Tushar Chande's Variable Index Dynamic Average — an EMA whose smoothing
/// factor is scaled by the absolute Chande Momentum Oscillator (`CMO`).
///
/// Strong directional momentum (high `|CMO|`) pushes the effective smoothing
/// constant toward the EMA-of-`period`'s natural rate; flat / choppy windows
/// (`|CMO|` close to zero) shrink it toward zero so VIDYA coasts on its prior
/// value:
///
/// ```text
/// alpha_base = 2 / (period + 1)
/// alpha_t = alpha_base * |CMO(cmo_period)| / 100
/// VIDYA_t = alpha_t * price_t + (1 - alpha_t) * VIDYA_{t-1}
/// ```
///
/// The series is seeded with the first price emitted after the `CMO`
/// warm-up (i.e. after `cmo_period + 1` inputs).
///
/// Reference: Tushar Chande, *Stocks & Commodities*, 1992.
///
/// # Example
///
/// ```
/// use wickra_core::{Indicator, Vidya};
///
/// let mut vidya = Vidya::new(14, 9).unwrap();
/// let mut last = None;
/// for i in 0..80 {
/// last = vidya.update(100.0 + f64::from(i));
/// }
/// assert!(last.is_some());
/// ```
#[derive(Debug, Clone)]
pub struct Vidya {
period: usize,
cmo_period: usize,
alpha_base: f64,
cmo: Cmo,
current: Option<f64>,
}
impl Vidya {
/// # Errors
/// Returns [`Error::PeriodZero`] if either period is zero.
pub fn new(period: usize, cmo_period: usize) -> Result<Self> {
if period == 0 || cmo_period == 0 {
return Err(Error::PeriodZero);
}
let alpha_base = 2.0 / (period as f64 + 1.0);
Ok(Self {
period,
cmo_period,
alpha_base,
cmo: Cmo::new(cmo_period)?,
current: None,
})
}
/// Configured `(period, cmo_period)`.
pub const fn periods(&self) -> (usize, usize) {
(self.period, self.cmo_period)
}
}
impl Indicator for Vidya {
type Input = f64;
type Output = f64;
fn update(&mut self, input: f64) -> Option<f64> {
if !input.is_finite() {
return self.current;
}
let cmo = self.cmo.update(input)?;
let alpha = self.alpha_base * (cmo.abs() / 100.0);
let prev = self.current.unwrap_or(input);
let next = alpha * input + (1.0 - alpha) * prev;
self.current = Some(next);
Some(next)
}
fn reset(&mut self) {
self.cmo.reset();
self.current = None;
}
fn warmup_period(&self) -> usize {
self.cmo_period + 1
}
fn is_ready(&self) -> bool {
self.current.is_some()
}
fn name(&self) -> &'static str {
"VIDYA"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
#[test]
fn rejects_zero_period() {
assert!(matches!(Vidya::new(0, 9), Err(Error::PeriodZero)));
assert!(matches!(Vidya::new(14, 0), Err(Error::PeriodZero)));
}
#[test]
fn accessors_and_metadata() {
let v = Vidya::new(14, 9).unwrap();
assert_eq!(v.periods(), (14, 9));
assert_eq!(v.warmup_period(), 10);
assert_eq!(v.name(), "VIDYA");
}
#[test]
fn constant_series_yields_the_constant() {
// Flat input -> CMO = 0 -> alpha = 0 -> VIDYA holds its seed value.
let mut v = Vidya::new(14, 4).unwrap();
let out = v.batch(&[42.0_f64; 30]);
for x in out.iter().skip(4).flatten() {
assert_relative_eq!(*x, 42.0, epsilon = 1e-12);
}
}
#[test]
fn pure_uptrend_alpha_equals_base() {
// Monotonic uptrend: CMO saturates at +100, so alpha = alpha_base.
// After warmup the recurrence is a plain EMA with that alpha; once
// the series is long enough VIDYA closely tracks the latest input.
let mut v = Vidya::new(2, 4).unwrap();
let prices: Vec<f64> = (1..=40).map(f64::from).collect();
let out = v.batch(&prices);
let last = out.last().unwrap().unwrap();
let latest = *prices.last().unwrap();
// alpha_base = 2/3, EMA(2) tracks close — last value is within 2 of
// the latest input after this many bars.
assert!(
(latest - last).abs() < 2.0,
"VIDYA should track close on a clean uptrend: {last} vs {latest}"
);
}
#[test]
fn warmup_emits_first_value_at_cmo_period_plus_one() {
let mut v = Vidya::new(14, 3).unwrap();
assert_eq!(v.warmup_period(), 4);
assert_eq!(v.update(10.0), None);
assert_eq!(v.update(11.0), None);
assert_eq!(v.update(12.0), None);
assert!(v.update(13.0).is_some());
}
#[test]
fn batch_equals_streaming() {
let prices: Vec<f64> = (1..=60)
.map(|i| 100.0 + (f64::from(i) * 0.2).sin() * 5.0)
.collect();
let mut a = Vidya::new(14, 9).unwrap();
let mut b = Vidya::new(14, 9).unwrap();
assert_eq!(
a.batch(&prices),
prices.iter().map(|p| b.update(*p)).collect::<Vec<_>>()
);
}
#[test]
fn reset_clears_state() {
let mut v = Vidya::new(14, 9).unwrap();
v.batch(&(1..=40).map(f64::from).collect::<Vec<_>>());
assert!(v.is_ready());
v.reset();
assert!(!v.is_ready());
assert_eq!(v.update(1.0), None);
}
#[test]
fn ignores_non_finite_input() {
let mut v = Vidya::new(14, 4).unwrap();
v.batch(&(1..=20).map(f64::from).collect::<Vec<_>>());
let before = v.update(21.0).unwrap();
assert_eq!(v.update(f64::NAN), Some(before));
assert_eq!(v.update(f64::INFINITY), Some(before));
}
}
+10 -9
View File
@@ -44,17 +44,18 @@ pub mod indicators;
pub use error::{Error, Result};
pub use indicators::{
AcceleratorOscillator, Adl, Adx, AdxOutput, Aroon, AroonOscillator, AroonOutput, Atr,
AtrTrailingStop, AwesomeOscillator, BalanceOfPower, BollingerBands, BollingerBandwidth,
BollingerOutput, Cci, ChaikinMoneyFlow, ChaikinOscillator, ChaikinVolatility, ChandeKrollStop,
ChandeKrollStopOutput, ChandelierExit, ChandelierExitOutput, ChoppinessIndex, Cmo, Coppock,
Dema, Donchian, DonchianOutput, Dpo, EaseOfMovement, Ema, ForceIndex, HistoricalVolatility,
Hma, Kama, Keltner, KeltnerOutput, LinRegAngle, LinRegSlope, LinearRegression, MacdIndicator,
MacdOutput, MassIndex, MedianPrice, Mfi, Mom, Natr, Obv, PercentB, Pmo, Ppo, Psar, Roc,
AcceleratorOscillator, Adl, Adx, AdxOutput, Alligator, AlligatorOutput, Alma, Aroon,
AroonOscillator, AroonOutput, Atr, AtrTrailingStop, AwesomeOscillator, BalanceOfPower,
BollingerBands, BollingerBandwidth, BollingerOutput, Cci, ChaikinMoneyFlow, ChaikinOscillator,
ChaikinVolatility, ChandeKrollStop, ChandeKrollStopOutput, ChandelierExit,
ChandelierExitOutput, ChoppinessIndex, Cmo, Coppock, Dema, Donchian, DonchianOutput, Dpo,
EaseOfMovement, Ema, Evwma, ForceIndex, Frama, HistoricalVolatility, Hma, Jma, Kama, Keltner,
KeltnerOutput, LinRegAngle, LinRegSlope, LinearRegression, MacdIndicator, MacdOutput,
MassIndex, McGinleyDynamic, MedianPrice, Mfi, Mom, Natr, Obv, PercentB, Pmo, Ppo, Psar, Roc,
RollingVwap, Rsi, Sma, Smma, StdDev, StochRsi, Stochastic, StochasticOutput, SuperTrend,
SuperTrendOutput, Tema, Trima, Trix, TrueRange, Tsi, TypicalPrice, UlcerIndex,
UltimateOscillator, VerticalHorizontalFilter, VolumePriceTrend, Vortex, VortexOutput, Vwap,
Vwma, WeightedClose, WilliamsR, Wma, ZScore, Zlema, T3,
UltimateOscillator, VerticalHorizontalFilter, Vidya, VolumePriceTrend, Vortex, VortexOutput,
Vwap, Vwma, WeightedClose, WilliamsR, Wma, ZScore, Zlema, T3,
};
pub use ohlcv::{Candle, Tick};
pub use traits::{BatchExt, Chain, Indicator};
+9 -2
View File
@@ -19,8 +19,8 @@
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion, Throughput};
use std::hint::black_box;
use wickra::{
Atr, BatchExt, BollingerBands, Candle, Ema, Indicator, MacdIndicator, Obv, Rsi, Sma,
Stochastic, Wma,
Alma, Atr, BatchExt, BollingerBands, Candle, Ema, Frama, Indicator, Jma, MacdIndicator,
McGinleyDynamic, Obv, Rsi, Sma, Stochastic, Vidya, Wma,
};
use wickra_data::csv::CandleReader;
@@ -139,6 +139,13 @@ fn benches(c: &mut Criterion) {
bench_scalar(c, "ema", &closes, || Ema::new(14).unwrap());
bench_scalar(c, "wma", &closes, || Wma::new(14).unwrap());
bench_scalar(c, "rsi", &closes, || Rsi::new(14).unwrap());
bench_scalar(c, "alma", &closes, || Alma::new(9, 0.85, 6.0).unwrap());
bench_scalar(c, "mcginley_dynamic", &closes, || {
McGinleyDynamic::new(10).unwrap()
});
bench_scalar(c, "frama", &closes, || Frama::new(16).unwrap());
bench_scalar(c, "vidya", &closes, || Vidya::new(14, 9).unwrap());
bench_scalar(c, "jma", &closes, || Jma::new(14, 0.0, 2).unwrap());
bench_macd(c, &closes);
bench_bollinger(c, &closes);
bench_candle_input(c, "atr", &candles, || Atr::new(14).unwrap());
+9 -4
View File
@@ -15,10 +15,10 @@
use libfuzzer_sys::fuzz_target;
use wickra_core::{
BatchExt, BollingerBands, Cmo, Coppock, Dema, Dpo, Ema, HistoricalVolatility, Hma, Indicator,
Kama, LinRegAngle, LinRegSlope, LinearRegression, MacdIndicator, Mom, Pmo, Ppo, Roc, Rsi, Sma,
Smma, StdDev, StochRsi, T3, Tema, Trima, Trix, Tsi, UlcerIndex, VerticalHorizontalFilter, Wma,
ZScore, Zlema,
Alma, BatchExt, BollingerBands, Cmo, Coppock, Dema, Dpo, Ema, Frama, HistoricalVolatility, Hma,
Indicator, Jma, Kama, LinRegAngle, LinRegSlope, LinearRegression, MacdIndicator,
McGinleyDynamic, Mom, Pmo, Ppo, Roc, Rsi, Sma, Smma, StdDev, StochRsi, T3, Tema, Trima, Trix,
Tsi, UlcerIndex, VerticalHorizontalFilter, Vidya, Wma, ZScore, Zlema,
};
/// Drive a single streaming + batch run through one scalar indicator. Marked
@@ -53,6 +53,11 @@ fuzz_target!(|data: Vec<f64>| {
drive(|| Trima::new(14).unwrap(), &data);
drive(|| Zlema::new(14).unwrap(), &data);
drive(|| Kama::new(10, 2, 30).unwrap(), &data);
drive(|| Alma::new(9, 0.85, 6.0).unwrap(), &data);
drive(|| McGinleyDynamic::new(10).unwrap(), &data);
drive(|| Frama::new(16).unwrap(), &data);
drive(|| Vidya::new(14, 9).unwrap(), &data);
drive(|| Jma::new(14, 0.0, 2).unwrap(), &data);
drive(|| T3::new(14, 0.7).unwrap(), &data);
drive(|| Mom::new(14).unwrap(), &data);
drive(|| Cmo::new(14).unwrap(), &data);
+5 -2
View File
@@ -23,10 +23,11 @@
use libfuzzer_sys::fuzz_target;
use wickra_core::{
AcceleratorOscillator, Adl, Adx, Aroon, AroonOscillator, Atr, AtrTrailingStop,
AcceleratorOscillator, Adl, Adx, Alligator, Aroon, AroonOscillator, Atr, AtrTrailingStop,
AwesomeOscillator, BalanceOfPower, BatchExt, Candle, Cci, ChaikinMoneyFlow, ChaikinOscillator,
ChaikinVolatility, ChandeKrollStop, ChandelierExit, ChoppinessIndex, Donchian, EaseOfMovement,
ForceIndex, Indicator, Keltner, MassIndex, MedianPrice, Mfi, Natr, Obv, Psar, RollingVwap,
Evwma, ForceIndex, Indicator, Keltner, MassIndex, MedianPrice, Mfi, Natr, Obv, Psar,
RollingVwap,
Stochastic, SuperTrend, TrueRange, TypicalPrice, UltimateOscillator, VolumePriceTrend, Vortex,
Vwap, Vwma, WeightedClose, WilliamsR,
};
@@ -88,6 +89,7 @@ fuzz_target!(|data: Vec<f64>| {
// --- Trend & Directional ---
drive(|| Adx::new(14).unwrap(), &candles);
drive(|| Aroon::new(14).unwrap(), &candles);
drive(|| Alligator::new(13, 8, 5).unwrap(), &candles);
drive(|| AroonOscillator::new(14).unwrap(), &candles);
drive(|| Vortex::new(14).unwrap(), &candles);
drive(|| MassIndex::new(9, 25).unwrap(), &candles);
@@ -107,6 +109,7 @@ fuzz_target!(|data: Vec<f64>| {
drive(Vwap::new, &candles);
drive(|| RollingVwap::new(20).unwrap(), &candles);
drive(|| Vwma::new(20).unwrap(), &candles);
drive(|| Evwma::new(20).unwrap(), &candles);
drive(Adl::new, &candles);
drive(VolumePriceTrend::new, &candles);
drive(|| ChaikinMoneyFlow::new(20).unwrap(), &candles);