Wickra 0.1.0: streaming-first technical indicators

A multi-language technical analysis library: 25 indicators across trend,
momentum, volatility, and volume families, every one a state machine with
O(1) per-tick updates. Batch evaluation is provided by a blanket extension
trait over the streaming primitive, so live trading bots and historical
backtests run the same code path.

What ships in this initial drop:

  crates/wickra-core   - 25 indicators, Indicator/BatchExt/Chain traits,
                          OHLCV types with validation; 171 unit tests,
                          property tests, Wilder/Bollinger textbook tests.
  crates/wickra        - top-level facade + criterion benches for every
                          indicator at 1K/10K/100K series sizes.
  crates/wickra-data   - streaming CSV reader, tick-to-candle aggregator,
                          multi-timeframe resampler, Binance Spot kline
                          WebSocket adapter behind feature live-binance;
                          11 unit + 1 doctest.
  bindings/python      - PyO3 + maturin, NumPy I/O, type stubs (.pyi),
                          56 pytest tests including streaming==batch
                          equivalence, Wilder reference values, lifecycle.
  bindings/node        - napi-rs native module, TypeScript .d.ts
                          auto-generated, 7 node --test cases.
  bindings/wasm        - wasm-bindgen ES module for browser/bundler/Node;
                          interactive HTML demo at examples/index.html.
  examples/            - Python and Rust scripts: backtest, live trading,
                          parallel multi-asset, multi-timeframe, Binance.
  benchmarks/          - cross-library comparison against TA-Lib,
                          pandas-ta, finta, talipp; Wickra wins every
                          category by 11-1030x (batch) and 17x+ streaming.
  .github/workflows/   - CI matrix (Rust + Python + Node + WASM on
                          Linux/macOS/Windows), release pipeline for
                          PyPI wheels and npm.

Indicators (25):
  Trend       SMA EMA WMA DEMA TEMA HMA KAMA
  Momentum    RSI MACD Stochastic CCI ROC WilliamsR ADX MFI TRIX
              AwesomeOscillator Aroon
  Volatility  BollingerBands ATR Keltner Donchian PSAR
  Volume      OBV VWAP (cumulative + rolling)

