Skip to main content

Module stochastic

Module stochastic 

Source
Expand description

Stochastic oscillator — one core, many packs via StochasticParams.

§Fast vs Full

Not two formulas: Full is Fast with extra %K smoothing.

StyleParamsMeaning
Fastk_smooth = 1Raw %K; %D = SMA(%K, d)
Fullk_smooth > 1%K = SMA(raw %K, k_smooth); %D = SMA(%K, d)

§Quant pattern — const pack + validated engine + .compute

This is the recommended way for production code that repeatedly runs the same stochastic variation. Build the pack once (often as a const), validate once into ValidatedStochastic, then call .compute on each new H/L/C batch. Construction is O(1); the O(n) work is only the series math.

use finance_solution::stocks::ta::{StochasticParams, ValidatedStochastic};

// 1) Strategy definition — fixed pack, zero heap, can live at module scope:
const FAST_9_3: StochasticParams = StochasticParams::fast(9, 3);
// Other common packs:
// const FAST_14_3: StochasticParams = StochasticParams::fast(14, 3);
// const FULL_14_3_3: StochasticParams = StochasticParams::full(14, 3, 3);
// const FULL_60_10_1: StochasticParams = StochasticParams::full(60, 10, 1);

// 2) Validate once at startup (period ≥ 1 checks):
let stoch = ValidatedStochastic::new(FAST_9_3).unwrap();

// 3) Hot path — many batches / symbols reuse `stoch`:
let series = stoch.compute(&h, &l, &c).unwrap();
assert_eq!(series.k.len(), h.len());
// series.k / series.d are Option<f64> with warm-up = None

Free function form (scripts / one-offs) is fine too — still uses the same Copy pack:

use finance_solution::stocks::ta::{stochastics, StochasticParams};
const FAST_9_3: StochasticParams = StochasticParams::fast(9, 3);
let _ = stochastics(&h, &l, &c, FAST_9_3).unwrap();

Sample stochastics_solution table (illustrative):

period   close      k      d
------  ------  -----  -----
     7   19.50    n/a    n/a
     8   19.60  72.00    n/a
    10   19.80  68.00  70.00

§Flat window (highest high == lowest low)

When the lookback range is zero, %K = 100 * (C − LL) / (HH − LL) is undefined.

PolicyProsCons
Always 50SimpleFake “neutral” every flat bar; can invent mean-reversion noise
None / skipHonestHoles in the series after warm-up; breaks some smoothers
Carry previous raw %K, else 50 on the first flatContinuous series; no spurious 50 flip-flopsStill conventional when no history

This crate uses carry-forward (else 50). Batch and [StochState] share the rule so live and research match. Documented so you can wrap with a different policy if your desk requires it.

Structs§

StochasticParams
Unvalidated (but Copy) stochastic parameter pack.
StochasticSeries
Aligned %K / %D output.
StochasticSolution
Teaching wrapper around StochasticSeries.
ValidatedStochastic
Params that passed period validation — safe to use in a tight loop.

Functions§

stochastics
Stochastic series with raw (possibly unvalidated) params — validates then computes.
stochastics_solution
Teaching solution: formulas + printable %K/%D table.