Expand description
Technical analysis indicators on price / volume series.
Scope of this module: pure batch building blocks a quant engine or notebook consumes. This crate does not run an event loop, subscribe to market data, or own portfolio state. See the crate README (“Quant pattern” and “Why not a streaming engine?”).
§Layers (performance)
| Layer | API | Cost class | Use |
|---|---|---|---|
| Config | *Params / Validated* (Copy) | O(1) validate once | Build at startup / const |
| Hot path (batch) | sma, ema, stochastics, macd, … | O(n) pure math, no String | Research, backtests |
| Hot path (live) | SmaState / StochState / … push / push_bars | O(1) / amortized O(1) per bar | Streaming payloads |
| Solution | *_solution | O(n) + formulas + tables | Teaching, audit, observability |
§Quant ergonomics — recommended pattern (const + validate + .compute)
Production code should not invent a new parameter list on every bar. Define the indicator variation once, validate once, reuse forever:
use finance_solution::stocks::ta::{
StochasticParams, ValidatedStochastic,
MacdParams, ValidatedMacd,
BollingerParams, ValidatedBollinger,
};
// --- Strategy knobs (module-level const packs) ---
const FAST_STOCH_9_3: StochasticParams = StochasticParams::fast(9, 3);
const MACD_12_26_9: MacdParams = MacdParams::standard();
const BB_20_2: BollingerParams = BollingerParams::standard();
// --- Startup: O(1) validation ---
let stoch = ValidatedStochastic::new(FAST_STOCH_9_3).unwrap();
let macd_eng = ValidatedMacd::new(MACD_12_26_9).unwrap();
let bb = ValidatedBollinger::new(BB_20_2).unwrap();
// --- Hot path: many symbols / many days ---
let kd = stoch.compute(&high, &low, &close).unwrap();
let m = macd_eng.compute(&closes).unwrap();
let bands = bb.compute(&closes).unwrap();
assert_eq!(kd.k.len(), high.len());
assert_eq!(m.macd.len(), closes.len());
assert_eq!(bands.middle.len(), closes.len());Why this shape?
- Clarity —
FAST_STOCH_9_3documents the strategy; no magic positional args. - Safety — period=0 fails at
new, not mid-batch. - Speed — validation is noise vs O(n) windows (see Criterion suite D).
- Variations — Fast(9,3), Full(14,3,3), MACD(8,17,9) are just different
constpacks on the same functions — no combinatorial API explosion.
Free functions (stochastics(...), macd(...), …) remain for scripts and doctests.
§Warm-up policy
Output length equals input length. Bars before a window is full are None.
Solution tables print warm-up as n/a.
§Indicators
§Incremental / streaming state (live bars)
For tick/5s/1m payloads, use *State types: push one bar at a time, push_bars for
multi-bar messages, or from_history then only push live updates. See state module docs
and the README quant-engine sketch. You call reset() on VWAP when your calendar says so.
Every public TA indicator has a matching *State. Running all of them on one symbol
each 5s bar is supported: hold one struct of states per symbol and call push sequentially.
That is caller-owned composition (and multi-symbol parallelism is caller-side rayon).
The crate does not ship a multi-indicator “run everything” engine.
Hot-window slides (after warm-up): SMA/EMA/WMA/HMA/BB/LinReg/RSI/ATR/OBV/ADX/… are O(1); Stoch/WillR HH/LL and Donchian max/min are amortized O(1) via monotonic deques.
Conventions worth knowing:
- Stochastic flat window (HH == LL): carry previous raw %K, else 50.
- Williams %R flat window: carry previous %R, else −50.
- Bollinger stdev:
StdevKind::Sample(n−1) default; optional population (n). - Batch = stream path: free functions /
Validated*::computeroute through the same*Statemachines as livepush(parity by construction).
Re-exports§
pub use crate::stocks::ta::moving_average::EmaState;pub use crate::stocks::ta::moving_average::SmaState;
Modules§
- advanced_
ma - Advanced moving averages: DEMA, TEMA, RMA (Wilder), KAMA
- adx
- Average Directional Index (ADX) / +DI / −DI / DX
- atr
- Average True Range (ATR)
- bollinger
- Bollinger Bands
- cci
- Commodity Channel Index (CCI)
- common
- Shared TA helpers (validation, warm-up cells, rolling stats).
- donchian
- Donchian channels
- keltner
- Keltner Channels
- linear_
regression - Rolling least-squares linear regression
- macd
- MACD (Moving Average Convergence Divergence)
- mfi
- Money Flow Index (MFI)
- momentum
- Rate of change / momentum (ROC, ROCP, MOM)
- moving_
average - Simple & exponential moving averages (SMA / EMA)
- obv
- On-Balance Volume (OBV)
- ring
- Fixed-capacity ring buffer for incremental TA windows (private helper).
- rsi
- Relative Strength Index (RSI)
- rvol
- Relative volume (RVOL)
- sar
- Parabolic SAR (Stop and Reverse)
- state
- Incremental state machines for live / streaming bar updates.
- stochastic
- Stochastic oscillator — one core, many packs via
StochasticParams. - supertrend
- Supertrend
- vwap
- VWAP (volume-weighted average price)
- willr
- Williams %R
Structs§
- AdxBar
Output - One-bar ADX pack (any field may still be warming up).
- AdxParams
- ADX / DI Wilder period.
- AdxSeries
- AdxSolution
- AdxState
- Incremental ADX / DI / DX.
- AtrParams
- ATR lookback pack (Wilder).
- AtrSeries
- AtrSolution
- AtrState
- Incremental Wilder ATR.
- Bollinger
BarOutput - One-bar Bollinger output.
- Bollinger
Params - Bollinger parameter pack.
- Bollinger
Series - Middle / upper / lower / %B series.
- Bollinger
Solution - Teaching solution + table.
- Bollinger
State - Incremental Bollinger Bands.
- CciParams
- CCI lookback (on typical price).
- CciSeries
- CciSolution
- CciState
- Incremental CCI. After warm-up each push is O(period) (mean absolute deviation).
- Dema
State - Double exponential moving average:
2·EMA − EMA(EMA). - Donchian
BarOutput - Donchian
Params - Donchian lookback.
- Donchian
Series - Donchian
Solution - Donchian
State - Incremental Donchian.
- EmaState
- Incremental EMA (α = 2/(period+1), seed = SMA of first
periodcloses). - HmaState
- Hull moving average state.
- Kama
Params - Kaufman Adaptive Moving Average parameters.
- Kama
State - Incremental KAMA.
- Keltner
BarOutput - Keltner
Params - Keltner parameter pack (Wilder ATR).
- Keltner
Series - Keltner
Solution - Keltner
State - Incremental Keltner (EMA mid + Wilder ATR).
- LinReg
Bar - One fitted window.
- LinReg
Params - Rolling regression window length.
- LinReg
Solution - LinReg
State - Incremental rolling regression on a caller-chosen series.
- Macd
BarOutput - One-bar MACD output (signal/hist may still be warming up).
- Macd
Params - MACD parameter pack:
fast < slow, all periods ≥ 1. - Macd
Series - Aligned MACD / signal / histogram series.
- Macd
Solution - Teaching wrapper with formula strings and a printable table.
- Macd
State - Incremental MACD (fast/slow/signal EMAs).
- MfiParams
- MfiSeries
- MfiSolution
- MfiState
- Incremental MFI.
- MomBar
Output - One-bar momentum pack.
- MomParams
- Lookback for MOM / ROC / ROCP.
- MomSeries
- MomSolution
- MomState
- Incremental MOM/ROC/ROCP (shared ring of last
periodcloses + current). - Natr
Series - Normalized ATR series.
- Natr
State - Incremental NATR (wraps
AtrState). - ObvParams
- OBV has no lookback; pack is a unit for API consistency.
- ObvSeries
- ObvSolution
- ObvState
- Incremental OBV. Each
pushis O(1). - RmaState
- Incremental Wilder RMA (also called SMMA). α = 1/
period. - RocSeries
- Rocp
Series - RsiParams
- RSI lookback pack (Wilder).
- RsiSeries
- RsiSolution
- RsiState
- Incremental Wilder RSI.
- Rvol
Params - RVOL lookback pack.
- Rvol
Series - Rvol
Solution - Rvol
State - Incremental relative volume.
- SarBar
Output - SarParams
- Parabolic SAR acceleration parameters.
- SarSeries
- SarSolution
- SarState
- Incremental Parabolic SAR.
- SmaState
- Incremental SMA. After warm-up, each
SmaState::pushis O(1). - Stoch
BarOutput - One-bar stochastic output (warm-up allowed as
None). - Stoch
State - Incremental stochastic (fast/full via
StochasticParams). - Stochastic
Params - Unvalidated (but
Copy) stochastic parameter pack. - Stochastic
Series - Aligned %K / %D output.
- Stochastic
Solution - Teaching wrapper around
StochasticSeries. - Supertrend
Bar - Supertrend
Params - Supertrend pack: Wilder ATR period + band multiplier.
- Supertrend
Series - Supertrend
Solution - Supertrend
State - Incremental Supertrend.
- Tema
State - Triple exponential moving average:
3·e1 − 3·e2 + e3. - Validated
Adx - Validated
Atr - Validated ATR config.
- Validated
Bollinger - Validated Bollinger config.
- Validated
Cci - Validated
Donchian - Validated
Kama - Validated
Keltner - Validated Keltner config.
- Validated
LinReg - Validated pack.
- Validated
Macd - Validated MACD config for reuse across many close series.
- Validated
Mfi - Validated
Mom - Validated
Obv - Validated pack (always succeeds).
- Validated
Rsi - Validated RSI config.
- Validated
Rvol - Validated RVOL config.
- Validated
Sar - Validated
Stochastic - Params that passed period validation — safe to use in a tight loop.
- Validated
Supertrend - Validated
Vwap - Validated VWAP config.
- Validated
Willr - Validated pack.
- Vwap
Params - VWAP parameter pack.
- Vwap
Series - Vwap
Solution - Vwap
State - Incremental VWAP (cumulative or rolling). Call
VwapState::resetat session open if desired. - Willr
Params - Williams %R lookback.
- Willr
Series - Willr
Solution - Willr
State - Incremental Williams %R.
- WmaState
- Incremental WMA: newest sample weight =
period, oldest weight = 1.
Enums§
- Stdev
Kind - Which denominator to use for window standard deviation (Bollinger, etc.).
- Vwap
Mode - Cumulative session vs rolling window.
- Vwap
Price Source - Price input for VWAP numerator.
Functions§
- adx
- adx_
solution - Examples
- atr
- atr_
solution - Examples
- bollinger
- bollinger_
solution - Teaching solution with formulas + table.
- cci
- cci_
solution - Examples
- dema
- DEMA of
periodcloses. - dema_
last - donchian
- donchian_
solution - ema
- EMA with span
period(α = 2 / (period + 1)). Seed = SMA of the firstperiodcloses. - ema_
last - Last defined EMA value, if any (via
EmaState). - hma
- Hull moving average of
period(must be ≥ 2). - hma_
last - kama
- Kaufman adaptive moving average.
- kama_
last - keltner
- keltner_
solution - Examples
- linear_
regression - Batch rolling OLS.
seriesis your choice of bar field (close, high, …). - linear_
regression_ solution - macd
- Free function: validate params then compute.
- macd_
solution - Solution with formulas + table for teaching / audit.
- mfi
- mfi_
solution - Examples
- mom
- mom_
solution - Examples
- natr
- Normalized ATR:
100 * ATR / closewhen both defined and close ≠ 0. - obv
- obv_
solution - Examples
- rma
- Wilder RMA / SMMA of
periodcloses. - rma_
last - roc
- rocp
- rsi
- rsi_
solution - Examples
- rvol
- rvol_
solution - Examples
- sar
- sar_
solution - Examples
- sma
- SMA of
periodcloses. Leadingperiod - 1values areNone. - sma_
last - Last defined SMA value, if any.
- stochastics
- Stochastic series with raw (possibly unvalidated) params — validates then computes.
- stochastics_
solution - Teaching solution: formulas + printable %K/%D table.
- supertrend
- supertrend_
solution - Examples
- tema
- TEMA of
periodcloses. - tema_
last - true_
range_ series - Per-bar true range series (same length as inputs). Bar 0 uses
H−Lonly. - vwap
- vwap_
solution - Examples
- willr
- willr_
solution - Examples
- wma
- Weighted moving average (newest weight =
period). - wma_
last