cargo clippy --workspace --all-targets -D warnings is clean. License: Apache-2.0.
This commit is contained in:
kingchenc
2026-05-21 17:50:45 +02:00
commit 3be267cb03
81 changed files with 14453 additions and 0 deletions
View File
+36
View File
@@ -0,0 +1,36 @@
"""Shared pytest fixtures for the Wickra Python test suite."""
from __future__ import annotations
import numpy as np
import pytest
@pytest.fixture
def linear_prices() -> np.ndarray:
"""Strictly increasing prices: 1, 2, 3, ..., 50."""
return np.arange(1.0, 51.0, dtype=np.float64)
@pytest.fixture
def constant_prices() -> np.ndarray:
"""50 prices of 100.0."""
return np.full(50, 100.0, dtype=np.float64)
@pytest.fixture
def sine_prices() -> np.ndarray:
"""Smooth sine-wave prices used to stress the indicators a little."""
t = np.arange(200, dtype=np.float64)
return 50.0 + 10.0 * np.sin(t * 0.13) + 4.0 * np.cos(t * 0.41)
@pytest.fixture
def ohlc_series() -> tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Synthetic high / low / close triple."""
t = np.arange(200, dtype=np.float64)
close = 100.0 + np.sin(t * 0.15) * 8.0 + np.cos(t * 0.32) * 3.0
spread = 0.5 + np.abs(np.sin(t * 0.07))
high = close + spread
low = close - spread
return high, low, close
+114
View File
@@ -0,0 +1,114 @@
"""Reference-value tests that pin numerical behaviour from the Python side."""
from __future__ import annotations
import math
import numpy as np
import pytest
import wickra as ta
def test_sma_constant_series():
out = ta.SMA(5).batch(np.full(20, 42.0, dtype=np.float64))
# First 4 are warmup -> NaN; rest equal 42.
assert np.all(np.isnan(out[:4]))
assert np.allclose(out[4:], 42.0)
def test_sma_known_window():
# SMA(3) of [2, 4, 6, 8, 10] -> [_, _, 4, 6, 8]
out = ta.SMA(3).batch(np.array([2.0, 4.0, 6.0, 8.0, 10.0]))
assert math.isnan(out[0]) and math.isnan(out[1])
np.testing.assert_allclose(out[2:], [4.0, 6.0, 8.0])
def test_ema_seed_equals_simple_mean_of_first_window():
# EMA(5) seed = mean([10, 20, 30, 40, 50]) = 30
out = ta.EMA(5).batch(np.array([10.0, 20.0, 30.0, 40.0, 50.0]))
assert math.isnan(out[0])
assert math.isclose(out[4], 30.0, abs_tol=1e-12)
def test_wma_known_window():
# WMA(4) of [1, 2, 3, 4] = (1*1 + 2*2 + 3*3 + 4*4)/10 = 3
out = ta.WMA(4).batch(np.array([1.0, 2.0, 3.0, 4.0]))
assert math.isnan(out[0]) and math.isnan(out[1]) and math.isnan(out[2])
assert math.isclose(out[3], 3.0, abs_tol=1e-12)
def test_rsi_pure_uptrend_is_100():
out = ta.RSI(14).batch(np.arange(1.0, 21.0, dtype=np.float64))
np.testing.assert_allclose(out[14:], 100.0)
def test_rsi_pure_downtrend_is_0():
out = ta.RSI(14).batch(np.arange(20.0, 0.0, -1.0))
np.testing.assert_allclose(out[14:], 0.0)
def test_rsi_flat_series_is_50():
out = ta.RSI(14).batch(np.full(30, 100.0))
np.testing.assert_allclose(out[14:], 50.0)
def test_rsi_wilder_textbook_first_value():
"""Wilder's original 14-period example, ~70.46 at the first emit."""
prices = np.array(
[
44.34, 44.09, 44.15, 43.61, 44.33, 44.83, 45.10, 45.42, 45.84, 46.08,
45.89, 46.03, 45.61, 46.28, 46.28,
],
dtype=np.float64,
)
out = ta.RSI(14).batch(prices)
assert math.isclose(out[14], 70.464, abs_tol=0.05)
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.
last = out[-1]
assert math.isclose(last[0], 0.0, abs_tol=1e-9)
assert math.isclose(last[1], 0.0, abs_tol=1e-9)
assert math.isclose(last[2], 0.0, abs_tol=1e-9)
def test_bollinger_constant_series_zero_width():
out = ta.BollingerBands(20, 2.0).batch(np.full(50, 100.0))
row = out[-1]
np.testing.assert_allclose(row, [100.0, 100.0, 100.0, 0.0], atol=1e-12)
def test_bollinger_upper_middle_lower_ordering():
out = ta.BollingerBands(20, 2.0).batch(np.linspace(50.0, 150.0, 100))
ready = out[~np.isnan(out[:, 0])]
assert np.all(ready[:, 0] >= ready[:, 1])
assert np.all(ready[:, 1] >= ready[:, 2])
assert np.all(ready[:, 3] >= 0.0)
def test_atr_constant_range_constant_output():
high = np.full(30, 11.0)
low = np.full(30, 9.0)
close = np.full(30, 10.0)
out = ta.ATR(14).batch(high, low, close)
# Once seeded, ATR equals the constant TR of 2.
np.testing.assert_allclose(out[13:], 2.0, atol=1e-12)
def test_stochastic_extremes():
# Close at the top of a 3-period range -> %K = 100.
high = np.array([10.0, 11.0, 12.0])
low = np.array([8.0, 9.0, 10.0])
close = np.array([9.0, 10.0, 12.0])
out = ta.Stochastic(3, 1).batch(high, low, close)
assert math.isclose(out[2, 0], 100.0, abs_tol=1e-12)
def test_obv_cumulative_known_sequence():
close = np.array([10.0, 11.0, 10.5, 10.5, 12.0])
volume = np.array([100.0, 20.0, 30.0, 40.0, 10.0])
out = ta.OBV().batch(close, volume)
np.testing.assert_allclose(out, [0.0, 20.0, -10.0, -10.0, 0.0])
+88
View File
@@ -0,0 +1,88 @@
"""Tests for the indicator lifecycle methods: reset, is_ready, warmup_period, repr."""
from __future__ import annotations
import numpy as np
import pytest
import wickra as ta
SCALAR_INDICATORS = [
(ta.SMA, (14,)),
(ta.EMA, (14,)),
(ta.WMA, (14,)),
(ta.RSI, (14,)),
(ta.MACD, ()),
(ta.BollingerBands, ()),
]
@pytest.mark.parametrize("cls, args", SCALAR_INDICATORS)
def test_is_ready_transitions_after_warmup(cls, args):
ind = cls(*args)
assert not ind.is_ready()
series = np.linspace(1.0, 200.0, 200)
ind.batch(series)
assert ind.is_ready()
@pytest.mark.parametrize("cls, args", SCALAR_INDICATORS)
def test_reset_returns_to_initial_state(cls, args):
ind = cls(*args)
ind.batch(np.linspace(1.0, 200.0, 200))
assert ind.is_ready()
ind.reset()
assert not ind.is_ready()
@pytest.mark.parametrize(
"cls, args, period",
[
(ta.SMA, (14,), 14),
(ta.EMA, (14,), 14),
(ta.WMA, (14,), 14),
(ta.RSI, (14,), 15),
(ta.BollingerBands, (20, 2.0), 20),
],
)
def test_warmup_period(cls, args, period):
assert cls(*args).warmup_period() == period
def test_repr_contains_class_and_parameters():
assert "SMA" in repr(ta.SMA(14))
assert "14" in repr(ta.SMA(14))
assert "BollingerBands" in repr(ta.BollingerBands(20, 2.0))
def test_constructor_rejects_zero_period():
with pytest.raises(ValueError):
ta.SMA(0)
with pytest.raises(ValueError):
ta.RSI(0)
def test_macd_rejects_fast_geq_slow():
with pytest.raises(ValueError):
ta.MACD(fast=26, slow=12, signal=9)
def test_bollinger_rejects_non_positive_multiplier():
with pytest.raises(ValueError):
ta.BollingerBands(20, 0.0)
with pytest.raises(ValueError):
ta.BollingerBands(20, -1.0)
def test_candle_dict_input_supported():
atr = ta.ATR(2)
atr.update({"open": 10.0, "high": 11.0, "low": 9.0, "close": 10.5, "volume": 1.0})
v = atr.update({"open": 10.5, "high": 12.0, "low": 10.0, "close": 11.0, "volume": 1.0})
assert v is not None
def test_candle_tuple_input_supported():
atr = ta.ATR(2)
atr.update((10.0, 11.0, 9.0, 10.5, 1.0, 0))
v = atr.update((10.5, 12.0, 10.0, 11.0, 1.0, 1))
assert v is not None
+57
View File
@@ -0,0 +1,57 @@
"""Smoke tests: every public class can be constructed and emits the right shape."""
from __future__ import annotations
import numpy as np
import pytest
import wickra as ta
def test_version_is_a_nonempty_string():
assert isinstance(ta.__version__, str)
assert ta.__version__
@pytest.mark.parametrize(
"cls, args",
[
(ta.SMA, (14,)),
(ta.EMA, (14,)),
(ta.WMA, (14,)),
(ta.RSI, (14,)),
],
)
def test_scalar_batch_returns_same_length(cls, args, sine_prices):
out = cls(*args).batch(sine_prices)
assert out.shape == sine_prices.shape
assert out.dtype == np.float64
def test_macd_batch_returns_n_by_3(sine_prices):
out = ta.MACD().batch(sine_prices)
assert out.shape == (sine_prices.size, 3)
def test_bollinger_batch_returns_n_by_4(sine_prices):
out = ta.BollingerBands().batch(sine_prices)
assert out.shape == (sine_prices.size, 4)
def test_atr_batch_shape(ohlc_series):
high, low, close = ohlc_series
out = ta.ATR(14).batch(high, low, close)
assert out.shape == close.shape
def test_stochastic_batch_shape(ohlc_series):
high, low, close = ohlc_series
out = ta.Stochastic(14, 3).batch(high, low, close)
assert out.shape == (close.size, 2)
def test_obv_batch_shape(ohlc_series):
_, _, close = ohlc_series
volume = np.ones_like(close)
out = ta.OBV().batch(close, volume)
assert out.shape == close.shape
@@ -0,0 +1,117 @@
"""For every indicator, batch(prices) must equal repeated update(price).
This is the central correctness contract of Wickra: the two APIs share one
implementation, so they cannot disagree. These tests verify it from Python
across the entire warmup → steady-state transition.
"""
from __future__ import annotations
import math
import numpy as np
import pytest
import wickra as ta
def _equal_with_nan(a: np.ndarray, b: np.ndarray, tol: float = 1e-9) -> bool:
"""NumPy ``==`` treats NaN as not-equal; emulate ``equal_nan`` for floats."""
if a.shape != b.shape:
return False
both_nan = np.isnan(a) & np.isnan(b)
diff_ok = np.where(both_nan, 0.0, np.abs(a - b))
return bool(np.all(diff_ok <= tol))
@pytest.mark.parametrize(
"cls, args",
[
(ta.SMA, (14,)),
(ta.EMA, (14,)),
(ta.WMA, (14,)),
(ta.RSI, (14,)),
],
)
def test_scalar_streaming_matches_batch(cls, args, sine_prices):
batch = cls(*args).batch(sine_prices)
streamer = cls(*args)
streamed = np.array(
[streamer.update(float(p)) if streamer is not None else None for p in sine_prices],
dtype=object,
)
# Map None -> NaN to compare against batch.
streamed = np.array(
[math.nan if v is None else float(v) for v in streamed], dtype=np.float64
)
assert _equal_with_nan(batch, streamed)
def test_macd_streaming_matches_batch(sine_prices):
batch = ta.MACD().batch(sine_prices)
streamer = ta.MACD()
rows = []
for p in sine_prices:
v = streamer.update(float(p))
if v is None:
rows.append([math.nan, math.nan, math.nan])
else:
rows.append(list(v))
streamed = np.array(rows, dtype=np.float64)
assert _equal_with_nan(batch, streamed)
def test_bollinger_streaming_matches_batch(sine_prices):
batch = ta.BollingerBands().batch(sine_prices)
streamer = ta.BollingerBands()
rows = []
for p in sine_prices:
v = streamer.update(float(p))
if v is None:
rows.append([math.nan, math.nan, math.nan, math.nan])
else:
rows.append(list(v))
streamed = np.array(rows, dtype=np.float64)
assert _equal_with_nan(batch, streamed)
def test_atr_streaming_matches_batch(ohlc_series):
high, low, close = ohlc_series
batch = ta.ATR(14).batch(high, low, close)
streamer = ta.ATR(14)
rows = []
for h, l, c in zip(high, low, close):
rows.append(streamer.update((float(c), float(h), float(l), float(c), 0.0, 0)))
streamed = np.array([math.nan if v is None else v for v in rows], dtype=np.float64)
assert _equal_with_nan(batch, streamed)
def test_stochastic_streaming_matches_batch(ohlc_series):
high, low, close = ohlc_series
batch = ta.Stochastic(14, 3).batch(high, low, close)
streamer = ta.Stochastic(14, 3)
rows = []
for h, l, c in zip(high, low, close):
v = streamer.update((float(c), float(h), float(l), float(c), 0.0, 0))
rows.append([math.nan, math.nan] if v is None else list(v))
streamed = np.array(rows, dtype=np.float64)
assert _equal_with_nan(batch, streamed)
def test_obv_streaming_matches_batch(ohlc_series):
_, _, close = ohlc_series
volume = np.ones_like(close)
batch = ta.OBV().batch(close, volume)
streamer = ta.OBV()
rows = []
for c, v in zip(close, volume):
rows.append(streamer.update((float(c), float(c), float(c), float(c), float(v), 0)))
streamed = np.array([math.nan if x is None else x for x in rows], dtype=np.float64)
assert _equal_with_nan(batch, streamed)