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:
@@ -0,0 +1,114 @@
|
||||
"""Offline backtest example: compute a basket of indicators over a CSV history.
|
||||
|
||||
Run with::
|
||||
|
||||
python -m examples.python.backtest path/to/ohlcv.csv
|
||||
|
||||
The CSV must have a header row with at least the columns
|
||||
``timestamp, open, high, low, close, volume``. The script computes a panel of
|
||||
indicators with the standard parameters used across Wickra's tests and
|
||||
prints a small summary of the resulting series — enough to verify that the
|
||||
indicators are wired correctly without pulling in pandas or a charting stack.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
from typing import List
|
||||
|
||||
import numpy as np
|
||||
|
||||
import wickra as ta
|
||||
|
||||
|
||||
@dataclass
|
||||
class History:
|
||||
timestamp: np.ndarray
|
||||
open: np.ndarray
|
||||
high: np.ndarray
|
||||
low: np.ndarray
|
||||
close: np.ndarray
|
||||
volume: np.ndarray
|
||||
|
||||
|
||||
def read_history(path: str) -> History:
|
||||
"""Load an OHLCV CSV into typed NumPy columns."""
|
||||
rows: List[List[str]] = []
|
||||
with open(path, newline="") as f:
|
||||
reader = csv.DictReader(f)
|
||||
for row in reader:
|
||||
rows.append(
|
||||
[
|
||||
row["timestamp"],
|
||||
row["open"],
|
||||
row["high"],
|
||||
row["low"],
|
||||
row["close"],
|
||||
row["volume"],
|
||||
]
|
||||
)
|
||||
if not rows:
|
||||
raise ValueError("CSV is empty")
|
||||
arr = np.array(rows, dtype=np.float64)
|
||||
return History(
|
||||
timestamp=arr[:, 0].astype(np.int64),
|
||||
open=arr[:, 1],
|
||||
high=arr[:, 2],
|
||||
low=arr[:, 3],
|
||||
close=arr[:, 4],
|
||||
volume=arr[:, 5],
|
||||
)
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
p = argparse.ArgumentParser(description=__doc__.splitlines()[0] if __doc__ else None)
|
||||
p.add_argument("path", help="Path to an OHLCV CSV file")
|
||||
p.add_argument("--rsi", type=int, default=14)
|
||||
p.add_argument("--ema", type=int, default=20)
|
||||
p.add_argument("--bb-period", type=int, default=20)
|
||||
p.add_argument("--bb-mult", type=float, default=2.0)
|
||||
return p.parse_args()
|
||||
|
||||
|
||||
def summarize(name: str, values: np.ndarray) -> None:
|
||||
valid = values[~np.isnan(values)]
|
||||
if valid.size == 0:
|
||||
print(f" {name:<12} (no valid samples — series too short)")
|
||||
return
|
||||
print(
|
||||
f" {name:<12} mean={valid.mean():>10.4f} min={valid.min():>10.4f} "
|
||||
f"max={valid.max():>10.4f} last={valid[-1]:>10.4f}"
|
||||
)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
args = parse_args()
|
||||
history = read_history(args.path)
|
||||
|
||||
rsi = ta.RSI(args.rsi).batch(history.close)
|
||||
ema = ta.EMA(args.ema).batch(history.close)
|
||||
macd = ta.MACD().batch(history.close) # shape (n, 3)
|
||||
bb = ta.BollingerBands(args.bb_period, args.bb_mult).batch(history.close) # (n, 4)
|
||||
atr = ta.ATR(14).batch(history.high, history.low, history.close)
|
||||
adx = ta.ADX(14).batch(history.high, history.low, history.close) # (n, 3)
|
||||
obv = ta.OBV().batch(history.close, history.volume)
|
||||
|
||||
print(f"Backtest summary for {args.path} ({history.close.size} bars)")
|
||||
summarize(f"RSI({args.rsi})", rsi)
|
||||
summarize(f"EMA({args.ema})", ema)
|
||||
summarize("MACD line", macd[:, 0])
|
||||
summarize("MACD hist", macd[:, 2])
|
||||
summarize(f"BB upper", bb[:, 0])
|
||||
summarize(f"BB lower", bb[:, 2])
|
||||
summarize("ATR(14)", atr)
|
||||
summarize("ADX(14)", adx[:, 2])
|
||||
summarize("OBV", obv)
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,146 @@
|
||||
"""Live trading skeleton: stream Binance kline ticks → incremental indicators → signals.
|
||||
|
||||
This example connects to Binance's public WebSocket feed (no API key needed)
|
||||
and runs RSI / MACD / Bollinger Bands on the close prices coming in. When the
|
||||
RSI crosses common overbought / oversold thresholds *and* the MACD histogram
|
||||
confirms the direction, a `Signal` event is printed. No orders are placed.
|
||||
|
||||
Run with::
|
||||
|
||||
python -m examples.python.live_trading --symbol BTCUSDT --interval 1m
|
||||
|
||||
Dependencies::
|
||||
|
||||
pip install websockets
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import signal
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
|
||||
import wickra as ta
|
||||
|
||||
try:
|
||||
import websockets
|
||||
except ImportError:
|
||||
print("This example needs the `websockets` package: pip install websockets", file=sys.stderr)
|
||||
raise
|
||||
|
||||
|
||||
BINANCE_WS = "wss://stream.binance.com:9443/stream"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Snapshot:
|
||||
rsi: Optional[float]
|
||||
macd_hist: Optional[float]
|
||||
bb_upper: Optional[float]
|
||||
bb_middle: Optional[float]
|
||||
bb_lower: Optional[float]
|
||||
close: float
|
||||
|
||||
|
||||
class StrategyState:
|
||||
"""Holds one streaming instance of each indicator and computes signals."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.rsi = ta.RSI(14)
|
||||
self.macd = ta.MACD()
|
||||
self.bb = ta.BollingerBands(20, 2.0)
|
||||
|
||||
def update(self, close: float) -> Snapshot:
|
||||
rsi = self.rsi.update(float(close))
|
||||
macd_v = self.macd.update(float(close))
|
||||
bb_v = self.bb.update(float(close))
|
||||
return Snapshot(
|
||||
rsi=rsi,
|
||||
macd_hist=macd_v[2] if macd_v else None,
|
||||
bb_upper=bb_v[0] if bb_v else None,
|
||||
bb_middle=bb_v[1] if bb_v else None,
|
||||
bb_lower=bb_v[2] if bb_v else None,
|
||||
close=float(close),
|
||||
)
|
||||
|
||||
|
||||
def emit_signal(snap: Snapshot, log: logging.Logger) -> None:
|
||||
if snap.rsi is None or snap.macd_hist is None or snap.bb_upper is None:
|
||||
return
|
||||
if snap.rsi > 70 and snap.macd_hist < 0 and snap.close >= snap.bb_upper:
|
||||
log.warning(
|
||||
"SELL candidate: rsi=%.1f hist=%.4f close=%.4f >= bb_upper=%.4f",
|
||||
snap.rsi, snap.macd_hist, snap.close, snap.bb_upper,
|
||||
)
|
||||
elif snap.rsi < 30 and snap.macd_hist > 0 and snap.close <= snap.bb_lower:
|
||||
log.warning(
|
||||
"BUY candidate: rsi=%.1f hist=%.4f close=%.4f <= bb_lower=%.4f",
|
||||
snap.rsi, snap.macd_hist, snap.close, snap.bb_lower,
|
||||
)
|
||||
|
||||
|
||||
async def run(symbol: str, interval: str) -> None:
|
||||
stream = f"{symbol.lower()}@kline_{interval}"
|
||||
url = f"{BINANCE_WS}?streams={stream}"
|
||||
log = logging.getLogger("wickra-live")
|
||||
state = StrategyState()
|
||||
log.info("Connecting to %s", url)
|
||||
async with websockets.connect(url, ping_interval=20) as ws:
|
||||
log.info("Connected, listening for %s klines", stream)
|
||||
async for raw in ws:
|
||||
envelope = json.loads(raw)
|
||||
payload = envelope.get("data", {})
|
||||
k = payload.get("k", {})
|
||||
close = float(k.get("c"))
|
||||
is_closed = bool(k.get("x"))
|
||||
snap = state.update(close)
|
||||
log.info(
|
||||
"%s close=%.4f rsi=%s hist=%s bb=%s",
|
||||
"BAR" if is_closed else "tick",
|
||||
close,
|
||||
f"{snap.rsi:.1f}" if snap.rsi else "--",
|
||||
f"{snap.macd_hist:+.4f}" if snap.macd_hist else "--",
|
||||
f"{snap.bb_lower:.2f}/{snap.bb_middle:.2f}/{snap.bb_upper:.2f}"
|
||||
if snap.bb_upper
|
||||
else "--",
|
||||
)
|
||||
emit_signal(snap, log)
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
p = argparse.ArgumentParser(description=__doc__.splitlines()[0] if __doc__ else None)
|
||||
p.add_argument("--symbol", default="BTCUSDT", help="trading pair")
|
||||
p.add_argument("--interval", default="1m", help="Binance kline interval")
|
||||
p.add_argument("--verbose", action="store_true")
|
||||
return p.parse_args()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
args = parse_args()
|
||||
logging.basicConfig(
|
||||
level=logging.DEBUG if args.verbose else logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(message)s",
|
||||
)
|
||||
loop = asyncio.new_event_loop()
|
||||
# Translate Ctrl+C into a clean loop stop.
|
||||
for sig in (signal.SIGINT, signal.SIGTERM):
|
||||
try:
|
||||
loop.add_signal_handler(sig, loop.stop)
|
||||
except NotImplementedError:
|
||||
pass # Windows does not support add_signal_handler for SIGTERM.
|
||||
try:
|
||||
loop.run_until_complete(run(args.symbol, args.interval))
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
finally:
|
||||
loop.close()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,110 @@
|
||||
"""Compute indicators on multiple timeframes from a single 1-minute feed.
|
||||
|
||||
Wickra exposes resampling on the Rust side (in `wickra-data`); from Python we
|
||||
roll up bars manually using NumPy because most users already have their data
|
||||
in a NumPy array and don't need the streaming-resample infrastructure for
|
||||
offline analysis.
|
||||
|
||||
Run with::
|
||||
|
||||
python -m examples.python.multi_timeframe path/to/1m.csv
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
from typing import Iterable, List, Tuple
|
||||
|
||||
import numpy as np
|
||||
|
||||
import wickra as ta
|
||||
|
||||
|
||||
def read_csv(path: str) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
|
||||
"""Read an OHLCV CSV into typed columns."""
|
||||
ts, o, h, l, c, v = [], [], [], [], [], []
|
||||
with open(path, newline="") as f:
|
||||
for row in csv.DictReader(f):
|
||||
ts.append(int(row["timestamp"]))
|
||||
o.append(float(row["open"]))
|
||||
h.append(float(row["high"]))
|
||||
l.append(float(row["low"]))
|
||||
c.append(float(row["close"]))
|
||||
v.append(float(row["volume"]))
|
||||
return (
|
||||
np.asarray(ts, dtype=np.int64),
|
||||
np.asarray(o, dtype=np.float64),
|
||||
np.asarray(h, dtype=np.float64),
|
||||
np.asarray(l, dtype=np.float64),
|
||||
np.asarray(c, dtype=np.float64),
|
||||
np.asarray(v, dtype=np.float64),
|
||||
)
|
||||
|
||||
|
||||
def resample(
|
||||
ts: np.ndarray,
|
||||
o: np.ndarray,
|
||||
h: np.ndarray,
|
||||
l: np.ndarray,
|
||||
c: np.ndarray,
|
||||
v: np.ndarray,
|
||||
bucket: int,
|
||||
) -> Tuple[np.ndarray, ...]:
|
||||
"""Aggregate bar-level columns into coarser buckets of size `bucket`."""
|
||||
bucket_index = (ts // bucket).astype(np.int64)
|
||||
boundaries = np.diff(bucket_index, prepend=bucket_index[0] - 1) != 0
|
||||
group_ids = np.cumsum(boundaries) - 1
|
||||
n_groups = int(group_ids.max()) + 1
|
||||
|
||||
new_ts = np.empty(n_groups, dtype=np.int64)
|
||||
new_o = np.empty(n_groups, dtype=np.float64)
|
||||
new_h = np.empty(n_groups, dtype=np.float64)
|
||||
new_l = np.empty(n_groups, dtype=np.float64)
|
||||
new_c = np.empty(n_groups, dtype=np.float64)
|
||||
new_v = np.empty(n_groups, dtype=np.float64)
|
||||
|
||||
for g in range(n_groups):
|
||||
mask = group_ids == g
|
||||
new_ts[g] = ts[mask][0]
|
||||
new_o[g] = o[mask][0]
|
||||
new_h[g] = h[mask].max()
|
||||
new_l[g] = l[mask].min()
|
||||
new_c[g] = c[mask][-1]
|
||||
new_v[g] = v[mask].sum()
|
||||
return new_ts, new_o, new_h, new_l, new_c, new_v
|
||||
|
||||
|
||||
def summarize(label: str, close: np.ndarray, high: np.ndarray, low: np.ndarray) -> None:
|
||||
rsi = ta.RSI(14).batch(close)
|
||||
macd = ta.MACD().batch(close)
|
||||
adx = ta.ADX(14).batch(high, low, close)
|
||||
last_macd_hist = macd[~np.isnan(macd[:, 2])][-1, 2] if np.any(~np.isnan(macd[:, 2])) else float("nan")
|
||||
last_adx = adx[~np.isnan(adx[:, 2])][-1, 2] if np.any(~np.isnan(adx[:, 2])) else float("nan")
|
||||
print(
|
||||
f" {label:<10} bars={close.size:>5} "
|
||||
f"last_close={close[-1]:>10.4f} rsi={rsi[~np.isnan(rsi)][-1]:>6.2f} "
|
||||
f"macd_hist={last_macd_hist:+.4f} adx={last_adx:>6.2f}"
|
||||
)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
p = argparse.ArgumentParser(description=__doc__.splitlines()[0] if __doc__ else None)
|
||||
p.add_argument("path", help="Path to a 1-minute OHLCV CSV (timestamps in milliseconds)")
|
||||
args = p.parse_args()
|
||||
|
||||
ts, o, h, l, c, v = read_csv(args.path)
|
||||
one_minute = 60_000
|
||||
|
||||
print(f"Multi-timeframe view of {args.path}")
|
||||
summarize("1m", c, h, l)
|
||||
for label, bucket in [("5m", 5), ("15m", 15), ("1h", 60), ("4h", 240), ("1d", 1440)]:
|
||||
if ts.size < bucket:
|
||||
continue
|
||||
rs_ts, rs_o, rs_h, rs_l, rs_c, rs_v = resample(ts, o, h, l, c, v, bucket * one_minute)
|
||||
summarize(label, rs_c, rs_h, rs_l)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Process indicators for many symbols in parallel.
|
||||
|
||||
Python's GIL makes pure-Python parallelism a poor fit, but Wickra's heavy
|
||||
lifting happens inside the Rust extension — which releases the GIL during
|
||||
batch computation. That means a `ThreadPoolExecutor` actually delivers
|
||||
multi-core speedup here.
|
||||
|
||||
Run with::
|
||||
|
||||
python -m examples.python.parallel_assets --assets 1000 --bars 5000
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import concurrent.futures
|
||||
import time
|
||||
from typing import Tuple
|
||||
|
||||
import numpy as np
|
||||
|
||||
import wickra as ta
|
||||
|
||||
|
||||
def synthesize_panel(n_assets: int, n_bars: int, seed: int = 0xBADC0FFEE0DDF00D) -> np.ndarray:
|
||||
"""Build an `(n_assets, n_bars)` matrix of synthetic prices."""
|
||||
rng = np.random.default_rng(seed & 0xFFFF_FFFF)
|
||||
drift = rng.standard_normal((n_assets, n_bars)) * 0.4
|
||||
return 100.0 + np.cumsum(drift, axis=1)
|
||||
|
||||
|
||||
def compute_one(prices: np.ndarray) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
|
||||
"""Return (RSI, EMA, MACD-line) for one asset."""
|
||||
rsi = ta.RSI(14).batch(prices)
|
||||
ema = ta.EMA(20).batch(prices)
|
||||
macd = ta.MACD().batch(prices)
|
||||
return rsi, ema, macd[:, 0]
|
||||
|
||||
|
||||
def main() -> int:
|
||||
p = argparse.ArgumentParser(description=__doc__.splitlines()[0] if __doc__ else None)
|
||||
p.add_argument("--assets", type=int, default=200)
|
||||
p.add_argument("--bars", type=int, default=5000)
|
||||
p.add_argument(
|
||||
"--workers",
|
||||
type=int,
|
||||
default=0,
|
||||
help="thread pool size; 0 means use os.cpu_count()",
|
||||
)
|
||||
args = p.parse_args()
|
||||
|
||||
print(f"Generating {args.assets}x{args.bars} synthetic panel…")
|
||||
panel = synthesize_panel(args.assets, args.bars)
|
||||
|
||||
# Serial baseline.
|
||||
t0 = time.perf_counter()
|
||||
serial_results = [compute_one(panel[i]) for i in range(args.assets)]
|
||||
t_serial = time.perf_counter() - t0
|
||||
print(f"Serial: {t_serial:.3f} s ({args.assets} assets)")
|
||||
|
||||
# Parallel.
|
||||
workers = args.workers or None
|
||||
t0 = time.perf_counter()
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool:
|
||||
parallel_results = list(pool.map(compute_one, panel))
|
||||
t_parallel = time.perf_counter() - t0
|
||||
used = workers or 0
|
||||
print(
|
||||
f"Parallel: {t_parallel:.3f} s (workers={used or 'os.cpu_count()'}, "
|
||||
f"speedup ~{t_serial / max(t_parallel, 1e-9):.2f}x)"
|
||||
)
|
||||
|
||||
# Sanity-check that the parallel results match the serial baseline.
|
||||
for i in range(args.assets):
|
||||
for s, p_ in zip(serial_results[i], parallel_results[i]):
|
||||
np.testing.assert_array_equal(s, p_)
|
||||
print("Parallel results match serial results — OK.")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user