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,30 @@
|
||||
[package]
|
||||
name = "wickra-node"
|
||||
description = "Node.js bindings for the Wickra streaming-first technical indicators library."
|
||||
version.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
# napi-build emits `cargo::` directives that require Rust >= 1.77; the rest of
|
||||
# the workspace stays at 1.75 because the core crate has no such dependency.
|
||||
rust-version = "1.77"
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
homepage.workspace = true
|
||||
readme.workspace = true
|
||||
keywords.workspace = true
|
||||
categories.workspace = true
|
||||
publish = false
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
wickra-core = { workspace = true }
|
||||
napi = { version = "2.16", features = ["napi8"] }
|
||||
napi-derive = "2.16"
|
||||
|
||||
[build-dependencies]
|
||||
napi-build = "2"
|
||||
@@ -0,0 +1,45 @@
|
||||
# @wickra/wickra
|
||||
|
||||
Node.js bindings for the Wickra streaming-first technical indicators library.
|
||||
|
||||
## Install
|
||||
|
||||
Once published, install per platform via the precompiled native package:
|
||||
|
||||
```bash
|
||||
npm install @wickra/wickra
|
||||
```
|
||||
|
||||
## Build from source
|
||||
|
||||
```bash
|
||||
cd bindings/node
|
||||
npm install
|
||||
npm run build
|
||||
npm test
|
||||
```
|
||||
|
||||
The native module is built via [napi-rs](https://napi.rs/). The build script
|
||||
produces a `wickra.<platform>-<arch>.node` binary in the package root that
|
||||
`index.js` loads at runtime.
|
||||
|
||||
## Usage
|
||||
|
||||
```js
|
||||
import { SMA, RSI, MACD, version } from '@wickra/wickra';
|
||||
|
||||
console.log('wickra', version());
|
||||
|
||||
// Batch:
|
||||
const prices = Array.from({ length: 1000 }, (_, i) => 100 + Math.sin(i * 0.1) * 5);
|
||||
const rsi = new RSI(14).batch(prices);
|
||||
|
||||
// Streaming:
|
||||
const macd = new MACD(12, 26, 9);
|
||||
for (const p of livePriceStream) {
|
||||
const v = macd.update(p);
|
||||
if (v && v.histogram > 0) console.log('bullish crossover candidate');
|
||||
}
|
||||
```
|
||||
|
||||
See `index.d.ts` for the full TypeScript surface.
|
||||
@@ -0,0 +1,82 @@
|
||||
// Smoke tests for the Wickra Node bindings.
|
||||
//
|
||||
// Run with:
|
||||
// cd bindings/node && npm install && npm run build && npm test
|
||||
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const wickra = require('..');
|
||||
|
||||
test('version is non-empty', () => {
|
||||
assert.ok(typeof wickra.version() === 'string');
|
||||
assert.ok(wickra.version().length > 0);
|
||||
});
|
||||
|
||||
test('SMA batch matches reference values', () => {
|
||||
const sma = new wickra.SMA(3);
|
||||
const out = sma.batch([2, 4, 6, 8, 10]);
|
||||
assert.ok(Number.isNaN(out[0]));
|
||||
assert.ok(Number.isNaN(out[1]));
|
||||
assert.equal(out[2], 4);
|
||||
assert.equal(out[3], 6);
|
||||
assert.equal(out[4], 8);
|
||||
});
|
||||
|
||||
test('RSI pure uptrend yields 100', () => {
|
||||
const rsi = new wickra.RSI(14);
|
||||
const prices = Array.from({ length: 20 }, (_, i) => i + 1);
|
||||
const out = rsi.batch(prices);
|
||||
for (let i = 14; i < out.length; i++) {
|
||||
assert.equal(out[i], 100);
|
||||
}
|
||||
});
|
||||
|
||||
test('streaming and batch agree on EMA', () => {
|
||||
const prices = Array.from({ length: 60 }, (_, i) => 100 + Math.sin(i * 0.3) * 5);
|
||||
const batch = new wickra.EMA(14).batch(prices);
|
||||
const ema = new wickra.EMA(14);
|
||||
const streamed = prices.map((p) => {
|
||||
const v = ema.update(p);
|
||||
return v === null || v === undefined ? NaN : v;
|
||||
});
|
||||
for (let i = 0; i < prices.length; i++) {
|
||||
if (Number.isNaN(batch[i])) {
|
||||
assert.ok(Number.isNaN(streamed[i]));
|
||||
} else {
|
||||
assert.ok(Math.abs(batch[i] - streamed[i]) < 1e-9);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('MACD returns macd/signal/histogram object', () => {
|
||||
const macd = new wickra.MACD(12, 26, 9);
|
||||
let value = null;
|
||||
for (let i = 1; i <= 60; i++) {
|
||||
value = macd.update(i);
|
||||
}
|
||||
assert.ok(value);
|
||||
assert.equal(typeof value.macd, 'number');
|
||||
assert.equal(typeof value.signal, 'number');
|
||||
assert.equal(typeof value.histogram, 'number');
|
||||
assert.ok(Math.abs(value.histogram - (value.macd - value.signal)) < 1e-9);
|
||||
});
|
||||
|
||||
test('ATR batch shape', () => {
|
||||
const high = Array.from({ length: 30 }, () => 11);
|
||||
const low = Array.from({ length: 30 }, () => 9);
|
||||
const close = Array.from({ length: 30 }, () => 10);
|
||||
const out = new wickra.ATR(14).batch(high, low, close);
|
||||
assert.equal(out.length, 30);
|
||||
// Once seeded, ATR is the constant TR of 2.
|
||||
for (let i = 13; i < 30; i++) {
|
||||
assert.ok(Math.abs(out[i] - 2) < 1e-9);
|
||||
}
|
||||
});
|
||||
|
||||
test('zero period is clamped to a valid window', () => {
|
||||
// Constructors cannot throw from JS (napi-rs 2.16 limitation), so they
|
||||
// clamp pathological values like period=0 to the smallest valid window.
|
||||
const sma = new wickra.SMA(0);
|
||||
assert.equal(sma.warmupPeriod(), 1);
|
||||
assert.equal(sma.update(42), 42);
|
||||
});
|
||||
@@ -0,0 +1,5 @@
|
||||
extern crate napi_build;
|
||||
|
||||
fn main() {
|
||||
napi_build::setup();
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
/* eslint-disable */
|
||||
/* prettier-ignore */
|
||||
// This loader is generated by `napi build --platform` at publish time. For
|
||||
// editable development just `require` the local debug binary that napi places
|
||||
// at the package root.
|
||||
|
||||
const { join } = require('node:path');
|
||||
const { existsSync } = require('node:fs');
|
||||
const { platform, arch } = process;
|
||||
|
||||
function loadNative() {
|
||||
// Try precompiled per-platform binary first (published wheels do this).
|
||||
const candidates = [
|
||||
`./wickra.${platform}-${arch}.node`,
|
||||
`./wickra.${platform}-${arch}-musl.node`,
|
||||
'./wickra.node',
|
||||
];
|
||||
for (const c of candidates) {
|
||||
const p = join(__dirname, c);
|
||||
if (existsSync(p)) {
|
||||
return require(p);
|
||||
}
|
||||
}
|
||||
throw new Error(
|
||||
`Wickra: no precompiled binary found for ${platform}-${arch}. ` +
|
||||
'Build from source with `napi build --release` or install a platform-specific package.'
|
||||
);
|
||||
}
|
||||
|
||||
module.exports = loadNative();
|
||||
@@ -0,0 +1,56 @@
|
||||
{
|
||||
"name": "@wickra/wickra",
|
||||
"version": "0.1.0",
|
||||
"description": "Streaming-first technical indicators: incremental, fast, install-free. Node bindings powered by Rust.",
|
||||
"main": "index.js",
|
||||
"types": "index.d.ts",
|
||||
"license": "Apache-2.0",
|
||||
"keywords": [
|
||||
"trading",
|
||||
"indicators",
|
||||
"technical-analysis",
|
||||
"ta-lib",
|
||||
"finance",
|
||||
"streaming",
|
||||
"rust"
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/wickra/wickra"
|
||||
},
|
||||
"files": [
|
||||
"index.js",
|
||||
"index.d.ts",
|
||||
"npm",
|
||||
"*.node"
|
||||
],
|
||||
"napi": {
|
||||
"name": "wickra",
|
||||
"triples": {
|
||||
"defaults": true,
|
||||
"additional": [
|
||||
"x86_64-unknown-linux-musl",
|
||||
"aarch64-unknown-linux-gnu",
|
||||
"i686-pc-windows-msvc",
|
||||
"armv7-unknown-linux-gnueabihf",
|
||||
"aarch64-apple-darwin",
|
||||
"aarch64-linux-android",
|
||||
"x86_64-unknown-freebsd",
|
||||
"aarch64-unknown-linux-musl",
|
||||
"aarch64-pc-windows-msvc"
|
||||
]
|
||||
}
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 16"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "napi build --platform --release",
|
||||
"build:debug": "napi build --platform",
|
||||
"prepublishOnly": "napi prepublish -t npm",
|
||||
"test": "node --test __tests__/"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@napi-rs/cli": "^2.18.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,723 @@
|
||||
//! Node.js bindings for Wickra via napi-rs.
|
||||
//!
|
||||
//! Build with:
|
||||
//! ```text
|
||||
//! cd bindings/node && npm install && npm run build
|
||||
//! ```
|
||||
//!
|
||||
//! Then `require("@wickra/wickra")` from Node.
|
||||
|
||||
#![allow(clippy::needless_pass_by_value)]
|
||||
#![allow(missing_debug_implementations)] // napi-derive auto-generates the Node-facing types.
|
||||
#![allow(clippy::unused_self)]
|
||||
#![allow(clippy::missing_const_for_fn)]
|
||||
|
||||
use napi::Error as NapiError;
|
||||
use napi::Status;
|
||||
use napi_derive::napi;
|
||||
use wickra_core as wc;
|
||||
use wickra_core::{BatchExt, Indicator};
|
||||
|
||||
fn map_err(e: wc::Error) -> NapiError {
|
||||
NapiError::new(Status::InvalidArg, e.to_string())
|
||||
}
|
||||
|
||||
/// Helper for constructors. `#[napi(constructor)]` in napi-rs 2.16 only accepts
|
||||
/// an infallible `Self` return, so we clamp parameters to the smallest valid value
|
||||
/// (which only matters for the pathological `period = 0` case) and then `expect`
|
||||
/// the rest, which can only fail for invariants that hold by construction.
|
||||
fn must<T>(r: Result<T, wc::Error>) -> T {
|
||||
r.expect("wickra: invalid indicator parameters")
|
||||
}
|
||||
|
||||
/// Clamp a period parameter so the underlying indicator never sees zero. JS
|
||||
/// callers who pass `0` get a window of `1` instead of a thrown exception —
|
||||
/// effectively a pass-through indicator that still produces valid outputs.
|
||||
const fn clamp_period(p: u32) -> usize {
|
||||
if p == 0 {
|
||||
1
|
||||
} else {
|
||||
p as usize
|
||||
}
|
||||
}
|
||||
|
||||
fn flatten(v: Vec<Option<f64>>) -> Vec<f64> {
|
||||
v.into_iter().map(|x| x.unwrap_or(f64::NAN)).collect()
|
||||
}
|
||||
|
||||
/// Library version (matches the Rust crate version).
|
||||
#[napi]
|
||||
pub fn version() -> String {
|
||||
env!("CARGO_PKG_VERSION").to_string()
|
||||
}
|
||||
|
||||
// ============================== Scalar indicators ==============================
|
||||
|
||||
macro_rules! node_scalar_indicator {
|
||||
($wrapper:ident, $node_name:literal, $rust_ty:ty) => {
|
||||
#[napi(js_name = $node_name)]
|
||||
pub struct $wrapper {
|
||||
inner: $rust_ty,
|
||||
}
|
||||
|
||||
#[napi]
|
||||
impl $wrapper {
|
||||
#[napi(constructor)]
|
||||
pub fn new(period: u32) -> Self {
|
||||
Self {
|
||||
inner: must(<$rust_ty>::new(clamp_period(period))),
|
||||
}
|
||||
}
|
||||
#[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))
|
||||
}
|
||||
#[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
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
node_scalar_indicator!(SmaNode, "SMA", wc::Sma);
|
||||
node_scalar_indicator!(EmaNode, "EMA", wc::Ema);
|
||||
node_scalar_indicator!(WmaNode, "WMA", wc::Wma);
|
||||
node_scalar_indicator!(RsiNode, "RSI", wc::Rsi);
|
||||
node_scalar_indicator!(DemaNode, "DEMA", wc::Dema);
|
||||
node_scalar_indicator!(TemaNode, "TEMA", wc::Tema);
|
||||
node_scalar_indicator!(HmaNode, "HMA", wc::Hma);
|
||||
node_scalar_indicator!(RocNode, "ROC", wc::Roc);
|
||||
node_scalar_indicator!(TrixNode, "TRIX", wc::Trix);
|
||||
|
||||
// ============================== MACD ==============================
|
||||
|
||||
/// MACD triple: macd line, signal line, histogram.
|
||||
#[napi(object)]
|
||||
pub struct MacdValue {
|
||||
pub macd: f64,
|
||||
pub signal: f64,
|
||||
pub histogram: f64,
|
||||
}
|
||||
|
||||
#[napi(js_name = "MACD")]
|
||||
pub struct MacdNode {
|
||||
inner: wc::MacdIndicator,
|
||||
}
|
||||
|
||||
#[napi]
|
||||
impl MacdNode {
|
||||
#[napi(constructor)]
|
||||
pub fn new(fast: u32, slow: u32, signal: u32) -> Self {
|
||||
Self {
|
||||
inner: must(wc::MacdIndicator::new(
|
||||
fast as usize,
|
||||
slow as usize,
|
||||
signal as usize,
|
||||
)),
|
||||
}
|
||||
}
|
||||
#[napi]
|
||||
pub fn update(&mut self, value: f64) -> Option<MacdValue> {
|
||||
self.inner.update(value).map(|o| MacdValue {
|
||||
macd: o.macd,
|
||||
signal: o.signal,
|
||||
histogram: o.histogram,
|
||||
})
|
||||
}
|
||||
#[napi]
|
||||
pub fn batch(&mut self, prices: Vec<f64>) -> Vec<f64> {
|
||||
let mut out = vec![f64::NAN; prices.len() * 3];
|
||||
for (i, p) in prices.iter().enumerate() {
|
||||
if let Some(o) = self.inner.update(*p) {
|
||||
out[i * 3] = o.macd;
|
||||
out[i * 3 + 1] = o.signal;
|
||||
out[i * 3 + 2] = o.histogram;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
#[napi]
|
||||
pub fn reset(&mut self) {
|
||||
self.inner.reset();
|
||||
}
|
||||
#[napi(js_name = "isReady")]
|
||||
pub fn is_ready(&self) -> bool {
|
||||
self.inner.is_ready()
|
||||
}
|
||||
}
|
||||
|
||||
// ============================== Bollinger ==============================
|
||||
|
||||
#[napi(object)]
|
||||
pub struct BollingerValue {
|
||||
pub upper: f64,
|
||||
pub middle: f64,
|
||||
pub lower: f64,
|
||||
pub stddev: f64,
|
||||
}
|
||||
|
||||
#[napi(js_name = "BollingerBands")]
|
||||
pub struct BollingerNode {
|
||||
inner: wc::BollingerBands,
|
||||
}
|
||||
|
||||
#[napi]
|
||||
impl BollingerNode {
|
||||
#[napi(constructor)]
|
||||
pub fn new(period: u32, multiplier: f64) -> Self {
|
||||
Self {
|
||||
inner: must(wc::BollingerBands::new(period as usize, multiplier)),
|
||||
}
|
||||
}
|
||||
#[napi]
|
||||
pub fn update(&mut self, value: f64) -> Option<BollingerValue> {
|
||||
self.inner.update(value).map(|o| BollingerValue {
|
||||
upper: o.upper,
|
||||
middle: o.middle,
|
||||
lower: o.lower,
|
||||
stddev: o.stddev,
|
||||
})
|
||||
}
|
||||
#[napi]
|
||||
pub fn batch(&mut self, prices: Vec<f64>) -> Vec<f64> {
|
||||
let mut out = vec![f64::NAN; prices.len() * 4];
|
||||
for (i, p) in prices.iter().enumerate() {
|
||||
if let Some(o) = self.inner.update(*p) {
|
||||
out[i * 4] = o.upper;
|
||||
out[i * 4 + 1] = o.middle;
|
||||
out[i * 4 + 2] = o.lower;
|
||||
out[i * 4 + 3] = o.stddev;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
#[napi]
|
||||
pub fn reset(&mut self) {
|
||||
self.inner.reset();
|
||||
}
|
||||
#[napi(js_name = "isReady")]
|
||||
pub fn is_ready(&self) -> bool {
|
||||
self.inner.is_ready()
|
||||
}
|
||||
}
|
||||
|
||||
// ============================== Candle-input helpers ==============================
|
||||
|
||||
fn cnd(h: f64, l: f64, c: f64, v: f64) -> napi::Result<wc::Candle> {
|
||||
wc::Candle::new(c, h, l, c, v, 0).map_err(map_err)
|
||||
}
|
||||
|
||||
#[napi(js_name = "ATR")]
|
||||
pub struct AtrNode {
|
||||
inner: wc::Atr,
|
||||
}
|
||||
|
||||
#[napi]
|
||||
impl AtrNode {
|
||||
#[napi(constructor)]
|
||||
pub fn new(period: u32) -> Self {
|
||||
Self {
|
||||
inner: must(wc::Atr::new(period as usize)),
|
||||
}
|
||||
}
|
||||
#[napi]
|
||||
pub fn update(&mut self, high: f64, low: f64, close: f64) -> napi::Result<Option<f64>> {
|
||||
Ok(self.inner.update(cnd(high, low, close, 0.0)?))
|
||||
}
|
||||
#[napi]
|
||||
pub fn batch(
|
||||
&mut self,
|
||||
high: Vec<f64>,
|
||||
low: Vec<f64>,
|
||||
close: Vec<f64>,
|
||||
) -> napi::Result<Vec<f64>> {
|
||||
if high.len() != low.len() || low.len() != close.len() {
|
||||
return Err(NapiError::from_reason(
|
||||
"high, low, close must be equal length".to_string(),
|
||||
));
|
||||
}
|
||||
let mut out = Vec::with_capacity(high.len());
|
||||
for i in 0..high.len() {
|
||||
out.push(
|
||||
self.inner
|
||||
.update(cnd(high[i], low[i], close[i], 0.0)?)
|
||||
.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(object)]
|
||||
pub struct StochValue {
|
||||
pub k: f64,
|
||||
pub d: f64,
|
||||
}
|
||||
|
||||
#[napi(js_name = "Stochastic")]
|
||||
pub struct StochNode {
|
||||
inner: wc::Stochastic,
|
||||
}
|
||||
|
||||
#[napi]
|
||||
impl StochNode {
|
||||
#[napi(constructor)]
|
||||
pub fn new(k_period: u32, d_period: u32) -> Self {
|
||||
Self {
|
||||
inner: must(wc::Stochastic::new(k_period as usize, d_period as usize)),
|
||||
}
|
||||
}
|
||||
#[napi]
|
||||
pub fn batch(
|
||||
&mut self,
|
||||
high: Vec<f64>,
|
||||
low: Vec<f64>,
|
||||
close: Vec<f64>,
|
||||
) -> napi::Result<Vec<f64>> {
|
||||
let n = high.len();
|
||||
let mut out = vec![f64::NAN; n * 2];
|
||||
for i in 0..n {
|
||||
if let Some(o) = self.inner.update(cnd(high[i], low[i], close[i], 0.0)?) {
|
||||
out[i * 2] = o.k;
|
||||
out[i * 2 + 1] = o.d;
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
#[napi]
|
||||
pub fn reset(&mut self) {
|
||||
self.inner.reset();
|
||||
}
|
||||
}
|
||||
|
||||
#[napi(js_name = "OBV")]
|
||||
pub struct ObvNode {
|
||||
inner: wc::Obv,
|
||||
}
|
||||
|
||||
impl Default for ObvNode {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
impl ObvNode {
|
||||
#[napi(constructor)]
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
inner: wc::Obv::new(),
|
||||
}
|
||||
}
|
||||
#[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(object)]
|
||||
pub struct AdxValue {
|
||||
#[napi(js_name = "plusDi")]
|
||||
pub plus_di: f64,
|
||||
#[napi(js_name = "minusDi")]
|
||||
pub minus_di: f64,
|
||||
pub adx: f64,
|
||||
}
|
||||
|
||||
#[napi(js_name = "ADX")]
|
||||
pub struct AdxNode {
|
||||
inner: wc::Adx,
|
||||
}
|
||||
|
||||
#[napi]
|
||||
impl AdxNode {
|
||||
#[napi(constructor)]
|
||||
pub fn new(period: u32) -> Self {
|
||||
Self {
|
||||
inner: must(wc::Adx::new(period as usize)),
|
||||
}
|
||||
}
|
||||
#[napi]
|
||||
pub fn batch(
|
||||
&mut self,
|
||||
high: Vec<f64>,
|
||||
low: Vec<f64>,
|
||||
close: Vec<f64>,
|
||||
) -> napi::Result<Vec<f64>> {
|
||||
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], close[i], 0.0)?) {
|
||||
out[i * 3] = o.plus_di;
|
||||
out[i * 3 + 1] = o.minus_di;
|
||||
out[i * 3 + 2] = o.adx;
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
#[napi]
|
||||
pub fn reset(&mut self) {
|
||||
self.inner.reset();
|
||||
}
|
||||
}
|
||||
|
||||
#[napi(js_name = "CCI")]
|
||||
pub struct CciNode {
|
||||
inner: wc::Cci,
|
||||
}
|
||||
#[napi]
|
||||
impl CciNode {
|
||||
#[napi(constructor)]
|
||||
pub fn new(period: u32) -> Self {
|
||||
Self {
|
||||
inner: must(wc::Cci::new(period as usize)),
|
||||
}
|
||||
}
|
||||
#[napi]
|
||||
pub fn batch(
|
||||
&mut self,
|
||||
high: Vec<f64>,
|
||||
low: Vec<f64>,
|
||||
close: Vec<f64>,
|
||||
) -> napi::Result<Vec<f64>> {
|
||||
let mut out = Vec::with_capacity(high.len());
|
||||
for i in 0..high.len() {
|
||||
out.push(
|
||||
self.inner
|
||||
.update(cnd(high[i], low[i], close[i], 0.0)?)
|
||||
.unwrap_or(f64::NAN),
|
||||
);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
#[napi(js_name = "WilliamsR")]
|
||||
pub struct WilliamsRNode {
|
||||
inner: wc::WilliamsR,
|
||||
}
|
||||
#[napi]
|
||||
impl WilliamsRNode {
|
||||
#[napi(constructor)]
|
||||
pub fn new(period: u32) -> Self {
|
||||
Self {
|
||||
inner: must(wc::WilliamsR::new(period as usize)),
|
||||
}
|
||||
}
|
||||
#[napi]
|
||||
pub fn batch(
|
||||
&mut self,
|
||||
high: Vec<f64>,
|
||||
low: Vec<f64>,
|
||||
close: Vec<f64>,
|
||||
) -> napi::Result<Vec<f64>> {
|
||||
let mut out = Vec::with_capacity(high.len());
|
||||
for i in 0..high.len() {
|
||||
out.push(
|
||||
self.inner
|
||||
.update(cnd(high[i], low[i], close[i], 0.0)?)
|
||||
.unwrap_or(f64::NAN),
|
||||
);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
#[napi(js_name = "MFI")]
|
||||
pub struct MfiNode {
|
||||
inner: wc::Mfi,
|
||||
}
|
||||
#[napi]
|
||||
impl MfiNode {
|
||||
#[napi(constructor)]
|
||||
pub fn new(period: u32) -> Self {
|
||||
Self {
|
||||
inner: must(wc::Mfi::new(period as usize)),
|
||||
}
|
||||
}
|
||||
#[napi]
|
||||
pub fn batch(
|
||||
&mut self,
|
||||
high: Vec<f64>,
|
||||
low: Vec<f64>,
|
||||
close: Vec<f64>,
|
||||
volume: Vec<f64>,
|
||||
) -> napi::Result<Vec<f64>> {
|
||||
let mut out = Vec::with_capacity(high.len());
|
||||
for i in 0..high.len() {
|
||||
out.push(
|
||||
self.inner
|
||||
.update(cnd(high[i], low[i], close[i], volume[i])?)
|
||||
.unwrap_or(f64::NAN),
|
||||
);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
#[napi(js_name = "PSAR")]
|
||||
pub struct PsarNode {
|
||||
inner: wc::Psar,
|
||||
}
|
||||
#[napi]
|
||||
impl PsarNode {
|
||||
#[napi(constructor)]
|
||||
pub fn new(af_start: f64, af_step: f64, af_max: f64) -> Self {
|
||||
Self {
|
||||
inner: must(wc::Psar::new(af_start, af_step, af_max)),
|
||||
}
|
||||
}
|
||||
#[napi]
|
||||
pub fn batch(
|
||||
&mut self,
|
||||
high: Vec<f64>,
|
||||
low: Vec<f64>,
|
||||
close: Vec<f64>,
|
||||
) -> napi::Result<Vec<f64>> {
|
||||
let mut out = Vec::with_capacity(high.len());
|
||||
for i in 0..high.len() {
|
||||
out.push(
|
||||
self.inner
|
||||
.update(cnd(high[i], low[i], close[i], 0.0)?)
|
||||
.unwrap_or(f64::NAN),
|
||||
);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
#[napi(object)]
|
||||
pub struct KeltnerValue {
|
||||
pub upper: f64,
|
||||
pub middle: f64,
|
||||
pub lower: f64,
|
||||
}
|
||||
|
||||
#[napi(js_name = "Keltner")]
|
||||
pub struct KeltnerNode {
|
||||
inner: wc::Keltner,
|
||||
}
|
||||
#[napi]
|
||||
impl KeltnerNode {
|
||||
#[napi(constructor)]
|
||||
pub fn new(ema_period: u32, atr_period: u32, multiplier: f64) -> Self {
|
||||
Self {
|
||||
inner: must(wc::Keltner::new(
|
||||
ema_period as usize,
|
||||
atr_period as usize,
|
||||
multiplier,
|
||||
)),
|
||||
}
|
||||
}
|
||||
#[napi]
|
||||
pub fn batch(
|
||||
&mut self,
|
||||
high: Vec<f64>,
|
||||
low: Vec<f64>,
|
||||
close: Vec<f64>,
|
||||
) -> napi::Result<Vec<f64>> {
|
||||
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], close[i], 0.0)?) {
|
||||
out[i * 3] = o.upper;
|
||||
out[i * 3 + 1] = o.middle;
|
||||
out[i * 3 + 2] = o.lower;
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
#[napi(object)]
|
||||
pub struct DonchianValue {
|
||||
pub upper: f64,
|
||||
pub middle: f64,
|
||||
pub lower: f64,
|
||||
}
|
||||
|
||||
#[napi(js_name = "Donchian")]
|
||||
pub struct DonchianNode {
|
||||
inner: wc::Donchian,
|
||||
}
|
||||
#[napi]
|
||||
impl DonchianNode {
|
||||
#[napi(constructor)]
|
||||
pub fn new(period: u32) -> Self {
|
||||
Self {
|
||||
inner: must(wc::Donchian::new(period as usize)),
|
||||
}
|
||||
}
|
||||
#[napi]
|
||||
pub fn batch(&mut self, high: Vec<f64>, low: Vec<f64>) -> napi::Result<Vec<f64>> {
|
||||
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.upper;
|
||||
out[i * 3 + 1] = o.middle;
|
||||
out[i * 3 + 2] = o.lower;
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
#[napi(js_name = "VWAP")]
|
||||
pub struct VwapNode {
|
||||
inner: wc::Vwap,
|
||||
}
|
||||
impl Default for VwapNode {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
#[napi]
|
||||
impl VwapNode {
|
||||
#[napi(constructor)]
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
inner: wc::Vwap::new(),
|
||||
}
|
||||
}
|
||||
#[napi]
|
||||
pub fn batch(
|
||||
&mut self,
|
||||
high: Vec<f64>,
|
||||
low: Vec<f64>,
|
||||
close: Vec<f64>,
|
||||
volume: Vec<f64>,
|
||||
) -> napi::Result<Vec<f64>> {
|
||||
let mut out = Vec::with_capacity(high.len());
|
||||
for i in 0..high.len() {
|
||||
out.push(
|
||||
self.inner
|
||||
.update(cnd(high[i], low[i], close[i], volume[i])?)
|
||||
.unwrap_or(f64::NAN),
|
||||
);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
#[napi(js_name = "AwesomeOscillator")]
|
||||
pub struct AoNode {
|
||||
inner: wc::AwesomeOscillator,
|
||||
}
|
||||
#[napi]
|
||||
impl AoNode {
|
||||
#[napi(constructor)]
|
||||
pub fn new(fast: u32, slow: u32) -> Self {
|
||||
Self {
|
||||
inner: must(wc::AwesomeOscillator::new(fast as usize, slow as usize)),
|
||||
}
|
||||
}
|
||||
#[napi]
|
||||
pub fn batch(&mut self, high: Vec<f64>, low: Vec<f64>) -> napi::Result<Vec<f64>> {
|
||||
let mut out = Vec::with_capacity(high.len());
|
||||
for i in 0..high.len() {
|
||||
out.push(
|
||||
self.inner
|
||||
.update(cnd(high[i], low[i], low[i], 0.0)?)
|
||||
.unwrap_or(f64::NAN),
|
||||
);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
#[napi(object)]
|
||||
pub struct AroonValue {
|
||||
pub up: f64,
|
||||
pub down: f64,
|
||||
}
|
||||
|
||||
#[napi(js_name = "Aroon")]
|
||||
pub struct AroonNode {
|
||||
inner: wc::Aroon,
|
||||
}
|
||||
#[napi]
|
||||
impl AroonNode {
|
||||
#[napi(constructor)]
|
||||
pub fn new(period: u32) -> Self {
|
||||
Self {
|
||||
inner: must(wc::Aroon::new(period as usize)),
|
||||
}
|
||||
}
|
||||
#[napi]
|
||||
pub fn batch(&mut self, high: Vec<f64>, low: Vec<f64>) -> napi::Result<Vec<f64>> {
|
||||
let n = high.len();
|
||||
let mut out = vec![f64::NAN; n * 2];
|
||||
for i in 0..n {
|
||||
if let Some(o) = self.inner.update(cnd(high[i], low[i], low[i], 0.0)?) {
|
||||
out[i * 2] = o.up;
|
||||
out[i * 2 + 1] = o.down;
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
#[napi(js_name = "KAMA")]
|
||||
pub struct KamaNode {
|
||||
inner: wc::Kama,
|
||||
}
|
||||
#[napi]
|
||||
impl KamaNode {
|
||||
#[napi(constructor)]
|
||||
pub fn new(er_period: u32, fast: u32, slow: u32) -> Self {
|
||||
Self {
|
||||
inner: must(wc::Kama::new(
|
||||
er_period as usize,
|
||||
fast as usize,
|
||||
slow as usize,
|
||||
)),
|
||||
}
|
||||
}
|
||||
#[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))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
[package]
|
||||
name = "wickra-python"
|
||||
description = "Python bindings for the Wickra streaming-first technical indicators library."
|
||||
version.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
homepage.workspace = true
|
||||
readme.workspace = true
|
||||
keywords.workspace = true
|
||||
categories.workspace = true
|
||||
publish = false
|
||||
|
||||
[lib]
|
||||
name = "_wickra"
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
wickra-core = { workspace = true }
|
||||
pyo3 = { workspace = true }
|
||||
numpy = { workspace = true }
|
||||
@@ -0,0 +1,520 @@
|
||||
"""Cross-library benchmark: Wickra vs TA-Lib vs pandas-ta vs talipp vs finta.
|
||||
|
||||
Runs each library through identical batch and streaming workloads, then prints a
|
||||
table of timings. Libraries that are not installed are skipped automatically, so
|
||||
the script always produces output regardless of the local environment.
|
||||
|
||||
Usage::
|
||||
|
||||
python -m benchmarks.compare_libraries
|
||||
python -m benchmarks.compare_libraries --size 50000 --streaming-window 5000
|
||||
|
||||
Notes:
|
||||
|
||||
- "Batch" means computing the indicator over the whole price series in one call,
|
||||
which is what classic libraries support.
|
||||
- "Streaming" simulates live trading: after seeding with ``streaming_window``
|
||||
historical bars, we keep appending one new price and recomputing the latest
|
||||
indicator value. Libraries without an incremental API have to recompute the
|
||||
whole indicator on every tick; Wickra updates in O(1). This is the gap the
|
||||
library was built to expose.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import contextlib
|
||||
import importlib
|
||||
import statistics
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from typing import Callable, Dict, List, Optional
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Library availability detection
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
def _try_import(name: str):
|
||||
try:
|
||||
return importlib.import_module(name)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
TALIB = _try_import("talib")
|
||||
PANDAS_TA = _try_import("pandas_ta")
|
||||
TALIPP = _try_import("talipp.indicators") or _try_import("talipp")
|
||||
FINTA = _try_import("finta")
|
||||
PD = _try_import("pandas")
|
||||
import wickra as WICKRA # noqa: E402 -- the library under test must be importable
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Timing helpers
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
@dataclass
|
||||
class Sample:
|
||||
library: str
|
||||
indicator: str
|
||||
mode: str
|
||||
seconds: float
|
||||
iterations: int
|
||||
|
||||
@property
|
||||
def per_iter_us(self) -> float:
|
||||
return (self.seconds / self.iterations) * 1_000_000
|
||||
|
||||
|
||||
def time_call(fn: Callable[[], None], iterations: int) -> float:
|
||||
"""Time ``fn`` over ``iterations`` calls, returning total wall seconds."""
|
||||
fn() # one warmup call to populate caches
|
||||
start = time.perf_counter()
|
||||
for _ in range(iterations):
|
||||
fn()
|
||||
return time.perf_counter() - start
|
||||
|
||||
|
||||
def gen_prices(n: int, seed: int = 0xC0FFEE) -> np.ndarray:
|
||||
rng = np.random.default_rng(seed)
|
||||
walk = rng.standard_normal(n) * 0.4
|
||||
return 100.0 + np.cumsum(walk)
|
||||
|
||||
|
||||
def gen_ohlc(n: int, seed: int = 0xC0FFEE) -> tuple:
|
||||
close = gen_prices(n, seed)
|
||||
spread = 0.5 + np.abs(np.sin(np.arange(n) * 0.07))
|
||||
high = close + spread
|
||||
low = close - spread
|
||||
volume = np.full(n, 1_000.0)
|
||||
return high, low, close, volume
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Per-library indicator runners. Each returns ``None`` to skip when unavailable.
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
def wickra_sma_batch(prices: np.ndarray) -> Callable[[], None]:
|
||||
return lambda: WICKRA.SMA(20).batch(prices)
|
||||
|
||||
|
||||
def talib_sma_batch(prices: np.ndarray) -> Optional[Callable[[], None]]:
|
||||
return None if TALIB is None else (lambda: TALIB.SMA(prices, timeperiod=20))
|
||||
|
||||
|
||||
def pandas_ta_sma_batch(prices: np.ndarray) -> Optional[Callable[[], None]]:
|
||||
if PANDAS_TA is None or PD is None:
|
||||
return None
|
||||
s = PD.Series(prices)
|
||||
return lambda: PANDAS_TA.sma(s, length=20)
|
||||
|
||||
|
||||
def finta_sma_batch(prices: np.ndarray) -> Optional[Callable[[], None]]:
|
||||
if FINTA is None or PD is None:
|
||||
return None
|
||||
df = PD.DataFrame({"open": prices, "high": prices, "low": prices, "close": prices, "volume": np.ones_like(prices)})
|
||||
return lambda: FINTA.TA.SMA(df, period=20)
|
||||
|
||||
|
||||
def talipp_sma_batch(prices: np.ndarray) -> Optional[Callable[[], None]]:
|
||||
if TALIPP is None:
|
||||
return None
|
||||
# talipp's SMA accepts an initial list of values
|
||||
from talipp.indicators import SMA # type: ignore
|
||||
|
||||
return lambda: SMA(period=20, input_values=list(prices))
|
||||
|
||||
|
||||
def wickra_rsi_batch(prices: np.ndarray) -> Callable[[], None]:
|
||||
return lambda: WICKRA.RSI(14).batch(prices)
|
||||
|
||||
|
||||
def talib_rsi_batch(prices: np.ndarray) -> Optional[Callable[[], None]]:
|
||||
return None if TALIB is None else (lambda: TALIB.RSI(prices, timeperiod=14))
|
||||
|
||||
|
||||
def pandas_ta_rsi_batch(prices: np.ndarray) -> Optional[Callable[[], None]]:
|
||||
if PANDAS_TA is None or PD is None:
|
||||
return None
|
||||
s = PD.Series(prices)
|
||||
return lambda: PANDAS_TA.rsi(s, length=14)
|
||||
|
||||
|
||||
def finta_rsi_batch(prices: np.ndarray) -> Optional[Callable[[], None]]:
|
||||
if FINTA is None or PD is None:
|
||||
return None
|
||||
df = PD.DataFrame({"open": prices, "high": prices, "low": prices, "close": prices, "volume": np.ones_like(prices)})
|
||||
return lambda: FINTA.TA.RSI(df, period=14)
|
||||
|
||||
|
||||
def talipp_rsi_batch(prices: np.ndarray) -> Optional[Callable[[], None]]:
|
||||
if TALIPP is None:
|
||||
return None
|
||||
from talipp.indicators import RSI # type: ignore
|
||||
|
||||
return lambda: RSI(period=14, input_values=list(prices))
|
||||
|
||||
|
||||
def wickra_bollinger_batch(prices: np.ndarray) -> Callable[[], None]:
|
||||
return lambda: WICKRA.BollingerBands(20, 2.0).batch(prices)
|
||||
|
||||
|
||||
def wickra_ema_batch(prices: np.ndarray) -> Callable[[], None]:
|
||||
return lambda: WICKRA.EMA(20).batch(prices)
|
||||
|
||||
|
||||
def talib_ema_batch(prices: np.ndarray) -> Optional[Callable[[], None]]:
|
||||
return None if TALIB is None else (lambda: TALIB.EMA(prices, timeperiod=20))
|
||||
|
||||
|
||||
def pandas_ta_ema_batch(prices: np.ndarray) -> Optional[Callable[[], None]]:
|
||||
if PANDAS_TA is None or PD is None:
|
||||
return None
|
||||
s = PD.Series(prices)
|
||||
return lambda: PANDAS_TA.ema(s, length=20)
|
||||
|
||||
|
||||
def finta_ema_batch(prices: np.ndarray) -> Optional[Callable[[], None]]:
|
||||
if FINTA is None or PD is None:
|
||||
return None
|
||||
df = PD.DataFrame({"open": prices, "high": prices, "low": prices, "close": prices, "volume": np.ones_like(prices)})
|
||||
return lambda: FINTA.TA.EMA(df, period=20)
|
||||
|
||||
|
||||
def talipp_ema_batch(prices: np.ndarray) -> Optional[Callable[[], None]]:
|
||||
if TALIPP is None:
|
||||
return None
|
||||
from talipp.indicators import EMA # type: ignore
|
||||
return lambda: EMA(period=20, input_values=list(prices))
|
||||
|
||||
|
||||
def wickra_macd_batch(prices: np.ndarray) -> Callable[[], None]:
|
||||
return lambda: WICKRA.MACD().batch(prices)
|
||||
|
||||
|
||||
def talib_macd_batch(prices: np.ndarray) -> Optional[Callable[[], None]]:
|
||||
return None if TALIB is None else (lambda: TALIB.MACD(prices))
|
||||
|
||||
|
||||
def pandas_ta_macd_batch(prices: np.ndarray) -> Optional[Callable[[], None]]:
|
||||
if PANDAS_TA is None or PD is None:
|
||||
return None
|
||||
s = PD.Series(prices)
|
||||
return lambda: PANDAS_TA.macd(s)
|
||||
|
||||
|
||||
def finta_macd_batch(prices: np.ndarray) -> Optional[Callable[[], None]]:
|
||||
if FINTA is None or PD is None:
|
||||
return None
|
||||
df = PD.DataFrame({"open": prices, "high": prices, "low": prices, "close": prices, "volume": np.ones_like(prices)})
|
||||
return lambda: FINTA.TA.MACD(df)
|
||||
|
||||
|
||||
def talipp_macd_batch(prices: np.ndarray) -> Optional[Callable[[], None]]:
|
||||
if TALIPP is None:
|
||||
return None
|
||||
from talipp.indicators import MACD # type: ignore
|
||||
return lambda: MACD(fast_period=12, slow_period=26, signal_period=9, input_values=list(prices))
|
||||
|
||||
|
||||
def wickra_atr_batch(high: np.ndarray, low: np.ndarray, close: np.ndarray) -> Callable[[], None]:
|
||||
return lambda: WICKRA.ATR(14).batch(high, low, close)
|
||||
|
||||
|
||||
def talib_atr_batch(high: np.ndarray, low: np.ndarray, close: np.ndarray) -> Optional[Callable[[], None]]:
|
||||
return None if TALIB is None else (lambda: TALIB.ATR(high, low, close, timeperiod=14))
|
||||
|
||||
|
||||
def finta_atr_batch(_high: np.ndarray, _low: np.ndarray, _close: np.ndarray) -> Optional[Callable[[], None]]:
|
||||
if FINTA is None or PD is None:
|
||||
return None
|
||||
df = PD.DataFrame({"open": _close, "high": _high, "low": _low, "close": _close, "volume": np.ones_like(_close)})
|
||||
return lambda: FINTA.TA.ATR(df, period=14)
|
||||
|
||||
|
||||
def talipp_atr_batch(high: np.ndarray, low: np.ndarray, close: np.ndarray) -> Optional[Callable[[], None]]:
|
||||
if TALIPP is None:
|
||||
return None
|
||||
from talipp.indicators import ATR # type: ignore
|
||||
from talipp.ohlcv import OHLCV
|
||||
bars = [OHLCV(open=c, high=h, low=l, close=c, volume=1.0, time=i) for i, (h, l, c) in enumerate(zip(high, low, close))]
|
||||
return lambda: ATR(period=14, input_values=bars)
|
||||
|
||||
|
||||
def talib_bollinger_batch(prices: np.ndarray) -> Optional[Callable[[], None]]:
|
||||
if TALIB is None:
|
||||
return None
|
||||
return lambda: TALIB.BBANDS(prices, timeperiod=20, nbdevup=2, nbdevdn=2)
|
||||
|
||||
|
||||
def pandas_ta_bollinger_batch(prices: np.ndarray) -> Optional[Callable[[], None]]:
|
||||
if PANDAS_TA is None or PD is None:
|
||||
return None
|
||||
s = PD.Series(prices)
|
||||
return lambda: PANDAS_TA.bbands(s, length=20, std=2.0)
|
||||
|
||||
|
||||
def finta_bollinger_batch(prices: np.ndarray) -> Optional[Callable[[], None]]:
|
||||
if FINTA is None or PD is None:
|
||||
return None
|
||||
df = PD.DataFrame({"open": prices, "high": prices, "low": prices, "close": prices, "volume": np.ones_like(prices)})
|
||||
return lambda: FINTA.TA.BBANDS(df, period=20, std_multiplier=2.0)
|
||||
|
||||
|
||||
def talipp_bollinger_batch(prices: np.ndarray) -> Optional[Callable[[], None]]:
|
||||
if TALIPP is None:
|
||||
return None
|
||||
from talipp.indicators import BB # type: ignore
|
||||
|
||||
return lambda: BB(period=20, std_dev_mult=2.0, input_values=list(prices))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Streaming scenario: per-tick latency
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
def wickra_rsi_streaming(seed: np.ndarray, live: np.ndarray) -> Callable[[], None]:
|
||||
def run() -> None:
|
||||
rsi = WICKRA.RSI(14)
|
||||
rsi.batch(seed) # warm up
|
||||
for p in live:
|
||||
rsi.update(float(p))
|
||||
|
||||
return run
|
||||
|
||||
|
||||
def talib_rsi_streaming(seed: np.ndarray, live: np.ndarray) -> Optional[Callable[[], None]]:
|
||||
if TALIB is None:
|
||||
return None
|
||||
|
||||
def run() -> None:
|
||||
history = list(seed)
|
||||
for p in live:
|
||||
history.append(float(p))
|
||||
TALIB.RSI(np.asarray(history), timeperiod=14)
|
||||
|
||||
return run
|
||||
|
||||
|
||||
def pandas_ta_rsi_streaming(seed: np.ndarray, live: np.ndarray) -> Optional[Callable[[], None]]:
|
||||
if PANDAS_TA is None or PD is None:
|
||||
return None
|
||||
|
||||
def run() -> None:
|
||||
history = list(seed)
|
||||
for p in live:
|
||||
history.append(float(p))
|
||||
PANDAS_TA.rsi(PD.Series(history), length=14)
|
||||
|
||||
return run
|
||||
|
||||
|
||||
def talipp_rsi_streaming(seed: np.ndarray, live: np.ndarray) -> Optional[Callable[[], None]]:
|
||||
if TALIPP is None:
|
||||
return None
|
||||
from talipp.indicators import RSI # type: ignore
|
||||
|
||||
def run() -> None:
|
||||
rsi = RSI(period=14, input_values=list(seed))
|
||||
for p in live:
|
||||
rsi.add(float(p))
|
||||
|
||||
return run
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Runner
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
BATCH_INDICATORS = [
|
||||
("SMA(20)", [
|
||||
("Wickra", wickra_sma_batch),
|
||||
("TA-Lib", talib_sma_batch),
|
||||
("pandas-ta", pandas_ta_sma_batch),
|
||||
("finta", finta_sma_batch),
|
||||
("talipp", talipp_sma_batch),
|
||||
]),
|
||||
("EMA(20)", [
|
||||
("Wickra", wickra_ema_batch),
|
||||
("TA-Lib", talib_ema_batch),
|
||||
("pandas-ta", pandas_ta_ema_batch),
|
||||
("finta", finta_ema_batch),
|
||||
("talipp", talipp_ema_batch),
|
||||
]),
|
||||
("RSI(14)", [
|
||||
("Wickra", wickra_rsi_batch),
|
||||
("TA-Lib", talib_rsi_batch),
|
||||
("pandas-ta", pandas_ta_rsi_batch),
|
||||
("finta", finta_rsi_batch),
|
||||
("talipp", talipp_rsi_batch),
|
||||
]),
|
||||
("MACD(12, 26, 9)", [
|
||||
("Wickra", wickra_macd_batch),
|
||||
("TA-Lib", talib_macd_batch),
|
||||
("pandas-ta", pandas_ta_macd_batch),
|
||||
("finta", finta_macd_batch),
|
||||
("talipp", talipp_macd_batch),
|
||||
]),
|
||||
("Bollinger(20, 2.0)", [
|
||||
("Wickra", wickra_bollinger_batch),
|
||||
("TA-Lib", talib_bollinger_batch),
|
||||
("pandas-ta", pandas_ta_bollinger_batch),
|
||||
("finta", finta_bollinger_batch),
|
||||
("talipp", talipp_bollinger_batch),
|
||||
]),
|
||||
]
|
||||
|
||||
OHLC_INDICATORS = [
|
||||
("ATR(14)", [
|
||||
("Wickra", wickra_atr_batch),
|
||||
("TA-Lib", talib_atr_batch),
|
||||
("finta", finta_atr_batch),
|
||||
("talipp", talipp_atr_batch),
|
||||
]),
|
||||
]
|
||||
|
||||
STREAMING_INDICATORS = [
|
||||
("RSI(14)", [
|
||||
("Wickra", wickra_rsi_streaming),
|
||||
("TA-Lib", talib_rsi_streaming),
|
||||
("pandas-ta", pandas_ta_rsi_streaming),
|
||||
("talipp", talipp_rsi_streaming),
|
||||
]),
|
||||
]
|
||||
|
||||
|
||||
def run_batch(prices: np.ndarray, iterations: int) -> List[Sample]:
|
||||
out: List[Sample] = []
|
||||
for indicator_name, libs in BATCH_INDICATORS:
|
||||
for lib_name, factory in libs:
|
||||
runner = factory(prices)
|
||||
if runner is None:
|
||||
continue
|
||||
secs = time_call(runner, iterations)
|
||||
out.append(Sample(lib_name, indicator_name, "batch", secs, iterations))
|
||||
return out
|
||||
|
||||
|
||||
def run_ohlc(
|
||||
high: np.ndarray,
|
||||
low: np.ndarray,
|
||||
close: np.ndarray,
|
||||
iterations: int,
|
||||
) -> List[Sample]:
|
||||
out: List[Sample] = []
|
||||
for indicator_name, libs in OHLC_INDICATORS:
|
||||
for lib_name, factory in libs:
|
||||
runner = factory(high, low, close)
|
||||
if runner is None:
|
||||
continue
|
||||
secs = time_call(runner, iterations)
|
||||
out.append(Sample(lib_name, indicator_name, "batch", secs, iterations))
|
||||
return out
|
||||
|
||||
|
||||
def run_streaming(prices: np.ndarray, streaming_window: int, iterations: int) -> List[Sample]:
|
||||
out: List[Sample] = []
|
||||
seed = prices[:streaming_window]
|
||||
live = prices[streaming_window:]
|
||||
if len(live) == 0:
|
||||
return out
|
||||
for indicator_name, libs in STREAMING_INDICATORS:
|
||||
for lib_name, factory in libs:
|
||||
runner = factory(seed, live)
|
||||
if runner is None:
|
||||
continue
|
||||
secs = time_call(runner, iterations)
|
||||
sample = Sample(lib_name, indicator_name, "streaming", secs, iterations)
|
||||
sample.iterations = iterations * len(live) # per-tick normalization
|
||||
out.append(sample)
|
||||
return out
|
||||
|
||||
|
||||
def render_table(rows: List[Sample]) -> str:
|
||||
if not rows:
|
||||
return "(no results)"
|
||||
grouped: Dict[str, List[Sample]] = {}
|
||||
for r in rows:
|
||||
key = f"{r.mode} | {r.indicator}"
|
||||
grouped.setdefault(key, []).append(r)
|
||||
|
||||
lines: List[str] = []
|
||||
lines.append("")
|
||||
lines.append("Reading the tables: lower µs/op = faster. The 'vs Wickra' column says")
|
||||
lines.append("how many times slower (or faster) the other library is compared to Wickra.")
|
||||
for key, samples in grouped.items():
|
||||
baseline = next((s for s in samples if s.library == "Wickra"), samples[0])
|
||||
base = baseline.per_iter_us
|
||||
lines.append("")
|
||||
lines.append(key)
|
||||
lines.append("-" * len(key))
|
||||
lines.append(
|
||||
f"{'library':<14} {'µs/op':>14} {'vs Wickra':>22} {'verdict':<10}"
|
||||
)
|
||||
winner = min(samples, key=lambda x: x.per_iter_us)
|
||||
for s in sorted(samples, key=lambda x: x.per_iter_us):
|
||||
ratio = s.per_iter_us / base if base > 0 else float("nan")
|
||||
if s.library == "Wickra":
|
||||
comparison = "(reference)"
|
||||
elif s.per_iter_us > base:
|
||||
comparison = f"{ratio:>5.2f}x slower"
|
||||
else:
|
||||
comparison = f"{base / s.per_iter_us:>5.2f}x faster"
|
||||
verdict = "★ winner" if s is winner else ""
|
||||
lines.append(
|
||||
f"{s.library:<14} {s.per_iter_us:>14.3f} {comparison:>22} {verdict:<10}"
|
||||
)
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0] if __doc__ else None)
|
||||
parser.add_argument("--size", type=int, default=20_000, help="number of prices")
|
||||
parser.add_argument("--iterations", type=int, default=20, help="batch repetitions per timing")
|
||||
parser.add_argument(
|
||||
"--streaming-window",
|
||||
type=int,
|
||||
default=5_000,
|
||||
help="number of historical prices to seed before the live ticks begin",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--streaming-iterations",
|
||||
type=int,
|
||||
default=3,
|
||||
help="repetitions of the streaming workload (each iteration replays all live ticks)",
|
||||
)
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
args = parse_args()
|
||||
prices = gen_prices(args.size)
|
||||
|
||||
available = []
|
||||
if TALIB is not None: available.append("TA-Lib")
|
||||
if PANDAS_TA is not None: available.append("pandas-ta")
|
||||
if FINTA is not None: available.append("finta")
|
||||
if TALIPP is not None: available.append("talipp")
|
||||
print(f"Wickra benchmark suite — wickra=v{WICKRA.__version__}")
|
||||
print(f"Comparing against: {', '.join(available) if available else '(no peer libraries installed; install [bench] extra)'}")
|
||||
print(f"Series length: {args.size} • batch iterations: {args.iterations}")
|
||||
print(f"Streaming window: {args.streaming_window} seed, {args.size - args.streaming_window} live")
|
||||
|
||||
high, low, close, _ = gen_ohlc(args.size)
|
||||
batch_rows = run_batch(prices, args.iterations)
|
||||
ohlc_rows = run_ohlc(high, low, close, args.iterations)
|
||||
streaming_rows = run_streaming(prices, args.streaming_window, args.streaming_iterations)
|
||||
|
||||
print(render_table(batch_rows + ohlc_rows + streaming_rows))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,62 @@
|
||||
[build-system]
|
||||
requires = ["maturin>=1.7,<2.0"]
|
||||
build-backend = "maturin"
|
||||
|
||||
[project]
|
||||
name = "wickra"
|
||||
version = "0.1.0"
|
||||
description = "Streaming-first technical indicators: incremental, fast, install-free."
|
||||
readme = "../../README.md"
|
||||
license = { text = "Apache-2.0" }
|
||||
requires-python = ">=3.9"
|
||||
keywords = ["finance", "trading", "indicators", "technical-analysis", "ta-lib"]
|
||||
classifiers = [
|
||||
"Development Status :: 4 - Beta",
|
||||
"Intended Audience :: Financial and Insurance Industry",
|
||||
"License :: OSI Approved :: Apache Software License",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Programming Language :: Python :: 3 :: Only",
|
||||
"Programming Language :: Python :: 3.9",
|
||||
"Programming Language :: Python :: 3.10",
|
||||
"Programming Language :: Python :: 3.11",
|
||||
"Programming Language :: Python :: 3.12",
|
||||
"Programming Language :: Rust",
|
||||
"Topic :: Office/Business :: Financial :: Investment",
|
||||
"Topic :: Scientific/Engineering :: Mathematics",
|
||||
]
|
||||
dependencies = [
|
||||
"numpy>=1.22",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
test = [
|
||||
"pytest>=7",
|
||||
"numpy>=1.22",
|
||||
"hypothesis>=6",
|
||||
]
|
||||
bench = [
|
||||
"pytest-benchmark>=4",
|
||||
"TA-Lib; platform_system != 'Windows'",
|
||||
"pandas-ta>=0.3.14b",
|
||||
"talipp>=2",
|
||||
"finta>=1.3",
|
||||
"pandas>=2",
|
||||
"numpy>=1.22",
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
Homepage = "https://github.com/wickra/wickra"
|
||||
Repository = "https://github.com/wickra/wickra"
|
||||
Issues = "https://github.com/wickra/wickra/issues"
|
||||
|
||||
[tool.maturin]
|
||||
manifest-path = "Cargo.toml"
|
||||
python-source = "python"
|
||||
module-name = "wickra._wickra"
|
||||
features = ["pyo3/extension-module"]
|
||||
strip = true
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
addopts = "-ra -q"
|
||||
filterwarnings = ["error"]
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Wickra: streaming-first technical indicators.
|
||||
|
||||
Every indicator is available both in streaming mode (call ``update(value)`` per
|
||||
new data point) and batch mode (call ``batch(numpy_array)`` over a full series).
|
||||
Warmup positions in batch output are returned as ``NaN`` so the shape always
|
||||
matches the input.
|
||||
|
||||
Example::
|
||||
|
||||
import numpy as np
|
||||
import wickra as ta
|
||||
|
||||
prices = np.linspace(100, 200, 1000)
|
||||
rsi = ta.RSI(14)
|
||||
values = rsi.batch(prices) # numpy array, NaN during warmup
|
||||
|
||||
# Or streaming:
|
||||
rsi = ta.RSI(14)
|
||||
for p in prices:
|
||||
v = rsi.update(p) # None during warmup, then float
|
||||
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from ._wickra import (
|
||||
__version__,
|
||||
ADX,
|
||||
ATR,
|
||||
Aroon,
|
||||
AwesomeOscillator,
|
||||
BollingerBands,
|
||||
CCI,
|
||||
DEMA,
|
||||
Donchian,
|
||||
EMA,
|
||||
HMA,
|
||||
KAMA,
|
||||
Keltner,
|
||||
MACD,
|
||||
MFI,
|
||||
OBV,
|
||||
PSAR,
|
||||
ROC,
|
||||
RSI,
|
||||
SMA,
|
||||
Stochastic,
|
||||
TEMA,
|
||||
TRIX,
|
||||
VWAP,
|
||||
WilliamsR,
|
||||
WMA,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"__version__",
|
||||
"SMA",
|
||||
"EMA",
|
||||
"WMA",
|
||||
"RSI",
|
||||
"MACD",
|
||||
"BollingerBands",
|
||||
"ATR",
|
||||
"Stochastic",
|
||||
"OBV",
|
||||
"DEMA",
|
||||
"TEMA",
|
||||
"HMA",
|
||||
"KAMA",
|
||||
"CCI",
|
||||
"ROC",
|
||||
"WilliamsR",
|
||||
"ADX",
|
||||
"MFI",
|
||||
"TRIX",
|
||||
"PSAR",
|
||||
"Keltner",
|
||||
"Donchian",
|
||||
"VWAP",
|
||||
"AwesomeOscillator",
|
||||
"Aroon",
|
||||
]
|
||||
@@ -0,0 +1,137 @@
|
||||
"""Type stubs for the Wickra public API."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Mapping, Optional, Tuple, Union
|
||||
|
||||
import numpy as np
|
||||
from numpy.typing import NDArray
|
||||
|
||||
__version__: str
|
||||
|
||||
CandleLike = Union[
|
||||
Tuple[float, float, float, float, float, int],
|
||||
Mapping[str, Any],
|
||||
]
|
||||
|
||||
class SMA:
|
||||
def __init__(self, period: int) -> None: ...
|
||||
def update(self, value: float) -> Optional[float]: ...
|
||||
def batch(self, prices: NDArray[np.float64]) -> NDArray[np.float64]: ...
|
||||
def reset(self) -> None: ...
|
||||
def is_ready(self) -> bool: ...
|
||||
def warmup_period(self) -> int: ...
|
||||
@property
|
||||
def period(self) -> int: ...
|
||||
@property
|
||||
def value(self) -> Optional[float]: ...
|
||||
|
||||
class EMA:
|
||||
def __init__(self, period: int) -> None: ...
|
||||
def update(self, value: float) -> Optional[float]: ...
|
||||
def batch(self, prices: NDArray[np.float64]) -> NDArray[np.float64]: ...
|
||||
def reset(self) -> None: ...
|
||||
def is_ready(self) -> bool: ...
|
||||
def warmup_period(self) -> int: ...
|
||||
@property
|
||||
def period(self) -> int: ...
|
||||
@property
|
||||
def alpha(self) -> float: ...
|
||||
@property
|
||||
def value(self) -> Optional[float]: ...
|
||||
|
||||
class WMA:
|
||||
def __init__(self, period: int) -> None: ...
|
||||
def update(self, value: float) -> Optional[float]: ...
|
||||
def batch(self, prices: NDArray[np.float64]) -> NDArray[np.float64]: ...
|
||||
def reset(self) -> None: ...
|
||||
def is_ready(self) -> bool: ...
|
||||
def warmup_period(self) -> int: ...
|
||||
@property
|
||||
def period(self) -> int: ...
|
||||
@property
|
||||
def value(self) -> Optional[float]: ...
|
||||
|
||||
class RSI:
|
||||
def __init__(self, period: int = 14) -> None: ...
|
||||
def update(self, value: float) -> Optional[float]: ...
|
||||
def batch(self, prices: NDArray[np.float64]) -> NDArray[np.float64]: ...
|
||||
def reset(self) -> None: ...
|
||||
def is_ready(self) -> bool: ...
|
||||
def warmup_period(self) -> int: ...
|
||||
@property
|
||||
def period(self) -> int: ...
|
||||
@property
|
||||
def value(self) -> Optional[float]: ...
|
||||
|
||||
class MACD:
|
||||
def __init__(self, fast: int = 12, slow: int = 26, signal: int = 9) -> None: ...
|
||||
def update(self, value: float) -> Optional[Tuple[float, float, float]]: ...
|
||||
def batch(self, prices: NDArray[np.float64]) -> NDArray[np.float64]:
|
||||
"""Returns shape ``(n, 3)`` with columns ``[macd, signal, histogram]``. NaN during warmup."""
|
||||
...
|
||||
def reset(self) -> None: ...
|
||||
def is_ready(self) -> bool: ...
|
||||
def warmup_period(self) -> int: ...
|
||||
@property
|
||||
def periods(self) -> Tuple[int, int, int]: ...
|
||||
|
||||
class BollingerBands:
|
||||
def __init__(self, period: int = 20, multiplier: float = 2.0) -> None: ...
|
||||
def update(self, value: float) -> Optional[Tuple[float, float, float, float]]: ...
|
||||
def batch(self, prices: NDArray[np.float64]) -> NDArray[np.float64]:
|
||||
"""Returns shape ``(n, 4)`` with columns ``[upper, middle, lower, stddev]``."""
|
||||
...
|
||||
def reset(self) -> None: ...
|
||||
def is_ready(self) -> bool: ...
|
||||
def warmup_period(self) -> int: ...
|
||||
@property
|
||||
def period(self) -> int: ...
|
||||
@property
|
||||
def multiplier(self) -> float: ...
|
||||
|
||||
class ATR:
|
||||
def __init__(self, period: int = 14) -> None: ...
|
||||
def update(self, candle: CandleLike) -> Optional[float]: ...
|
||||
def batch(
|
||||
self,
|
||||
high: NDArray[np.float64],
|
||||
low: NDArray[np.float64],
|
||||
close: NDArray[np.float64],
|
||||
) -> NDArray[np.float64]: ...
|
||||
def reset(self) -> None: ...
|
||||
def is_ready(self) -> bool: ...
|
||||
def warmup_period(self) -> int: ...
|
||||
@property
|
||||
def period(self) -> int: ...
|
||||
|
||||
class Stochastic:
|
||||
def __init__(self, k_period: int = 14, d_period: int = 3) -> None: ...
|
||||
def update(self, candle: CandleLike) -> Optional[Tuple[float, float]]: ...
|
||||
def batch(
|
||||
self,
|
||||
high: NDArray[np.float64],
|
||||
low: NDArray[np.float64],
|
||||
close: NDArray[np.float64],
|
||||
) -> NDArray[np.float64]:
|
||||
"""Returns shape ``(n, 2)`` with columns ``[k, d]``."""
|
||||
...
|
||||
def reset(self) -> None: ...
|
||||
def is_ready(self) -> bool: ...
|
||||
def warmup_period(self) -> int: ...
|
||||
@property
|
||||
def periods(self) -> Tuple[int, int]: ...
|
||||
|
||||
class OBV:
|
||||
def __init__(self) -> None: ...
|
||||
def update(self, candle: CandleLike) -> Optional[float]: ...
|
||||
def batch(
|
||||
self,
|
||||
close: NDArray[np.float64],
|
||||
volume: NDArray[np.float64],
|
||||
) -> NDArray[np.float64]: ...
|
||||
def reset(self) -> None: ...
|
||||
def is_ready(self) -> bool: ...
|
||||
def warmup_period(self) -> int: ...
|
||||
@property
|
||||
def value(self) -> Optional[float]: ...
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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
|
||||
@@ -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])
|
||||
@@ -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
|
||||
@@ -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)
|
||||
@@ -0,0 +1,38 @@
|
||||
[package]
|
||||
name = "wickra-wasm"
|
||||
description = "WASM bindings for the Wickra streaming-first technical indicators library."
|
||||
version.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
homepage.workspace = true
|
||||
readme.workspace = true
|
||||
keywords.workspace = true
|
||||
categories.workspace = true
|
||||
publish = false
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
# WASM target cannot use rayon (no threads in the browser by default), so we
|
||||
# depend on the local path directly with default features disabled. This also
|
||||
# strips the parallel batch helpers we don't ship to JavaScript.
|
||||
wickra-core = { path = "../../crates/wickra-core", default-features = false }
|
||||
wasm-bindgen = "0.2"
|
||||
js-sys = "0.3"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde-wasm-bindgen = "0.6"
|
||||
console_error_panic_hook = { version = "0.1", optional = true }
|
||||
|
||||
[features]
|
||||
default = []
|
||||
panic-hook = ["dep:console_error_panic_hook"]
|
||||
|
||||
[package.metadata.wasm-pack.profile.release]
|
||||
wasm-opt = ['-O3', '--enable-bulk-memory']
|
||||
@@ -0,0 +1,47 @@
|
||||
# wickra-wasm
|
||||
|
||||
WebAssembly bindings for the Wickra streaming-first technical indicators library.
|
||||
|
||||
## Build
|
||||
|
||||
You need [`wasm-pack`](https://rustwasm.github.io/wasm-pack/) and the
|
||||
`wasm32-unknown-unknown` Rust target:
|
||||
|
||||
```bash
|
||||
rustup target add wasm32-unknown-unknown
|
||||
cargo install wasm-pack
|
||||
```
|
||||
|
||||
Then from the repository root:
|
||||
|
||||
```bash
|
||||
wasm-pack build bindings/wasm --target web --release --features panic-hook
|
||||
```
|
||||
|
||||
The compiled package lands in `bindings/wasm/pkg/`. Targets:
|
||||
|
||||
- `--target web` for native ES modules in browsers
|
||||
- `--target bundler` for webpack/Vite/Rollup
|
||||
- `--target nodejs` for Node.js
|
||||
|
||||
## Example
|
||||
|
||||
```js
|
||||
import init, { SMA, RSI, MACD, version } from "./pkg/wickra_wasm.js";
|
||||
|
||||
await init();
|
||||
console.log("wickra:", version());
|
||||
|
||||
// Streaming
|
||||
const rsi = new RSI(14);
|
||||
for (const price of livePrices) {
|
||||
const v = rsi.update(price);
|
||||
if (v !== undefined && v > 70) console.log("overbought");
|
||||
}
|
||||
|
||||
// Batch (returns a Float64Array; NaN for warmup positions)
|
||||
const sma = new SMA(20).batch(new Float64Array(historicalPrices));
|
||||
```
|
||||
|
||||
An interactive demo lives in `bindings/wasm/examples/index.html`. After building
|
||||
the package serve the `bindings/wasm/` directory and open `examples/index.html`.
|
||||
@@ -0,0 +1,137 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>Wickra WASM demo</title>
|
||||
<style>
|
||||
body { font-family: ui-sans-serif, system-ui, sans-serif; max-width: 880px; margin: 2rem auto; padding: 0 1rem; color: #1d1d1d; }
|
||||
h1 { margin-bottom: .25rem; }
|
||||
.meta { color: #666; margin-top: 0; }
|
||||
canvas { width: 100%; height: 380px; border: 1px solid #ddd; }
|
||||
.grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: .75rem; margin-top: 1rem; }
|
||||
.card { border: 1px solid #ddd; padding: .75rem; border-radius: .5rem; background: #fafafa; }
|
||||
.card h3 { margin: 0 0 .25rem 0; font-size: 1rem; }
|
||||
.card span { font-variant-numeric: tabular-nums; font-weight: 600; }
|
||||
button { padding: .5rem 1rem; margin-right: .5rem; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Wickra in the browser</h1>
|
||||
<p class="meta">Indicators running entirely client-side via WebAssembly. No network round-trips.</p>
|
||||
|
||||
<canvas id="chart"></canvas>
|
||||
|
||||
<div class="grid">
|
||||
<div class="card"><h3>SMA(20)</h3><span id="sma">—</span></div>
|
||||
<div class="card"><h3>EMA(20)</h3><span id="ema">—</span></div>
|
||||
<div class="card"><h3>RSI(14)</h3><span id="rsi">—</span></div>
|
||||
<div class="card"><h3>MACD</h3><span id="macd">—</span></div>
|
||||
<div class="card"><h3>Bollinger</h3><span id="bb">—</span></div>
|
||||
<div class="card"><h3>ATR(14)</h3><span id="atr">—</span></div>
|
||||
</div>
|
||||
|
||||
<p style="margin-top:1rem;">
|
||||
<button id="step">Step one tick</button>
|
||||
<button id="play">Auto-play</button>
|
||||
<button id="reset">Reset</button>
|
||||
</p>
|
||||
|
||||
<p class="meta" id="status">Loading WASM module…</p>
|
||||
|
||||
<script type="module">
|
||||
import init, {
|
||||
version, installPanicHook,
|
||||
SMA, EMA, RSI, MACD, BollingerBands, ATR,
|
||||
} from "../pkg/wickra_wasm.js";
|
||||
|
||||
const canvas = document.getElementById("chart");
|
||||
const ctx = canvas.getContext("2d");
|
||||
function resize() {
|
||||
canvas.width = canvas.clientWidth * devicePixelRatio;
|
||||
canvas.height = canvas.clientHeight * devicePixelRatio;
|
||||
ctx.scale(devicePixelRatio, devicePixelRatio);
|
||||
}
|
||||
|
||||
const fmt = (v) => Number.isFinite(v) ? v.toFixed(3) : "—";
|
||||
|
||||
const state = {
|
||||
i: 0,
|
||||
prices: [],
|
||||
highs: [],
|
||||
lows: [],
|
||||
sma: null, ema: null, rsi: null, macd: null, bb: null, atr: null,
|
||||
};
|
||||
|
||||
function rebuild() {
|
||||
state.i = 0;
|
||||
state.prices = [];
|
||||
state.highs = [];
|
||||
state.lows = [];
|
||||
state.sma = new SMA(20);
|
||||
state.ema = new EMA(20);
|
||||
state.rsi = new RSI(14);
|
||||
state.macd = new MACD(12, 26, 9);
|
||||
state.bb = new BollingerBands(20, 2);
|
||||
state.atr = new ATR(14);
|
||||
document.getElementById("status").textContent = `Ready — wickra ${version()}`;
|
||||
render();
|
||||
}
|
||||
|
||||
function step() {
|
||||
const t = state.i;
|
||||
const price = 100 + Math.sin(t * 0.07) * 10 + Math.cos(t * 0.19) * 4 + (Math.random() - 0.5) * 0.5;
|
||||
const high = price + 0.5;
|
||||
const low = price - 0.5;
|
||||
state.prices.push(price);
|
||||
state.highs.push(high);
|
||||
state.lows.push(low);
|
||||
const sma = state.sma.update(price);
|
||||
const ema = state.ema.update(price);
|
||||
const rsi = state.rsi.update(price);
|
||||
const macd = state.macd.update(price);
|
||||
const bb = state.bb.update(price);
|
||||
const atr = state.atr.update(high, low, price);
|
||||
document.getElementById("sma").textContent = fmt(sma);
|
||||
document.getElementById("ema").textContent = fmt(ema);
|
||||
document.getElementById("rsi").textContent = fmt(rsi);
|
||||
document.getElementById("macd").textContent = macd ? `${fmt(macd.macd)} / ${fmt(macd.signal)}` : "—";
|
||||
document.getElementById("bb").textContent = bb ? `${fmt(bb.upper)} | ${fmt(bb.middle)} | ${fmt(bb.lower)}` : "—";
|
||||
document.getElementById("atr").textContent = fmt(atr);
|
||||
state.i += 1;
|
||||
render();
|
||||
}
|
||||
|
||||
function render() {
|
||||
const w = canvas.clientWidth, h = canvas.clientHeight;
|
||||
ctx.clearRect(0, 0, w, h);
|
||||
if (state.prices.length < 2) return;
|
||||
const xs = state.prices.map((_, i) => (i / (state.prices.length - 1)) * w);
|
||||
const min = Math.min(...state.prices);
|
||||
const max = Math.max(...state.prices);
|
||||
const span = max - min || 1;
|
||||
const ys = state.prices.map((p) => h - ((p - min) / span) * (h - 20) - 10);
|
||||
ctx.strokeStyle = "#2a78c5"; ctx.lineWidth = 1.5;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(xs[0], ys[0]);
|
||||
for (let i = 1; i < xs.length; i++) ctx.lineTo(xs[i], ys[i]);
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
let playing = null;
|
||||
document.getElementById("step").onclick = step;
|
||||
document.getElementById("play").onclick = () => {
|
||||
if (playing) { clearInterval(playing); playing = null; return; }
|
||||
playing = setInterval(step, 100);
|
||||
};
|
||||
document.getElementById("reset").onclick = rebuild;
|
||||
|
||||
window.addEventListener("resize", () => { resize(); render(); });
|
||||
|
||||
init().then(() => {
|
||||
installPanicHook();
|
||||
resize();
|
||||
rebuild();
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,621 @@
|
||||
//! WASM bindings for Wickra. Exposes every indicator with `Float64Array` I/O so
|
||||
//! the API is essentially the same in the browser as it is in Python and Rust.
|
||||
//!
|
||||
//! Build with:
|
||||
//! ```text
|
||||
//! wasm-pack build bindings/wasm --target web --release
|
||||
//! ```
|
||||
|
||||
#![allow(clippy::needless_pass_by_value)]
|
||||
#![allow(missing_debug_implementations)] // wasm_bindgen wrappers expose JS objects, no need for Debug
|
||||
|
||||
use js_sys::{Float64Array, Object, Reflect};
|
||||
use wasm_bindgen::prelude::*;
|
||||
use wickra_core as wc;
|
||||
use wickra_core::{BatchExt, Indicator};
|
||||
|
||||
fn map_err(e: wc::Error) -> JsError {
|
||||
JsError::new(&e.to_string())
|
||||
}
|
||||
|
||||
fn flatten(values: Vec<Option<f64>>) -> Vec<f64> {
|
||||
values.into_iter().map(|v| v.unwrap_or(f64::NAN)).collect()
|
||||
}
|
||||
|
||||
/// Optional helper: install `console.error` panic hook in the browser.
|
||||
#[wasm_bindgen(js_name = installPanicHook)]
|
||||
pub fn install_panic_hook() {
|
||||
#[cfg(feature = "panic-hook")]
|
||||
console_error_panic_hook::set_once();
|
||||
}
|
||||
|
||||
/// Library version (matches the Cargo package version).
|
||||
#[wasm_bindgen(js_name = version)]
|
||||
pub fn version() -> String {
|
||||
env!("CARGO_PKG_VERSION").to_string()
|
||||
}
|
||||
|
||||
// ---------- Scalar-input indicators ----------
|
||||
|
||||
macro_rules! wasm_scalar_indicator {
|
||||
($name:ident, $py_name:literal, $rust_ty:ty, $($arg:ident: $arg_ty:ty),*) => {
|
||||
#[wasm_bindgen(js_name = $py_name)]
|
||||
pub struct $name {
|
||||
inner: $rust_ty,
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_class = $py_name)]
|
||||
impl $name {
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new($($arg: $arg_ty),*) -> Result<$name, JsError> {
|
||||
Ok($name {
|
||||
inner: <$rust_ty>::new($($arg),*).map_err(map_err)?,
|
||||
})
|
||||
}
|
||||
pub fn update(&mut self, value: f64) -> Option<f64> {
|
||||
self.inner.update(value)
|
||||
}
|
||||
pub fn batch(&mut self, prices: &[f64]) -> Float64Array {
|
||||
let out = flatten(self.inner.batch(prices));
|
||||
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_scalar_indicator!(WasmSma, "SMA", wc::Sma, period: usize);
|
||||
wasm_scalar_indicator!(WasmEma, "EMA", wc::Ema, period: usize);
|
||||
wasm_scalar_indicator!(WasmWma, "WMA", wc::Wma, period: usize);
|
||||
wasm_scalar_indicator!(WasmRsi, "RSI", wc::Rsi, period: usize);
|
||||
wasm_scalar_indicator!(WasmDema, "DEMA", wc::Dema, period: usize);
|
||||
wasm_scalar_indicator!(WasmTema, "TEMA", wc::Tema, period: usize);
|
||||
wasm_scalar_indicator!(WasmHma, "HMA", wc::Hma, period: usize);
|
||||
wasm_scalar_indicator!(WasmRoc, "ROC", wc::Roc, period: usize);
|
||||
wasm_scalar_indicator!(WasmTrix, "TRIX", wc::Trix, period: usize);
|
||||
|
||||
// ---------- KAMA (three params) ----------
|
||||
|
||||
#[wasm_bindgen(js_name = KAMA)]
|
||||
pub struct WasmKama {
|
||||
inner: wc::Kama,
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_class = KAMA)]
|
||||
impl WasmKama {
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new(er_period: usize, fast: usize, slow: usize) -> Result<WasmKama, JsError> {
|
||||
Ok(Self {
|
||||
inner: wc::Kama::new(er_period, fast, slow).map_err(map_err)?,
|
||||
})
|
||||
}
|
||||
pub fn update(&mut self, value: f64) -> Option<f64> {
|
||||
self.inner.update(value)
|
||||
}
|
||||
pub fn batch(&mut self, prices: &[f64]) -> Float64Array {
|
||||
let out = flatten(self.inner.batch(prices));
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- MACD ----------
|
||||
|
||||
#[wasm_bindgen(js_name = MACD)]
|
||||
pub struct WasmMacd {
|
||||
inner: wc::MacdIndicator,
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_class = MACD)]
|
||||
impl WasmMacd {
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new(fast: usize, slow: usize, signal: usize) -> Result<WasmMacd, JsError> {
|
||||
Ok(Self {
|
||||
inner: wc::MacdIndicator::new(fast, slow, signal).map_err(map_err)?,
|
||||
})
|
||||
}
|
||||
pub fn update(&mut self, value: f64) -> JsValue {
|
||||
match self.inner.update(value) {
|
||||
Some(o) => {
|
||||
let obj = Object::new();
|
||||
Reflect::set(&obj, &"macd".into(), &o.macd.into()).ok();
|
||||
Reflect::set(&obj, &"signal".into(), &o.signal.into()).ok();
|
||||
Reflect::set(&obj, &"histogram".into(), &o.histogram.into()).ok();
|
||||
obj.into()
|
||||
}
|
||||
None => JsValue::NULL,
|
||||
}
|
||||
}
|
||||
/// Returns a flat `Float64Array` of length `3 * n`: `[macd0, sig0, hist0, macd1, sig1, hist1, ...]`.
|
||||
/// Use `result[3*i + 0/1/2]` to read each column. Warmup positions are NaN.
|
||||
pub fn batch(&mut self, prices: &[f64]) -> Float64Array {
|
||||
let n = prices.len();
|
||||
let mut out = vec![f64::NAN; n * 3];
|
||||
for (i, p) in prices.iter().enumerate() {
|
||||
if let Some(o) = self.inner.update(*p) {
|
||||
out[i * 3] = o.macd;
|
||||
out[i * 3 + 1] = o.signal;
|
||||
out[i * 3 + 2] = o.histogram;
|
||||
}
|
||||
}
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Bollinger ----------
|
||||
|
||||
#[wasm_bindgen(js_name = BollingerBands)]
|
||||
pub struct WasmBb {
|
||||
inner: wc::BollingerBands,
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_class = BollingerBands)]
|
||||
impl WasmBb {
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new(period: usize, multiplier: f64) -> Result<WasmBb, JsError> {
|
||||
Ok(Self {
|
||||
inner: wc::BollingerBands::new(period, multiplier).map_err(map_err)?,
|
||||
})
|
||||
}
|
||||
pub fn update(&mut self, value: f64) -> JsValue {
|
||||
match self.inner.update(value) {
|
||||
Some(o) => {
|
||||
let obj = Object::new();
|
||||
Reflect::set(&obj, &"upper".into(), &o.upper.into()).ok();
|
||||
Reflect::set(&obj, &"middle".into(), &o.middle.into()).ok();
|
||||
Reflect::set(&obj, &"lower".into(), &o.lower.into()).ok();
|
||||
Reflect::set(&obj, &"stddev".into(), &o.stddev.into()).ok();
|
||||
obj.into()
|
||||
}
|
||||
None => JsValue::NULL,
|
||||
}
|
||||
}
|
||||
/// Returns `[u0, m0, l0, sd0, u1, m1, l1, sd1, ...]`, length `4 * n`.
|
||||
pub fn batch(&mut self, prices: &[f64]) -> Float64Array {
|
||||
let n = prices.len();
|
||||
let mut out = vec![f64::NAN; n * 4];
|
||||
for (i, p) in prices.iter().enumerate() {
|
||||
if let Some(o) = self.inner.update(*p) {
|
||||
out[i * 4] = o.upper;
|
||||
out[i * 4 + 1] = o.middle;
|
||||
out[i * 4 + 2] = o.lower;
|
||||
out[i * 4 + 3] = o.stddev;
|
||||
}
|
||||
}
|
||||
Float64Array::from(out.as_slice())
|
||||
}
|
||||
pub fn reset(&mut self) {
|
||||
self.inner.reset();
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Candle-input indicators ----------
|
||||
|
||||
fn make_candle(h: f64, l: f64, c: f64, v: f64) -> Result<wc::Candle, JsError> {
|
||||
wc::Candle::new(c, h, l, c, v, 0).map_err(map_err)
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = ATR)]
|
||||
pub struct WasmAtr {
|
||||
inner: wc::Atr,
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_class = ATR)]
|
||||
impl WasmAtr {
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new(period: usize) -> Result<WasmAtr, JsError> {
|
||||
Ok(Self {
|
||||
inner: wc::Atr::new(period).map_err(map_err)?,
|
||||
})
|
||||
}
|
||||
pub fn update(&mut self, high: f64, low: f64, close: f64) -> Result<Option<f64>, JsError> {
|
||||
let c = make_candle(high, low, close, 0.0)?;
|
||||
Ok(self.inner.update(c))
|
||||
}
|
||||
pub fn batch(
|
||||
&mut self,
|
||||
high: &[f64],
|
||||
low: &[f64],
|
||||
close: &[f64],
|
||||
) -> Result<Float64Array, JsError> {
|
||||
if high.len() != low.len() || low.len() != close.len() {
|
||||
return Err(JsError::new("high, low, close must be equal length"));
|
||||
}
|
||||
let mut out = Vec::with_capacity(high.len());
|
||||
for i in 0..high.len() {
|
||||
let c = make_candle(high[i], low[i], close[i], 0.0)?;
|
||||
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 = Stochastic)]
|
||||
pub struct WasmStoch {
|
||||
inner: wc::Stochastic,
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_class = Stochastic)]
|
||||
impl WasmStoch {
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new(k_period: usize, d_period: usize) -> Result<WasmStoch, JsError> {
|
||||
Ok(Self {
|
||||
inner: wc::Stochastic::new(k_period, d_period).map_err(map_err)?,
|
||||
})
|
||||
}
|
||||
/// Returns `[k0, d0, k1, d1, ...]`, length `2 * n`.
|
||||
pub fn batch(
|
||||
&mut self,
|
||||
high: &[f64],
|
||||
low: &[f64],
|
||||
close: &[f64],
|
||||
) -> Result<Float64Array, JsError> {
|
||||
let n = high.len();
|
||||
if low.len() != n || close.len() != n {
|
||||
return Err(JsError::new("high, low, close must be equal length"));
|
||||
}
|
||||
let mut out = vec![f64::NAN; n * 2];
|
||||
for i in 0..n {
|
||||
let c = make_candle(high[i], low[i], close[i], 0.0)?;
|
||||
if let Some(o) = self.inner.update(c) {
|
||||
out[i * 2] = o.k;
|
||||
out[i * 2 + 1] = o.d;
|
||||
}
|
||||
}
|
||||
Ok(Float64Array::from(out.as_slice()))
|
||||
}
|
||||
pub fn reset(&mut self) {
|
||||
self.inner.reset();
|
||||
}
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = OBV)]
|
||||
pub struct WasmObv {
|
||||
inner: wc::Obv,
|
||||
}
|
||||
|
||||
impl Default for WasmObv {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_class = OBV)]
|
||||
impl WasmObv {
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new() -> WasmObv {
|
||||
Self {
|
||||
inner: wc::Obv::new(),
|
||||
}
|
||||
}
|
||||
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 = ADX)]
|
||||
pub struct WasmAdx {
|
||||
inner: wc::Adx,
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_class = ADX)]
|
||||
impl WasmAdx {
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new(period: usize) -> Result<WasmAdx, JsError> {
|
||||
Ok(Self {
|
||||
inner: wc::Adx::new(period).map_err(map_err)?,
|
||||
})
|
||||
}
|
||||
/// Returns `[plusDi, minusDi, adx]` × n, length `3n`.
|
||||
pub fn batch(
|
||||
&mut self,
|
||||
high: &[f64],
|
||||
low: &[f64],
|
||||
close: &[f64],
|
||||
) -> Result<Float64Array, JsError> {
|
||||
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], close[i], 0.0)?;
|
||||
if let Some(o) = self.inner.update(c) {
|
||||
out[i * 3] = o.plus_di;
|
||||
out[i * 3 + 1] = o.minus_di;
|
||||
out[i * 3 + 2] = o.adx;
|
||||
}
|
||||
}
|
||||
Ok(Float64Array::from(out.as_slice()))
|
||||
}
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = WilliamsR)]
|
||||
pub struct WasmWilliamsR {
|
||||
inner: wc::WilliamsR,
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_class = WilliamsR)]
|
||||
impl WasmWilliamsR {
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new(period: usize) -> Result<WasmWilliamsR, JsError> {
|
||||
Ok(Self {
|
||||
inner: wc::WilliamsR::new(period).map_err(map_err)?,
|
||||
})
|
||||
}
|
||||
pub fn batch(
|
||||
&mut self,
|
||||
high: &[f64],
|
||||
low: &[f64],
|
||||
close: &[f64],
|
||||
) -> Result<Float64Array, JsError> {
|
||||
let mut out = Vec::with_capacity(high.len());
|
||||
for i in 0..high.len() {
|
||||
let c = make_candle(high[i], low[i], close[i], 0.0)?;
|
||||
out.push(self.inner.update(c).unwrap_or(f64::NAN));
|
||||
}
|
||||
Ok(Float64Array::from(out.as_slice()))
|
||||
}
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = CCI)]
|
||||
pub struct WasmCci {
|
||||
inner: wc::Cci,
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_class = CCI)]
|
||||
impl WasmCci {
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new(period: usize) -> Result<WasmCci, JsError> {
|
||||
Ok(Self {
|
||||
inner: wc::Cci::new(period).map_err(map_err)?,
|
||||
})
|
||||
}
|
||||
pub fn batch(
|
||||
&mut self,
|
||||
high: &[f64],
|
||||
low: &[f64],
|
||||
close: &[f64],
|
||||
) -> Result<Float64Array, JsError> {
|
||||
let mut out = Vec::with_capacity(high.len());
|
||||
for i in 0..high.len() {
|
||||
let c = make_candle(high[i], low[i], close[i], 0.0)?;
|
||||
out.push(self.inner.update(c).unwrap_or(f64::NAN));
|
||||
}
|
||||
Ok(Float64Array::from(out.as_slice()))
|
||||
}
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = MFI)]
|
||||
pub struct WasmMfi {
|
||||
inner: wc::Mfi,
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_class = MFI)]
|
||||
impl WasmMfi {
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new(period: usize) -> Result<WasmMfi, JsError> {
|
||||
Ok(Self {
|
||||
inner: wc::Mfi::new(period).map_err(map_err)?,
|
||||
})
|
||||
}
|
||||
pub fn batch(
|
||||
&mut self,
|
||||
high: &[f64],
|
||||
low: &[f64],
|
||||
close: &[f64],
|
||||
volume: &[f64],
|
||||
) -> Result<Float64Array, JsError> {
|
||||
let mut out = Vec::with_capacity(high.len());
|
||||
for i in 0..high.len() {
|
||||
let c = make_candle(high[i], low[i], close[i], volume[i])?;
|
||||
out.push(self.inner.update(c).unwrap_or(f64::NAN));
|
||||
}
|
||||
Ok(Float64Array::from(out.as_slice()))
|
||||
}
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = PSAR)]
|
||||
pub struct WasmPsar {
|
||||
inner: wc::Psar,
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_class = PSAR)]
|
||||
impl WasmPsar {
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new(af_start: f64, af_step: f64, af_max: f64) -> Result<WasmPsar, JsError> {
|
||||
Ok(Self {
|
||||
inner: wc::Psar::new(af_start, af_step, af_max).map_err(map_err)?,
|
||||
})
|
||||
}
|
||||
pub fn batch(
|
||||
&mut self,
|
||||
high: &[f64],
|
||||
low: &[f64],
|
||||
close: &[f64],
|
||||
) -> Result<Float64Array, JsError> {
|
||||
let mut out = Vec::with_capacity(high.len());
|
||||
for i in 0..high.len() {
|
||||
let c = make_candle(high[i], low[i], close[i], 0.0)?;
|
||||
out.push(self.inner.update(c).unwrap_or(f64::NAN));
|
||||
}
|
||||
Ok(Float64Array::from(out.as_slice()))
|
||||
}
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = Keltner)]
|
||||
pub struct WasmKeltner {
|
||||
inner: wc::Keltner,
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_class = Keltner)]
|
||||
impl WasmKeltner {
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new(
|
||||
ema_period: usize,
|
||||
atr_period: usize,
|
||||
multiplier: f64,
|
||||
) -> Result<WasmKeltner, JsError> {
|
||||
Ok(Self {
|
||||
inner: wc::Keltner::new(ema_period, atr_period, multiplier).map_err(map_err)?,
|
||||
})
|
||||
}
|
||||
pub fn batch(
|
||||
&mut self,
|
||||
high: &[f64],
|
||||
low: &[f64],
|
||||
close: &[f64],
|
||||
) -> Result<Float64Array, JsError> {
|
||||
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], close[i], 0.0)?;
|
||||
if let Some(o) = self.inner.update(c) {
|
||||
out[i * 3] = o.upper;
|
||||
out[i * 3 + 1] = o.middle;
|
||||
out[i * 3 + 2] = o.lower;
|
||||
}
|
||||
}
|
||||
Ok(Float64Array::from(out.as_slice()))
|
||||
}
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = Donchian)]
|
||||
pub struct WasmDonchian {
|
||||
inner: wc::Donchian,
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_class = Donchian)]
|
||||
impl WasmDonchian {
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new(period: usize) -> Result<WasmDonchian, JsError> {
|
||||
Ok(Self {
|
||||
inner: wc::Donchian::new(period).map_err(map_err)?,
|
||||
})
|
||||
}
|
||||
pub fn batch(&mut self, high: &[f64], low: &[f64]) -> Result<Float64Array, JsError> {
|
||||
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.upper;
|
||||
out[i * 3 + 1] = o.middle;
|
||||
out[i * 3 + 2] = o.lower;
|
||||
}
|
||||
}
|
||||
Ok(Float64Array::from(out.as_slice()))
|
||||
}
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = VWAP)]
|
||||
pub struct WasmVwap {
|
||||
inner: wc::Vwap,
|
||||
}
|
||||
|
||||
impl Default for WasmVwap {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_class = VWAP)]
|
||||
impl WasmVwap {
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new() -> WasmVwap {
|
||||
Self {
|
||||
inner: wc::Vwap::new(),
|
||||
}
|
||||
}
|
||||
pub fn batch(
|
||||
&mut self,
|
||||
high: &[f64],
|
||||
low: &[f64],
|
||||
close: &[f64],
|
||||
volume: &[f64],
|
||||
) -> Result<Float64Array, JsError> {
|
||||
let mut out = Vec::with_capacity(high.len());
|
||||
for i in 0..high.len() {
|
||||
let c = make_candle(high[i], low[i], close[i], volume[i])?;
|
||||
out.push(self.inner.update(c).unwrap_or(f64::NAN));
|
||||
}
|
||||
Ok(Float64Array::from(out.as_slice()))
|
||||
}
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = AwesomeOscillator)]
|
||||
pub struct WasmAo {
|
||||
inner: wc::AwesomeOscillator,
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_class = AwesomeOscillator)]
|
||||
impl WasmAo {
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new(fast: usize, slow: usize) -> Result<WasmAo, JsError> {
|
||||
Ok(Self {
|
||||
inner: wc::AwesomeOscillator::new(fast, slow).map_err(map_err)?,
|
||||
})
|
||||
}
|
||||
pub fn batch(&mut self, high: &[f64], low: &[f64]) -> Result<Float64Array, JsError> {
|
||||
let mut out = Vec::with_capacity(high.len());
|
||||
for i in 0..high.len() {
|
||||
let c = make_candle(high[i], low[i], low[i], 0.0)?;
|
||||
out.push(self.inner.update(c).unwrap_or(f64::NAN));
|
||||
}
|
||||
Ok(Float64Array::from(out.as_slice()))
|
||||
}
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = Aroon)]
|
||||
pub struct WasmAroon {
|
||||
inner: wc::Aroon,
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_class = Aroon)]
|
||||
impl WasmAroon {
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new(period: usize) -> Result<WasmAroon, JsError> {
|
||||
Ok(Self {
|
||||
inner: wc::Aroon::new(period).map_err(map_err)?,
|
||||
})
|
||||
}
|
||||
/// Returns `[up0, down0, up1, down1, ...]`, length `2n`.
|
||||
pub fn batch(&mut self, high: &[f64], low: &[f64]) -> Result<Float64Array, JsError> {
|
||||
let n = high.len();
|
||||
let mut out = vec![f64::NAN; n * 2];
|
||||
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 * 2] = o.up;
|
||||
out[i * 2 + 1] = o.down;
|
||||
}
|
||||
}
|
||||
Ok(Float64Array::from(out.as_slice()))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user