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)–O(window) 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)
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

§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.
BollingerBarOutput
One-bar Bollinger output.
BollingerParams
Bollinger parameter pack.
BollingerSeries
Middle / upper / lower / %B series.
BollingerSolution
Teaching solution + table.
BollingerState
Incremental Bollinger Bands (sample stdev on the window).
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.
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.
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).
RsiParams
RSI lookback pack (Wilder).
RsiSeries
RsiSolution
RsiState
Incremental Wilder RSI.
RvolParams
RVOL lookback pack.
RvolSeries
RvolSolution
RvolState
Incremental relative volume.
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.
ValidatedAtr
Validated ATR config.
ValidatedBollinger
Validated Bollinger config.
ValidatedDonchian
ValidatedKeltner
Validated Keltner config.
ValidatedLinReg
Validated pack.
ValidatedMacd
Validated MACD config for reuse across many close series.
ValidatedRsi
Validated RSI config.
ValidatedRvol
Validated RVOL config.
ValidatedStochastic
Params that passed period validation — safe to use in a tight loop.
ValidatedVwap
Validated VWAP config.
VwapParams
VWAP parameter pack.
VwapSeries
VwapSolution
VwapState
Incremental VWAP (cumulative or rolling). Call VwapState::reset at session open if desired.
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§

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 first period closes.
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. 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.
rsi
rsi_solution
Examples
rvol
rvol_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.
vwap
vwap_solution
Examples
wma
Weighted moving average (newest weight = period).
wma_last