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)–O(window) 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
| Indicator | Params / presets | Series | Solution + table |
|---|---|---|---|
| SMA / EMA / WMA / HMA | period | sma, ema, wma, hma (+ *State) | — |
| Stochastic | StochasticParams::fast / full | stochastics | stochastics_solution |
| MACD | MacdParams::standard (12,26,9) | [macd] | macd_solution |
| Bollinger | BollingerParams::standard (20,2, sample stdev) | [bollinger] | bollinger_solution |
| Keltner | KeltnerParams::standard (20,10,2) | [keltner] | keltner_solution |
| Donchian | DonchianParams::period_20 | [donchian] | donchian_solution |
| VWAP | VwapParams::cumulative_typical | [vwap] | vwap_solution |
| RVOL | RvolParams::days_20 | [rvol] | rvol_solution |
| RSI | RsiParams::period_14 | [rsi] | rsi_solution |
| ATR | AtrParams::period_14 | [atr] | atr_solution |
| LinReg | LinRegParams::period_20 | [linear_regression] | linear_regression_solution |
§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.
Conventions worth knowing:
- Stochastic flat window (HH == LL): carry previous raw %K, else 50.
- Bollinger stdev:
StdevKind::Sample(n−1) default; optional population (n). - SMA/EMA batch shares code with
SmaState/EmaState(parity by construction).
Re-exports§
pub use crate::stocks::ta::moving_average::EmaState;pub use crate::stocks::ta::moving_average::SmaState;
Modules§
- atr
- Average True Range (ATR)
- bollinger
- Bollinger Bands
- 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)
- moving_
average - Simple & exponential moving averages (SMA / EMA)
- ring
- Fixed-capacity ring buffer for incremental TA windows (private helper).
- rsi
- Relative Strength Index (RSI)
- rvol
- Relative volume (RVOL)
- state
- Incremental state machines for live / streaming bar updates.
- stochastic
- Stochastic oscillator — one core, many packs via
StochasticParams. - vwap
- VWAP (volume-weighted average price)
Structs§
- 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 (sample stdev on the window).
- 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.
- 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
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).
- 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.
- 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. - Validated
Atr - Validated ATR config.
- Validated
Bollinger - Validated Bollinger config.
- Validated
Donchian - Validated
Keltner - Validated Keltner config.
- Validated
LinReg - Validated pack.
- Validated
Macd - Validated MACD config for reuse across many close series.
- Validated
Rsi - Validated RSI config.
- Validated
Rvol - Validated RVOL config.
- Validated
Stochastic - Params that passed period validation — safe to use in a tight loop.
- Validated
Vwap - Validated VWAP config.
- Vwap
Params - VWAP parameter pack.
- Vwap
Series - Vwap
Solution - Vwap
State - Incremental VWAP (cumulative or rolling). Call
VwapState::resetat session open if desired. - 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§
- atr
- atr_
solution - Examples
- bollinger
- bollinger_
solution - Teaching solution with formulas + table.
- 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 - 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.
- rsi
- rsi_
solution - Examples
- rvol
- rvol_
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.
- vwap
- vwap_
solution - Examples
- wma
- Weighted moving average (newest weight =
period). - wma_
last