Wickra 0.1.0: streaming-first technical indicators

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

What ships in this initial drop:

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

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

cargo clippy --workspace --all-targets -D warnings is clean. License: Apache-2.0.
This commit is contained in:
kingchenc
2026-05-21 17:50:45 +02:00
commit 3be267cb03
81 changed files with 14453 additions and 0 deletions
+28
View File
@@ -0,0 +1,28 @@
[package]
name = "wickra-core"
description = "Core streaming-first technical indicators engine for the Wickra 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
[lints]
workspace = true
[dependencies]
thiserror = { workspace = true }
rayon = { workspace = true, optional = true }
[features]
default = ["parallel"]
parallel = ["dep:rayon"]
[dev-dependencies]
approx = { workspace = true }
proptest = { workspace = true }
@@ -0,0 +1,7 @@
# Seeds for failure cases proptest has generated in the past. It is
# automatically read and these particular cases re-run before any
# novel cases are generated.
#
# It is recommended to check this file in to source control so that
# everyone who runs the test benefits from these saved cases.
cc 1f6ec76a79c756aa0bba27231cbc15b38b06ea04e60c14686051486a401b67e4 # shrinks to period = 2, prices = [355.3914886788121, 0.0]
+30
View File
@@ -0,0 +1,30 @@
//! Error types used across `wickra-core`.
use thiserror::Error;
/// Errors that can occur when constructing or operating on an indicator.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum Error {
/// A period (window length) must be at least one.
#[error("period must be greater than zero")]
PeriodZero,
/// A specific minimum period requirement was not met (e.g. MACD needs slow > fast).
#[error("invalid period: {message}")]
InvalidPeriod { message: &'static str },
/// A non-finite value (NaN or infinity) was passed where a finite price was expected.
#[error("input value must be finite (got NaN or infinity)")]
NonFiniteInput,
/// A candle whose components do not form a valid bar (e.g. high < low) was provided.
#[error("invalid candle: {message}")]
InvalidCandle { message: &'static str },
/// A multiplier or factor must be strictly positive.
#[error("multiplier must be greater than zero")]
NonPositiveMultiplier,
}
/// Convenience alias for `Result<T, wickra_core::Error>`.
pub type Result<T> = core::result::Result<T, Error>;
+298
View File
@@ -0,0 +1,298 @@
//! Average Directional Index (ADX) with +DI / -DI components.
use crate::error::{Error, Result};
use crate::ohlcv::Candle;
use crate::traits::Indicator;
/// ADX output: the three Wilder lines.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct AdxOutput {
/// Plus Directional Indicator.
pub plus_di: f64,
/// Minus Directional Indicator.
pub minus_di: f64,
/// Average Directional Index (smoothed |DX|).
pub adx: f64,
}
/// Wilder's Average Directional Index.
///
/// Uses Wilder smoothing throughout. First `period` candles seed the directional
/// movement / true range sums; the next `period` candles produce DX values that
/// seed the ADX. The first complete `AdxOutput` is emitted after `2 * period`
/// candles.
#[allow(clippy::struct_field_names)] // adx_value pairs with adx (the output line) — renaming hurts clarity
#[derive(Debug, Clone)]
pub struct Adx {
period: usize,
prev: Option<Candle>,
// Wilder-smoothed sums during seeding.
tr_seed: f64,
plus_dm_seed: f64,
minus_dm_seed: f64,
seed_count: usize,
// Smoothed running values after seeding.
tr_smooth: Option<f64>,
plus_dm_smooth: Option<f64>,
minus_dm_smooth: Option<f64>,
// ADX seeding.
dx_buf: Vec<f64>,
adx_value: Option<f64>,
last_plus_di: f64,
last_minus_di: f64,
}
impl Adx {
/// # Errors
/// Returns [`Error::PeriodZero`] if `period == 0`.
pub fn new(period: usize) -> Result<Self> {
if period == 0 {
return Err(Error::PeriodZero);
}
Ok(Self {
period,
prev: None,
tr_seed: 0.0,
plus_dm_seed: 0.0,
minus_dm_seed: 0.0,
seed_count: 0,
tr_smooth: None,
plus_dm_smooth: None,
minus_dm_smooth: None,
dx_buf: Vec::with_capacity(period),
adx_value: None,
last_plus_di: 0.0,
last_minus_di: 0.0,
})
}
/// Configured period.
pub const fn period(&self) -> usize {
self.period
}
}
fn directional_movement(prev: &Candle, current: &Candle) -> (f64, f64) {
let up = current.high - prev.high;
let down = prev.low - current.low;
let plus_dm = if up > down && up > 0.0 { up } else { 0.0 };
let minus_dm = if down > up && down > 0.0 { down } else { 0.0 };
(plus_dm, minus_dm)
}
impl Indicator for Adx {
type Input = Candle;
type Output = AdxOutput;
fn update(&mut self, candle: Candle) -> Option<AdxOutput> {
let Some(prev) = self.prev else {
self.prev = Some(candle);
return None;
};
self.prev = Some(candle);
let tr = candle.true_range(Some(prev.close));
let (plus_dm, minus_dm) = directional_movement(&prev, &candle);
let n = self.period as f64;
let (tr_v, plus_v, minus_v) = if let (Some(t), Some(p), Some(m)) =
(self.tr_smooth, self.plus_dm_smooth, self.minus_dm_smooth)
{
let t_new = t - t / n + tr;
let p_new = p - p / n + plus_dm;
let m_new = m - m / n + minus_dm;
self.tr_smooth = Some(t_new);
self.plus_dm_smooth = Some(p_new);
self.minus_dm_smooth = Some(m_new);
(t_new, p_new, m_new)
} else {
self.tr_seed += tr;
self.plus_dm_seed += plus_dm;
self.minus_dm_seed += minus_dm;
self.seed_count += 1;
if self.seed_count < self.period {
return None;
}
self.tr_smooth = Some(self.tr_seed);
self.plus_dm_smooth = Some(self.plus_dm_seed);
self.minus_dm_smooth = Some(self.minus_dm_seed);
(self.tr_seed, self.plus_dm_seed, self.minus_dm_seed)
};
let plus_di = if tr_v == 0.0 {
0.0
} else {
100.0 * plus_v / tr_v
};
let minus_di = if tr_v == 0.0 {
0.0
} else {
100.0 * minus_v / tr_v
};
self.last_plus_di = plus_di;
self.last_minus_di = minus_di;
let dx_den = plus_di + minus_di;
let dx = if dx_den == 0.0 {
0.0
} else {
100.0 * (plus_di - minus_di).abs() / dx_den
};
if let Some(prev_adx) = self.adx_value {
let new_adx = (prev_adx * (n - 1.0) + dx) / n;
self.adx_value = Some(new_adx);
return Some(AdxOutput {
plus_di,
minus_di,
adx: new_adx,
});
}
self.dx_buf.push(dx);
if self.dx_buf.len() == self.period {
let seed = self.dx_buf.iter().sum::<f64>() / n;
self.adx_value = Some(seed);
return Some(AdxOutput {
plus_di,
minus_di,
adx: seed,
});
}
None
}
fn reset(&mut self) {
self.prev = None;
self.tr_seed = 0.0;
self.plus_dm_seed = 0.0;
self.minus_dm_seed = 0.0;
self.seed_count = 0;
self.tr_smooth = None;
self.plus_dm_smooth = None;
self.minus_dm_smooth = None;
self.dx_buf.clear();
self.adx_value = None;
self.last_plus_di = 0.0;
self.last_minus_di = 0.0;
}
fn warmup_period(&self) -> usize {
2 * self.period
}
fn is_ready(&self) -> bool {
self.adx_value.is_some()
}
fn name(&self) -> &'static str {
"ADX"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
fn c(h: f64, l: f64, cl: f64) -> Candle {
Candle::new(cl, h, l, cl, 1.0, 0).unwrap()
}
#[test]
fn pure_uptrend_yields_plus_di_dominant() {
// Strict uptrend: highs increase, lows increase, ADX should trend up,
// +DI should dominate -DI.
let candles: Vec<Candle> = (0..50)
.map(|i| {
let base = 100.0 + f64::from(i) * 2.0;
c(base + 1.0, base - 0.5, base + 0.5)
})
.collect();
let mut adx = Adx::new(14).unwrap();
let last = adx
.batch(&candles)
.into_iter()
.flatten()
.last()
.expect("emits");
assert!(
last.plus_di > last.minus_di,
"+DI {} should exceed -DI {}",
last.plus_di,
last.minus_di
);
assert!(last.adx > 0.0);
}
#[test]
fn pure_downtrend_yields_minus_di_dominant() {
let candles: Vec<Candle> = (0..50)
.rev()
.map(|i| {
let base = 100.0 + f64::from(i) * 2.0;
c(base + 1.0, base - 0.5, base + 0.5)
})
.collect();
let mut adx = Adx::new(14).unwrap();
let last = adx
.batch(&candles)
.into_iter()
.flatten()
.last()
.expect("emits");
assert!(last.minus_di > last.plus_di);
}
#[test]
fn rejects_zero_period() {
assert!(Adx::new(0).is_err());
}
#[test]
fn batch_equals_streaming() {
let candles: Vec<Candle> = (0..60)
.map(|i| {
let base = 100.0 + (f64::from(i) * 0.3).sin() * 5.0;
c(base + 1.0, base - 1.0, base)
})
.collect();
let mut a = Adx::new(14).unwrap();
let mut b = Adx::new(14).unwrap();
assert_eq!(
a.batch(&candles),
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
);
}
#[test]
fn reset_clears_state() {
let candles: Vec<Candle> = (0..40).map(|_| c(11.0, 9.0, 10.0)).collect();
let mut adx = Adx::new(14).unwrap();
adx.batch(&candles);
adx.reset();
assert!(!adx.is_ready());
}
#[test]
fn outputs_remain_finite() {
let candles: Vec<Candle> = (0..200)
.map(|i| {
let m = 100.0 + (f64::from(i) * 0.2).sin() * 5.0;
c(m + 1.0, m - 1.0, m)
})
.collect();
let mut adx = Adx::new(14).unwrap();
for v in adx.batch(&candles).into_iter().flatten() {
assert!(v.plus_di.is_finite() && v.minus_di.is_finite() && v.adx.is_finite());
}
// Sanity: ADX is bounded by 100.
let last = adx.batch(&candles).into_iter().flatten().last().unwrap();
assert!(last.adx <= 100.0 + 1e-6);
assert_relative_eq!(0.0_f64.max(last.adx), last.adx, epsilon = 1e-9);
}
}
+156
View File
@@ -0,0 +1,156 @@
//! Aroon Up / Down indicator.
use std::collections::VecDeque;
use crate::error::{Error, Result};
use crate::ohlcv::Candle;
use crate::traits::Indicator;
/// Aroon output: up and down strengths in [0, 100].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct AroonOutput {
/// Time since the highest high, expressed as a percentage of the window.
pub up: f64,
/// Time since the lowest low, same convention.
pub down: f64,
}
/// Aroon indicator: tracks how many bars since the highest high and lowest low
/// inside a `period + 1`-bar window. Returned as a percentage.
#[derive(Debug, Clone)]
pub struct Aroon {
period: usize,
candles: VecDeque<Candle>,
}
impl Aroon {
/// # Errors
/// Returns [`Error::PeriodZero`] if `period == 0`.
pub fn new(period: usize) -> Result<Self> {
if period == 0 {
return Err(Error::PeriodZero);
}
Ok(Self {
period,
candles: VecDeque::with_capacity(period + 1),
})
}
/// Configured period.
pub const fn period(&self) -> usize {
self.period
}
}
impl Indicator for Aroon {
type Input = Candle;
type Output = AroonOutput;
fn update(&mut self, candle: Candle) -> Option<AroonOutput> {
if self.candles.len() == self.period + 1 {
self.candles.pop_front();
}
self.candles.push_back(candle);
if self.candles.len() < self.period + 1 {
return None;
}
// Find the index (0 = oldest) of the highest high and lowest low.
let (mut hh_idx, mut ll_idx) = (0_usize, 0_usize);
let (mut hh, mut ll) = (f64::NEG_INFINITY, f64::INFINITY);
for (i, c) in self.candles.iter().enumerate() {
if c.high >= hh {
hh = c.high;
hh_idx = i;
}
if c.low <= ll {
ll = c.low;
ll_idx = i;
}
}
let n = self.period as f64;
let up = 100.0 * hh_idx as f64 / n;
let down = 100.0 * ll_idx as f64 / n;
Some(AroonOutput { up, down })
}
fn reset(&mut self) {
self.candles.clear();
}
fn warmup_period(&self) -> usize {
self.period + 1
}
fn is_ready(&self) -> bool {
self.candles.len() == self.period + 1
}
fn name(&self) -> &'static str {
"Aroon"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
fn c(h: f64, l: f64, cl: f64) -> Candle {
Candle::new(cl, h, l, cl, 1.0, 0).unwrap()
}
#[test]
fn pure_uptrend_aroon_up_100() {
let candles: Vec<Candle> = (1..=15)
.map(|i| c(f64::from(i) + 1.0, f64::from(i) - 1.0, f64::from(i)))
.collect();
let mut a = Aroon::new(14).unwrap();
let last = a.batch(&candles).into_iter().flatten().last().unwrap();
assert_relative_eq!(last.up, 100.0, epsilon = 1e-9);
// The lowest low is at the oldest position (index 0).
assert_relative_eq!(last.down, 0.0, epsilon = 1e-9);
}
#[test]
fn pure_downtrend_aroon_down_100() {
let candles: Vec<Candle> = (1..=15)
.rev()
.map(|i| c(f64::from(i) + 1.0, f64::from(i) - 1.0, f64::from(i)))
.collect();
let mut a = Aroon::new(14).unwrap();
let last = a.batch(&candles).into_iter().flatten().last().unwrap();
assert_relative_eq!(last.down, 100.0, epsilon = 1e-9);
}
#[test]
fn batch_equals_streaming() {
let candles: Vec<Candle> = (0..40)
.map(|i| {
let m = 50.0 + (f64::from(i) * 0.3).sin() * 5.0;
c(m + 1.0, m - 1.0, m)
})
.collect();
let mut a = Aroon::new(14).unwrap();
let mut b = Aroon::new(14).unwrap();
assert_eq!(
a.batch(&candles),
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
);
}
#[test]
fn outputs_in_range() {
let candles: Vec<Candle> = (0..200)
.map(|i| {
let m = 50.0 + (f64::from(i) * 0.2).sin() * 5.0;
c(m + 1.0, m - 1.0, m)
})
.collect();
let mut a = Aroon::new(14).unwrap();
for o in a.batch(&candles).into_iter().flatten() {
assert!((0.0..=100.0).contains(&o.up));
assert!((0.0..=100.0).contains(&o.down));
}
}
}
+190
View File
@@ -0,0 +1,190 @@
//! Average True Range (Wilder).
use crate::error::{Error, Result};
use crate::ohlcv::Candle;
use crate::traits::Indicator;
/// Average True Range with Wilder smoothing.
///
/// The first emitted value, by convention, appears after `period` candles: the
/// first `period 1` true-range values seed the Wilder average alongside the
/// `period`-th, then the smoothed update begins.
#[derive(Debug, Clone)]
pub struct Atr {
period: usize,
prev_close: Option<f64>,
seed_buf: Vec<f64>,
avg: Option<f64>,
}
impl Atr {
/// Construct an ATR with the given Wilder period.
///
/// # Errors
///
/// Returns [`Error::PeriodZero`] if `period == 0`.
pub fn new(period: usize) -> Result<Self> {
if period == 0 {
return Err(Error::PeriodZero);
}
Ok(Self {
period,
prev_close: None,
seed_buf: Vec::with_capacity(period),
avg: None,
})
}
/// Configured period.
pub const fn period(&self) -> usize {
self.period
}
/// Current value if available.
pub const fn value(&self) -> Option<f64> {
self.avg
}
}
impl Indicator for Atr {
type Input = Candle;
type Output = f64;
fn update(&mut self, candle: Candle) -> Option<f64> {
let tr = candle.true_range(self.prev_close);
self.prev_close = Some(candle.close);
if let Some(avg) = self.avg {
let n = self.period as f64;
let new_avg = avg.mul_add(n - 1.0, tr) / n;
self.avg = Some(new_avg);
return Some(new_avg);
}
self.seed_buf.push(tr);
if self.seed_buf.len() == self.period {
let seed = self.seed_buf.iter().copied().sum::<f64>() / self.period as f64;
self.avg = Some(seed);
return Some(seed);
}
None
}
fn reset(&mut self) {
self.prev_close = None;
self.seed_buf.clear();
self.avg = None;
}
fn warmup_period(&self) -> usize {
self.period
}
fn is_ready(&self) -> bool {
self.avg.is_some()
}
fn name(&self) -> &'static str {
"ATR"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
fn c(h: f64, l: f64, cl: f64) -> Candle {
// ts/open/volume don't affect ATR; use safe placeholders.
Candle::new(cl, h, l, cl, 1.0, 0).unwrap()
}
#[test]
fn rejects_zero_period() {
assert!(matches!(Atr::new(0), Err(Error::PeriodZero)));
}
#[test]
fn warmup_emits_on_period_th_candle() {
let candles = vec![
c(2.0, 1.0, 1.5),
c(3.0, 2.0, 2.5),
c(4.0, 3.0, 3.5),
c(5.0, 4.0, 4.5),
c(6.0, 5.0, 5.5),
];
let mut atr = Atr::new(3).unwrap();
let out = atr.batch(&candles);
assert!(out[0].is_none());
assert!(out[1].is_none());
assert!(out[2].is_some());
assert!(out[3].is_some());
}
#[test]
fn constant_range_yields_constant_atr() {
// Every candle has H=11, L=9, C=10 -> TR=2 (no gaps).
let candles: Vec<Candle> = (0..30).map(|_| c(11.0, 9.0, 10.0)).collect();
let mut atr = Atr::new(14).unwrap();
let out = atr.batch(&candles);
for v in out.iter().skip(13).flatten() {
assert_relative_eq!(*v, 2.0, epsilon = 1e-12);
}
}
#[test]
fn gap_up_uses_high_minus_prev_close() {
// Previous close 5, current candle H=10 L=9 C=9.5 -> TR = max(1, 5, 4) = 5.
let candles = vec![
c(6.0, 4.0, 5.0), // prev close = 5
c(10.0, 9.0, 9.5), // TR = 5
];
let mut atr = Atr::new(2).unwrap();
let out = atr.batch(&candles);
// Seed window covers TR_1 and TR_2. TR_1 = H1-L1 = 2 (no prev close). TR_2 = 5.
// Seed = (2+5)/2 = 3.5
assert_relative_eq!(out[1].unwrap(), 3.5, epsilon = 1e-12);
}
#[test]
fn batch_equals_streaming() {
let candles: Vec<Candle> = (0..40)
.map(|i| {
let mid = f64::from(i) + 10.0;
c(mid + 0.5, mid - 0.5, mid)
})
.collect();
let mut a = Atr::new(14).unwrap();
let mut b = Atr::new(14).unwrap();
assert_eq!(
a.batch(&candles),
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
);
}
#[test]
fn reset_clears_state() {
let candles: Vec<Candle> = (0..20).map(|_| c(11.0, 9.0, 10.0)).collect();
let mut atr = Atr::new(5).unwrap();
atr.batch(&candles);
assert!(atr.is_ready());
atr.reset();
assert!(!atr.is_ready());
assert_eq!(atr.update(candles[0]), None);
}
#[test]
fn never_negative() {
let candles: Vec<Candle> = (0..200)
.map(|i| {
let base = 100.0 + (f64::from(i) * 0.3).sin() * 5.0;
c(base + 1.0, base - 1.0, base)
})
.collect();
let mut atr = Atr::new(14).unwrap();
for v in atr.batch(&candles).into_iter().flatten() {
assert!(v >= 0.0, "ATR must be non-negative: {v}");
}
}
}
@@ -0,0 +1,117 @@
//! Awesome Oscillator (Bill Williams).
use crate::error::{Error, Result};
use crate::indicators::sma::Sma;
use crate::ohlcv::Candle;
use crate::traits::Indicator;
/// Awesome Oscillator: `SMA(median_price, 5) - SMA(median_price, 34)`.
#[derive(Debug, Clone)]
pub struct AwesomeOscillator {
fast: Sma,
slow: Sma,
fast_period: usize,
slow_period: usize,
}
impl AwesomeOscillator {
/// # Errors
/// Returns [`Error::PeriodZero`] for zero periods or [`Error::InvalidPeriod`] when fast >= slow.
pub fn new(fast: usize, slow: usize) -> Result<Self> {
if fast == 0 || slow == 0 {
return Err(Error::PeriodZero);
}
if fast >= slow {
return Err(Error::InvalidPeriod {
message: "AO fast period must be strictly less than slow",
});
}
Ok(Self {
fast: Sma::new(fast)?,
slow: Sma::new(slow)?,
fast_period: fast,
slow_period: slow,
})
}
/// Classic Bill Williams configuration: (5, 34).
pub fn classic() -> Self {
Self::new(5, 34).expect("classic AO periods are valid")
}
/// Configured `(fast, slow)` periods.
pub const fn periods(&self) -> (usize, usize) {
(self.fast_period, self.slow_period)
}
}
impl Indicator for AwesomeOscillator {
type Input = Candle;
type Output = f64;
fn update(&mut self, candle: Candle) -> Option<f64> {
let median = candle.median_price();
let f = self.fast.update(median);
let s = self.slow.update(median);
match (f, s) {
(Some(a), Some(b)) => Some(a - b),
_ => None,
}
}
fn reset(&mut self) {
self.fast.reset();
self.slow.reset();
}
fn warmup_period(&self) -> usize {
self.slow_period
}
fn is_ready(&self) -> bool {
self.slow.is_ready()
}
fn name(&self) -> &'static str {
"AwesomeOscillator"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
fn c(h: f64, l: f64, cl: f64) -> Candle {
Candle::new(cl, h, l, cl, 1.0, 0).unwrap()
}
#[test]
fn constant_series_yields_zero() {
let candles: Vec<Candle> = (0..80).map(|_| c(11.0, 9.0, 10.0)).collect();
let mut ao = AwesomeOscillator::classic();
let last = ao.batch(&candles).into_iter().flatten().last().unwrap();
assert_relative_eq!(last, 0.0, epsilon = 1e-9);
}
#[test]
fn rejects_fast_geq_slow() {
assert!(AwesomeOscillator::new(34, 5).is_err());
assert!(AwesomeOscillator::new(5, 5).is_err());
assert!(AwesomeOscillator::new(0, 5).is_err());
}
#[test]
fn batch_equals_streaming() {
let candles: Vec<Candle> = (0..50)
.map(|i| c(f64::from(i) + 1.0, f64::from(i) - 1.0, f64::from(i)))
.collect();
let mut a = AwesomeOscillator::classic();
let mut b = AwesomeOscillator::classic();
assert_eq!(
a.batch(&candles),
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
);
}
}
@@ -0,0 +1,243 @@
//! Bollinger Bands.
use std::collections::VecDeque;
use crate::error::{Error, Result};
use crate::traits::Indicator;
/// Bollinger Bands output.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct BollingerOutput {
/// Upper band: `middle + multiplier * stddev`.
pub upper: f64,
/// Middle band: SMA over the window.
pub middle: f64,
/// Lower band: `middle multiplier * stddev`.
pub lower: f64,
/// Sample standard deviation (denominator `period`, population stddev) used to build
/// the bands. Reported separately because some callers compute their own bands.
pub stddev: f64,
}
/// Bollinger Bands with SMA middle band and population standard deviation envelopes.
///
/// Standard parameters are `period = 20`, `multiplier = 2.0`. Bollinger's original
/// publication uses population (not sample) standard deviation, which matches every
/// reference implementation (TA-Lib, pandas-ta, etc.).
#[derive(Debug, Clone)]
pub struct BollingerBands {
period: usize,
multiplier: f64,
window: VecDeque<f64>,
sum: f64,
sum_sq: f64,
}
impl BollingerBands {
/// Construct a new Bollinger Bands indicator.
///
/// # Errors
///
/// Returns [`Error::PeriodZero`] for `period == 0` and
/// [`Error::NonPositiveMultiplier`] for `multiplier <= 0`.
pub fn new(period: usize, multiplier: f64) -> Result<Self> {
if period == 0 {
return Err(Error::PeriodZero);
}
if !multiplier.is_finite() || multiplier <= 0.0 {
return Err(Error::NonPositiveMultiplier);
}
Ok(Self {
period,
multiplier,
window: VecDeque::with_capacity(period),
sum: 0.0,
sum_sq: 0.0,
})
}
/// Classic configuration: `period = 20`, `multiplier = 2.0`.
pub fn classic() -> Self {
Self::new(20, 2.0).expect("classic Bollinger parameters are valid")
}
/// Configured period.
pub const fn period(&self) -> usize {
self.period
}
/// Configured multiplier.
pub const fn multiplier(&self) -> f64 {
self.multiplier
}
fn current(&self) -> Option<BollingerOutput> {
if self.window.len() != self.period {
return None;
}
let n = self.period as f64;
let mean = self.sum / n;
// Population variance: E[x^2] - (E[x])^2. Clamp small negative values that arise
// from catastrophic cancellation on near-constant inputs.
let var = (self.sum_sq / n - mean * mean).max(0.0);
let stddev = var.sqrt();
Some(BollingerOutput {
upper: mean + self.multiplier * stddev,
middle: mean,
lower: mean - self.multiplier * stddev,
stddev,
})
}
}
impl Indicator for BollingerBands {
type Input = f64;
type Output = BollingerOutput;
fn update(&mut self, input: f64) -> Option<BollingerOutput> {
if !input.is_finite() {
return self.current();
}
if self.window.len() == self.period {
let old = self.window.pop_front().expect("non-empty");
self.sum -= old;
self.sum_sq -= old * old;
}
self.window.push_back(input);
self.sum += input;
self.sum_sq += input * input;
self.current()
}
fn reset(&mut self) {
self.window.clear();
self.sum = 0.0;
self.sum_sq = 0.0;
}
fn warmup_period(&self) -> usize {
self.period
}
fn is_ready(&self) -> bool {
self.window.len() == self.period
}
fn name(&self) -> &'static str {
"BollingerBands"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
fn naive(prices: &[f64], period: usize, mult: f64) -> Option<BollingerOutput> {
if prices.len() < period {
return None;
}
let w = &prices[prices.len() - period..];
let mean = w.iter().sum::<f64>() / period as f64;
let var = w.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / period as f64;
let s = var.sqrt();
Some(BollingerOutput {
upper: mean + mult * s,
middle: mean,
lower: mean - mult * s,
stddev: s,
})
}
#[test]
fn rejects_zero_period() {
assert!(matches!(
BollingerBands::new(0, 2.0),
Err(Error::PeriodZero)
));
}
#[test]
fn rejects_non_positive_multiplier() {
assert!(matches!(
BollingerBands::new(20, 0.0),
Err(Error::NonPositiveMultiplier)
));
assert!(matches!(
BollingerBands::new(20, -1.0),
Err(Error::NonPositiveMultiplier)
));
assert!(matches!(
BollingerBands::new(20, f64::NAN),
Err(Error::NonPositiveMultiplier)
));
}
#[test]
fn warmup_returns_none() {
let mut bb = BollingerBands::new(5, 2.0).unwrap();
for v in [1.0, 2.0, 3.0, 4.0] {
assert!(bb.update(v).is_none());
}
assert!(bb.update(5.0).is_some());
}
#[test]
fn constant_series_yields_zero_stddev() {
let mut bb = BollingerBands::new(10, 2.0).unwrap();
let out = bb.batch(&[5.0_f64; 30]);
let last = out.iter().rev().flatten().next().unwrap();
assert_relative_eq!(last.middle, 5.0, epsilon = 1e-12);
assert_relative_eq!(last.stddev, 0.0, epsilon = 1e-12);
assert_relative_eq!(last.upper, 5.0, epsilon = 1e-12);
assert_relative_eq!(last.lower, 5.0, epsilon = 1e-12);
}
#[test]
fn matches_naive_definition() {
let prices: Vec<f64> = (1..=60)
.map(|i| (f64::from(i) * 0.3).sin() * 10.0 + 50.0)
.collect();
let mut bb = BollingerBands::new(20, 2.0).unwrap();
let out = bb.batch(&prices);
for i in 19..prices.len() {
let got = out[i].unwrap();
let want = naive(&prices[..=i], 20, 2.0).unwrap();
assert_relative_eq!(got.middle, want.middle, epsilon = 1e-9);
assert_relative_eq!(got.stddev, want.stddev, epsilon = 1e-9);
assert_relative_eq!(got.upper, want.upper, epsilon = 1e-9);
assert_relative_eq!(got.lower, want.lower, epsilon = 1e-9);
}
}
#[test]
fn upper_above_middle_above_lower() {
let prices: Vec<f64> = (1..=100).map(f64::from).collect();
let mut bb = BollingerBands::new(20, 2.0).unwrap();
for o in bb.batch(&prices).into_iter().flatten() {
assert!(o.upper >= o.middle);
assert!(o.middle >= o.lower);
}
}
#[test]
fn batch_equals_streaming() {
let prices: Vec<f64> = (1..=50).map(|i| f64::from(i) * 0.7).collect();
let mut a = BollingerBands::new(10, 2.0).unwrap();
let mut b = BollingerBands::new(10, 2.0).unwrap();
assert_eq!(
a.batch(&prices),
prices.iter().map(|p| b.update(*p)).collect::<Vec<_>>()
);
}
#[test]
fn reset_clears_state() {
let mut bb = BollingerBands::new(5, 2.0).unwrap();
bb.batch(&[1.0, 2.0, 3.0, 4.0, 5.0]);
assert!(bb.is_ready());
bb.reset();
assert!(!bb.is_ready());
}
}
+150
View File
@@ -0,0 +1,150 @@
//! Commodity Channel Index (CCI).
use std::collections::VecDeque;
use crate::error::{Error, Result};
use crate::ohlcv::Candle;
use crate::traits::Indicator;
/// Commodity Channel Index.
///
/// `CCI = (TP - SMA(TP)) / (0.015 * mean absolute deviation of TP)`, where
/// `TP = (high + low + close) / 3`.
#[derive(Debug, Clone)]
pub struct Cci {
period: usize,
factor: f64,
window: VecDeque<f64>,
sum: f64,
}
impl Cci {
/// Construct a new CCI with the canonical 0.015 scaling factor.
///
/// # Errors
/// Returns [`Error::PeriodZero`] if `period == 0`.
pub fn new(period: usize) -> Result<Self> {
Self::with_factor(period, 0.015)
}
/// Construct a CCI with a custom scaling factor (the standard literature
/// uses 0.015 to put roughly 70 % of values inside ±100).
///
/// # Errors
/// Returns [`Error::PeriodZero`] if `period == 0` and
/// [`Error::NonPositiveMultiplier`] if `factor <= 0`.
pub fn with_factor(period: usize, factor: f64) -> Result<Self> {
if period == 0 {
return Err(Error::PeriodZero);
}
if !factor.is_finite() || factor <= 0.0 {
return Err(Error::NonPositiveMultiplier);
}
Ok(Self {
period,
factor,
window: VecDeque::with_capacity(period),
sum: 0.0,
})
}
/// Configured period.
pub const fn period(&self) -> usize {
self.period
}
}
impl Indicator for Cci {
type Input = Candle;
type Output = f64;
fn update(&mut self, candle: Candle) -> Option<f64> {
let tp = candle.typical_price();
if self.window.len() == self.period {
let old = self.window.pop_front().expect("non-empty");
self.sum -= old;
}
self.window.push_back(tp);
self.sum += tp;
if self.window.len() < self.period {
return None;
}
let n = self.period as f64;
let mean = self.sum / n;
let mad: f64 = self.window.iter().map(|v| (v - mean).abs()).sum::<f64>() / n;
if mad == 0.0 {
return Some(0.0);
}
Some((tp - mean) / (self.factor * mad))
}
fn reset(&mut self) {
self.window.clear();
self.sum = 0.0;
}
fn warmup_period(&self) -> usize {
self.period
}
fn is_ready(&self) -> bool {
self.window.len() == self.period
}
fn name(&self) -> &'static str {
"CCI"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
fn c(h: f64, l: f64, cl: f64) -> Candle {
Candle::new(cl, h, l, cl, 1.0, 0).unwrap()
}
#[test]
fn flat_candles_yield_zero() {
let candles: Vec<Candle> = (0..30).map(|_| c(10.0, 10.0, 10.0)).collect();
let mut cci = Cci::new(20).unwrap();
for v in cci.batch(&candles).into_iter().flatten() {
assert_relative_eq!(v, 0.0, epsilon = 1e-12);
}
}
#[test]
fn rejects_invalid_input() {
assert!(Cci::new(0).is_err());
assert!(Cci::with_factor(20, 0.0).is_err());
assert!(Cci::with_factor(20, -1.0).is_err());
}
#[test]
fn batch_equals_streaming() {
let candles: Vec<Candle> = (0..60)
.map(|i| {
let m = 50.0 + (f64::from(i) * 0.2).sin() * 10.0;
c(m + 1.0, m - 1.0, m)
})
.collect();
let mut a = Cci::new(20).unwrap();
let mut b = Cci::new(20).unwrap();
assert_eq!(
a.batch(&candles),
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
);
}
#[test]
fn reset_clears_state() {
let candles: Vec<Candle> = (0..30).map(|_| c(10.0, 10.0, 10.0)).collect();
let mut cci = Cci::new(20).unwrap();
cci.batch(&candles);
assert!(cci.is_ready());
cci.reset();
assert!(!cci.is_ready());
}
}
+117
View File
@@ -0,0 +1,117 @@
//! Double Exponential Moving Average (DEMA).
use crate::error::Result;
use crate::indicators::ema::Ema;
use crate::traits::Indicator;
/// Double Exponential Moving Average: `2 * EMA - EMA(EMA)`.
///
/// Designed by Patrick Mulloy to reduce the lag of a single EMA while keeping
/// the smoothing benefit.
#[derive(Debug, Clone)]
pub struct Dema {
ema1: Ema,
ema2: Ema,
period: usize,
}
impl Dema {
/// # Errors
/// Returns [`crate::Error::PeriodZero`] if `period == 0`.
pub fn new(period: usize) -> Result<Self> {
Ok(Self {
ema1: Ema::new(period)?,
ema2: Ema::new(period)?,
period,
})
}
/// Configured period.
pub const fn period(&self) -> usize {
self.period
}
}
impl Indicator for Dema {
type Input = f64;
type Output = f64;
fn update(&mut self, input: f64) -> Option<f64> {
let e1 = self.ema1.update(input)?;
let e2 = self.ema2.update(e1)?;
Some(2.0 * e1 - e2)
}
fn reset(&mut self) {
self.ema1.reset();
self.ema2.reset();
}
fn warmup_period(&self) -> usize {
// EMA1 seeds at period, then EMA2 needs another (period - 1) values to seed.
2 * self.period - 1
}
fn is_ready(&self) -> bool {
self.ema2.is_ready()
}
fn name(&self) -> &'static str {
"DEMA"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
#[test]
fn constant_series_yields_constant_dema() {
let mut dema = Dema::new(5).unwrap();
let out = dema.batch(&[100.0_f64; 60]);
let last = out.iter().rev().flatten().next().unwrap();
assert_relative_eq!(*last, 100.0, epsilon = 1e-9);
}
#[test]
fn linear_uptrend_dema_above_ema_eventually() {
// On a linear uptrend DEMA should be ahead of (greater than) a plain EMA,
// because the second-order correction removes lag.
let prices: Vec<f64> = (1..=200).map(f64::from).collect();
let mut dema = Dema::new(20).unwrap();
let mut ema = Ema::new(20).unwrap();
let dema_out = dema.batch(&prices);
let ema_out = ema.batch(&prices);
// Compare at the last index where both are ready.
let d = dema_out.last().unwrap().unwrap();
let e = ema_out.last().unwrap().unwrap();
assert!(d > e, "DEMA={d} should exceed EMA={e} on uptrend");
}
#[test]
fn batch_equals_streaming() {
let prices: Vec<f64> = (1..=80).map(|i| f64::from(i) * 0.5).collect();
let mut a = Dema::new(7).unwrap();
let mut b = Dema::new(7).unwrap();
assert_eq!(
a.batch(&prices),
prices.iter().map(|p| b.update(*p)).collect::<Vec<_>>()
);
}
#[test]
fn reset_clears_state() {
let mut dema = Dema::new(5).unwrap();
dema.batch(&(1..=50).map(f64::from).collect::<Vec<_>>());
assert!(dema.is_ready());
dema.reset();
assert!(!dema.is_ready());
}
#[test]
fn rejects_zero_period() {
assert!(Dema::new(0).is_err());
}
}
@@ -0,0 +1,141 @@
//! Donchian Channels.
use std::collections::VecDeque;
use crate::error::{Error, Result};
use crate::ohlcv::Candle;
use crate::traits::Indicator;
/// Donchian Channels output.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct DonchianOutput {
/// Highest high over the lookback.
pub upper: f64,
/// Average of upper and lower.
pub middle: f64,
/// Lowest low over the lookback.
pub lower: f64,
}
/// Donchian Channels: rolling highest high / lowest low envelopes.
#[derive(Debug, Clone)]
pub struct Donchian {
period: usize,
candles: VecDeque<Candle>,
}
impl Donchian {
/// # Errors
/// Returns [`Error::PeriodZero`] if `period == 0`.
pub fn new(period: usize) -> Result<Self> {
if period == 0 {
return Err(Error::PeriodZero);
}
Ok(Self {
period,
candles: VecDeque::with_capacity(period),
})
}
/// Configured period.
pub const fn period(&self) -> usize {
self.period
}
}
impl Indicator for Donchian {
type Input = Candle;
type Output = DonchianOutput;
fn update(&mut self, candle: Candle) -> Option<DonchianOutput> {
if self.candles.len() == self.period {
self.candles.pop_front();
}
self.candles.push_back(candle);
if self.candles.len() < self.period {
return None;
}
let upper = self
.candles
.iter()
.map(|c| c.high)
.fold(f64::NEG_INFINITY, f64::max);
let lower = self
.candles
.iter()
.map(|c| c.low)
.fold(f64::INFINITY, f64::min);
Some(DonchianOutput {
upper,
middle: (upper + lower) / 2.0,
lower,
})
}
fn reset(&mut self) {
self.candles.clear();
}
fn warmup_period(&self) -> usize {
self.period
}
fn is_ready(&self) -> bool {
self.candles.len() == self.period
}
fn name(&self) -> &'static str {
"DonchianChannels"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
fn c(h: f64, l: f64, cl: f64) -> Candle {
Candle::new(cl, h, l, cl, 1.0, 0).unwrap()
}
#[test]
fn flat_market_yields_equal_bands() {
let candles: Vec<Candle> = (0..20).map(|_| c(11.0, 9.0, 10.0)).collect();
let mut d = Donchian::new(5).unwrap();
let last = d.batch(&candles).into_iter().flatten().last().unwrap();
assert_relative_eq!(last.upper, 11.0, epsilon = 1e-12);
assert_relative_eq!(last.lower, 9.0, epsilon = 1e-12);
assert_relative_eq!(last.middle, 10.0, epsilon = 1e-12);
}
#[test]
fn batch_equals_streaming() {
let candles: Vec<Candle> = (0..40)
.map(|i| c(f64::from(i) + 2.0, f64::from(i), f64::from(i) + 1.0))
.collect();
let mut a = Donchian::new(10).unwrap();
let mut b = Donchian::new(10).unwrap();
assert_eq!(
a.batch(&candles),
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
);
}
#[test]
fn upper_above_middle_above_lower() {
let candles: Vec<Candle> = (0..50)
.map(|i| c(f64::from(i) + 1.0, f64::from(i) - 1.0, f64::from(i)))
.collect();
let mut d = Donchian::new(10).unwrap();
for o in d.batch(&candles).into_iter().flatten() {
assert!(o.upper >= o.middle);
assert!(o.middle >= o.lower);
}
}
#[test]
fn rejects_zero_period() {
assert!(Donchian::new(0).is_err());
}
}
+224
View File
@@ -0,0 +1,224 @@
//! Exponential Moving Average.
use crate::error::{Error, Result};
use crate::traits::Indicator;
/// Exponential Moving Average with smoothing factor `alpha = 2 / (period + 1)`.
///
/// The first value is seeded with the simple mean of the first `period` inputs
/// (the classical TA-Lib convention). From then on each new input contributes
/// `alpha * input + (1 - alpha) * previous`.
#[derive(Debug, Clone)]
pub struct Ema {
period: usize,
alpha: f64,
state: Option<f64>,
warmup_buf: Vec<f64>,
}
impl Ema {
/// Construct an EMA with the given period.
///
/// # Errors
///
/// Returns [`Error::PeriodZero`] if `period == 0`.
pub fn new(period: usize) -> Result<Self> {
if period == 0 {
return Err(Error::PeriodZero);
}
let alpha = 2.0 / (period as f64 + 1.0);
Ok(Self {
period,
alpha,
state: None,
warmup_buf: Vec::with_capacity(period),
})
}
/// Construct an EMA with a custom smoothing factor `alpha in (0, 1]`.
///
/// The reported `period` is derived from `alpha` via `2/alpha - 1` and rounded;
/// `warmup_period()` falls back to `1` because the implementation seeds from the
/// very first input.
///
/// # Errors
///
/// Returns [`Error::InvalidPeriod`] if `alpha` is not in `(0.0, 1.0]` or non-finite.
pub fn with_alpha(alpha: f64) -> Result<Self> {
if !alpha.is_finite() || alpha <= 0.0 || alpha > 1.0 {
return Err(Error::InvalidPeriod {
message: "alpha must be in (0.0, 1.0]",
});
}
Ok(Self {
period: 1,
alpha,
state: None,
warmup_buf: Vec::with_capacity(1),
})
}
/// Configured period.
pub const fn period(&self) -> usize {
self.period
}
/// Smoothing factor.
pub const fn alpha(&self) -> f64 {
self.alpha
}
/// Current value if available.
pub const fn value(&self) -> Option<f64> {
self.state
}
/// Internal helper that feeds a value without finiteness validation. The caller
/// guarantees `input.is_finite()`. Used by MACD which has already validated.
pub(crate) fn step_unchecked(&mut self, input: f64) -> Option<f64> {
if let Some(prev) = self.state {
let new = self.alpha.mul_add(input, (1.0 - self.alpha) * prev);
self.state = Some(new);
return Some(new);
}
self.warmup_buf.push(input);
if self.warmup_buf.len() == self.period {
let seed = self.warmup_buf.iter().copied().sum::<f64>() / self.period as f64;
self.state = Some(seed);
return Some(seed);
}
None
}
}
impl Indicator for Ema {
type Input = f64;
type Output = f64;
fn update(&mut self, input: f64) -> Option<f64> {
if !input.is_finite() {
return self.state;
}
self.step_unchecked(input)
}
fn reset(&mut self) {
self.state = None;
self.warmup_buf.clear();
}
fn warmup_period(&self) -> usize {
self.period
}
fn is_ready(&self) -> bool {
self.state.is_some()
}
fn name(&self) -> &'static str {
"EMA"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
#[test]
fn new_rejects_zero_period() {
assert!(matches!(Ema::new(0), Err(Error::PeriodZero)));
}
#[test]
fn warmup_returns_none_until_seed() {
let mut ema = Ema::new(3).unwrap();
assert_eq!(ema.update(1.0), None);
assert_eq!(ema.update(2.0), None);
assert_eq!(ema.update(3.0), Some(2.0)); // seed = SMA([1,2,3]) = 2
}
#[test]
fn first_value_equals_sma_seed() {
let mut ema = Ema::new(5).unwrap();
let inputs = [10.0, 20.0, 30.0, 40.0, 50.0];
let mut last = None;
for v in inputs {
last = ema.update(v);
}
assert_relative_eq!(last.unwrap(), 30.0, epsilon = 1e-12);
}
#[test]
fn alpha_matches_period_formula() {
let ema = Ema::new(10).unwrap();
assert_relative_eq!(ema.alpha(), 2.0 / 11.0, epsilon = 1e-15);
}
#[test]
fn step_after_seed_uses_alpha_formula() {
// period=3 => alpha = 0.5; seed = mean([1,2,3]) = 2; next input 10
// expected = 0.5*10 + 0.5*2 = 6
let mut ema = Ema::new(3).unwrap();
ema.batch(&[1.0, 2.0, 3.0]);
assert_relative_eq!(ema.update(10.0).unwrap(), 6.0, epsilon = 1e-12);
}
#[test]
fn constant_series_converges_to_constant() {
let mut ema = Ema::new(10).unwrap();
let out = ema.batch(&[42.0_f64; 100]);
for x in out.iter().skip(9) {
assert_relative_eq!(x.unwrap(), 42.0, epsilon = 1e-9);
}
}
#[test]
fn with_alpha_validates_range() {
assert!(Ema::with_alpha(0.5).is_ok());
assert!(Ema::with_alpha(1.0).is_ok());
assert!(matches!(
Ema::with_alpha(0.0),
Err(Error::InvalidPeriod { .. })
));
assert!(matches!(
Ema::with_alpha(1.5),
Err(Error::InvalidPeriod { .. })
));
assert!(matches!(
Ema::with_alpha(f64::NAN),
Err(Error::InvalidPeriod { .. })
));
}
#[test]
fn reset_clears_state() {
let mut ema = Ema::new(3).unwrap();
ema.batch(&[1.0, 2.0, 3.0]);
assert!(ema.is_ready());
ema.reset();
assert!(!ema.is_ready());
assert_eq!(ema.update(1.0), None);
}
#[test]
fn batch_equals_streaming() {
let prices: Vec<f64> = (1..=30).map(f64::from).collect();
let mut a = Ema::new(5).unwrap();
let mut b = Ema::new(5).unwrap();
assert_eq!(
a.batch(&prices),
prices.iter().map(|p| b.update(*p)).collect::<Vec<_>>()
);
}
#[test]
fn ignores_non_finite_input() {
let mut ema = Ema::new(3).unwrap();
ema.batch(&[1.0, 2.0, 3.0]);
let before = ema.value();
assert_eq!(ema.update(f64::NAN), before);
assert_eq!(ema.update(f64::INFINITY), before);
}
}
+112
View File
@@ -0,0 +1,112 @@
//! Hull Moving Average (HMA).
use crate::error::{Error, Result};
use crate::indicators::wma::Wma;
use crate::traits::Indicator;
/// Hull Moving Average: `WMA(2 * WMA(n/2) - WMA(n), sqrt(n))`.
///
/// Designed by Alan Hull as a lag-free moving average that is also responsive.
/// The square root of the period is rounded to the nearest integer (minimum 1).
#[derive(Debug, Clone)]
pub struct Hma {
period: usize,
half_wma: Wma,
full_wma: Wma,
smooth_wma: Wma,
}
impl Hma {
/// # Errors
/// Returns [`Error::PeriodZero`] if `period == 0`.
pub fn new(period: usize) -> Result<Self> {
if period == 0 {
return Err(Error::PeriodZero);
}
let half = (period / 2).max(1);
let smooth = (period as f64).sqrt().round() as usize;
let smooth = smooth.max(1);
Ok(Self {
period,
half_wma: Wma::new(half)?,
full_wma: Wma::new(period)?,
smooth_wma: Wma::new(smooth)?,
})
}
/// Configured period.
pub const fn period(&self) -> usize {
self.period
}
}
impl Indicator for Hma {
type Input = f64;
type Output = f64;
fn update(&mut self, input: f64) -> Option<f64> {
let h = self.half_wma.update(input)?;
let f = self.full_wma.update(input)?;
let diff = 2.0 * h - f;
self.smooth_wma.update(diff)
}
fn reset(&mut self) {
self.half_wma.reset();
self.full_wma.reset();
self.smooth_wma.reset();
}
fn warmup_period(&self) -> usize {
let sm = (self.period as f64).sqrt().round() as usize;
self.period + sm.max(1) - 1
}
fn is_ready(&self) -> bool {
self.smooth_wma.is_ready()
}
fn name(&self) -> &'static str {
"HMA"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
#[test]
fn constant_series_yields_constant_hma() {
let mut hma = Hma::new(9).unwrap();
let out = hma.batch(&[10.0_f64; 80]);
let last = out.iter().rev().flatten().next().unwrap();
assert_relative_eq!(*last, 10.0, epsilon = 1e-9);
}
#[test]
fn batch_equals_streaming() {
let prices: Vec<f64> = (1..=100).map(|i| f64::from(i) * 0.7).collect();
let mut a = Hma::new(9).unwrap();
let mut b = Hma::new(9).unwrap();
assert_eq!(
a.batch(&prices),
prices.iter().map(|p| b.update(*p)).collect::<Vec<_>>()
);
}
#[test]
fn reset_clears_state() {
let mut hma = Hma::new(9).unwrap();
hma.batch(&(1..=80).map(f64::from).collect::<Vec<_>>());
assert!(hma.is_ready());
hma.reset();
assert!(!hma.is_ready());
}
#[test]
fn rejects_zero_period() {
assert!(Hma::new(0).is_err());
}
}
+157
View File
@@ -0,0 +1,157 @@
//! Kaufman's Adaptive Moving Average (KAMA).
use std::collections::VecDeque;
use crate::error::{Error, Result};
use crate::traits::Indicator;
/// Kaufman's Adaptive Moving Average.
///
/// KAMA adapts its smoothing constant to volatility: efficient (trending) markets
/// get a fast smoothing constant, choppy markets get a slow one. Parameters are
/// the efficiency-ratio lookback (`er_period`, default 10), the fast EMA period
/// (`fast`, default 2) and the slow EMA period (`slow`, default 30).
#[derive(Debug, Clone)]
pub struct Kama {
er_period: usize,
fast_sc: f64,
slow_sc: f64,
window: VecDeque<f64>,
state: Option<f64>,
}
impl Kama {
/// # Errors
/// Returns [`Error::PeriodZero`] / [`Error::InvalidPeriod`] for bad parameters.
pub fn new(er_period: usize, fast: usize, slow: usize) -> Result<Self> {
if er_period == 0 || fast == 0 || slow == 0 {
return Err(Error::PeriodZero);
}
if fast >= slow {
return Err(Error::InvalidPeriod {
message: "KAMA fast period must be strictly less than slow",
});
}
let fast_sc = 2.0 / (fast as f64 + 1.0);
let slow_sc = 2.0 / (slow as f64 + 1.0);
Ok(Self {
er_period,
fast_sc,
slow_sc,
window: VecDeque::with_capacity(er_period + 1),
state: None,
})
}
/// Classic Kaufman parameters: (10, 2, 30).
pub fn classic() -> Self {
Self::new(10, 2, 30).expect("classic KAMA parameters are valid")
}
/// Configured `(er_period, fast, slow)` periods.
pub fn periods(&self) -> (usize, f64, f64) {
(self.er_period, self.fast_sc, self.slow_sc)
}
}
impl Indicator for Kama {
type Input = f64;
type Output = f64;
fn update(&mut self, input: f64) -> Option<f64> {
if !input.is_finite() {
return self.state;
}
if self.window.len() == self.er_period + 1 {
self.window.pop_front();
}
self.window.push_back(input);
if self.window.len() < self.er_period + 1 {
return None;
}
let first = *self.window.front().expect("non-empty");
let last = *self.window.back().expect("non-empty");
let direction = (last - first).abs();
let volatility: f64 = self
.window
.iter()
.zip(self.window.iter().skip(1))
.map(|(a, b)| (b - a).abs())
.sum();
let er = if volatility == 0.0 {
0.0
} else {
direction / volatility
};
let sc = (er * (self.fast_sc - self.slow_sc) + self.slow_sc).powi(2);
let prev = self.state.unwrap_or(first);
let new = prev + sc * (input - prev);
self.state = Some(new);
Some(new)
}
fn reset(&mut self) {
self.window.clear();
self.state = None;
}
fn warmup_period(&self) -> usize {
self.er_period + 1
}
fn is_ready(&self) -> bool {
self.state.is_some()
}
fn name(&self) -> &'static str {
"KAMA"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
#[test]
fn constant_series_yields_constant_kama() {
let mut k = Kama::classic();
let out = k.batch(&[100.0_f64; 100]);
let last = out.iter().rev().flatten().next().unwrap();
assert_relative_eq!(*last, 100.0, epsilon = 1e-9);
}
#[test]
fn rejects_invalid_periods() {
assert!(Kama::new(0, 2, 30).is_err());
assert!(Kama::new(10, 30, 2).is_err()); // fast >= slow
assert!(Kama::new(10, 2, 2).is_err()); // fast == slow
}
#[test]
fn batch_equals_streaming() {
let prices: Vec<f64> = (1..=120)
.map(|i| (f64::from(i) * 0.2).sin() * 5.0 + f64::from(i) * 0.1)
.collect();
let mut a = Kama::classic();
let mut b = Kama::classic();
assert_eq!(
a.batch(&prices),
prices.iter().map(|p| b.update(*p)).collect::<Vec<_>>()
);
}
#[test]
fn reset_clears_state() {
let mut k = Kama::classic();
k.batch(&(1..=50).map(f64::from).collect::<Vec<_>>());
assert!(k.is_ready());
k.reset();
assert!(!k.is_ready());
}
}
@@ -0,0 +1,142 @@
//! Keltner Channels.
use crate::error::{Error, Result};
use crate::indicators::atr::Atr;
use crate::indicators::ema::Ema;
use crate::ohlcv::Candle;
use crate::traits::Indicator;
/// Keltner Channels output.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct KeltnerOutput {
/// Upper band = middle + multiplier * ATR.
pub upper: f64,
/// Middle band = EMA of typical price.
pub middle: f64,
/// Lower band = middle - multiplier * ATR.
pub lower: f64,
}
/// Keltner Channels: an EMA centerline with bands sized by ATR.
#[derive(Debug, Clone)]
pub struct Keltner {
ema: Ema,
atr: Atr,
multiplier: f64,
ema_period: usize,
atr_period: usize,
}
impl Keltner {
/// # Errors
/// Returns [`Error::PeriodZero`] / [`Error::NonPositiveMultiplier`] on invalid inputs.
pub fn new(ema_period: usize, atr_period: usize, multiplier: f64) -> Result<Self> {
if !multiplier.is_finite() || multiplier <= 0.0 {
return Err(Error::NonPositiveMultiplier);
}
Ok(Self {
ema: Ema::new(ema_period)?,
atr: Atr::new(atr_period)?,
multiplier,
ema_period,
atr_period,
})
}
/// Classic configuration: EMA(20), ATR(10), 2.0x multiplier.
pub fn classic() -> Self {
Self::new(20, 10, 2.0).expect("classic Keltner parameters are valid")
}
/// Configured `(ema_period, atr_period, multiplier)`.
pub const fn periods(&self) -> (usize, usize, f64) {
(self.ema_period, self.atr_period, self.multiplier)
}
}
impl Indicator for Keltner {
type Input = Candle;
type Output = KeltnerOutput;
fn update(&mut self, candle: Candle) -> Option<KeltnerOutput> {
let mid = self.ema.update(candle.typical_price())?;
let atr = self.atr.update(candle)?;
Some(KeltnerOutput {
upper: mid + self.multiplier * atr,
middle: mid,
lower: mid - self.multiplier * atr,
})
}
fn reset(&mut self) {
self.ema.reset();
self.atr.reset();
}
fn warmup_period(&self) -> usize {
self.ema_period.max(self.atr_period)
}
fn is_ready(&self) -> bool {
self.ema.is_ready() && self.atr.is_ready()
}
fn name(&self) -> &'static str {
"KeltnerChannels"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
fn c(h: f64, l: f64, cl: f64) -> Candle {
Candle::new(cl, h, l, cl, 1.0, 0).unwrap()
}
#[test]
fn flat_market_collapses_bands() {
let candles: Vec<Candle> = (0..50).map(|_| c(10.0, 10.0, 10.0)).collect();
let mut k = Keltner::new(20, 10, 2.0).unwrap();
let last = k.batch(&candles).into_iter().flatten().last().unwrap();
assert_relative_eq!(last.upper, last.middle, epsilon = 1e-9);
assert_relative_eq!(last.lower, last.middle, epsilon = 1e-9);
}
#[test]
fn upper_above_middle_above_lower() {
let candles: Vec<Candle> = (0..100)
.map(|i| {
let m = 100.0 + (f64::from(i) * 0.2).sin() * 5.0;
c(m + 1.0, m - 1.0, m)
})
.collect();
let mut k = Keltner::classic();
for o in k.batch(&candles).into_iter().flatten() {
assert!(o.upper >= o.middle);
assert!(o.middle >= o.lower);
}
}
#[test]
fn batch_equals_streaming() {
let candles: Vec<Candle> = (0..50)
.map(|i| c(f64::from(i) + 1.0, f64::from(i) - 1.0, f64::from(i)))
.collect();
let mut a = Keltner::classic();
let mut b = Keltner::classic();
assert_eq!(
a.batch(&candles),
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
);
}
#[test]
fn rejects_invalid_input() {
assert!(Keltner::new(0, 10, 2.0).is_err());
assert!(Keltner::new(20, 10, 0.0).is_err());
assert!(Keltner::new(20, 10, -1.0).is_err());
}
}
+230
View File
@@ -0,0 +1,230 @@
//! Moving Average Convergence Divergence (MACD).
use crate::error::{Error, Result};
use crate::indicators::ema::Ema;
use crate::traits::Indicator;
/// MACD output: the three classic series at a given step.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MacdOutput {
/// Fast EMA slow EMA.
pub macd: f64,
/// EMA of `macd` over the signal period.
pub signal: f64,
/// `macd signal`.
pub histogram: f64,
}
/// MACD = EMA(fast) EMA(slow), with a signal EMA on top.
///
/// Standard parameters are `fast = 12`, `slow = 26`, `signal = 9`. The signal EMA
/// is seeded from the first `signal` raw MACD values, so the first full
/// [`MacdOutput`] is emitted after `slow + signal 1` inputs (assuming the
/// slow EMA seeded by then).
#[derive(Debug, Clone)]
pub struct MacdIndicator {
fast: Ema,
slow: Ema,
signal_ema: Ema,
fast_period: usize,
slow_period: usize,
signal_period: usize,
last: Option<MacdOutput>,
}
impl MacdIndicator {
/// Construct a MACD with the given periods.
///
/// # Errors
///
/// Returns [`Error::PeriodZero`] if any period is zero, and
/// [`Error::InvalidPeriod`] if `fast >= slow`.
pub fn new(fast: usize, slow: usize, signal: usize) -> Result<Self> {
if fast == 0 || slow == 0 || signal == 0 {
return Err(Error::PeriodZero);
}
if fast >= slow {
return Err(Error::InvalidPeriod {
message: "fast period must be strictly less than slow period",
});
}
Ok(Self {
fast: Ema::new(fast)?,
slow: Ema::new(slow)?,
signal_ema: Ema::new(signal)?,
fast_period: fast,
slow_period: slow,
signal_period: signal,
last: None,
})
}
/// Default `(12, 26, 9)` configuration, matching every classical chart package.
pub fn classic() -> Self {
Self::new(12, 26, 9).expect("classic MACD periods are valid")
}
/// Configured periods as `(fast, slow, signal)`.
pub const fn periods(&self) -> (usize, usize, usize) {
(self.fast_period, self.slow_period, self.signal_period)
}
/// Most recent fully-computed output if available.
pub const fn value(&self) -> Option<MacdOutput> {
self.last
}
}
impl Indicator for MacdIndicator {
type Input = f64;
type Output = MacdOutput;
fn update(&mut self, input: f64) -> Option<MacdOutput> {
if !input.is_finite() {
return self.last;
}
let fast = self.fast.update(input);
let slow = self.slow.update(input);
match (fast, slow) {
(Some(f), Some(s)) => {
let macd = f - s;
let signal = self.signal_ema.update(macd)?;
let out = MacdOutput {
macd,
signal,
histogram: macd - signal,
};
self.last = Some(out);
Some(out)
}
_ => None,
}
}
fn reset(&mut self) {
self.fast.reset();
self.slow.reset();
self.signal_ema.reset();
self.last = None;
}
fn warmup_period(&self) -> usize {
// Slow EMA needs `slow` inputs to seed; signal EMA needs another `signal - 1`.
self.slow_period + self.signal_period - 1
}
fn is_ready(&self) -> bool {
self.last.is_some()
}
fn name(&self) -> &'static str {
"MACD"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
#[test]
fn rejects_fast_geq_slow() {
assert!(matches!(
MacdIndicator::new(26, 12, 9),
Err(Error::InvalidPeriod { .. })
));
assert!(matches!(
MacdIndicator::new(12, 12, 9),
Err(Error::InvalidPeriod { .. })
));
}
#[test]
fn rejects_zero_periods() {
assert!(matches!(
MacdIndicator::new(0, 26, 9),
Err(Error::PeriodZero)
));
assert!(matches!(
MacdIndicator::new(12, 0, 9),
Err(Error::PeriodZero)
));
assert!(matches!(
MacdIndicator::new(12, 26, 0),
Err(Error::PeriodZero)
));
}
#[test]
fn first_emission_matches_warmup_period() {
let prices: Vec<f64> = (1..=60).map(f64::from).collect();
let mut macd = MacdIndicator::classic();
let out = macd.batch(&prices);
let warmup = macd.warmup_period();
// Indices 0..warmup-1 are None, index warmup-1 might be Some or might still need
// the signal EMA's seeding. Our warmup_period is the index at which the first
// signal value appears: slow + signal - 1.
for x in out.iter().take(warmup - 1) {
assert!(x.is_none(), "expected None within warmup");
}
assert!(
out[warmup - 1].is_some(),
"expected first emission at warmup_period - 1 ({warmup} idx)"
);
}
#[test]
fn histogram_equals_macd_minus_signal() {
let prices: Vec<f64> = (1..=80).map(|i| f64::from(i) * 0.5).collect();
let mut macd = MacdIndicator::classic();
for v in macd.batch(&prices).into_iter().flatten() {
assert_relative_eq!(v.histogram, v.macd - v.signal, epsilon = 1e-12);
}
}
#[test]
fn constant_series_yields_zero_macd_eventually() {
let mut macd = MacdIndicator::classic();
let out = macd.batch(&[100.0_f64; 200]);
// Both EMAs converge to 100, so MACD must approach 0.
let last = out.iter().rev().flatten().next().expect("emits a value");
assert_relative_eq!(last.macd, 0.0, epsilon = 1e-9);
assert_relative_eq!(last.signal, 0.0, epsilon = 1e-9);
assert_relative_eq!(last.histogram, 0.0, epsilon = 1e-9);
}
#[test]
fn rising_series_macd_positive_then_signal_catches_up() {
let prices: Vec<f64> = (1..=200).map(f64::from).collect();
let mut macd = MacdIndicator::classic();
let out = macd.batch(&prices);
let last = out.iter().rev().flatten().next().unwrap();
assert!(last.macd > 0.0, "rising series must yield positive MACD");
}
#[test]
fn batch_equals_streaming() {
let prices: Vec<f64> = (1..=100)
.map(|i| (f64::from(i) * 0.4).cos() * 10.0)
.collect();
let mut a = MacdIndicator::classic();
let mut b = MacdIndicator::classic();
assert_eq!(
a.batch(&prices),
prices.iter().map(|p| b.update(*p)).collect::<Vec<_>>()
);
}
#[test]
fn reset_clears_state() {
let mut macd = MacdIndicator::classic();
macd.batch(&(1..=80).map(f64::from).collect::<Vec<_>>());
assert!(macd.is_ready());
macd.reset();
assert!(!macd.is_ready());
assert_eq!(macd.update(1.0), None);
}
}
+166
View File
@@ -0,0 +1,166 @@
//! Money Flow Index (MFI).
use std::collections::VecDeque;
use crate::error::{Error, Result};
use crate::ohlcv::Candle;
use crate::traits::Indicator;
/// Money Flow Index: a volume-weighted version of RSI.
///
/// `MFI = 100 - 100 / (1 + positive_money_flow / negative_money_flow)` where
/// money flow is `typical_price * volume`, classified positive when TP increases
/// and negative when it decreases.
#[derive(Debug, Clone)]
pub struct Mfi {
period: usize,
prev_tp: Option<f64>,
pos_window: VecDeque<f64>,
neg_window: VecDeque<f64>,
pos_sum: f64,
neg_sum: f64,
}
impl Mfi {
/// # Errors
/// Returns [`Error::PeriodZero`] if `period == 0`.
pub fn new(period: usize) -> Result<Self> {
if period == 0 {
return Err(Error::PeriodZero);
}
Ok(Self {
period,
prev_tp: None,
pos_window: VecDeque::with_capacity(period),
neg_window: VecDeque::with_capacity(period),
pos_sum: 0.0,
neg_sum: 0.0,
})
}
/// Configured period.
pub const fn period(&self) -> usize {
self.period
}
}
impl Indicator for Mfi {
type Input = Candle;
type Output = f64;
fn update(&mut self, candle: Candle) -> Option<f64> {
let tp = candle.typical_price();
let mf = tp * candle.volume;
let (pos_flow, neg_flow) = match self.prev_tp {
None => (0.0, 0.0),
Some(prev) => {
if tp > prev {
(mf, 0.0)
} else if tp < prev {
(0.0, mf)
} else {
(0.0, 0.0)
}
}
};
if self.pos_window.len() == self.period {
self.pos_sum -= self.pos_window.pop_front().expect("non-empty");
self.neg_sum -= self.neg_window.pop_front().expect("non-empty");
}
self.pos_window.push_back(pos_flow);
self.neg_window.push_back(neg_flow);
self.pos_sum += pos_flow;
self.neg_sum += neg_flow;
self.prev_tp = Some(tp);
// Need period+1 candles total (the first one only gives prev_tp).
if self.prev_tp.is_none() || self.pos_window.len() < self.period {
return None;
}
// Need at least one comparison-based flow inside the window, otherwise we
// are still on the very first candle.
if self.pos_sum == 0.0 && self.neg_sum == 0.0 {
return Some(50.0);
}
if self.neg_sum == 0.0 {
return Some(100.0);
}
let mr = self.pos_sum / self.neg_sum;
Some(100.0 - 100.0 / (1.0 + mr))
}
fn reset(&mut self) {
self.prev_tp = None;
self.pos_window.clear();
self.neg_window.clear();
self.pos_sum = 0.0;
self.neg_sum = 0.0;
}
fn warmup_period(&self) -> usize {
self.period
}
fn is_ready(&self) -> bool {
self.pos_window.len() == self.period
}
fn name(&self) -> &'static str {
"MFI"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
fn c(price: f64, volume: f64) -> Candle {
Candle::new(price, price, price, price, volume, 0).unwrap()
}
#[test]
fn pure_uptrend_yields_high_mfi() {
let candles: Vec<Candle> = (1..30).map(|i| c(f64::from(i), 100.0)).collect();
let mut mfi = Mfi::new(14).unwrap();
let last = mfi.batch(&candles).into_iter().flatten().last().unwrap();
assert_relative_eq!(last, 100.0, epsilon = 1e-9);
}
#[test]
fn pure_downtrend_yields_low_mfi() {
let candles: Vec<Candle> = (1..30).rev().map(|i| c(f64::from(i), 100.0)).collect();
let mut mfi = Mfi::new(14).unwrap();
let last = mfi.batch(&candles).into_iter().flatten().last().unwrap();
assert_relative_eq!(last, 0.0, epsilon = 1e-9);
}
#[test]
fn batch_equals_streaming() {
let candles: Vec<Candle> = (0..40).map(|i| c(f64::from(i) + 10.0, 50.0)).collect();
let mut a = Mfi::new(14).unwrap();
let mut b = Mfi::new(14).unwrap();
assert_eq!(
a.batch(&candles),
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
);
}
#[test]
fn reset_clears_state() {
let candles: Vec<Candle> = (1..30).map(|i| c(f64::from(i), 100.0)).collect();
let mut mfi = Mfi::new(14).unwrap();
mfi.batch(&candles);
assert!(mfi.is_ready());
mfi.reset();
assert!(!mfi.is_ready());
}
#[test]
fn rejects_zero_period() {
assert!(Mfi::new(0).is_err());
}
}
+57
View File
@@ -0,0 +1,57 @@
//! Built-in indicators. Every indicator implements [`crate::Indicator`].
//!
//! Modules are organised internally by category (trend, momentum, volatility,
//! volume) but every public name is also re-exported flat from this module and
//! from the crate root for convenience.
mod adx;
mod aroon;
mod atr;
mod awesome_oscillator;
mod bollinger;
mod cci;
mod dema;
mod donchian;
mod ema;
mod hma;
mod kama;
mod keltner;
mod macd;
mod mfi;
mod obv;
mod psar;
mod roc;
mod rsi;
mod sma;
mod stochastic;
mod tema;
mod trix;
mod vwap;
mod williams_r;
mod wma;
pub use adx::{Adx, AdxOutput};
pub use aroon::{Aroon, AroonOutput};
pub use atr::Atr;
pub use awesome_oscillator::AwesomeOscillator;
pub use bollinger::{BollingerBands, BollingerOutput};
pub use cci::Cci;
pub use dema::Dema;
pub use donchian::{Donchian, DonchianOutput};
pub use ema::Ema;
pub use hma::Hma;
pub use kama::Kama;
pub use keltner::{Keltner, KeltnerOutput};
pub use macd::{MacdIndicator, MacdOutput};
pub use mfi::Mfi;
pub use obv::Obv;
pub use psar::Psar;
pub use roc::Roc;
pub use rsi::Rsi;
pub use sma::Sma;
pub use stochastic::{Stochastic, StochasticOutput};
pub use tema::Tema;
pub use trix::Trix;
pub use vwap::{RollingVwap, Vwap};
pub use williams_r::WilliamsR;
pub use wma::Wma;
+159
View File
@@ -0,0 +1,159 @@
//! On-Balance Volume.
use crate::ohlcv::Candle;
use crate::traits::Indicator;
/// On-Balance Volume: a cumulative signed-volume series.
///
/// Each candle adds `+volume`, `-volume`, or `0` depending on whether its close
/// is above, below, or equal to the previous close. The first value (after the
/// first candle) is conventionally `0`.
#[derive(Debug, Clone, Default)]
pub struct Obv {
prev_close: Option<f64>,
total: f64,
has_emitted: bool,
}
impl Obv {
/// Construct a new OBV instance starting at zero.
pub const fn new() -> Self {
Self {
prev_close: None,
total: 0.0,
has_emitted: false,
}
}
/// Current cumulative value if at least one candle has been ingested.
pub const fn value(&self) -> Option<f64> {
if self.has_emitted {
Some(self.total)
} else {
None
}
}
}
impl Indicator for Obv {
type Input = Candle;
type Output = f64;
fn update(&mut self, candle: Candle) -> Option<f64> {
// The first candle establishes the baseline at 0; subsequent candles
// add/subtract their volume based on close direction. Equal closes do nothing.
if let Some(prev) = self.prev_close {
if candle.close > prev {
self.total += candle.volume;
} else if candle.close < prev {
self.total -= candle.volume;
}
}
self.prev_close = Some(candle.close);
self.has_emitted = true;
Some(self.total)
}
fn reset(&mut self) {
self.prev_close = None;
self.total = 0.0;
self.has_emitted = false;
}
fn warmup_period(&self) -> usize {
1
}
fn is_ready(&self) -> bool {
self.has_emitted
}
fn name(&self) -> &'static str {
"OBV"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
fn c(close: f64, volume: f64) -> Candle {
Candle::new(close, close, close, close, volume, 0).unwrap()
}
#[test]
fn first_candle_baseline_zero() {
let mut obv = Obv::new();
assert_relative_eq!(obv.update(c(10.0, 100.0)).unwrap(), 0.0, epsilon = 1e-12);
}
#[test]
fn up_close_adds_volume() {
let mut obv = Obv::new();
obv.update(c(10.0, 100.0)); // baseline 0
let v = obv.update(c(11.0, 50.0)).unwrap();
assert_relative_eq!(v, 50.0, epsilon = 1e-12);
}
#[test]
fn down_close_subtracts_volume() {
let mut obv = Obv::new();
obv.update(c(10.0, 100.0));
let v = obv.update(c(9.0, 50.0)).unwrap();
assert_relative_eq!(v, -50.0, epsilon = 1e-12);
}
#[test]
fn equal_close_does_nothing() {
let mut obv = Obv::new();
obv.update(c(10.0, 100.0));
let v = obv.update(c(10.0, 50.0)).unwrap();
assert_relative_eq!(v, 0.0, epsilon = 1e-12);
}
#[test]
fn cumulative_sequence() {
let candles = vec![
c(10.0, 100.0), // baseline
c(11.0, 20.0), // +20
c(10.5, 30.0), // -30
c(10.5, 40.0), // unchanged
c(12.0, 10.0), // +10
];
let mut obv = Obv::new();
let out = obv.batch(&candles);
assert_relative_eq!(out[0].unwrap(), 0.0, epsilon = 1e-12);
assert_relative_eq!(out[1].unwrap(), 20.0, epsilon = 1e-12);
assert_relative_eq!(out[2].unwrap(), -10.0, epsilon = 1e-12);
assert_relative_eq!(out[3].unwrap(), -10.0, epsilon = 1e-12);
assert_relative_eq!(out[4].unwrap(), 0.0, epsilon = 1e-12);
}
#[test]
fn batch_equals_streaming() {
let candles: Vec<Candle> = (0..20)
.map(|i| {
let cl = 10.0 + (f64::from(i) * 0.5).sin();
c(cl, 1.0)
})
.collect();
let mut a = Obv::new();
let mut b = Obv::new();
assert_eq!(
a.batch(&candles),
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
);
}
#[test]
fn reset_clears_state() {
let mut obv = Obv::new();
obv.batch(&[c(10.0, 50.0), c(11.0, 30.0)]);
assert!(obv.is_ready());
obv.reset();
assert!(!obv.is_ready());
assert_eq!(obv.value(), None);
}
}
+241
View File
@@ -0,0 +1,241 @@
//! Parabolic SAR (Wilder).
use crate::error::{Error, Result};
use crate::ohlcv::Candle;
use crate::traits::Indicator;
/// Trade direction in the SAR state machine.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Trend {
Up,
Down,
}
/// Parabolic Stop And Reverse.
///
/// Implementation follows Wilder's original recursion: each step computes a new
/// SAR from the previous SAR, extreme point (EP) and acceleration factor (AF);
/// the trend flips when price crosses the SAR.
#[derive(Debug, Clone)]
pub struct Psar {
af_start: f64,
af_step: f64,
af_max: f64,
initialised: bool,
prev_high: f64,
prev_low: f64,
trend: Trend,
sar: f64,
ep: f64,
af: f64,
}
impl Psar {
/// Construct PSAR with explicit acceleration parameters.
///
/// # Errors
/// Returns [`Error::NonPositiveMultiplier`] / [`Error::InvalidPeriod`] for invalid params.
pub fn new(af_start: f64, af_step: f64, af_max: f64) -> Result<Self> {
if !af_start.is_finite() || !af_step.is_finite() || !af_max.is_finite() {
return Err(Error::NonPositiveMultiplier);
}
if af_start <= 0.0 || af_step <= 0.0 || af_max <= 0.0 {
return Err(Error::NonPositiveMultiplier);
}
if af_start > af_max {
return Err(Error::InvalidPeriod {
message: "af_start must be <= af_max",
});
}
Ok(Self {
af_start,
af_step,
af_max,
initialised: false,
prev_high: 0.0,
prev_low: 0.0,
trend: Trend::Up,
sar: 0.0,
ep: 0.0,
af: af_start,
})
}
/// Wilder's defaults: `(0.02, 0.02, 0.20)`.
pub fn classic() -> Self {
Self::new(0.02, 0.02, 0.20).expect("classic PSAR params are valid")
}
}
impl Indicator for Psar {
type Input = Candle;
type Output = f64;
fn update(&mut self, candle: Candle) -> Option<f64> {
if !self.initialised {
// Seed: the first emitted SAR comes on the second candle. Initial trend
// is chosen by whether the second close is above or below the first.
self.prev_high = candle.high;
self.prev_low = candle.low;
self.sar = candle.low;
self.ep = candle.high;
self.trend = Trend::Up;
self.af = self.af_start;
self.initialised = true;
return None;
}
// Predicted SAR for this period (before clamping to prior two extremes).
let mut new_sar = self.sar + self.af * (self.ep - self.sar);
// Wilder rule: SAR cannot penetrate today's or yesterday's range.
let prev_h = self.prev_high;
let prev_l = self.prev_low;
new_sar = match self.trend {
Trend::Up => new_sar.min(prev_l).min(candle.low),
Trend::Down => new_sar.max(prev_h).max(candle.high),
};
let mut output_sar = new_sar;
// Check for trend reversal.
let reversed = match self.trend {
Trend::Up => candle.low <= new_sar,
Trend::Down => candle.high >= new_sar,
};
if reversed {
// Flip trend, reset AF and EP, place SAR at prior EP.
output_sar = self.ep;
self.trend = match self.trend {
Trend::Up => Trend::Down,
Trend::Down => Trend::Up,
};
self.ep = match self.trend {
Trend::Up => candle.high,
Trend::Down => candle.low,
};
self.af = self.af_start;
} else {
// Update EP and AF if a new extreme has been reached.
match self.trend {
Trend::Up => {
if candle.high > self.ep {
self.ep = candle.high;
self.af = (self.af + self.af_step).min(self.af_max);
}
}
Trend::Down => {
if candle.low < self.ep {
self.ep = candle.low;
self.af = (self.af + self.af_step).min(self.af_max);
}
}
}
}
self.sar = output_sar;
self.prev_high = candle.high;
self.prev_low = candle.low;
Some(output_sar)
}
fn reset(&mut self) {
self.initialised = false;
self.af = self.af_start;
self.sar = 0.0;
self.ep = 0.0;
}
fn warmup_period(&self) -> usize {
2
}
fn is_ready(&self) -> bool {
self.initialised
}
fn name(&self) -> &'static str {
"PSAR"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
fn c(h: f64, l: f64, cl: f64) -> Candle {
Candle::new(cl, h, l, cl, 1.0, 0).unwrap()
}
#[test]
fn first_candle_returns_none() {
let mut psar = Psar::classic();
assert_eq!(psar.update(c(11.0, 9.0, 10.0)), None);
}
#[test]
fn pure_uptrend_sar_below_lows() {
let candles: Vec<Candle> = (0..40)
.map(|i| {
let base = 100.0 + f64::from(i);
c(base + 0.5, base - 0.5, base)
})
.collect();
let mut psar = Psar::classic();
for (i, sar) in psar.batch(&candles).into_iter().enumerate() {
if let Some(s) = sar {
assert!(
s <= candles[i].low + 1e-9,
"SAR {s} should be <= low {} at i={i}",
candles[i].low
);
}
}
}
#[test]
fn pure_downtrend_sar_above_highs() {
let candles: Vec<Candle> = (0..40)
.rev()
.map(|i| {
let base = 100.0 + f64::from(i);
c(base + 0.5, base - 0.5, base)
})
.collect();
let mut psar = Psar::classic();
let outs = psar.batch(&candles);
// After the trend establishes downward, SAR should sit above highs.
for (i, sar) in outs.into_iter().enumerate().skip(5) {
if let Some(s) = sar {
assert!(s >= candles[i].high - 1e-9);
}
}
}
#[test]
fn batch_equals_streaming() {
let candles: Vec<Candle> = (0..60)
.map(|i| {
let m = 100.0 + (f64::from(i) * 0.3).sin() * 8.0;
c(m + 1.0, m - 1.0, m)
})
.collect();
let mut a = Psar::classic();
let mut b = Psar::classic();
assert_eq!(
a.batch(&candles),
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
);
}
#[test]
fn rejects_invalid_params() {
assert!(Psar::new(0.0, 0.02, 0.20).is_err());
assert!(Psar::new(0.02, 0.0, 0.20).is_err());
assert!(Psar::new(0.30, 0.02, 0.20).is_err());
assert!(Psar::new(f64::NAN, 0.02, 0.20).is_err());
}
}
+120
View File
@@ -0,0 +1,120 @@
//! Rate of Change (ROC).
use std::collections::VecDeque;
use crate::error::{Error, Result};
use crate::traits::Indicator;
/// Rate of Change as a percentage: `(close - close[period]) / close[period] * 100`.
#[derive(Debug, Clone)]
pub struct Roc {
period: usize,
window: VecDeque<f64>,
}
impl Roc {
/// # Errors
/// Returns [`Error::PeriodZero`] if `period == 0`.
pub fn new(period: usize) -> Result<Self> {
if period == 0 {
return Err(Error::PeriodZero);
}
Ok(Self {
period,
window: VecDeque::with_capacity(period + 1),
})
}
/// Configured period.
pub const fn period(&self) -> usize {
self.period
}
}
impl Indicator for Roc {
type Input = f64;
type Output = f64;
fn update(&mut self, input: f64) -> Option<f64> {
if !input.is_finite() {
return None;
}
if self.window.len() == self.period + 1 {
self.window.pop_front();
}
self.window.push_back(input);
if self.window.len() < self.period + 1 {
return None;
}
let prev = *self.window.front().expect("non-empty");
if prev == 0.0 {
return Some(0.0);
}
Some((input - prev) / prev * 100.0)
}
fn reset(&mut self) {
self.window.clear();
}
fn warmup_period(&self) -> usize {
self.period + 1
}
fn is_ready(&self) -> bool {
self.window.len() == self.period + 1
}
fn name(&self) -> &'static str {
"ROC"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
#[test]
fn constant_series_yields_zero() {
let mut roc = Roc::new(5).unwrap();
let out = roc.batch(&[10.0_f64; 20]);
for v in out.iter().skip(5).flatten() {
assert_relative_eq!(*v, 0.0, epsilon = 1e-12);
}
}
#[test]
fn known_value() {
// ROC(3) where prev = 100, now = 110 -> 10%
let mut roc = Roc::new(3).unwrap();
let out = roc.batch(&[100.0, 105.0, 108.0, 110.0]);
assert_relative_eq!(out[3].unwrap(), 10.0, epsilon = 1e-12);
}
#[test]
fn batch_equals_streaming() {
let prices: Vec<f64> = (1..=30).map(|i| f64::from(i) * 2.0).collect();
let mut a = Roc::new(5).unwrap();
let mut b = Roc::new(5).unwrap();
assert_eq!(
a.batch(&prices),
prices.iter().map(|p| b.update(*p)).collect::<Vec<_>>()
);
}
#[test]
fn reset_clears_state() {
let mut roc = Roc::new(5).unwrap();
roc.batch(&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
assert!(roc.is_ready());
roc.reset();
assert!(!roc.is_ready());
}
#[test]
fn rejects_zero_period() {
assert!(Roc::new(0).is_err());
}
}
+247
View File
@@ -0,0 +1,247 @@
//! Relative Strength Index using Wilder's smoothing.
use crate::error::{Error, Result};
use crate::traits::Indicator;
/// Relative Strength Index (Wilder, 1978).
///
/// Uses Wilder's smoothing (an EMA with `alpha = 1 / period`). The first output
/// is produced after `period + 1` inputs: the seed averages the first `period`
/// gains and losses, and the first emitted RSI corresponds to the input at
/// index `period`.
#[derive(Debug, Clone)]
pub struct Rsi {
period: usize,
prev_close: Option<f64>,
// Wilder seeds with the simple average of the first `period` gains/losses,
// then transitions to recursive smoothing.
seed_buf_gains: Vec<f64>,
seed_buf_losses: Vec<f64>,
avg_gain: Option<f64>,
avg_loss: Option<f64>,
last_value: Option<f64>,
}
impl Rsi {
/// Construct an RSI with the given Wilder period.
///
/// # Errors
///
/// Returns [`Error::PeriodZero`] if `period == 0`.
pub fn new(period: usize) -> Result<Self> {
if period == 0 {
return Err(Error::PeriodZero);
}
Ok(Self {
period,
prev_close: None,
seed_buf_gains: Vec::with_capacity(period),
seed_buf_losses: Vec::with_capacity(period),
avg_gain: None,
avg_loss: None,
last_value: None,
})
}
/// Configured period.
pub const fn period(&self) -> usize {
self.period
}
/// Current value if available.
pub const fn value(&self) -> Option<f64> {
self.last_value
}
fn rsi_from_avgs(avg_gain: f64, avg_loss: f64) -> f64 {
if avg_loss == 0.0 {
if avg_gain == 0.0 {
// No movement at all -> RSI undefined; standard convention returns 50.
50.0
} else {
100.0
}
} else {
let rs = avg_gain / avg_loss;
100.0 - 100.0 / (1.0 + rs)
}
}
}
impl Indicator for Rsi {
type Input = f64;
type Output = f64;
fn update(&mut self, input: f64) -> Option<f64> {
if !input.is_finite() {
return self.last_value;
}
let Some(prev) = self.prev_close else {
self.prev_close = Some(input);
return None;
};
self.prev_close = Some(input);
let diff = input - prev;
let gain = if diff > 0.0 { diff } else { 0.0 };
let loss = if diff < 0.0 { -diff } else { 0.0 };
if let (Some(ag), Some(al)) = (self.avg_gain, self.avg_loss) {
let n = self.period as f64;
let new_ag = (ag * (n - 1.0) + gain) / n;
let new_al = (al * (n - 1.0) + loss) / n;
self.avg_gain = Some(new_ag);
self.avg_loss = Some(new_al);
let v = Self::rsi_from_avgs(new_ag, new_al);
self.last_value = Some(v);
return Some(v);
}
self.seed_buf_gains.push(gain);
self.seed_buf_losses.push(loss);
if self.seed_buf_gains.len() == self.period {
let ag = self.seed_buf_gains.iter().sum::<f64>() / self.period as f64;
let al = self.seed_buf_losses.iter().sum::<f64>() / self.period as f64;
self.avg_gain = Some(ag);
self.avg_loss = Some(al);
let v = Self::rsi_from_avgs(ag, al);
self.last_value = Some(v);
return Some(v);
}
None
}
fn reset(&mut self) {
self.prev_close = None;
self.seed_buf_gains.clear();
self.seed_buf_losses.clear();
self.avg_gain = None;
self.avg_loss = None;
self.last_value = None;
}
fn warmup_period(&self) -> usize {
self.period + 1
}
fn is_ready(&self) -> bool {
self.last_value.is_some()
}
fn name(&self) -> &'static str {
"RSI"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
#[test]
fn new_rejects_zero_period() {
assert!(matches!(Rsi::new(0), Err(Error::PeriodZero)));
}
#[test]
fn warmup_period_is_period_plus_one() {
let rsi = Rsi::new(14).unwrap();
assert_eq!(rsi.warmup_period(), 15);
}
#[test]
fn first_emission_at_index_period() {
// RSI(14) needs 14 diffs => 15 inputs before first value.
let prices: Vec<f64> = (1..=20).map(f64::from).collect();
let mut rsi = Rsi::new(14).unwrap();
let out = rsi.batch(&prices);
// indices 0..14 -> None, index 14 -> first Some
for x in &out[..14] {
assert!(x.is_none());
}
assert!(out[14].is_some());
}
#[test]
fn pure_uptrend_yields_rsi_100() {
let prices: Vec<f64> = (1..=20).map(f64::from).collect();
let mut rsi = Rsi::new(14).unwrap();
let out = rsi.batch(&prices);
// All diffs are positive => avg_loss == 0 => RSI == 100
for v in out.iter().filter_map(|x| x.as_ref()) {
assert_relative_eq!(*v, 100.0, epsilon = 1e-9);
}
}
#[test]
fn pure_downtrend_yields_rsi_0() {
let prices: Vec<f64> = (1..=20).rev().map(f64::from).collect();
let mut rsi = Rsi::new(14).unwrap();
let out = rsi.batch(&prices);
for v in out.iter().filter_map(|x| x.as_ref()) {
assert_relative_eq!(*v, 0.0, epsilon = 1e-9);
}
}
#[test]
fn flat_series_yields_rsi_50() {
let prices = [10.0_f64; 30];
let mut rsi = Rsi::new(14).unwrap();
let out = rsi.batch(&prices);
for v in out.iter().filter_map(|x| x.as_ref()) {
assert_relative_eq!(*v, 50.0, epsilon = 1e-12);
}
}
#[test]
fn classic_wilder_textbook_values() {
// Wilder's original example from "New Concepts in Technical Trading Systems",
// 14-period RSI. We compute the first value at index 14 and compare to the
// value Wilder publishes (~70.46).
// Source: classic textbook table, reproduced in many references (e.g. Investopedia).
let prices = [
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,
];
let mut rsi = Rsi::new(14).unwrap();
let out = rsi.batch(&prices);
let first = out[14].expect("first RSI emitted at index period");
assert_relative_eq!(first, 70.464, epsilon = 0.05);
}
#[test]
fn rsi_stays_in_0_100_range() {
let prices: Vec<f64> = (0..200)
.map(|i| 100.0 + (f64::from(i) * 0.7).sin() * 10.0)
.collect();
let mut rsi = Rsi::new(14).unwrap();
for x in rsi.batch(&prices).into_iter().flatten() {
assert!((0.0..=100.0).contains(&x), "RSI out of range: {x}");
}
}
#[test]
fn reset_clears_state() {
let mut rsi = Rsi::new(5).unwrap();
rsi.batch(&[1.0, 2.0, 3.0, 2.0, 4.0, 5.0, 6.0]);
assert!(rsi.is_ready());
rsi.reset();
assert!(!rsi.is_ready());
assert_eq!(rsi.update(1.0), None);
}
#[test]
fn batch_equals_streaming() {
let prices: Vec<f64> = (1..=40)
.map(|i| (f64::from(i) * 0.3).sin() * 5.0 + f64::from(i))
.collect();
let mut a = Rsi::new(7).unwrap();
let mut b = Rsi::new(7).unwrap();
assert_eq!(
a.batch(&prices),
prices.iter().map(|p| b.update(*p)).collect::<Vec<_>>()
);
}
}
+200
View File
@@ -0,0 +1,200 @@
//! Simple Moving Average.
use std::collections::VecDeque;
use crate::error::{Error, Result};
use crate::traits::Indicator;
/// Simple Moving Average over a fixed window.
///
/// Maintains a rolling sum so each update is O(1). Output equals
/// `sum(last `period` prices) / period` once the window is full; `None` before.
#[derive(Debug, Clone)]
pub struct Sma {
period: usize,
window: VecDeque<f64>,
sum: f64,
}
impl Sma {
/// Construct a new SMA with the given window length.
///
/// # Errors
///
/// Returns [`Error::PeriodZero`] if `period == 0`.
pub fn new(period: usize) -> Result<Self> {
if period == 0 {
return Err(Error::PeriodZero);
}
Ok(Self {
period,
window: VecDeque::with_capacity(period),
sum: 0.0,
})
}
/// Configured window length.
pub const fn period(&self) -> usize {
self.period
}
/// Current value if available.
pub fn value(&self) -> Option<f64> {
if self.window.len() == self.period {
Some(self.sum / self.period as f64)
} else {
None
}
}
}
impl Indicator for Sma {
type Input = f64;
type Output = f64;
fn update(&mut self, input: f64) -> Option<f64> {
if !input.is_finite() {
return self.value();
}
if self.window.len() == self.period {
// Drop the oldest from the sum to keep numerical drift bounded by recomputing
// the sum after each pop; a single subtract works in O(1) and is acceptable
// here because we use f64 throughout.
let old = self.window.pop_front().expect("window non-empty");
self.sum -= old;
}
self.window.push_back(input);
self.sum += input;
self.value()
}
fn reset(&mut self) {
self.window.clear();
self.sum = 0.0;
}
fn warmup_period(&self) -> usize {
self.period
}
fn is_ready(&self) -> bool {
self.window.len() == self.period
}
fn name(&self) -> &'static str {
"SMA"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
#[test]
fn new_rejects_zero_period() {
assert!(matches!(Sma::new(0), Err(Error::PeriodZero)));
}
#[test]
fn warmup_returns_none() {
let mut sma = Sma::new(3).unwrap();
assert_eq!(sma.update(1.0), None);
assert_eq!(sma.update(2.0), None);
assert_eq!(sma.update(3.0), Some(2.0));
}
#[test]
fn rolls_window_after_full() {
let mut sma = Sma::new(3).unwrap();
let out: Vec<_> = [1.0, 2.0, 3.0, 4.0, 5.0]
.iter()
.map(|p| sma.update(*p))
.collect();
assert_eq!(out, vec![None, None, Some(2.0), Some(3.0), Some(4.0)]);
}
#[test]
fn period_one_is_pass_through() {
let mut sma = Sma::new(1).unwrap();
assert_eq!(sma.update(5.0), Some(5.0));
assert_eq!(sma.update(10.0), Some(10.0));
}
#[test]
fn ignores_non_finite_input_but_keeps_state() {
let mut sma = Sma::new(3).unwrap();
sma.update(1.0);
sma.update(2.0);
sma.update(3.0);
assert_eq!(sma.update(f64::NAN), Some(2.0));
assert_eq!(sma.update(f64::INFINITY), Some(2.0));
// Non-finite inputs were not pushed; window still holds 1,2,3.
assert_eq!(sma.update(6.0), Some((2.0 + 3.0 + 6.0) / 3.0));
}
#[test]
fn reset_clears_state() {
let mut sma = Sma::new(3).unwrap();
sma.batch(&[1.0, 2.0, 3.0]);
assert!(sma.is_ready());
sma.reset();
assert!(!sma.is_ready());
assert_eq!(sma.update(10.0), None);
}
#[test]
fn batch_equals_streaming() {
let prices: Vec<f64> = (1..=20).map(f64::from).collect();
let mut a = Sma::new(5).unwrap();
let batch = a.batch(&prices);
let mut b = Sma::new(5).unwrap();
let streamed: Vec<_> = prices.iter().map(|p| b.update(*p)).collect();
assert_eq!(batch, streamed);
}
#[test]
fn known_reference_values() {
// SMA(3) of [2, 4, 6, 8, 10] -> [_, _, 4, 6, 8]
let mut sma = Sma::new(3).unwrap();
let out = sma.batch(&[2.0, 4.0, 6.0, 8.0, 10.0]);
assert_eq!(out[2], Some(4.0));
assert_eq!(out[3], Some(6.0));
assert_eq!(out[4], Some(8.0));
}
#[test]
fn constant_series_yields_constant_sma() {
let mut sma = Sma::new(5).unwrap();
let v = sma.batch(&[7.0; 10]);
for x in v.iter().skip(4) {
assert_relative_eq!(x.unwrap(), 7.0, epsilon = 1e-12);
}
}
proptest::proptest! {
#![proptest_config(proptest::test_runner::Config::with_cases(64))]
#[test]
fn sma_matches_naive_definition(
period in 1usize..20,
prices in proptest::collection::vec(-1000.0_f64..1000.0, 0..200),
) {
let mut sma = Sma::new(period).unwrap();
let stream: Vec<_> = prices.iter().map(|p| sma.update(*p)).collect();
for (i, got) in stream.iter().enumerate() {
if i + 1 < period {
proptest::prop_assert!(got.is_none());
} else {
let window = &prices[i + 1 - period..=i];
let expected = window.iter().sum::<f64>() / period as f64;
let actual = got.expect("ready");
proptest::prop_assert!(
(actual - expected).abs() < 1e-9,
"i={i} actual={actual} expected={expected}"
);
}
}
}
}
}
@@ -0,0 +1,315 @@
//! Stochastic Oscillator (%K and %D).
use std::collections::VecDeque;
use crate::error::{Error, Result};
use crate::indicators::sma::Sma;
use crate::ohlcv::Candle;
use crate::traits::Indicator;
/// Stochastic Oscillator output.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct StochasticOutput {
/// Raw %K: `100 * (close - LL) / (HH - LL)` over the lookback.
pub k: f64,
/// %D: SMA of %K over the smoothing period.
pub d: f64,
}
/// Fast Stochastic Oscillator.
///
/// Maintains rolling highest-high and lowest-low over the lookback period via a
/// monotonic deque, giving O(1) amortized updates. %D is an SMA of the %K series.
#[derive(Debug, Clone)]
pub struct Stochastic {
k_period: usize,
d_period: usize,
candles: VecDeque<Candle>,
// Monotonic deques over candle indices in the rolling window.
hh_idx: VecDeque<usize>, // indices of candidates for highest high (front = current max)
ll_idx: VecDeque<usize>, // indices of candidates for lowest low (front = current min)
// Absolute count of candles ever ingested. Used so monotonic-deque indices stay unique.
count: usize,
d_sma: Sma,
last_k: Option<f64>,
}
impl Stochastic {
/// Construct a stochastic with %K lookback and %D smoothing periods.
///
/// # Errors
///
/// Returns [`Error::PeriodZero`] if either period is zero.
pub fn new(k_period: usize, d_period: usize) -> Result<Self> {
if k_period == 0 || d_period == 0 {
return Err(Error::PeriodZero);
}
Ok(Self {
k_period,
d_period,
candles: VecDeque::with_capacity(k_period),
hh_idx: VecDeque::with_capacity(k_period),
ll_idx: VecDeque::with_capacity(k_period),
count: 0,
d_sma: Sma::new(d_period)?,
last_k: None,
})
}
/// Classic fast stochastic: `%K = 14`, `%D = 3`.
pub fn classic() -> Self {
Self::new(14, 3).expect("classic stochastic periods are valid")
}
/// Configured `(k_period, d_period)`.
pub const fn periods(&self) -> (usize, usize) {
(self.k_period, self.d_period)
}
fn push_window(&mut self, candle: Candle) {
let idx = self.count;
self.count += 1;
// Drop deque entries that are outside the window.
let oldest_keep_idx = idx.saturating_sub(self.k_period - 1);
while let Some(&front) = self.hh_idx.front() {
if front < oldest_keep_idx {
self.hh_idx.pop_front();
} else {
break;
}
}
while let Some(&front) = self.ll_idx.front() {
if front < oldest_keep_idx {
self.ll_idx.pop_front();
} else {
break;
}
}
// Maintain monotonic-decreasing deque for highs.
while let Some(&back) = self.hh_idx.back() {
let back_off = back - idx.saturating_sub(self.candles.len());
if self.candles[back_off].high <= candle.high {
self.hh_idx.pop_back();
} else {
break;
}
}
self.hh_idx.push_back(idx);
// Maintain monotonic-increasing deque for lows.
while let Some(&back) = self.ll_idx.back() {
let back_off = back - idx.saturating_sub(self.candles.len());
if self.candles[back_off].low >= candle.low {
self.ll_idx.pop_back();
} else {
break;
}
}
self.ll_idx.push_back(idx);
if self.candles.len() == self.k_period {
self.candles.pop_front();
}
self.candles.push_back(candle);
}
fn current_extremes(&self) -> (f64, f64) {
let base = self.count - self.candles.len();
let hi = self.candles[self.hh_idx[0] - base].high;
let lo = self.candles[self.ll_idx[0] - base].low;
(hi, lo)
}
}
impl Indicator for Stochastic {
type Input = Candle;
type Output = StochasticOutput;
fn update(&mut self, candle: Candle) -> Option<StochasticOutput> {
self.push_window(candle);
if self.candles.len() < self.k_period {
return None;
}
let (hh, ll) = self.current_extremes();
let range = hh - ll;
let k = if range == 0.0 {
// Flat range; convention: 50 (neutral, like RSI on flat input).
50.0
} else {
100.0 * (candle.close - ll) / range
};
self.last_k = Some(k);
let d = self.d_sma.update(k)?;
Some(StochasticOutput { k, d })
}
fn reset(&mut self) {
self.candles.clear();
self.hh_idx.clear();
self.ll_idx.clear();
self.count = 0;
self.d_sma.reset();
self.last_k = None;
}
fn warmup_period(&self) -> usize {
self.k_period + self.d_period - 1
}
fn is_ready(&self) -> bool {
self.d_sma.is_ready()
}
fn name(&self) -> &'static str {
"Stochastic"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
fn c(h: f64, l: f64, cl: f64) -> Candle {
Candle::new(cl, h, l, cl, 1.0, 0).unwrap()
}
/// Naive %K computation for cross-checks.
fn naive_k(candles: &[Candle], k_period: usize) -> Vec<Option<f64>> {
candles
.iter()
.enumerate()
.map(|(i, _)| {
if i + 1 < k_period {
None
} else {
let w = &candles[i + 1 - k_period..=i];
let hh = w.iter().map(|x| x.high).fold(f64::NEG_INFINITY, f64::max);
let ll = w.iter().map(|x| x.low).fold(f64::INFINITY, f64::min);
let range = hh - ll;
let cl = candles[i].close;
Some(if range == 0.0 {
50.0
} else {
100.0 * (cl - ll) / range
})
}
})
.collect()
}
#[test]
fn rejects_zero_periods() {
assert!(matches!(Stochastic::new(0, 3), Err(Error::PeriodZero)));
assert!(matches!(Stochastic::new(14, 0), Err(Error::PeriodZero)));
}
#[test]
fn close_at_high_yields_k_100() {
let candles = vec![
c(10.0, 8.0, 9.0),
c(11.0, 9.0, 10.0),
c(12.0, 10.0, 12.0), // close == high == HH
];
let mut s = Stochastic::new(3, 1).unwrap();
let out = s.batch(&candles);
assert_relative_eq!(out[2].unwrap().k, 100.0, epsilon = 1e-12);
}
#[test]
fn close_at_low_yields_k_0() {
let candles = vec![
c(10.0, 8.0, 9.0),
c(11.0, 9.0, 10.0),
c(12.0, 8.0, 8.0), // close == LL
];
let mut s = Stochastic::new(3, 1).unwrap();
let out = s.batch(&candles);
assert_relative_eq!(out[2].unwrap().k, 0.0, epsilon = 1e-12);
}
#[test]
fn flat_range_yields_k_50() {
let candles: Vec<Candle> = (0..20).map(|_| c(10.0, 10.0, 10.0)).collect();
let mut s = Stochastic::new(14, 3).unwrap();
for o in s.batch(&candles).into_iter().flatten() {
assert_relative_eq!(o.k, 50.0, epsilon = 1e-12);
assert_relative_eq!(o.d, 50.0, epsilon = 1e-12);
}
}
#[test]
fn k_matches_naive() {
let candles: Vec<Candle> = (0..60)
.map(|i| {
let mid = 50.0 + (f64::from(i) * 0.4).sin() * 10.0;
c(mid + 2.0, mid - 2.0, mid + (f64::from(i) * 0.7).cos())
})
.collect();
let mut s = Stochastic::new(14, 3).unwrap();
let out = s.batch(&candles);
let naive = naive_k(&candles, 14);
for (i, got) in out.iter().enumerate() {
if let Some(o) = got {
let n = naive[i].expect("naive ready");
assert_relative_eq!(o.k, n, epsilon = 1e-9);
}
}
}
#[test]
fn d_is_sma_of_k() {
let candles: Vec<Candle> = (0..60)
.map(|i| {
let mid = 50.0 + f64::from(i).sin() * 5.0;
c(mid + 1.5, mid - 1.5, mid)
})
.collect();
let mut s = Stochastic::new(14, 3).unwrap();
let out = s.batch(&candles);
// The naive %K series gives us the ground-truth values that %D should average.
let naive_ks = naive_k(&candles, 14);
// The first emitted %D corresponds to the SMA of the first three valid %K values
// (i.e. those at indices 13, 14, 15). At that point %D becomes ready, and the
// first `Some(_)` output appears at index 15.
let first_emit_idx = out
.iter()
.position(Option::is_some)
.expect("d eventually emits");
let first_d = out[first_emit_idx].unwrap().d;
let k_window = &naive_ks[first_emit_idx - 2..=first_emit_idx];
let want = k_window
.iter()
.map(|v| v.expect("naive K ready inside window"))
.sum::<f64>()
/ 3.0;
assert_relative_eq!(first_d, want, epsilon = 1e-9);
}
#[test]
fn batch_equals_streaming() {
let candles: Vec<Candle> = (0..50)
.map(|i| {
let mid = 100.0 + f64::from(i) * 0.5;
c(mid + 2.0, mid - 2.0, mid)
})
.collect();
let mut a = Stochastic::new(14, 3).unwrap();
let mut b = Stochastic::new(14, 3).unwrap();
assert_eq!(
a.batch(&candles),
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
);
}
#[test]
fn reset_clears_state() {
let mut s = Stochastic::new(5, 3).unwrap();
let candles: Vec<Candle> = (0..10).map(|i| c(10.0 + f64::from(i), 5.0, 7.0)).collect();
s.batch(&candles);
assert!(s.is_ready());
s.reset();
assert!(!s.is_ready());
assert_eq!(s.update(candles[0]), None);
}
}
+107
View File
@@ -0,0 +1,107 @@
//! Triple Exponential Moving Average (TEMA).
use crate::error::Result;
use crate::indicators::ema::Ema;
use crate::traits::Indicator;
/// Triple Exponential Moving Average: `3 * EMA1 - 3 * EMA2 + EMA3`,
/// where `EMA2 = EMA(EMA1)` and `EMA3 = EMA(EMA2)`.
///
/// Reduces lag further than DEMA at the cost of more responsiveness to noise.
#[derive(Debug, Clone)]
pub struct Tema {
ema1: Ema,
ema2: Ema,
ema3: Ema,
period: usize,
}
impl Tema {
/// # Errors
/// Returns [`crate::Error::PeriodZero`] if `period == 0`.
pub fn new(period: usize) -> Result<Self> {
Ok(Self {
ema1: Ema::new(period)?,
ema2: Ema::new(period)?,
ema3: Ema::new(period)?,
period,
})
}
/// Configured period.
pub const fn period(&self) -> usize {
self.period
}
}
impl Indicator for Tema {
type Input = f64;
type Output = f64;
fn update(&mut self, input: f64) -> Option<f64> {
let e1 = self.ema1.update(input)?;
let e2 = self.ema2.update(e1)?;
let e3 = self.ema3.update(e2)?;
Some(3.0 * e1 - 3.0 * e2 + e3)
}
fn reset(&mut self) {
self.ema1.reset();
self.ema2.reset();
self.ema3.reset();
}
fn warmup_period(&self) -> usize {
3 * self.period - 2
}
fn is_ready(&self) -> bool {
self.ema3.is_ready()
}
fn name(&self) -> &'static str {
"TEMA"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
#[test]
fn constant_series_yields_constant_tema() {
let mut tema = Tema::new(5).unwrap();
let out = tema.batch(&[42.0_f64; 80]);
let last = out.iter().rev().flatten().next().unwrap();
assert_relative_eq!(*last, 42.0, epsilon = 1e-9);
}
#[test]
fn batch_equals_streaming() {
let prices: Vec<f64> = (1..=80)
.map(|i| (f64::from(i) * 0.3).sin() * 10.0)
.collect();
let mut a = Tema::new(5).unwrap();
let mut b = Tema::new(5).unwrap();
assert_eq!(
a.batch(&prices),
prices.iter().map(|p| b.update(*p)).collect::<Vec<_>>()
);
}
#[test]
fn reset_clears_state() {
let mut tema = Tema::new(5).unwrap();
tema.batch(&(1..=80).map(f64::from).collect::<Vec<_>>());
assert!(tema.is_ready());
tema.reset();
assert!(!tema.is_ready());
}
#[test]
fn rejects_zero_period() {
assert!(Tema::new(0).is_err());
}
}
+131
View File
@@ -0,0 +1,131 @@
//! TRIX: triple-smoothed EMA percent rate of change.
use crate::error::Result;
use crate::indicators::ema::Ema;
use crate::traits::Indicator;
/// TRIX: the 1-period percent rate of change of a triple-smoothed EMA.
///
/// `TRIX = 100 * (TR_t - TR_{t-1}) / TR_{t-1}` where
/// `TR_t = EMA(EMA(EMA(price)))`.
#[derive(Debug, Clone)]
pub struct Trix {
ema1: Ema,
ema2: Ema,
ema3: Ema,
prev_tr: Option<f64>,
period: usize,
}
impl Trix {
/// # Errors
/// Returns [`crate::Error::PeriodZero`] if `period == 0`.
pub fn new(period: usize) -> Result<Self> {
Ok(Self {
ema1: Ema::new(period)?,
ema2: Ema::new(period)?,
ema3: Ema::new(period)?,
prev_tr: None,
period,
})
}
/// Configured period.
pub const fn period(&self) -> usize {
self.period
}
}
impl Indicator for Trix {
type Input = f64;
type Output = f64;
fn update(&mut self, input: f64) -> Option<f64> {
let e1 = self.ema1.update(input)?;
let e2 = self.ema2.update(e1)?;
let e3 = self.ema3.update(e2)?;
match self.prev_tr {
Some(prev) if prev != 0.0 => {
let trix = 100.0 * (e3 - prev) / prev;
self.prev_tr = Some(e3);
Some(trix)
}
Some(_) => {
self.prev_tr = Some(e3);
Some(0.0)
}
None => {
self.prev_tr = Some(e3);
None
}
}
}
fn reset(&mut self) {
self.ema1.reset();
self.ema2.reset();
self.ema3.reset();
self.prev_tr = None;
}
fn warmup_period(&self) -> usize {
// Triple EMA seeds at 3*period-2; plus one extra for the rate of change.
3 * self.period - 1
}
fn is_ready(&self) -> bool {
self.prev_tr.is_some() && self.ema3.is_ready()
}
fn name(&self) -> &'static str {
"TRIX"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
#[test]
fn constant_series_yields_zero_trix() {
let mut trix = Trix::new(5).unwrap();
let out = trix.batch(&[100.0_f64; 80]);
let last = out.iter().rev().flatten().next().unwrap();
assert_relative_eq!(*last, 0.0, epsilon = 1e-9);
}
#[test]
fn rising_series_eventually_positive_trix() {
let prices: Vec<f64> = (1..=200).map(f64::from).collect();
let mut trix = Trix::new(5).unwrap();
let last = trix.batch(&prices).into_iter().flatten().last().unwrap();
assert!(last > 0.0);
}
#[test]
fn batch_equals_streaming() {
let prices: Vec<f64> = (1..=80).map(|i| f64::from(i) * 1.3).collect();
let mut a = Trix::new(7).unwrap();
let mut b = Trix::new(7).unwrap();
assert_eq!(
a.batch(&prices),
prices.iter().map(|p| b.update(*p)).collect::<Vec<_>>()
);
}
#[test]
fn reset_clears_state() {
let mut trix = Trix::new(5).unwrap();
trix.batch(&(1..=80).map(f64::from).collect::<Vec<_>>());
assert!(trix.is_ready());
trix.reset();
assert!(!trix.is_ready());
}
#[test]
fn rejects_zero_period() {
assert!(Trix::new(0).is_err());
}
}
+213
View File
@@ -0,0 +1,213 @@
//! Volume-Weighted Average Price (VWAP).
//!
//! Two variants are offered: a cumulative `Vwap` that runs forever (the
//! intraday convention), and a rolling-window `RollingVwap` for streaming bots
//! that need a finite-memory price benchmark.
use std::collections::VecDeque;
use crate::error::{Error, Result};
use crate::ohlcv::Candle;
use crate::traits::Indicator;
/// Cumulative session VWAP. Call [`Indicator::reset`] at the start of each
/// session (e.g. trading-day boundary) to restart the accumulation.
#[derive(Debug, Clone, Default)]
pub struct Vwap {
sum_pv: f64,
sum_v: f64,
has_emitted: bool,
}
impl Vwap {
/// Construct a fresh cumulative VWAP.
pub const fn new() -> Self {
Self {
sum_pv: 0.0,
sum_v: 0.0,
has_emitted: false,
}
}
/// Current VWAP if at least one candle with non-zero volume has been observed.
pub fn value(&self) -> Option<f64> {
if self.sum_v == 0.0 {
None
} else {
Some(self.sum_pv / self.sum_v)
}
}
}
impl Indicator for Vwap {
type Input = Candle;
type Output = f64;
fn update(&mut self, candle: Candle) -> Option<f64> {
let tp = candle.typical_price();
self.sum_pv += tp * candle.volume;
self.sum_v += candle.volume;
if self.sum_v == 0.0 {
return None;
}
self.has_emitted = true;
Some(self.sum_pv / self.sum_v)
}
fn reset(&mut self) {
self.sum_pv = 0.0;
self.sum_v = 0.0;
self.has_emitted = false;
}
fn warmup_period(&self) -> usize {
1
}
fn is_ready(&self) -> bool {
self.has_emitted
}
fn name(&self) -> &'static str {
"VWAP"
}
}
/// Rolling-window VWAP: a finite-memory variant for bots that don't want
/// unbounded accumulation.
#[derive(Debug, Clone)]
pub struct RollingVwap {
period: usize,
window: VecDeque<(f64, f64)>, // (typical_price * volume, volume)
sum_pv: f64,
sum_v: f64,
}
impl RollingVwap {
/// # Errors
/// Returns [`Error::PeriodZero`] if `period == 0`.
pub fn new(period: usize) -> Result<Self> {
if period == 0 {
return Err(Error::PeriodZero);
}
Ok(Self {
period,
window: VecDeque::with_capacity(period),
sum_pv: 0.0,
sum_v: 0.0,
})
}
/// Configured rolling window length.
pub const fn period(&self) -> usize {
self.period
}
}
impl Indicator for RollingVwap {
type Input = Candle;
type Output = f64;
fn update(&mut self, candle: Candle) -> Option<f64> {
let pv = candle.typical_price() * candle.volume;
if self.window.len() == self.period {
let (old_pv, old_v) = self.window.pop_front().expect("non-empty");
self.sum_pv -= old_pv;
self.sum_v -= old_v;
}
self.window.push_back((pv, candle.volume));
self.sum_pv += pv;
self.sum_v += candle.volume;
if self.window.len() < self.period || self.sum_v == 0.0 {
return None;
}
Some(self.sum_pv / self.sum_v)
}
fn reset(&mut self) {
self.window.clear();
self.sum_pv = 0.0;
self.sum_v = 0.0;
}
fn warmup_period(&self) -> usize {
self.period
}
fn is_ready(&self) -> bool {
self.window.len() == self.period && self.sum_v > 0.0
}
fn name(&self) -> &'static str {
"RollingVWAP"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
fn c(price: f64, volume: f64) -> Candle {
Candle::new(price, price, price, price, volume, 0).unwrap()
}
#[test]
fn cumulative_vwap_equal_volumes_equals_mean() {
let candles = vec![c(10.0, 1.0), c(20.0, 1.0), c(30.0, 1.0)];
let mut v = Vwap::new();
let out = v.batch(&candles);
assert_relative_eq!(out[2].unwrap(), 20.0, epsilon = 1e-12);
}
#[test]
fn cumulative_vwap_weighted() {
// Two candles: 10@1 and 20@3 -> (10*1 + 20*3) / (1+3) = 70/4 = 17.5
let candles = vec![c(10.0, 1.0), c(20.0, 3.0)];
let mut v = Vwap::new();
let out = v.batch(&candles);
assert_relative_eq!(out[1].unwrap(), 17.5, epsilon = 1e-12);
}
#[test]
fn rolling_vwap_window_slides() {
let candles = vec![c(10.0, 1.0), c(20.0, 1.0), c(30.0, 1.0), c(40.0, 1.0)];
let mut v = RollingVwap::new(3).unwrap();
let out = v.batch(&candles);
assert!(out[1].is_none());
// index 2 -> (10+20+30)/3 = 20
assert_relative_eq!(out[2].unwrap(), 20.0, epsilon = 1e-12);
// index 3 -> (20+30+40)/3 = 30
assert_relative_eq!(out[3].unwrap(), 30.0, epsilon = 1e-12);
}
#[test]
fn batch_equals_streaming_cumulative() {
let candles: Vec<Candle> = (1..20).map(|i| c(f64::from(i), 1.0)).collect();
let mut a = Vwap::new();
let mut b = Vwap::new();
assert_eq!(
a.batch(&candles),
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
);
}
#[test]
fn batch_equals_streaming_rolling() {
let candles: Vec<Candle> = (1..30)
.map(|i| c(f64::from(i), f64::from(i % 5 + 1)))
.collect();
let mut a = RollingVwap::new(10).unwrap();
let mut b = RollingVwap::new(10).unwrap();
assert_eq!(
a.batch(&candles),
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
);
}
#[test]
fn rolling_rejects_zero_period() {
assert!(RollingVwap::new(0).is_err());
}
}
@@ -0,0 +1,141 @@
//! Williams %R.
use std::collections::VecDeque;
use crate::error::{Error, Result};
use crate::ohlcv::Candle;
use crate::traits::Indicator;
/// Williams %R: `-100 * (HH - close) / (HH - LL)` over the lookback window.
///
/// Values lie in `[-100, 0]` and approximate the mirror image of the fast
/// Stochastic %K.
#[derive(Debug, Clone)]
pub struct WilliamsR {
period: usize,
candles: VecDeque<Candle>,
}
impl WilliamsR {
/// # Errors
/// Returns [`Error::PeriodZero`] if `period == 0`.
pub fn new(period: usize) -> Result<Self> {
if period == 0 {
return Err(Error::PeriodZero);
}
Ok(Self {
period,
candles: VecDeque::with_capacity(period),
})
}
/// Configured period.
pub const fn period(&self) -> usize {
self.period
}
}
impl Indicator for WilliamsR {
type Input = Candle;
type Output = f64;
fn update(&mut self, candle: Candle) -> Option<f64> {
if self.candles.len() == self.period {
self.candles.pop_front();
}
self.candles.push_back(candle);
if self.candles.len() < self.period {
return None;
}
let hh = self
.candles
.iter()
.map(|c| c.high)
.fold(f64::NEG_INFINITY, f64::max);
let ll = self
.candles
.iter()
.map(|c| c.low)
.fold(f64::INFINITY, f64::min);
let range = hh - ll;
if range == 0.0 {
return Some(-50.0);
}
Some(-100.0 * (hh - candle.close) / range)
}
fn reset(&mut self) {
self.candles.clear();
}
fn warmup_period(&self) -> usize {
self.period
}
fn is_ready(&self) -> bool {
self.candles.len() == self.period
}
fn name(&self) -> &'static str {
"WilliamsR"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
fn c(h: f64, l: f64, cl: f64) -> Candle {
Candle::new(cl, h, l, cl, 1.0, 0).unwrap()
}
#[test]
fn close_at_high_yields_zero() {
let candles = vec![c(10.0, 8.0, 9.0), c(11.0, 9.0, 10.0), c(12.0, 10.0, 12.0)];
let mut w = WilliamsR::new(3).unwrap();
let out = w.batch(&candles);
assert_relative_eq!(out[2].unwrap(), 0.0, epsilon = 1e-12);
}
#[test]
fn close_at_low_yields_minus_100() {
let candles = vec![c(12.0, 10.0, 11.0), c(11.0, 9.0, 10.0), c(10.0, 8.0, 8.0)];
let mut w = WilliamsR::new(3).unwrap();
let out = w.batch(&candles);
assert_relative_eq!(out[2].unwrap(), -100.0, epsilon = 1e-12);
}
#[test]
fn within_range() {
let candles: Vec<Candle> = (0..100)
.map(|i| {
let m = 50.0 + (f64::from(i) * 0.3).sin() * 5.0;
c(m + 1.0, m - 1.0, m)
})
.collect();
let mut w = WilliamsR::new(14).unwrap();
for v in w.batch(&candles).into_iter().flatten() {
assert!((-100.0..=0.0).contains(&v), "%R out of range: {v}");
}
}
#[test]
fn batch_equals_streaming() {
let candles: Vec<Candle> = (0..30)
.map(|i| c(f64::from(i) + 2.0, f64::from(i), f64::from(i) + 1.0))
.collect();
let mut a = WilliamsR::new(5).unwrap();
let mut b = WilliamsR::new(5).unwrap();
assert_eq!(
a.batch(&candles),
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
);
}
#[test]
fn rejects_zero_period() {
assert!(WilliamsR::new(0).is_err());
}
}
+229
View File
@@ -0,0 +1,229 @@
//! Weighted Moving Average (linear weights).
use std::collections::VecDeque;
use crate::error::{Error, Result};
use crate::traits::Indicator;
/// Weighted Moving Average with linear weights `1, 2, ..., period`.
///
/// Output is `sum(weight_i * price_i) / sum(weights)`. Maintained incrementally in
/// O(1) by keeping the rolling sum of values and the rolling weighted sum.
#[derive(Debug, Clone)]
pub struct Wma {
period: usize,
window: VecDeque<f64>,
weight_sum: f64, // sum_i (weight_i * value_i)
value_sum: f64, // sum_i (value_i)
weights_total: f64,
}
impl Wma {
/// Construct a new WMA with the given window length.
///
/// # Errors
///
/// Returns [`Error::PeriodZero`] if `period == 0`.
pub fn new(period: usize) -> Result<Self> {
if period == 0 {
return Err(Error::PeriodZero);
}
let n = period as f64;
let weights_total = n * (n + 1.0) / 2.0;
Ok(Self {
period,
window: VecDeque::with_capacity(period),
weight_sum: 0.0,
value_sum: 0.0,
weights_total,
})
}
/// Configured period.
pub const fn period(&self) -> usize {
self.period
}
/// Current value if available.
pub fn value(&self) -> Option<f64> {
if self.window.len() == self.period {
Some(self.weight_sum / self.weights_total)
} else {
None
}
}
}
impl Indicator for Wma {
type Input = f64;
type Output = f64;
fn update(&mut self, input: f64) -> Option<f64> {
if !input.is_finite() {
return self.value();
}
if self.window.len() < self.period {
// Warmup. Just accumulate; compute weight_sum once when the window first
// becomes full to avoid having to track changing weights during warmup.
self.window.push_back(input);
self.value_sum += input;
if self.window.len() == self.period {
self.weight_sum = self
.window
.iter()
.enumerate()
.map(|(i, v)| (i as f64 + 1.0) * v)
.sum();
}
return self.value();
}
// Steady state: slide the window. With weights [1, 2, ..., period],
// new_weight_sum = old_weight_sum - old_value_sum + period * new_input
// because every retained element's weight drops by one and the newcomer
// enters at weight = period. Order matters: subtract `value_sum` BEFORE
// updating it.
let oldest = self.window.pop_front().expect("window non-empty");
self.weight_sum = self.weight_sum - self.value_sum + self.period as f64 * input;
self.value_sum = self.value_sum - oldest + input;
self.window.push_back(input);
self.value()
}
fn reset(&mut self) {
self.window.clear();
self.weight_sum = 0.0;
self.value_sum = 0.0;
}
fn warmup_period(&self) -> usize {
self.period
}
fn is_ready(&self) -> bool {
self.window.len() == self.period
}
fn name(&self) -> &'static str {
"WMA"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
/// Reference implementation: explicit weighted average over a window.
fn wma_naive(prices: &[f64], period: usize) -> Vec<Option<f64>> {
let weights_total = (period as f64) * (period as f64 + 1.0) / 2.0;
prices
.iter()
.enumerate()
.map(|(i, _)| {
if i + 1 < period {
None
} else {
let window = &prices[i + 1 - period..=i];
let s: f64 = window
.iter()
.enumerate()
.map(|(j, p)| (j as f64 + 1.0) * p)
.sum();
Some(s / weights_total)
}
})
.collect()
}
#[test]
fn new_rejects_zero_period() {
assert!(matches!(Wma::new(0), Err(Error::PeriodZero)));
}
#[test]
fn warmup_returns_none() {
let mut wma = Wma::new(3).unwrap();
assert_eq!(wma.update(1.0), None);
assert_eq!(wma.update(2.0), None);
// WMA(3) of [1,2,3]: oldest = 1 (weight 1), middle = 2 (weight 2), newest = 3 (weight 3)
// -> (1*1 + 2*2 + 3*3) / (1+2+3) = 14/6
assert_relative_eq!(wma.update(3.0).unwrap(), 14.0 / 6.0, epsilon = 1e-12);
}
#[test]
fn known_values_period_4() {
// WMA(4) weights 1,2,3,4 (total 10); inputs [1,2,3,4]:
// (1*1 + 2*2 + 3*3 + 4*4) / 10 = (1+4+9+16)/10 = 30/10 = 3.0
let mut wma = Wma::new(4).unwrap();
let v = wma.batch(&[1.0, 2.0, 3.0, 4.0]);
assert_relative_eq!(v[3].unwrap(), 3.0, epsilon = 1e-12);
}
#[test]
fn matches_naive_over_random_inputs() {
let prices: Vec<f64> = (1..=30).map(|i| f64::from(i) * 1.7 - 5.0).collect();
let mut wma = Wma::new(7).unwrap();
let got = wma.batch(&prices);
let want = wma_naive(&prices, 7);
for (g, w) in got.iter().zip(want.iter()) {
match (g, w) {
(None, None) => {}
(Some(a), Some(b)) => assert_relative_eq!(*a, *b, epsilon = 1e-9),
_ => panic!("warmup mismatch"),
}
}
}
#[test]
fn period_one_is_pass_through() {
let mut wma = Wma::new(1).unwrap();
assert_relative_eq!(wma.update(5.5).unwrap(), 5.5, epsilon = 1e-12);
assert_relative_eq!(wma.update(7.5).unwrap(), 7.5, epsilon = 1e-12);
}
#[test]
fn reset_clears_state() {
let mut wma = Wma::new(4).unwrap();
wma.batch(&[1.0, 2.0, 3.0, 4.0, 5.0]);
assert!(wma.is_ready());
wma.reset();
assert!(!wma.is_ready());
assert_eq!(wma.update(10.0), None);
}
#[test]
fn batch_equals_streaming() {
let prices: Vec<f64> = (1..=20).map(|i| f64::from(i) * 0.5).collect();
let mut a = Wma::new(5).unwrap();
let mut b = Wma::new(5).unwrap();
assert_eq!(
a.batch(&prices),
prices.iter().map(|p| b.update(*p)).collect::<Vec<_>>()
);
}
proptest::proptest! {
#![proptest_config(proptest::test_runner::Config::with_cases(48))]
#[test]
fn proptest_matches_naive(
period in 1usize..15,
prices in proptest::collection::vec(-500.0_f64..500.0, 0..120),
) {
let mut wma = Wma::new(period).unwrap();
let got = wma.batch(&prices);
let want = wma_naive(&prices, period);
proptest::prop_assert_eq!(got.len(), want.len());
for (g, w) in got.iter().zip(want.iter()) {
match (g, w) {
(None, None) => {}
(Some(a), Some(b)) => proptest::prop_assert!(
(a - b).abs() < 1e-7,
"got={a} want={b}"
),
_ => proptest::prop_assert!(false, "warmup mismatch"),
}
}
}
}
}
+53
View File
@@ -0,0 +1,53 @@
//! `wickra-core`: streaming-first technical indicators.
//!
//! The core engine of Wickra. Every indicator is implemented as a state machine
//! that consumes inputs one at a time via [`Indicator::update`] in constant time.
//! Batch evaluation is provided as a blanket extension trait so the same code
//! path serves both online (tick-by-tick) and offline (historical) workloads.
//!
//! # Design
//!
//! - **Streaming-first.** State is held by the indicator instance, so a new value
//! only re-computes deltas, not the whole series.
//! - **Batch is free.** [`BatchExt::batch`] is a blanket implementation that
//! simply replays `update` over a slice. Writing one implementation gives both
//! APIs.
//! - **Composable.** Indicators implement [`Indicator<Input = f64, Output = f64>`]
//! wherever they conceptually take a price, so they can be chained via
//! [`Chain`].
//! - **No `unsafe`.** The crate forbids `unsafe_code` in the workspace lints.
//!
//! # Quick start
//!
//! ```
//! use wickra_core::{BatchExt, Indicator, Sma};
//!
//! // Streaming:
//! let mut sma = Sma::new(3).unwrap();
//! assert_eq!(sma.update(1.0), None);
//! assert_eq!(sma.update(2.0), None);
//! assert_eq!(sma.update(3.0), Some(2.0));
//!
//! // Batch (replays `update` internally):
//! let mut sma = Sma::new(3).unwrap();
//! let out = sma.batch(&[1.0, 2.0, 3.0, 4.0]);
//! assert_eq!(out, vec![None, None, Some(2.0), Some(3.0)]);
//! ```
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
mod error;
mod ohlcv;
mod traits;
pub mod indicators;
pub use error::{Error, Result};
pub use indicators::{
Adx, AdxOutput, Aroon, AroonOutput, Atr, AwesomeOscillator, BollingerBands, BollingerOutput,
Cci, Dema, Donchian, DonchianOutput, Ema, Hma, Kama, Keltner, KeltnerOutput, MacdIndicator,
MacdOutput, Mfi, Obv, Psar, Roc, RollingVwap, Rsi, Sma, Stochastic, StochasticOutput, Tema,
Trix, Vwap, WilliamsR, Wma,
};
pub use ohlcv::{Candle, Tick};
pub use traits::{BatchExt, Chain, Indicator};
+285
View File
@@ -0,0 +1,285 @@
//! OHLCV value types: candles and ticks.
use crate::error::{Error, Result};
/// A single OHLCV bar.
///
/// Timestamps are unitless `i64` values so callers can use whatever epoch resolution
/// they prefer (milliseconds, microseconds, seconds…). Wickra never inspects them
/// numerically beyond passing them through.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Candle {
/// Bar open price.
pub open: f64,
/// Bar high price.
pub high: f64,
/// Bar low price.
pub low: f64,
/// Bar close price.
pub close: f64,
/// Bar volume.
pub volume: f64,
/// Bar timestamp (caller-defined epoch / resolution).
pub timestamp: i64,
}
impl Candle {
/// Construct a new candle, validating the OHLC relationships and finiteness.
///
/// # Errors
///
/// Returns [`Error::InvalidCandle`] if any of these invariants are violated:
/// - `high >= max(open, close, low)`
/// - `low <= min(open, close, high)`
/// - all of `open`, `high`, `low`, `close`, `volume` are finite
/// - `volume >= 0`
pub fn new(
open: f64,
high: f64,
low: f64,
close: f64,
volume: f64,
timestamp: i64,
) -> Result<Self> {
if !(open.is_finite() && high.is_finite() && low.is_finite() && close.is_finite()) {
return Err(Error::InvalidCandle {
message: "open, high, low, close must all be finite",
});
}
if !volume.is_finite() {
return Err(Error::InvalidCandle {
message: "volume must be finite",
});
}
if volume < 0.0 {
return Err(Error::InvalidCandle {
message: "volume must be non-negative",
});
}
if high < low {
return Err(Error::InvalidCandle {
message: "high must be >= low",
});
}
if high < open || high < close {
return Err(Error::InvalidCandle {
message: "high must be >= open and >= close",
});
}
if low > open || low > close {
return Err(Error::InvalidCandle {
message: "low must be <= open and <= close",
});
}
Ok(Self {
open,
high,
low,
close,
volume,
timestamp,
})
}
/// Construct a candle without validation. The caller asserts that all OHLC
/// invariants hold and that no field is NaN or infinite.
pub const fn new_unchecked(
open: f64,
high: f64,
low: f64,
close: f64,
volume: f64,
timestamp: i64,
) -> Self {
Self {
open,
high,
low,
close,
volume,
timestamp,
}
}
/// The typical price `(high + low + close) / 3`. Used by CCI, MFI, VWAP, etc.
#[inline]
pub fn typical_price(&self) -> f64 {
(self.high + self.low + self.close) / 3.0
}
/// The mid price `(high + low) / 2`.
#[inline]
pub fn median_price(&self) -> f64 {
(self.high + self.low) / 2.0
}
/// The weighted close `(high + low + 2*close) / 4`.
#[inline]
pub fn weighted_close(&self) -> f64 {
(self.high + self.low + 2.0 * self.close) / 4.0
}
/// True range of this candle relative to a previous close: `max(H-L, |H-prev|, |L-prev|)`.
/// If no previous close is supplied, falls back to `high - low`.
#[inline]
pub fn true_range(&self, prev_close: Option<f64>) -> f64 {
let hl = self.high - self.low;
match prev_close {
Some(prev) => {
let hp = (self.high - prev).abs();
let lp = (self.low - prev).abs();
hl.max(hp).max(lp)
}
None => hl,
}
}
}
/// A single trade tick.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Tick {
/// Trade price.
pub price: f64,
/// Trade size.
pub volume: f64,
/// Trade timestamp (caller-defined epoch / resolution).
pub timestamp: i64,
}
impl Tick {
/// Construct a new tick, validating finiteness and non-negativity of volume.
///
/// # Errors
///
/// Returns [`Error::NonFiniteInput`] if `price` or `volume` is NaN or infinite,
/// or [`Error::InvalidCandle`] for `volume < 0`.
pub fn new(price: f64, volume: f64, timestamp: i64) -> Result<Self> {
if !price.is_finite() || !volume.is_finite() {
return Err(Error::NonFiniteInput);
}
if volume < 0.0 {
return Err(Error::InvalidCandle {
message: "tick volume must be non-negative",
});
}
Ok(Self {
price,
volume,
timestamp,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn candle_new_accepts_valid_ohlc() {
let c = Candle::new(10.0, 11.0, 9.0, 10.5, 100.0, 1).unwrap();
assert_eq!(c.open, 10.0);
assert_eq!(c.high, 11.0);
assert_eq!(c.low, 9.0);
assert_eq!(c.close, 10.5);
assert_eq!(c.volume, 100.0);
assert_eq!(c.timestamp, 1);
}
#[test]
fn candle_new_rejects_high_below_low() {
let err = Candle::new(10.0, 9.0, 10.0, 10.0, 1.0, 0).unwrap_err();
assert!(matches!(err, Error::InvalidCandle { .. }));
}
#[test]
fn candle_new_rejects_high_below_close() {
let err = Candle::new(10.0, 10.0, 9.0, 11.0, 1.0, 0).unwrap_err();
assert!(matches!(err, Error::InvalidCandle { .. }));
}
#[test]
fn candle_new_rejects_low_above_open() {
let err = Candle::new(10.0, 11.0, 10.5, 10.5, 1.0, 0).unwrap_err();
assert!(matches!(err, Error::InvalidCandle { .. }));
}
#[test]
fn candle_new_rejects_negative_volume() {
let err = Candle::new(10.0, 11.0, 9.0, 10.5, -1.0, 0).unwrap_err();
assert!(matches!(err, Error::InvalidCandle { .. }));
}
#[test]
fn candle_new_rejects_nan_price() {
let err = Candle::new(f64::NAN, 11.0, 9.0, 10.5, 1.0, 0).unwrap_err();
assert!(matches!(err, Error::InvalidCandle { .. }));
}
#[test]
fn candle_typical_price() {
let c = Candle::new(10.0, 12.0, 9.0, 11.0, 1.0, 0).unwrap();
assert_eq!(c.typical_price(), (12.0 + 9.0 + 11.0) / 3.0);
}
#[test]
fn candle_median_price() {
let c = Candle::new(10.0, 12.0, 8.0, 11.0, 1.0, 0).unwrap();
assert_eq!(c.median_price(), 10.0);
}
#[test]
fn candle_weighted_close() {
let c = Candle::new(10.0, 12.0, 8.0, 11.0, 1.0, 0).unwrap();
assert_eq!(c.weighted_close(), (12.0 + 8.0 + 22.0) / 4.0);
}
#[test]
fn candle_true_range_without_prev() {
let c = Candle::new(10.0, 12.0, 8.0, 11.0, 1.0, 0).unwrap();
assert_eq!(c.true_range(None), 4.0);
}
#[test]
fn candle_true_range_with_gap_up() {
// Previous close 6, today's range 8-12: gap covered by |H-prev|=6
let c = Candle::new(10.0, 12.0, 8.0, 11.0, 1.0, 0).unwrap();
assert_eq!(c.true_range(Some(6.0)), 6.0);
}
#[test]
fn candle_true_range_with_gap_down() {
// Previous close 14, today's range 8-12: gap covered by |L-prev|=6
let c = Candle::new(10.0, 12.0, 8.0, 11.0, 1.0, 0).unwrap();
assert_eq!(c.true_range(Some(14.0)), 6.0);
}
#[test]
fn tick_new_accepts_valid() {
let t = Tick::new(100.5, 0.5, 42).unwrap();
assert_eq!(t.price, 100.5);
assert_eq!(t.volume, 0.5);
assert_eq!(t.timestamp, 42);
}
#[test]
fn tick_new_rejects_nan() {
assert!(matches!(
Tick::new(f64::NAN, 1.0, 0),
Err(Error::NonFiniteInput)
));
}
#[test]
fn tick_new_rejects_inf() {
assert!(matches!(
Tick::new(f64::INFINITY, 1.0, 0),
Err(Error::NonFiniteInput)
));
}
#[test]
fn tick_new_rejects_negative_volume() {
let err = Tick::new(100.0, -1.0, 0).unwrap_err();
assert!(matches!(err, Error::InvalidCandle { .. }));
}
}
+287
View File
@@ -0,0 +1,287 @@
//! Core traits: the [`Indicator`] state machine and the [`BatchExt`] blanket extension.
/// A streaming technical indicator.
///
/// Every indicator in Wickra implements this trait. The contract is:
///
/// - [`update`](Indicator::update) is called once per input point and must be O(1) in
/// the input length. Pre-existing buffered state may be touched, but no full
/// recomputation over the entire series is permitted.
/// - The returned `Option<Output>` is `None` while the indicator is still in its
/// *warmup* phase (insufficient inputs to produce a defined value), and `Some`
/// once it is ready.
/// - [`reset`](Indicator::reset) clears all state, returning the indicator to the
/// exact configuration it had immediately after construction.
///
/// Implementors that consume scalar prices use `Input = f64` so they automatically
/// gain access to chaining via [`Chain`].
pub trait Indicator {
/// Type of one input data point (typically `f64` for a price, or `Candle` / `Tick`).
type Input;
/// Type of one output value.
type Output;
/// Feed one new data point into the indicator and return the freshly computed
/// output, or `None` if the indicator is still warming up.
fn update(&mut self, input: Self::Input) -> Option<Self::Output>;
/// Reset all internal state, leaving the indicator equivalent to a freshly
/// constructed instance with the same parameters.
fn reset(&mut self);
/// Number of inputs required before the first non-`None` output can be produced.
fn warmup_period(&self) -> usize;
/// Whether the indicator has emitted at least one value since the last reset.
fn is_ready(&self) -> bool;
/// Stable, human-readable indicator name. Used by chaining and diagnostics.
fn name(&self) -> &'static str;
}
/// Blanket extension that adds batch evaluation to every [`Indicator`].
///
/// The naive `batch` simply replays `update` over a slice, which is always correct
/// because `update` is the only state transition. Concrete indicators may override
/// `batch` if they have a faster vectorized path; the default keeps the contract
/// `batch == repeated update`.
pub trait BatchExt: Indicator {
/// Run the indicator over a slice of inputs in order, returning one output (or
/// `None` during warmup) per input.
fn batch(&mut self, inputs: &[Self::Input]) -> Vec<Option<Self::Output>>
where
Self::Input: Clone,
{
let mut out = Vec::with_capacity(inputs.len());
for x in inputs {
out.push(self.update(x.clone()));
}
out
}
/// Run an independent copy of the indicator over each input series in parallel.
///
/// Each asset is processed by its own fresh instance built via `make`, so state
/// never leaks across assets. Requires the `parallel` feature (enabled by
/// default), which pulls in `rayon`.
#[cfg(feature = "parallel")]
fn batch_parallel<F>(
inputs_per_asset: &[Vec<Self::Input>],
make: F,
) -> Vec<Vec<Option<Self::Output>>>
where
Self: Sized + Send,
Self::Input: Sync + Clone,
Self::Output: Send,
F: Fn() -> Self + Sync + Send,
{
use rayon::prelude::*;
inputs_per_asset
.par_iter()
.map(|series| {
let mut ind = make();
ind.batch(series)
})
.collect()
}
}
impl<T: Indicator> BatchExt for T {}
/// Chain two indicators so the output of the first becomes the input of the second.
///
/// Both indicators must agree on `f64` as the bridging type, which is the common
/// case for price-in/value-out indicators. The chain itself is an indicator, so
/// chains can be nested arbitrarily.
///
/// # Example
///
/// ```
/// use wickra_core::{Chain, Ema, Indicator, Rsi};
///
/// // RSI(7) on top of EMA(14). EMA seeds at input 14, then RSI needs 7+1 more
/// // valid inputs to emit, so the chain becomes ready at input 21.
/// let mut chain = Chain::new(Ema::new(14).unwrap(), Rsi::new(7).unwrap());
/// for i in 1..=21 {
/// chain.update(f64::from(i));
/// }
/// assert!(chain.is_ready());
/// ```
#[derive(Debug, Clone)]
pub struct Chain<A, B>
where
A: Indicator<Input = f64, Output = f64>,
B: Indicator<Input = f64>,
{
first: A,
second: B,
}
impl<A, B> Chain<A, B>
where
A: Indicator<Input = f64, Output = f64>,
B: Indicator<Input = f64>,
{
/// Construct a chain whose inputs flow through `first` and then `second`.
pub const fn new(first: A, second: B) -> Self {
Self { first, second }
}
/// Add a third stage on top.
pub fn then<C>(self, third: C) -> Chain<Self, C>
where
C: Indicator<Input = f64>,
Self: Indicator<Input = f64, Output = f64>,
{
Chain::new(self, third)
}
/// Borrow the upstream indicator.
pub const fn first(&self) -> &A {
&self.first
}
/// Borrow the downstream indicator.
pub const fn second(&self) -> &B {
&self.second
}
}
impl<A, B> Indicator for Chain<A, B>
where
A: Indicator<Input = f64, Output = f64>,
B: Indicator<Input = f64>,
{
type Input = f64;
type Output = B::Output;
fn update(&mut self, input: f64) -> Option<Self::Output> {
self.first.update(input).and_then(|v| self.second.update(v))
}
fn reset(&mut self) {
self.first.reset();
self.second.reset();
}
fn warmup_period(&self) -> usize {
// Conservative upper bound: both stages must warm up.
self.first.warmup_period() + self.second.warmup_period()
}
fn is_ready(&self) -> bool {
self.first.is_ready() && self.second.is_ready()
}
fn name(&self) -> &'static str {
"Chain"
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A trivial test indicator: identity (passes input through).
#[derive(Debug, Default)]
struct Identity {
seen: bool,
}
impl Indicator for Identity {
type Input = f64;
type Output = f64;
fn update(&mut self, input: f64) -> Option<f64> {
self.seen = true;
Some(input)
}
fn reset(&mut self) {
self.seen = false;
}
fn warmup_period(&self) -> usize {
0
}
fn is_ready(&self) -> bool {
self.seen
}
fn name(&self) -> &'static str {
"Identity"
}
}
/// Another trivial test indicator: scales input by 2.
#[derive(Debug, Default)]
struct Doubler {
seen: bool,
}
impl Indicator for Doubler {
type Input = f64;
type Output = f64;
fn update(&mut self, input: f64) -> Option<f64> {
self.seen = true;
Some(input * 2.0)
}
fn reset(&mut self) {
self.seen = false;
}
fn warmup_period(&self) -> usize {
0
}
fn is_ready(&self) -> bool {
self.seen
}
fn name(&self) -> &'static str {
"Doubler"
}
}
#[test]
fn batch_replays_update() {
let mut id = Identity::default();
let out = id.batch(&[1.0, 2.0, 3.0]);
assert_eq!(out, vec![Some(1.0), Some(2.0), Some(3.0)]);
}
#[test]
fn chain_pipes_first_into_second() {
let mut c = Chain::new(Doubler::default(), Doubler::default());
// 5 -> 10 -> 20
assert_eq!(c.update(5.0), Some(20.0));
}
#[test]
fn chain_is_ready_only_after_both_stages_emit() {
let mut c = Chain::new(Doubler::default(), Doubler::default());
assert!(!c.is_ready());
c.update(1.0);
assert!(c.is_ready());
}
#[test]
fn chain_reset_propagates() {
let mut c = Chain::new(Doubler::default(), Doubler::default());
c.update(1.0);
assert!(c.is_ready());
c.reset();
assert!(!c.is_ready());
}
#[test]
fn chain_three_levels_via_then() {
let c = Chain::new(Doubler::default(), Doubler::default()).then(Doubler::default());
let mut c = c;
// 1 -> 2 -> 4 -> 8
assert_eq!(c.update(1.0), Some(8.0));
}
#[cfg(feature = "parallel")]
#[test]
fn batch_parallel_runs_independent_instances() {
let series: Vec<Vec<f64>> = vec![vec![1.0, 2.0, 3.0], vec![4.0, 5.0, 6.0]];
let out = Doubler::batch_parallel(&series, Doubler::default);
assert_eq!(out.len(), 2);
assert_eq!(out[0], vec![Some(2.0), Some(4.0), Some(6.0)]);
assert_eq!(out[1], vec![Some(8.0), Some(10.0), Some(12.0)]);
}
}
+45
View File
@@ -0,0 +1,45 @@
[package]
name = "wickra-data"
description = "Data sources for Wickra: CSV readers, tick-to-candle aggregator, and live exchange feeds."
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
[lints]
workspace = true
[dependencies]
wickra-core = { workspace = true }
thiserror = { workspace = true }
csv = "1.3"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
# Async / live feeds are opt-in: only pulled when a `live-*` feature is requested.
tokio = { version = "1", features = ["rt", "rt-multi-thread", "macros", "net", "time", "io-util"], optional = true }
tokio-tungstenite = { version = "0.24", optional = true, features = ["native-tls"] }
futures-util = { version = "0.3", optional = true }
url = { version = "2", optional = true }
[features]
default = []
# Each exchange is gated so users only pay for the WS stack they actually want.
live-binance = ["dep:tokio", "dep:tokio-tungstenite", "dep:futures-util", "dep:url"]
[dev-dependencies]
approx = { workspace = true }
tempfile = "3"
wickra = { path = "../wickra" }
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
[[example]]
name = "live_binance"
path = "../../examples/rust/live_binance.rs"
required-features = ["live-binance"]
+226
View File
@@ -0,0 +1,226 @@
//! Roll trade ticks up into candles of an arbitrary timeframe.
use crate::error::{Error, Result};
use wickra_core::{Candle, Tick};
/// A candle bucket size measured in the same unit as the tick timestamps.
///
/// Wickra is unit-agnostic about timestamps: choose whichever makes sense for
/// your source (milliseconds for Binance trade events, microseconds for IB,
/// seconds for daily bars).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Timeframe {
bucket: i64,
}
impl Timeframe {
/// Construct a timeframe with the given bucket size in the chosen unit.
///
/// # Errors
/// Returns [`Error::InvalidTimeframe`] if `bucket <= 0`.
pub fn new(bucket: i64) -> Result<Self> {
if bucket <= 0 {
return Err(Error::InvalidTimeframe(format!(
"bucket size must be positive, got {bucket}"
)));
}
Ok(Self { bucket })
}
/// Convenience: build a millisecond timeframe.
pub fn millis(ms: i64) -> Result<Self> {
Self::new(ms)
}
/// Convenience: build a seconds-resolution timeframe.
pub fn seconds(s: i64) -> Result<Self> {
Self::new(s)
}
/// One-minute timeframe in milliseconds (`60_000`).
pub fn one_minute_ms() -> Self {
Self::new(60_000).expect("60_000 > 0")
}
/// Bucket size.
pub const fn bucket(self) -> i64 {
self.bucket
}
/// Floor a raw timestamp to this timeframe's bucket boundary.
pub fn floor(self, ts: i64) -> i64 {
ts - ts.rem_euclid(self.bucket)
}
}
/// Incrementally builds candles out of arriving ticks.
///
/// Each call to [`TickAggregator::push`] returns `Some(Candle)` if a previously
/// open bar just closed (i.e. the new tick belongs to a new bucket). Use
/// [`TickAggregator::flush`] at the end of a stream to capture the final open
/// bar.
#[derive(Debug, Clone)]
pub struct TickAggregator {
timeframe: Timeframe,
open_bar: Option<OpenBar>,
}
#[derive(Debug, Clone, Copy)]
struct OpenBar {
bucket_start: i64,
open: f64,
high: f64,
low: f64,
close: f64,
volume: f64,
}
impl OpenBar {
fn from_tick(t: Tick, bucket_start: i64) -> Self {
Self {
bucket_start,
open: t.price,
high: t.price,
low: t.price,
close: t.price,
volume: t.volume,
}
}
fn absorb(&mut self, t: Tick) {
if t.price > self.high {
self.high = t.price;
}
if t.price < self.low {
self.low = t.price;
}
self.close = t.price;
self.volume += t.volume;
}
fn into_candle(self) -> Candle {
Candle::new_unchecked(
self.open,
self.high,
self.low,
self.close,
self.volume,
self.bucket_start,
)
}
}
impl TickAggregator {
/// Construct a new aggregator for the given timeframe.
pub fn new(timeframe: Timeframe) -> Self {
Self {
timeframe,
open_bar: None,
}
}
/// Push a tick. Returns `Some(Candle)` if a bar boundary was crossed and a
/// previously open bar just closed.
///
/// # Errors
/// Returns an error if `tick.timestamp` is strictly less than the start of
/// the currently open bar (out-of-order ticks are not supported).
pub fn push(&mut self, tick: Tick) -> Result<Option<Candle>> {
let bucket = self.timeframe.floor(tick.timestamp);
if let Some(mut bar) = self.open_bar {
if bucket < bar.bucket_start {
return Err(Error::Malformed(format!(
"tick timestamp {} is older than the open bar start {}",
tick.timestamp, bar.bucket_start
)));
}
if bucket > bar.bucket_start {
// Close the previous bar and start a new one with this tick.
self.open_bar = Some(OpenBar::from_tick(tick, bucket));
return Ok(Some(bar.into_candle()));
}
bar.absorb(tick);
self.open_bar = Some(bar);
return Ok(None);
}
self.open_bar = Some(OpenBar::from_tick(tick, bucket));
Ok(None)
}
/// Drain the currently open bar (if any) and return it. Useful at the end of
/// a backtest or when shutting down a live aggregator.
pub fn flush(&mut self) -> Option<Candle> {
self.open_bar.take().map(OpenBar::into_candle)
}
/// Configured timeframe.
pub const fn timeframe(&self) -> Timeframe {
self.timeframe
}
}
#[cfg(test)]
mod tests {
use super::*;
fn t(price: f64, ts: i64) -> Tick {
Tick::new(price, 1.0, ts).unwrap()
}
#[test]
fn timeframe_rejects_non_positive() {
assert!(Timeframe::new(0).is_err());
assert!(Timeframe::new(-1).is_err());
}
#[test]
fn floors_to_bucket_boundary() {
let tf = Timeframe::new(100).unwrap();
assert_eq!(tf.floor(0), 0);
assert_eq!(tf.floor(99), 0);
assert_eq!(tf.floor(100), 100);
assert_eq!(tf.floor(150), 100);
assert_eq!(tf.floor(250), 200);
}
#[test]
fn aggregates_ticks_into_one_candle_within_bucket() {
let mut agg = TickAggregator::new(Timeframe::new(60).unwrap());
assert_eq!(agg.push(t(10.0, 0)).unwrap(), None);
assert_eq!(agg.push(t(12.0, 15)).unwrap(), None);
assert_eq!(agg.push(t(8.0, 30)).unwrap(), None);
assert_eq!(agg.push(t(11.0, 50)).unwrap(), None);
let bar = agg.flush().expect("open bar");
assert_eq!(bar.open, 10.0);
assert_eq!(bar.high, 12.0);
assert_eq!(bar.low, 8.0);
assert_eq!(bar.close, 11.0);
assert!((bar.volume - 4.0).abs() < 1e-12);
assert_eq!(bar.timestamp, 0);
}
#[test]
fn emits_candle_on_bucket_crossing() {
let mut agg = TickAggregator::new(Timeframe::new(60).unwrap());
agg.push(t(10.0, 0)).unwrap();
agg.push(t(12.0, 30)).unwrap();
let closed = agg.push(t(15.0, 60)).unwrap().expect("emits");
assert_eq!(closed.open, 10.0);
assert_eq!(closed.high, 12.0);
assert_eq!(closed.low, 10.0);
assert_eq!(closed.close, 12.0);
// The new tick at ts=60 opens the next bar.
let still_open = agg.flush().unwrap();
assert_eq!(still_open.open, 15.0);
assert_eq!(still_open.timestamp, 60);
}
#[test]
fn rejects_out_of_order_ticks() {
let mut agg = TickAggregator::new(Timeframe::new(60).unwrap());
agg.push(t(10.0, 100)).unwrap();
let err = agg.push(t(11.0, 30)).unwrap_err();
assert!(matches!(err, Error::Malformed(_)));
}
}
+129
View File
@@ -0,0 +1,129 @@
//! Stream OHLCV candles out of a CSV file.
//!
//! The reader is generic over the column layout, but ships with a sensible
//! default ("timestamp,open,high,low,close,volume") that matches the standard
//! Binance / Yahoo Finance / kaggle dataset format.
use std::path::Path;
use serde::Deserialize;
use crate::error::{Error, Result};
use wickra_core::Candle;
/// Default OHLCV CSV row layout.
///
/// The timestamp is parsed as an `i64`; if your file ships an RFC3339 / ISO8601
/// string instead, use [`CandleReader::with_timestamp_parser`].
#[derive(Debug, Clone, Deserialize)]
pub struct DefaultRow {
pub timestamp: i64,
pub open: f64,
pub high: f64,
pub low: f64,
pub close: f64,
pub volume: f64,
}
impl DefaultRow {
fn into_candle(self) -> Result<Candle> {
Candle::new(
self.open,
self.high,
self.low,
self.close,
self.volume,
self.timestamp,
)
.map_err(Error::from)
}
}
/// Streaming OHLCV CSV reader.
#[derive(Debug)]
pub struct CandleReader<R: std::io::Read> {
reader: csv::Reader<R>,
}
impl CandleReader<std::fs::File> {
/// Open a CSV file at `path`. The first line is treated as a header by default.
pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
let reader = csv::ReaderBuilder::new()
.has_headers(true)
.from_path(path)?;
Ok(Self { reader })
}
}
impl<R: std::io::Read> CandleReader<R> {
/// Build a reader from any [`std::io::Read`] source.
pub fn from_reader(inner: R) -> Self {
Self {
reader: csv::ReaderBuilder::new()
.has_headers(true)
.from_reader(inner),
}
}
/// Replace the underlying reader; useful for testing.
pub fn from_csv_reader(reader: csv::Reader<R>) -> Self {
Self { reader }
}
/// Iterator over decoded candles.
pub fn candles(&mut self) -> impl Iterator<Item = Result<Candle>> + '_ {
self.reader.deserialize::<DefaultRow>().map(|row_res| {
let row = row_res?;
row.into_candle()
})
}
/// Read the entire stream into a `Vec<Candle>`. Convenient for backtests.
pub fn read_all(&mut self) -> Result<Vec<Candle>> {
self.candles().collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
#[test]
fn reads_well_formed_csv() {
let mut tmp = tempfile::NamedTempFile::new().unwrap();
writeln!(tmp, "timestamp,open,high,low,close,volume").unwrap();
writeln!(tmp, "1,10.0,11.0,9.0,10.5,100").unwrap();
writeln!(tmp, "2,10.5,11.5,10.0,11.0,150").unwrap();
writeln!(tmp, "3,11.0,12.0,10.5,11.5,200").unwrap();
tmp.flush().unwrap();
let mut r = CandleReader::open(tmp.path()).unwrap();
let candles = r.read_all().unwrap();
assert_eq!(candles.len(), 3);
assert_eq!(candles[0].open, 10.0);
assert_eq!(candles[2].close, 11.5);
assert_eq!(candles[1].timestamp, 2);
}
#[test]
fn rejects_invalid_ohlc() {
let mut tmp = tempfile::NamedTempFile::new().unwrap();
writeln!(tmp, "timestamp,open,high,low,close,volume").unwrap();
// high < low → core validation rejects it.
writeln!(tmp, "1,10.0,8.0,9.0,9.5,100").unwrap();
tmp.flush().unwrap();
let mut r = CandleReader::open(tmp.path()).unwrap();
let candles: Result<Vec<Candle>> = r.candles().collect();
assert!(candles.is_err());
}
#[test]
fn from_reader_works_on_in_memory_data() {
let data = "timestamp,open,high,low,close,volume\n1,1,2,0,1,10\n2,1,2,0,1,10\n";
let mut r = CandleReader::from_reader(data.as_bytes());
let v = r.read_all().unwrap();
assert_eq!(v.len(), 2);
}
}
+33
View File
@@ -0,0 +1,33 @@
//! Error types specific to the data sources.
use thiserror::Error;
/// Errors produced by the data layer.
#[derive(Debug, Error)]
pub enum Error {
#[error("I/O error: {0}")]
Io(#[from] std::io::Error),
#[error("CSV error: {0}")]
Csv(#[from] csv::Error),
#[error("invalid timeframe: {0}")]
InvalidTimeframe(String),
#[error("indicator-core error: {0}")]
Core(#[from] wickra_core::Error),
#[error("malformed payload: {0}")]
Malformed(String),
#[cfg(feature = "live-binance")]
#[error("websocket error: {0}")]
WebSocket(#[from] tokio_tungstenite::tungstenite::Error),
#[cfg(feature = "live-binance")]
#[error("JSON decode error: {0}")]
Json(#[from] serde_json::Error),
}
/// Convenience alias for `Result<T, wickra_data::Error>`.
pub type Result<T> = core::result::Result<T, Error>;
+24
View File
@@ -0,0 +1,24 @@
//! `wickra-data`: offline and online data sources for the Wickra indicator engine.
//!
//! - [`csv`]: stream OHLCV bars out of CSV files without buffering the whole
//! history in memory.
//! - [`aggregator`]: roll trade ticks up into candles of arbitrary timeframes.
//! - [`resample`]: convert a stream of candles from one timeframe to a coarser one.
//! - [`live`] (feature `live-binance`): connect to exchange websockets and yield
//! typed events compatible with the rest of the crate.
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
// `tokio_tungstenite::Error` is large by itself (~200 B). Boxing every Err
// variant per clippy::result_large_err just shifts allocation pressure into
// the hot path. We accept the size because errors are rare in this crate.
#![allow(clippy::result_large_err)]
pub mod aggregator;
pub mod csv;
pub mod error;
pub mod resample;
#[cfg(feature = "live-binance")]
pub mod live;
pub use error::{Error, Result};
+4
View File
@@ -0,0 +1,4 @@
//! Live exchange feeds. Each adapter is feature-gated; the Binance adapter
//! lives behind the `live-binance` feature.
pub mod binance;
+293
View File
@@ -0,0 +1,293 @@
//! Binance spot WebSocket kline feed.
//!
//! Subscribes to Binance's `<symbol>@kline_<interval>` stream and emits a
//! [`KlineEvent`] every time the server pushes a new tick. The event tells you
//! whether the current candle is still open or has just closed.
//!
//! Example (requires the `live-binance` feature):
//!
//! ```no_run
//! use wickra_data::live::binance::{BinanceKlineStream, Interval};
//! # async fn run() -> wickra_data::Result<()> {
//! let mut stream = BinanceKlineStream::connect(&["BTCUSDT".to_string()], Interval::OneMinute).await?;
//! while let Some(event) = stream.next_event().await? {
//! if event.is_closed {
//! println!("closed {} @ {}", event.symbol, event.candle.close);
//! }
//! }
//! # Ok(()) }
//! ```
use futures_util::SinkExt;
use futures_util::StreamExt;
use serde::Deserialize;
use tokio::net::TcpStream;
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::MaybeTlsStream;
use tokio_tungstenite::WebSocketStream;
use crate::error::{Error, Result};
use wickra_core::Candle;
/// Supported Binance kline intervals. The `as_str` value matches Binance's
/// wire-format strings (`"1m"`, `"5m"`, `"1h"`, etc.).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Interval {
OneSecond,
OneMinute,
ThreeMinutes,
FiveMinutes,
FifteenMinutes,
ThirtyMinutes,
OneHour,
TwoHours,
FourHours,
SixHours,
EightHours,
TwelveHours,
OneDay,
OneWeek,
}
impl Interval {
/// Wire-format string used in the stream name.
pub fn as_str(self) -> &'static str {
match self {
Self::OneSecond => "1s",
Self::OneMinute => "1m",
Self::ThreeMinutes => "3m",
Self::FiveMinutes => "5m",
Self::FifteenMinutes => "15m",
Self::ThirtyMinutes => "30m",
Self::OneHour => "1h",
Self::TwoHours => "2h",
Self::FourHours => "4h",
Self::SixHours => "6h",
Self::EightHours => "8h",
Self::TwelveHours => "12h",
Self::OneDay => "1d",
Self::OneWeek => "1w",
}
}
}
/// One push from the Binance kline stream.
#[derive(Debug, Clone)]
pub struct KlineEvent {
/// Symbol in lowercase form as sent by Binance (e.g. `"btcusdt"`).
pub symbol: String,
/// Interval the candle belongs to.
pub interval: Interval,
/// Candle in its current state (may still be open).
pub candle: Candle,
/// Whether the candle has been closed by the server. Closed events are the
/// only ones safe to use for bar-completion logic.
pub is_closed: bool,
}
/// A live Binance kline stream.
#[derive(Debug)]
pub struct BinanceKlineStream {
socket: WebSocketStream<MaybeTlsStream<TcpStream>>,
/// Interval requested at connect time. Used to tag every event.
interval: Interval,
}
/// Wire-format representation of an incoming Binance kline tick. Public so callers
/// can deserialize it themselves if they prefer.
#[derive(Debug, Clone, Deserialize)]
pub struct RawWsEnvelope {
/// Stream name, e.g. `"btcusdt@kline_1m"`.
pub stream: String,
pub data: RawKlinePayload,
}
#[derive(Debug, Clone, Deserialize)]
pub struct RawKlinePayload {
#[serde(rename = "e")]
pub event_type: String,
#[serde(rename = "E")]
pub event_time: i64,
#[serde(rename = "s")]
pub symbol: String,
#[serde(rename = "k")]
pub kline: RawKline,
}
#[derive(Debug, Clone, Deserialize)]
pub struct RawKline {
#[serde(rename = "t")]
pub open_time: i64,
#[serde(rename = "T")]
pub close_time: i64,
#[serde(rename = "s")]
pub symbol: String,
#[serde(rename = "i")]
pub interval: String,
#[serde(rename = "o")]
pub open: String,
#[serde(rename = "c")]
pub close: String,
#[serde(rename = "h")]
pub high: String,
#[serde(rename = "l")]
pub low: String,
#[serde(rename = "v")]
pub volume: String,
#[serde(rename = "x")]
pub is_closed: bool,
}
impl BinanceKlineStream {
/// Connect to Binance's combined-stream endpoint for one or more symbols.
///
/// Symbols may be passed in either case; they are lowercased to match
/// Binance's stream-name conventions.
pub async fn connect(symbols: &[String], interval: Interval) -> Result<Self> {
if symbols.is_empty() {
return Err(Error::Malformed(
"BinanceKlineStream requires at least one symbol".into(),
));
}
let streams: Vec<String> = symbols
.iter()
.map(|s| format!("{}@kline_{}", s.to_lowercase(), interval.as_str()))
.collect();
let url = format!(
"wss://stream.binance.com:9443/stream?streams={}",
streams.join("/")
);
let url = url::Url::parse(&url).map_err(|e| Error::Malformed(e.to_string()))?;
let (socket, _) = tokio_tungstenite::connect_async(url.as_str()).await?;
Ok(Self { socket, interval })
}
/// Receive the next kline event. Yields `Ok(None)` when the server closes
/// the connection cleanly.
pub async fn next_event(&mut self) -> Result<Option<KlineEvent>> {
loop {
let msg = match self.socket.next().await {
Some(Ok(m)) => m,
Some(Err(e)) => return Err(Error::from(e)),
None => return Ok(None),
};
match msg {
Message::Text(text) => {
let envelope: RawWsEnvelope = serde_json::from_str(&text)?;
return Ok(Some(envelope.into_event(self.interval)?));
}
Message::Binary(bytes) => {
let envelope: RawWsEnvelope = serde_json::from_slice(&bytes)?;
return Ok(Some(envelope.into_event(self.interval)?));
}
Message::Ping(payload) => {
self.socket.send(Message::Pong(payload)).await?;
}
Message::Pong(_) | Message::Frame(_) => {}
Message::Close(_) => return Ok(None),
}
}
}
/// Close the underlying socket cleanly.
pub async fn close(mut self) -> Result<()> {
self.socket.close(None).await?;
Ok(())
}
}
impl RawWsEnvelope {
fn into_event(self, interval: Interval) -> Result<KlineEvent> {
let k = self.data.kline;
let open: f64 = k
.open
.parse()
.map_err(|_| Error::Malformed(format!("bad open '{}'", k.open)))?;
let high: f64 = k
.high
.parse()
.map_err(|_| Error::Malformed(format!("bad high '{}'", k.high)))?;
let low: f64 = k
.low
.parse()
.map_err(|_| Error::Malformed(format!("bad low '{}'", k.low)))?;
let close: f64 = k
.close
.parse()
.map_err(|_| Error::Malformed(format!("bad close '{}'", k.close)))?;
let volume: f64 = k
.volume
.parse()
.map_err(|_| Error::Malformed(format!("bad volume '{}'", k.volume)))?;
let candle = Candle::new(open, high, low, close, volume, k.open_time)?;
Ok(KlineEvent {
symbol: self.data.symbol.to_lowercase(),
interval,
candle,
is_closed: k.is_closed,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_real_binance_payload() {
// Sample event format from Binance's public docs (truncated).
let json = r#"{
"stream": "btcusdt@kline_1m",
"data": {
"e": "kline",
"E": 1700000000000,
"s": "BTCUSDT",
"k": {
"t": 1700000000000,
"T": 1700000059999,
"s": "BTCUSDT",
"i": "1m",
"f": 1,
"L": 100,
"o": "30000.0",
"c": "30050.0",
"h": "30100.0",
"l": "29950.0",
"v": "12.5",
"n": 50,
"x": false,
"q": "375000.0",
"V": "6.25",
"Q": "187500.0",
"B": "0"
}
}
}"#;
let env: RawWsEnvelope = serde_json::from_str(json).unwrap();
let evt = env.into_event(Interval::OneMinute).unwrap();
assert_eq!(evt.symbol, "btcusdt");
assert_eq!(evt.candle.open, 30_000.0);
assert_eq!(evt.candle.close, 30_050.0);
assert!(!evt.is_closed);
assert_eq!(evt.interval, Interval::OneMinute);
}
#[test]
fn rejects_non_parsable_numbers() {
let json = r#"{
"stream": "btcusdt@kline_1m",
"data": {
"e": "kline", "E": 0, "s": "BTCUSDT",
"k": {
"t": 0, "T": 0, "s": "BTCUSDT", "i": "1m",
"f": 0, "L": 0,
"o": "not-a-number", "c": "0", "h": "0", "l": "0",
"v": "0", "n": 0, "x": false, "q": "0", "V": "0", "Q": "0", "B": "0"
}
}
}"#;
let env: RawWsEnvelope = serde_json::from_str(json).unwrap();
let err = env.into_event(Interval::OneMinute).unwrap_err();
assert!(matches!(err, Error::Malformed(_)));
}
}
+153
View File
@@ -0,0 +1,153 @@
//! Resample an existing candle stream from a finer timeframe to a coarser one.
use crate::aggregator::Timeframe;
use crate::error::Result;
use wickra_core::Candle;
/// Roll a stream of candles up to a coarser timeframe.
///
/// Used to derive 5m bars from a 1m feed, or 1h bars from 5m bars, without
/// touching the original tick stream. The output timeframe's bucket must be a
/// strict multiple of the input timeframe's bucket, but this is not enforced
/// — callers are responsible for picking sensible aggregations.
#[derive(Debug, Clone)]
pub struct Resampler {
timeframe: Timeframe,
open: Option<RolledBar>,
}
#[derive(Debug, Clone, Copy)]
struct RolledBar {
bucket_start: i64,
open: f64,
high: f64,
low: f64,
close: f64,
volume: f64,
}
impl RolledBar {
fn from_candle(c: Candle, bucket_start: i64) -> Self {
Self {
bucket_start,
open: c.open,
high: c.high,
low: c.low,
close: c.close,
volume: c.volume,
}
}
fn absorb(&mut self, c: Candle) {
if c.high > self.high {
self.high = c.high;
}
if c.low < self.low {
self.low = c.low;
}
self.close = c.close;
self.volume += c.volume;
}
fn into_candle(self) -> Candle {
Candle::new_unchecked(
self.open,
self.high,
self.low,
self.close,
self.volume,
self.bucket_start,
)
}
}
impl Resampler {
/// Build a resampler targeting the given output timeframe.
pub fn new(timeframe: Timeframe) -> Self {
Self {
timeframe,
open: None,
}
}
/// Push a finer-grained candle. Returns the coarser candle that just closed,
/// if any.
pub fn push(&mut self, candle: Candle) -> Option<Candle> {
let bucket = self.timeframe.floor(candle.timestamp);
match self.open {
Some(mut bar) if bucket == bar.bucket_start => {
bar.absorb(candle);
self.open = Some(bar);
None
}
Some(bar) => {
let closed = bar.into_candle();
self.open = Some(RolledBar::from_candle(candle, bucket));
Some(closed)
}
None => {
self.open = Some(RolledBar::from_candle(candle, bucket));
None
}
}
}
/// Flush the currently open coarser bar, if any.
pub fn flush(&mut self) -> Option<Candle> {
self.open.take().map(RolledBar::into_candle)
}
}
/// Roll an entire iterator of candles into a `Vec` of coarser candles. The final
/// open bar (if any) is appended via [`Resampler::flush`].
pub fn resample_all<I>(timeframe: Timeframe, iter: I) -> Result<Vec<Candle>>
where
I: IntoIterator<Item = Result<Candle>>,
{
let mut r = Resampler::new(timeframe);
let mut out = Vec::new();
for c in iter {
let c = c?;
if let Some(closed) = r.push(c) {
out.push(closed);
}
}
if let Some(last) = r.flush() {
out.push(last);
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
fn c(ts: i64, o: f64, h: f64, l: f64, cl: f64, v: f64) -> Candle {
Candle::new(o, h, l, cl, v, ts).unwrap()
}
#[test]
fn resamples_1m_to_5m() {
let tf = Timeframe::new(5).unwrap();
let one_m = vec![
c(0, 10.0, 11.0, 9.0, 10.5, 10.0),
c(1, 10.5, 12.0, 10.0, 11.5, 12.0),
c(2, 11.5, 13.0, 11.0, 12.5, 15.0),
c(3, 12.5, 12.8, 11.5, 12.0, 8.0),
c(4, 12.0, 12.2, 11.0, 11.5, 6.0),
c(5, 11.5, 11.9, 11.0, 11.5, 4.0),
];
let rolled = resample_all(tf, one_m.into_iter().map(Ok)).unwrap();
// First 5 candles share bucket 0 -> aggregate. Last candle opens bucket 5.
assert_eq!(rolled.len(), 2);
let a = rolled[0];
assert_eq!(a.open, 10.0);
assert_eq!(a.close, 11.5);
assert_eq!(a.high, 13.0);
assert_eq!(a.low, 9.0);
assert!((a.volume - 51.0).abs() < 1e-12);
let b = rolled[1];
assert_eq!(b.open, 11.5);
assert_eq!(b.timestamp, 5);
}
}
+38
View File
@@ -0,0 +1,38 @@
[package]
name = "wickra"
description = "Streaming-first technical analysis library: incremental indicators, drop-in TA-Lib replacement, multi-language."
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
[lints]
workspace = true
[dependencies]
wickra-core = { workspace = true }
[features]
default = ["parallel"]
parallel = ["wickra-core/parallel"]
[dev-dependencies]
approx = { workspace = true }
criterion = { workspace = true }
proptest = { workspace = true }
wickra-data = { path = "../wickra-data" }
[[bench]]
name = "indicators"
harness = false
[[example]]
name = "backtest"
path = "../../examples/rust/backtest.rs"
required-features = []
+142
View File
@@ -0,0 +1,142 @@
//! Microbenchmarks for every built-in indicator.
//!
//! Run with:
//! ```text
//! cargo bench -p wickra
//! ```
//!
//! Each benchmark feeds a deterministic synthetic price series through both the
//! streaming (`update` loop) and batch APIs of an indicator. Sizes cover small
//! (1 000), medium (10 000), and large (100 000) workloads.
use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion, Throughput};
use wickra::{
Atr, BatchExt, BollingerBands, Candle, Ema, Indicator, MacdIndicator, Obv, Rsi, Sma,
Stochastic, Wma,
};
/// Deterministic synthetic price series of length `n`.
fn price_series(n: usize) -> Vec<f64> {
(0..n)
.map(|i| {
let t = i as f64;
100.0 + (t * 0.013).sin() * 12.0 + (t * 0.071).cos() * 4.0 + (t * 0.003).sin() * 30.0
})
.collect()
}
/// Synthetic OHLC candle series.
fn candle_series(n: usize) -> Vec<Candle> {
let closes = price_series(n);
closes
.iter()
.enumerate()
.map(|(i, c)| {
let t = i as f64;
let spread = 0.5 + (t * 0.05).sin().abs();
// Benchmark synthetic data: i originates from a usize counter capped at 100_000,
// well within i64::MAX. The wrap-around lint does not apply here.
#[allow(clippy::cast_possible_wrap)]
let ts = i as i64;
Candle::new_unchecked(*c, c + spread, c - spread, *c, 1_000.0, ts)
})
.collect()
}
fn bench_scalar<I, F>(c: &mut Criterion, name: &str, sizes: &[usize], make: F)
where
F: Fn() -> I,
I: Indicator<Input = f64, Output = f64> + BatchExt,
{
let mut group = c.benchmark_group(name);
for &n in sizes {
let series = price_series(n);
group.throughput(Throughput::Elements(n as u64));
group.bench_with_input(BenchmarkId::new("streaming", n), &series, |b, prices| {
b.iter(|| {
let mut ind = make();
for p in prices {
black_box(ind.update(*p));
}
});
});
group.bench_with_input(BenchmarkId::new("batch", n), &series, |b, prices| {
b.iter(|| {
let mut ind = make();
black_box(ind.batch(prices));
});
});
}
group.finish();
}
fn bench_macd(c: &mut Criterion, sizes: &[usize]) {
let mut group = c.benchmark_group("macd");
for &n in sizes {
let series = price_series(n);
group.throughput(Throughput::Elements(n as u64));
group.bench_with_input(BenchmarkId::new("streaming", n), &series, |b, prices| {
b.iter(|| {
let mut ind = MacdIndicator::classic();
for p in prices {
black_box(ind.update(*p));
}
});
});
}
group.finish();
}
fn bench_bollinger(c: &mut Criterion, sizes: &[usize]) {
let mut group = c.benchmark_group("bollinger");
for &n in sizes {
let series = price_series(n);
group.throughput(Throughput::Elements(n as u64));
group.bench_with_input(BenchmarkId::new("streaming", n), &series, |b, prices| {
b.iter(|| {
let mut ind = BollingerBands::classic();
for p in prices {
black_box(ind.update(*p));
}
});
});
}
group.finish();
}
fn bench_candle_input<I, F, O>(c: &mut Criterion, name: &str, sizes: &[usize], make: F)
where
F: Fn() -> I,
I: Indicator<Input = Candle, Output = O>,
{
let mut group = c.benchmark_group(name);
for &n in sizes {
let candles = candle_series(n);
group.throughput(Throughput::Elements(n as u64));
group.bench_with_input(BenchmarkId::new("streaming", n), &candles, |b, candles| {
b.iter(|| {
let mut ind = make();
for c in candles {
black_box(ind.update(*c));
}
});
});
}
group.finish();
}
fn benches(c: &mut Criterion) {
let sizes = [1_000_usize, 10_000, 100_000];
bench_scalar(c, "sma", &sizes, || Sma::new(14).unwrap());
bench_scalar(c, "ema", &sizes, || Ema::new(14).unwrap());
bench_scalar(c, "wma", &sizes, || Wma::new(14).unwrap());
bench_scalar(c, "rsi", &sizes, || Rsi::new(14).unwrap());
bench_macd(c, &sizes);
bench_bollinger(c, &sizes);
bench_candle_input(c, "atr", &sizes, || Atr::new(14).unwrap());
bench_candle_input(c, "stochastic", &sizes, Stochastic::classic);
bench_candle_input(c, "obv", &sizes, Obv::new);
}
criterion_group!(name = wickra_benches; config = Criterion::default(); targets = benches);
criterion_main!(wickra_benches);
+21
View File
@@ -0,0 +1,21 @@
//! Wickra: streaming-first technical analysis.
//!
//! This crate is a thin re-export of [`wickra_core`] so downstream users can depend on
//! a single `wickra` package without thinking about the internal split. Every public
//! item lives in `wickra_core`; only the names re-exported here are part of the stable
//! public API.
//!
//! # Example
//!
//! ```
//! use wickra::{Indicator, Sma};
//!
//! let mut sma = Sma::new(3).unwrap();
//! let prices = [1.0, 2.0, 3.0, 4.0, 5.0];
//! let out: Vec<Option<f64>> = prices.iter().map(|p| sma.update(*p)).collect();
//! assert_eq!(out, vec![None, None, Some(2.0), Some(3.0), Some(4.0)]);
//! ```
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
pub use wickra_core::*;