F12: add price transforms and rolling linear regression
- Rust core: typical_price.rs ((H+L+C)/3), median_price.rs ((H+L)/2), weighted_close.rs ((H+L+2C)/4) — stateless per-bar OHLC transforms — and linreg.rs (LinearRegression — endpoint of a rolling ordinary-least-squares fit) and linreg_slope.rs (LinRegSlope — slope of that fit). Each with a full Indicator impl, runnable doctest and reference / property / warmup / reset / batch==streaming tests. - Python: PyTypicalPrice / PyMedianPrice / PyWeightedClose / PyLinearRegression / PyLinRegSlope PyO3 classes + module registration + .pyi stubs. - Node: explicit TypicalPriceNode / MedianPriceNode / WeightedCloseNode / LinearRegressionNode / LinRegSlopeNode; index.d.ts and index.js updated. - WASM: explicit WasmTypicalPrice / WasmMedianPrice / WasmWeightedClose; WasmLinearRegression / WasmLinRegSlope via the scalar macro. - Wiki: a new indicators/statistics/ folder with five Indicator-*.md pages, a new "Statistics" family in Indicators-Overview.md and Home.md. cargo fmt + clippy (core/wickra/data/wasm/node) clean; 454 core tests, 25 data tests and 66 doctests green.
This commit is contained in:
@@ -0,0 +1,198 @@
|
||||
//! Linear Regression (rolling least-squares endpoint).
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Linear Regression — the endpoint of a rolling least-squares fit.
|
||||
///
|
||||
/// Over the last `period` inputs, indexed `x = 0, 1, …, period − 1`, it fits
|
||||
/// the line `y = a + b·x` by ordinary least squares and reports the line's
|
||||
/// value at the most recent point:
|
||||
///
|
||||
/// ```text
|
||||
/// b (slope) = (n·Σxy − Σx·Σy) / (n·Σxx − (Σx)²)
|
||||
/// a (intercept) = (Σy − b·Σx) / n
|
||||
/// LinearReg = a + b·(period − 1)
|
||||
/// ```
|
||||
///
|
||||
/// This is TA-Lib's `LINEARREG`: a smoothed price that lags less than an SMA
|
||||
/// because it extrapolates the *local trend* forward to the current bar
|
||||
/// instead of averaging it away. The `Σx` terms depend only on `period`, so
|
||||
/// they are computed once; each `update` is O(period).
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use wickra_core::{Indicator, LinearRegression};
|
||||
///
|
||||
/// let mut indicator = LinearRegression::new(14).unwrap();
|
||||
/// let mut last = None;
|
||||
/// for i in 0..80 {
|
||||
/// last = indicator.update(f64::from(i));
|
||||
/// }
|
||||
/// assert!(last.is_some());
|
||||
/// ```
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct LinearRegression {
|
||||
period: usize,
|
||||
window: VecDeque<f64>,
|
||||
sum_x: f64,
|
||||
denom: f64,
|
||||
}
|
||||
|
||||
impl LinearRegression {
|
||||
/// Construct a new rolling linear regression over `period` inputs.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns [`Error::InvalidPeriod`] if `period < 2` — a regression line is
|
||||
/// undefined for fewer than two points.
|
||||
pub fn new(period: usize) -> Result<Self> {
|
||||
if period < 2 {
|
||||
return Err(Error::InvalidPeriod {
|
||||
message: "linear regression needs period >= 2",
|
||||
});
|
||||
}
|
||||
let n = period as f64;
|
||||
// Closed forms for x = 0, 1, …, period − 1.
|
||||
let sum_x = n * (n - 1.0) / 2.0;
|
||||
let sum_xx = (n - 1.0) * n * (2.0 * n - 1.0) / 6.0;
|
||||
Ok(Self {
|
||||
period,
|
||||
window: VecDeque::with_capacity(period),
|
||||
sum_x,
|
||||
denom: n * sum_xx - sum_x * sum_x,
|
||||
})
|
||||
}
|
||||
|
||||
/// Configured period.
|
||||
pub const fn period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
|
||||
/// Ordinary-least-squares `(slope, endpoint)` over the current full window.
|
||||
fn fit(&self) -> (f64, f64) {
|
||||
let n = self.period as f64;
|
||||
let mut sum_y = 0.0;
|
||||
let mut sum_xy = 0.0;
|
||||
for (x, &y) in self.window.iter().enumerate() {
|
||||
sum_y += y;
|
||||
sum_xy += x as f64 * y;
|
||||
}
|
||||
let slope = (n * sum_xy - self.sum_x * sum_y) / self.denom;
|
||||
let intercept = (sum_y - slope * self.sum_x) / n;
|
||||
(slope, intercept + slope * (n - 1.0))
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for LinearRegression {
|
||||
type Input = f64;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, value: f64) -> Option<f64> {
|
||||
if self.window.len() == self.period {
|
||||
self.window.pop_front();
|
||||
}
|
||||
self.window.push_back(value);
|
||||
if self.window.len() < self.period {
|
||||
return None;
|
||||
}
|
||||
Some(self.fit().1)
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.window.clear();
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.window.len() == self.period
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"LinearRegression"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
#[test]
|
||||
fn reference_values() {
|
||||
// period 3 over [1, 2, 9]: fit y = 0 + 4x, endpoint = 0 + 4·2 = 8.
|
||||
let mut lr = LinearRegression::new(3).unwrap();
|
||||
let out = lr.batch(&[1.0, 2.0, 9.0]);
|
||||
assert!(out[0].is_none());
|
||||
assert!(out[1].is_none());
|
||||
assert_relative_eq!(out[2].unwrap(), 8.0, epsilon = 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn perfect_line_returns_current_value() {
|
||||
// The regression of a perfectly linear series is that line itself, so
|
||||
// its endpoint equals the current value.
|
||||
let prices: Vec<f64> = (0..40).map(|i| 2.0 * f64::from(i) + 5.0).collect();
|
||||
let mut lr = LinearRegression::new(10).unwrap();
|
||||
for (i, v) in lr.batch(&prices).into_iter().enumerate() {
|
||||
if let Some(v) = v {
|
||||
assert_relative_eq!(v, 2.0 * i as f64 + 5.0, epsilon = 1e-6);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_series_returns_the_constant() {
|
||||
let mut lr = LinearRegression::new(8).unwrap();
|
||||
for v in lr.batch(&[42.0; 20]).into_iter().flatten() {
|
||||
assert_relative_eq!(v, 42.0, epsilon = 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_value_on_period_th_input() {
|
||||
let mut lr = LinearRegression::new(5).unwrap();
|
||||
let out = lr.batch(&[1.0, 3.0, 2.0, 5.0, 4.0, 6.0]);
|
||||
for (i, v) in out.iter().enumerate().take(4) {
|
||||
assert!(v.is_none(), "index {i} must be None during warmup");
|
||||
}
|
||||
assert!(out[4].is_some(), "first value lands at index period - 1");
|
||||
assert_eq!(lr.warmup_period(), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_period_below_two() {
|
||||
assert!(LinearRegression::new(0).is_err());
|
||||
assert!(LinearRegression::new(1).is_err());
|
||||
assert!(LinearRegression::new(2).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut lr = LinearRegression::new(5).unwrap();
|
||||
lr.batch(&[1.0, 2.0, 3.0, 4.0, 5.0]);
|
||||
assert!(lr.is_ready());
|
||||
lr.reset();
|
||||
assert!(!lr.is_ready());
|
||||
assert_eq!(lr.update(1.0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let prices: Vec<f64> = (0..60)
|
||||
.map(|i| 50.0 + (f64::from(i) * 0.3).sin() * 10.0)
|
||||
.collect();
|
||||
let mut a = LinearRegression::new(14).unwrap();
|
||||
let mut b = LinearRegression::new(14).unwrap();
|
||||
assert_eq!(
|
||||
a.batch(&prices),
|
||||
prices.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
//! Linear Regression Slope.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Linear Regression Slope — the slope of a rolling least-squares fit.
|
||||
///
|
||||
/// Over the last `period` inputs, indexed `x = 0, 1, …, period − 1`, it fits
|
||||
/// the line `y = a + b·x` by ordinary least squares and reports the slope:
|
||||
///
|
||||
/// ```text
|
||||
/// b = (n·Σxy − Σx·Σy) / (n·Σxx − (Σx)²)
|
||||
/// ```
|
||||
///
|
||||
/// This is TA-Lib's `LINEARREG_SLOPE`: a momentum-like reading of how steeply
|
||||
/// price is trending over the window — positive while it rises, negative
|
||||
/// while it falls, near zero when it is flat — without the band-pass quirks
|
||||
/// of a difference-based oscillator. The `Σx` terms depend only on `period`,
|
||||
/// so they are computed once; each `update` is O(period).
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use wickra_core::{Indicator, LinRegSlope};
|
||||
///
|
||||
/// let mut indicator = LinRegSlope::new(14).unwrap();
|
||||
/// let mut last = None;
|
||||
/// for i in 0..80 {
|
||||
/// last = indicator.update(f64::from(i));
|
||||
/// }
|
||||
/// assert!(last.is_some());
|
||||
/// ```
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct LinRegSlope {
|
||||
period: usize,
|
||||
window: VecDeque<f64>,
|
||||
sum_x: f64,
|
||||
denom: f64,
|
||||
}
|
||||
|
||||
impl LinRegSlope {
|
||||
/// Construct a new rolling linear-regression slope over `period` inputs.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns [`Error::InvalidPeriod`] if `period < 2` — a regression line is
|
||||
/// undefined for fewer than two points.
|
||||
pub fn new(period: usize) -> Result<Self> {
|
||||
if period < 2 {
|
||||
return Err(Error::InvalidPeriod {
|
||||
message: "linear regression slope needs period >= 2",
|
||||
});
|
||||
}
|
||||
let n = period as f64;
|
||||
// Closed forms for x = 0, 1, …, period − 1.
|
||||
let sum_x = n * (n - 1.0) / 2.0;
|
||||
let sum_xx = (n - 1.0) * n * (2.0 * n - 1.0) / 6.0;
|
||||
Ok(Self {
|
||||
period,
|
||||
window: VecDeque::with_capacity(period),
|
||||
sum_x,
|
||||
denom: n * sum_xx - sum_x * sum_x,
|
||||
})
|
||||
}
|
||||
|
||||
/// Configured period.
|
||||
pub const fn period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for LinRegSlope {
|
||||
type Input = f64;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, value: f64) -> Option<f64> {
|
||||
if self.window.len() == self.period {
|
||||
self.window.pop_front();
|
||||
}
|
||||
self.window.push_back(value);
|
||||
if self.window.len() < self.period {
|
||||
return None;
|
||||
}
|
||||
let n = self.period as f64;
|
||||
let mut sum_y = 0.0;
|
||||
let mut sum_xy = 0.0;
|
||||
for (x, &y) in self.window.iter().enumerate() {
|
||||
sum_y += y;
|
||||
sum_xy += x as f64 * y;
|
||||
}
|
||||
Some((n * sum_xy - self.sum_x * sum_y) / self.denom)
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.window.clear();
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
self.period
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.window.len() == self.period
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"LinRegSlope"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
#[test]
|
||||
fn reference_values() {
|
||||
// period 3 over [1, 2, 9]: fit y = 0 + 4x, so the slope is 4.
|
||||
let mut ls = LinRegSlope::new(3).unwrap();
|
||||
let out = ls.batch(&[1.0, 2.0, 9.0]);
|
||||
assert!(out[0].is_none());
|
||||
assert!(out[1].is_none());
|
||||
assert_relative_eq!(out[2].unwrap(), 4.0, epsilon = 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn perfect_line_returns_its_step() {
|
||||
// A series rising by a fixed step has exactly that slope.
|
||||
let prices: Vec<f64> = (0..40).map(|i| 2.5 * f64::from(i) + 7.0).collect();
|
||||
let mut ls = LinRegSlope::new(10).unwrap();
|
||||
for v in ls.batch(&prices).into_iter().flatten() {
|
||||
assert_relative_eq!(v, 2.5, epsilon = 1e-6);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_series_has_zero_slope() {
|
||||
let mut ls = LinRegSlope::new(8).unwrap();
|
||||
for v in ls.batch(&[42.0; 20]).into_iter().flatten() {
|
||||
assert_relative_eq!(v, 0.0, epsilon = 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn falling_series_has_negative_slope() {
|
||||
let prices: Vec<f64> = (0..30).map(|i| 100.0 - f64::from(i)).collect();
|
||||
let mut ls = LinRegSlope::new(10).unwrap();
|
||||
for v in ls.batch(&prices).into_iter().flatten() {
|
||||
assert!(v < 0.0, "a falling series must have a negative slope");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_value_on_period_th_input() {
|
||||
let mut ls = LinRegSlope::new(5).unwrap();
|
||||
let out = ls.batch(&[1.0, 3.0, 2.0, 5.0, 4.0, 6.0]);
|
||||
for (i, v) in out.iter().enumerate().take(4) {
|
||||
assert!(v.is_none(), "index {i} must be None during warmup");
|
||||
}
|
||||
assert!(out[4].is_some(), "first value lands at index period - 1");
|
||||
assert_eq!(ls.warmup_period(), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_period_below_two() {
|
||||
assert!(LinRegSlope::new(0).is_err());
|
||||
assert!(LinRegSlope::new(1).is_err());
|
||||
assert!(LinRegSlope::new(2).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut ls = LinRegSlope::new(5).unwrap();
|
||||
ls.batch(&[1.0, 2.0, 3.0, 4.0, 5.0]);
|
||||
assert!(ls.is_ready());
|
||||
ls.reset();
|
||||
assert!(!ls.is_ready());
|
||||
assert_eq!(ls.update(1.0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let prices: Vec<f64> = (0..60)
|
||||
.map(|i| 50.0 + (f64::from(i) * 0.3).sin() * 10.0)
|
||||
.collect();
|
||||
let mut a = LinRegSlope::new(14).unwrap();
|
||||
let mut b = LinRegSlope::new(14).unwrap();
|
||||
assert_eq!(
|
||||
a.batch(&prices),
|
||||
prices.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
//! Median Price.
|
||||
|
||||
use crate::ohlcv::Candle;
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Median Price — the bar's `(high + low) / 2`.
|
||||
///
|
||||
/// The midpoint of the bar's range, ignoring where it opened or closed. It is
|
||||
/// the price series Bill Williams' [`AwesomeOscillator`](crate::AwesomeOscillator)
|
||||
/// is built on, and a smoother stand-in for the close when feeding other
|
||||
/// indicators. As a stateless per-bar transform it emits a value from the
|
||||
/// very first candle.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use wickra_core::{Candle, Indicator, MedianPrice};
|
||||
///
|
||||
/// let mut indicator = MedianPrice::new();
|
||||
/// let mut last = None;
|
||||
/// for i in 0..80 {
|
||||
/// let base = 100.0 + f64::from(i);
|
||||
/// let candle =
|
||||
/// Candle::new(base, base + 2.0, base - 2.0, base + 1.0, 10.0, i64::from(i)).unwrap();
|
||||
/// last = indicator.update(candle);
|
||||
/// }
|
||||
/// assert!(last.is_some());
|
||||
/// ```
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct MedianPrice {
|
||||
has_emitted: bool,
|
||||
}
|
||||
|
||||
impl MedianPrice {
|
||||
/// Construct a new Median Price transform.
|
||||
pub const fn new() -> Self {
|
||||
Self { has_emitted: false }
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for MedianPrice {
|
||||
type Input = Candle;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, candle: Candle) -> Option<f64> {
|
||||
self.has_emitted = true;
|
||||
Some(candle.median_price())
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.has_emitted = false;
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
1
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.has_emitted
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"MedianPrice"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
fn candle(open: f64, high: f64, low: f64, close: f64, ts: i64) -> Candle {
|
||||
Candle::new(open, high, low, close, 1.0, ts).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reference_value() {
|
||||
// (high + low) / 2 = (12 + 8) / 2 = 10.
|
||||
let mut mp = MedianPrice::new();
|
||||
assert_relative_eq!(
|
||||
mp.update(candle(10.0, 12.0, 8.0, 11.0, 0)).unwrap(),
|
||||
10.0,
|
||||
epsilon = 1e-12
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emits_from_first_candle() {
|
||||
let mut mp = MedianPrice::new();
|
||||
assert_eq!(mp.warmup_period(), 1);
|
||||
assert!(!mp.is_ready());
|
||||
assert!(mp.update(candle(10.0, 11.0, 9.0, 10.0, 0)).is_some());
|
||||
assert!(mp.is_ready());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut mp = MedianPrice::new();
|
||||
mp.update(candle(10.0, 11.0, 9.0, 10.0, 0));
|
||||
assert!(mp.is_ready());
|
||||
mp.reset();
|
||||
assert!(!mp.is_ready());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let candles: Vec<Candle> = (0..40)
|
||||
.map(|i| {
|
||||
let base = 100.0 + i as f64;
|
||||
candle(base, base + 2.0, base - 2.0, base + 1.0, i)
|
||||
})
|
||||
.collect();
|
||||
let mut a = MedianPrice::new();
|
||||
let mut b = MedianPrice::new();
|
||||
assert_eq!(
|
||||
a.batch(&candles),
|
||||
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -30,8 +30,11 @@ mod historical_volatility;
|
||||
mod hma;
|
||||
mod kama;
|
||||
mod keltner;
|
||||
mod linreg;
|
||||
mod linreg_slope;
|
||||
mod macd;
|
||||
mod mass_index;
|
||||
mod median_price;
|
||||
mod mfi;
|
||||
mod mom;
|
||||
mod natr;
|
||||
@@ -53,12 +56,14 @@ mod tema;
|
||||
mod trima;
|
||||
mod trix;
|
||||
mod tsi;
|
||||
mod typical_price;
|
||||
mod ulcer_index;
|
||||
mod ultimate_oscillator;
|
||||
mod vortex;
|
||||
mod vpt;
|
||||
mod vwap;
|
||||
mod vwma;
|
||||
mod weighted_close;
|
||||
mod williams_r;
|
||||
mod wma;
|
||||
mod zlema;
|
||||
@@ -89,8 +94,11 @@ pub use historical_volatility::HistoricalVolatility;
|
||||
pub use hma::Hma;
|
||||
pub use kama::Kama;
|
||||
pub use keltner::{Keltner, KeltnerOutput};
|
||||
pub use linreg::LinearRegression;
|
||||
pub use linreg_slope::LinRegSlope;
|
||||
pub use macd::{MacdIndicator, MacdOutput};
|
||||
pub use mass_index::MassIndex;
|
||||
pub use median_price::MedianPrice;
|
||||
pub use mfi::Mfi;
|
||||
pub use mom::Mom;
|
||||
pub use natr::Natr;
|
||||
@@ -112,12 +120,14 @@ pub use tema::Tema;
|
||||
pub use trima::Trima;
|
||||
pub use trix::Trix;
|
||||
pub use tsi::Tsi;
|
||||
pub use typical_price::TypicalPrice;
|
||||
pub use ulcer_index::UlcerIndex;
|
||||
pub use ultimate_oscillator::UltimateOscillator;
|
||||
pub use vortex::{Vortex, VortexOutput};
|
||||
pub use vpt::VolumePriceTrend;
|
||||
pub use vwap::{RollingVwap, Vwap};
|
||||
pub use vwma::Vwma;
|
||||
pub use weighted_close::WeightedClose;
|
||||
pub use williams_r::WilliamsR;
|
||||
pub use wma::Wma;
|
||||
pub use zlema::Zlema;
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
//! Typical Price.
|
||||
|
||||
use crate::ohlcv::Candle;
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Typical Price — the bar's `(high + low + close) / 3`.
|
||||
///
|
||||
/// A single representative price per bar that weights the close no more
|
||||
/// heavily than the two extremes. It is the price series that
|
||||
/// [`Cci`](crate::Cci) and [`Mfi`](crate::Mfi) are built on, and a common
|
||||
/// input to feed other indicators in place of the raw close. As a stateless
|
||||
/// per-bar transform it emits a value from the very first candle.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use wickra_core::{Candle, Indicator, TypicalPrice};
|
||||
///
|
||||
/// let mut indicator = TypicalPrice::new();
|
||||
/// let mut last = None;
|
||||
/// for i in 0..80 {
|
||||
/// let base = 100.0 + f64::from(i);
|
||||
/// let candle =
|
||||
/// Candle::new(base, base + 2.0, base - 2.0, base + 1.0, 10.0, i64::from(i)).unwrap();
|
||||
/// last = indicator.update(candle);
|
||||
/// }
|
||||
/// assert!(last.is_some());
|
||||
/// ```
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct TypicalPrice {
|
||||
has_emitted: bool,
|
||||
}
|
||||
|
||||
impl TypicalPrice {
|
||||
/// Construct a new Typical Price transform.
|
||||
pub const fn new() -> Self {
|
||||
Self { has_emitted: false }
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for TypicalPrice {
|
||||
type Input = Candle;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, candle: Candle) -> Option<f64> {
|
||||
self.has_emitted = true;
|
||||
Some(candle.typical_price())
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.has_emitted = false;
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
1
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.has_emitted
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"TypicalPrice"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
fn candle(open: f64, high: f64, low: f64, close: f64, ts: i64) -> Candle {
|
||||
Candle::new(open, high, low, close, 1.0, ts).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reference_value() {
|
||||
// (high + low + close) / 3 = (12 + 6 + 9) / 3 = 9.
|
||||
let mut tp = TypicalPrice::new();
|
||||
assert_relative_eq!(
|
||||
tp.update(candle(9.0, 12.0, 6.0, 9.0, 0)).unwrap(),
|
||||
9.0,
|
||||
epsilon = 1e-12
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emits_from_first_candle() {
|
||||
let mut tp = TypicalPrice::new();
|
||||
assert_eq!(tp.warmup_period(), 1);
|
||||
assert!(!tp.is_ready());
|
||||
assert!(tp.update(candle(10.0, 11.0, 9.0, 10.0, 0)).is_some());
|
||||
assert!(tp.is_ready());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut tp = TypicalPrice::new();
|
||||
tp.update(candle(10.0, 11.0, 9.0, 10.0, 0));
|
||||
assert!(tp.is_ready());
|
||||
tp.reset();
|
||||
assert!(!tp.is_ready());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let candles: Vec<Candle> = (0..40)
|
||||
.map(|i| {
|
||||
let base = 100.0 + i as f64;
|
||||
candle(base, base + 2.0, base - 2.0, base + 1.0, i)
|
||||
})
|
||||
.collect();
|
||||
let mut a = TypicalPrice::new();
|
||||
let mut b = TypicalPrice::new();
|
||||
assert_eq!(
|
||||
a.batch(&candles),
|
||||
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
//! Weighted Close.
|
||||
|
||||
use crate::ohlcv::Candle;
|
||||
use crate::traits::Indicator;
|
||||
|
||||
/// Weighted Close — the bar's `(high + low + 2·close) / 4`.
|
||||
///
|
||||
/// A representative per-bar price that, unlike the [`TypicalPrice`](crate::TypicalPrice),
|
||||
/// gives the close double weight — useful when the closing print matters more
|
||||
/// than the extremes for your strategy. As a stateless per-bar transform it
|
||||
/// emits a value from the very first candle.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use wickra_core::{Candle, Indicator, WeightedClose};
|
||||
///
|
||||
/// let mut indicator = WeightedClose::new();
|
||||
/// let mut last = None;
|
||||
/// for i in 0..80 {
|
||||
/// let base = 100.0 + f64::from(i);
|
||||
/// let candle =
|
||||
/// Candle::new(base, base + 2.0, base - 2.0, base + 1.0, 10.0, i64::from(i)).unwrap();
|
||||
/// last = indicator.update(candle);
|
||||
/// }
|
||||
/// assert!(last.is_some());
|
||||
/// ```
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct WeightedClose {
|
||||
has_emitted: bool,
|
||||
}
|
||||
|
||||
impl WeightedClose {
|
||||
/// Construct a new Weighted Close transform.
|
||||
pub const fn new() -> Self {
|
||||
Self { has_emitted: false }
|
||||
}
|
||||
}
|
||||
|
||||
impl Indicator for WeightedClose {
|
||||
type Input = Candle;
|
||||
type Output = f64;
|
||||
|
||||
fn update(&mut self, candle: Candle) -> Option<f64> {
|
||||
self.has_emitted = true;
|
||||
Some(candle.weighted_close())
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.has_emitted = false;
|
||||
}
|
||||
|
||||
fn warmup_period(&self) -> usize {
|
||||
1
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.has_emitted
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"WeightedClose"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::traits::BatchExt;
|
||||
use approx::assert_relative_eq;
|
||||
|
||||
fn candle(open: f64, high: f64, low: f64, close: f64, ts: i64) -> Candle {
|
||||
Candle::new(open, high, low, close, 1.0, ts).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reference_value() {
|
||||
// (high + low + 2·close) / 4 = (12 + 8 + 2·11) / 4 = 42 / 4 = 10.5.
|
||||
let mut wc = WeightedClose::new();
|
||||
assert_relative_eq!(
|
||||
wc.update(candle(10.0, 12.0, 8.0, 11.0, 0)).unwrap(),
|
||||
10.5,
|
||||
epsilon = 1e-12
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emits_from_first_candle() {
|
||||
let mut wc = WeightedClose::new();
|
||||
assert_eq!(wc.warmup_period(), 1);
|
||||
assert!(!wc.is_ready());
|
||||
assert!(wc.update(candle(10.0, 11.0, 9.0, 10.0, 0)).is_some());
|
||||
assert!(wc.is_ready());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_clears_state() {
|
||||
let mut wc = WeightedClose::new();
|
||||
wc.update(candle(10.0, 11.0, 9.0, 10.0, 0));
|
||||
assert!(wc.is_ready());
|
||||
wc.reset();
|
||||
assert!(!wc.is_ready());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_equals_streaming() {
|
||||
let candles: Vec<Candle> = (0..40)
|
||||
.map(|i| {
|
||||
let base = 100.0 + i as f64;
|
||||
candle(base, base + 2.0, base - 2.0, base + 1.0, i)
|
||||
})
|
||||
.collect();
|
||||
let mut a = WeightedClose::new();
|
||||
let mut b = WeightedClose::new();
|
||||
assert_eq!(
|
||||
a.batch(&candles),
|
||||
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user