Skip to main content

Module ta

Module ta 

Source
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)

LayerAPICost classUse
Config*Params / Validated* (Copy)O(1) validate onceBuild at startup / const
Hot path (batch)sma, ema, stochastics, macd, …O(n) pure math, no StringResearch, backtests
Hot path (live)SmaState / StochState / … push / push_barsO(1) / amortized O(1) per barStreaming payloads
Solution*_solutionO(n) + formulas + tablesTeaching, audit, observability

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?

  1. ClarityFAST_STOCH_9_3 documents the strategy; no magic positional args.
  2. Safety — period=0 fails at new, not mid-batch.
  3. Speed — validation is noise vs O(n) windows (see Criterion suite D).
  4. Variations — Fast(9,3), Full(14,3,3), MACD(8,17,9) are just different const packs 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

IndicatorParams / presetsSeriesSolution + table
SMA / EMA / WMA / HMAperiodsma, ema, wma, hma (+ *State)
RMA / DEMA / TEMA / KAMAperiod / KamaParamsrma, dema, tema, kama
StochasticStochasticParams::fast / fullstochasticsstochastics_solution
MACDMacdParams::standard (12,26,9)[macd]macd_solution
BollingerBollingerParams::standard (20,2, sample stdev)[bollinger]bollinger_solution
KeltnerKeltnerParams::standard (20,10,2)[keltner]keltner_solution
DonchianDonchianParams::period_20[donchian]donchian_solution
VWAPVwapParams::cumulative_typical[vwap]vwap_solution
RVOLRvolParams::days_20[rvol]rvol_solution
RSIRsiParams::period_14[rsi]rsi_solution
ATRAtrParams::period_14[atr]atr_solution
LinRegLinRegParams::period_20[linear_regression]linear_regression_solution
Williams %RWillrParams::period_14[willr]willr_solution
OBVObvParams::default_pack[obv]obv_solution
CCICciParams::period_20[cci]cci_solution
ADX / DI / DXAdxParams::period_14[adx]adx_solution
MOM / ROC / ROCPMomParams::period_10mom, roc, rocpmom_solution
MFIMfiParams::period_14[mfi]mfi_solution
SupertrendSupertrendParams::standard[supertrend]supertrend_solution
Parabolic SARSarParams::standard[sar]sar_solution
TR / NATRtrue_range_series, natr— / via ATR

§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*::compute route through the same *State machines as live push (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§

AdxBarOutput
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.
BollingerBarOutput
One-bar Bollinger output.
BollingerParams
Bollinger parameter pack.
BollingerSeries
Middle / upper / lower / %B series.
BollingerSolution
Teaching solution + table.
BollingerState
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).
DemaState
Double exponential moving average: 2·EMA − EMA(EMA).
DonchianBarOutput
DonchianParams
Donchian lookback.
DonchianSeries
DonchianSolution
DonchianState
Incremental Donchian.
EmaState
Incremental EMA (α = 2/(period+1), seed = SMA of first period closes).
HmaState
Hull moving average state.
KamaParams
Kaufman Adaptive Moving Average parameters.
KamaState
Incremental KAMA.
KeltnerBarOutput
KeltnerParams
Keltner parameter pack (Wilder ATR).
KeltnerSeries
KeltnerSolution
KeltnerState
Incremental Keltner (EMA mid + Wilder ATR).
LinRegBar
One fitted window.
LinRegParams
Rolling regression window length.
LinRegSolution
LinRegState
Incremental rolling regression on a caller-chosen series.
MacdBarOutput
One-bar MACD output (signal/hist may still be warming up).
MacdParams
MACD parameter pack: fast < slow, all periods ≥ 1.
MacdSeries
Aligned MACD / signal / histogram series.
MacdSolution
Teaching wrapper with formula strings and a printable table.
MacdState
Incremental MACD (fast/slow/signal EMAs).
MfiParams
MfiSeries
MfiSolution
MfiState
Incremental MFI.
MomBarOutput
One-bar momentum pack.
MomParams
Lookback for MOM / ROC / ROCP.
MomSeries
MomSolution
MomState
Incremental MOM/ROC/ROCP (shared ring of last period closes + current).
NatrSeries
Normalized ATR series.
NatrState
Incremental NATR (wraps AtrState).
ObvParams
OBV has no lookback; pack is a unit for API consistency.
ObvSeries
ObvSolution
ObvState
Incremental OBV. Each push is O(1).
RmaState
Incremental Wilder RMA (also called SMMA). α = 1/period.
RocSeries
RocpSeries
RsiParams
RSI lookback pack (Wilder).
RsiSeries
RsiSolution
RsiState
Incremental Wilder RSI.
RvolParams
RVOL lookback pack.
RvolSeries
RvolSolution
RvolState
Incremental relative volume.
SarBarOutput
SarParams
Parabolic SAR acceleration parameters.
SarSeries
SarSolution
SarState
Incremental Parabolic SAR.
SmaState
Incremental SMA. After warm-up, each SmaState::push is O(1).
StochBarOutput
One-bar stochastic output (warm-up allowed as None).
StochState
Incremental stochastic (fast/full via StochasticParams).
StochasticParams
Unvalidated (but Copy) stochastic parameter pack.
StochasticSeries
Aligned %K / %D output.
StochasticSolution
Teaching wrapper around StochasticSeries.
SupertrendBar
SupertrendParams
Supertrend pack: Wilder ATR period + band multiplier.
SupertrendSeries
SupertrendSolution
SupertrendState
Incremental Supertrend.
TemaState
Triple exponential moving average: 3·e1 − 3·e2 + e3.
ValidatedAdx
ValidatedAtr
Validated ATR config.
ValidatedBollinger
Validated Bollinger config.
ValidatedCci
ValidatedDonchian
ValidatedKama
ValidatedKeltner
Validated Keltner config.
ValidatedLinReg
Validated pack.
ValidatedMacd
Validated MACD config for reuse across many close series.
ValidatedMfi
ValidatedMom
ValidatedObv
Validated pack (always succeeds).
ValidatedRsi
Validated RSI config.
ValidatedRvol
Validated RVOL config.
ValidatedSar
ValidatedStochastic
Params that passed period validation — safe to use in a tight loop.
ValidatedSupertrend
ValidatedVwap
Validated VWAP config.
ValidatedWillr
Validated pack.
VwapParams
VWAP parameter pack.
VwapSeries
VwapSolution
VwapState
Incremental VWAP (cumulative or rolling). Call VwapState::reset at session open if desired.
WillrParams
Williams %R lookback.
WillrSeries
WillrSolution
WillrState
Incremental Williams %R.
WmaState
Incremental WMA: newest sample weight = period, oldest weight = 1.

Enums§

StdevKind
Which denominator to use for window standard deviation (Bollinger, etc.).
VwapMode
Cumulative session vs rolling window.
VwapPriceSource
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 period closes.
dema_last
donchian
donchian_solution
ema
EMA with span period (α = 2 / (period + 1)). Seed = SMA of the first period closes.
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. series is 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 / close when both defined and close ≠ 0.
obv
obv_solution
Examples
rma
Wilder RMA / SMMA of period closes.
rma_last
roc
rocp
rsi
rsi_solution
Examples
rvol
rvol_solution
Examples
sar
sar_solution
Examples
sma
SMA of period closes. Leading period - 1 values are None.
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 period closes.
tema_last
true_range_series
Per-bar true range series (same length as inputs). Bar 0 uses H−L only.
vwap
vwap_solution
Examples
willr
willr_solution
Examples
wma
Weighted moving average (newest weight = period).
wma_last