Stochastic Fast (StochF)

Parameters: fastk_period = 5 | fastd_period = 3 | fastd_matype = 0

Overview

Fast Stochastic measures momentum by comparing the current closing price to the recent high low range over a specified period. Unlike the traditional Stochastic Oscillator, the fast version skips the initial smoothing of %K, providing more responsive signals to price changes. The indicator produces two lines: %K shows where the current price stands relative to the recent range, while %D is a moving average of %K that acts as a signal line. Values oscillate between 0 and 100, with readings above 80 typically indicating overbought conditions and below 20 suggesting oversold levels. Traders watch for %K and %D crossovers as potential trading signals, as well as divergences between the indicator and price action. Default parameters are a 5 period lookback for %K and a 3 period SMA for %D, optimized for catching early momentum shifts.

Implementation Examples

Get started with StochF using slices or candles:

use vectorta::indicators::stochf::{stochf, StochfInput, StochfParams};
use vectorta::utilities::data_loader::{Candles, read_candles_from_csv};

// From high/low/close slices
let high = vec![/* ... */];
let low = vec![/* ... */];
let close = vec![/* ... */];
let params = StochfParams { fastk_period: Some(5), fastd_period: Some(3), fastd_matype: Some(0) };
let input = StochfInput::from_slices(&high, &low, &close, params);
let out = stochf(&input)?;
println!("K[0..5]={:?}", &out.k[..5.min(out.k.len())]);

// From Candles with defaults (fastk=5, fastd=3, SMA)
let candles: Candles = read_candles_from_csv("data/sample.csv")?;
let input = StochfInput::with_default_candles(&candles);
let out = stochf(&input)?;

API Reference

Input Methods
// From candles (custom params)
StochfInput::from_candles(&Candles, StochfParams) -> StochfInput

// From high/low/close slices
StochfInput::from_slices(&[f64], &[f64], &[f64], StochfParams) -> StochfInput

// Candles with defaults (fastk=5, fastd=3, SMA)
StochfInput::with_default_candles(&Candles) -> StochfInput
Parameters Structure
#[derive(Debug, Clone)]
pub struct StochfParams {
    pub fastk_period: Option<usize>, // Default: 5
    pub fastd_period: Option<usize>, // Default: 3
    pub fastd_matype: Option<usize>, // Default: 0 (SMA for %D)
}
Output Structure
#[derive(Debug, Clone)]
pub struct StochfOutput {
    pub k: Vec<f64>, // Fast %K
    pub d: Vec<f64>, // Fast %D (SMA when matype=0, else NaN)
}
Validation, Warmup & NaNs
  • fastk_period > 0 and fastd_period > 0; both must be ≤ input length or StochfError::InvalidPeriod.
  • First finite triplet index is detected; if none, StochfError::AllValuesNaN. After that, need at least fastk_period valid points or NotEnoughValidData.
  • Warmup: K indices [.. first + fastk - 1] are NaN; D indices [.. first + fastk + fastd - 2] are NaN.
  • If fastd_matype != 0, %D is not computed and remains NaN (no error).
  • Zero-range bars (HH = LL): %K is 100 when close == HH, else 0.
Error Handling
use vectorta::indicators::stochf::{stochf, StochfError};

match stochf(&input) {
    Ok(output) => process(output.k, output.d),
    Err(StochfError::EmptyData) => eprintln!("Empty or mismatched input/output"),
    Err(StochfError::InvalidPeriod { fastk, fastd, data_len }) =>
        eprintln!("Invalid periods: k={}, d={}, len={}", fastk, fastd, data_len),
    Err(StochfError::AllValuesNaN) => eprintln!("All input values are NaN"),
    Err(StochfError::NotEnoughValidData { needed, valid }) =>
        eprintln!("Need {} valid points after first finite, got {}", needed, valid),
    Err(StochfError::InvalidOutputSize { expected, k_got, d_got }) =>
        eprintln!("Batch output size mismatch: expected={}, k_got={}, d_got={}", expected, k_got, d_got),
}

Python Bindings

Basic Usage

Compute StochF from NumPy arrays (fastk=5, fastd=3 by default):

import numpy as np
from vectorta import stochf

high = np.array([...], dtype=np.float64)
low = np.array([...], dtype=np.float64)
close = np.array([...], dtype=np.float64)

# Defaults
k, d = stochf(high, low, close)

# Custom parameters and kernel selection
k, d = stochf(high, low, close, fastk_period=5, fastd_period=3, fastd_matype=0, kernel="auto")
print(k.shape, d.shape)
Streaming Real-time Updates
from vectorta import StochfStream

stream = StochfStream(fastk_period=5, fastd_period=3, fastd_matype=0)
for h, l, c in hlc_feed:
    out = stream.update(h, l, c)
    if out is not None:
        k, d = out
        use(k, d)
Batch Parameter Optimization

Run many parameter combinations on the same data:

import numpy as np
from vectorta import stochf_batch

high = np.array([...], dtype=np.float64)
low = np.array([...], dtype=np.float64)
close = np.array([...], dtype=np.float64)

fastk_range = (5, 14, 1)
fastd_range = (3, 3, 0)

result = stochf_batch(high, low, close, fastk_range=fastk_range, fastd_range=fastd_range, kernel="auto")

# Results are reshaped: k_values[rows, cols], d_values[rows, cols]
print(result["k_values"].shape, result["d_values"].shape)
print(result["fastk_periods"], result["fastd_periods"])
CUDA Acceleration

CUDA support for StochF is currently under development. The API will follow the same pattern as other CUDA-enabled indicators.

JavaScript/WASM Bindings

Basic Usage

Calculate StochF in JavaScript/TypeScript:

import { stochf_js } from 'vectorta-wasm';

const high = new Float64Array([/* ... */]);
const low = new Float64Array([/* ... */]);
const close = new Float64Array([/* ... */]);

// Args: high, low, close, fastk_period, fastd_period, fastd_matype
const values = stochf_js(high, low, close, 5, 3, 0);

// Result layout: [K..., D...] (concatenated)
const len = high.length;
const k = values.slice(0, len);
const d = values.slice(len);
console.log('K,D', k, d);
Memory-Efficient Operations

Use zero-copy operations for large datasets:

import { stochf_alloc, stochf_free, stochf_into, memory } from 'vectorta-wasm';

const len = high.length;
const inHigh = stochf_alloc(len);
const inLow = stochf_alloc(len);
const inClose = stochf_alloc(len);
const outK = stochf_alloc(len);
const outD = stochf_alloc(len);

new Float64Array(memory.buffer, inHigh, len).set(high);
new Float64Array(memory.buffer, inLow, len).set(low);
new Float64Array(memory.buffer, inClose, len).set(close);

// Compute directly into pre-allocated memory
stochf_into(inHigh, inLow, inClose, outK, outD, len, 5, 3, 0);

const k = new Float64Array(memory.buffer, outK, len).slice();
const d = new Float64Array(memory.buffer, outD, len).slice();

stochf_free(inHigh, len);
stochf_free(inLow, len);
stochf_free(inClose, len);
stochf_free(outK, len);
stochf_free(outD, len);
Batch Processing

Test multiple parameter combinations efficiently:

import { stochf_batch } from 'vectorta-wasm';

const cfg = { fastk_range: [5, 14, 1], fastd_range: [3, 3, 0] };
const res = stochf_batch(high, low, close, cfg);

// res = { k_values, d_values, rows, cols, combos }
const rows = res.rows, cols = res.cols;
const firstKRow = res.k_values.slice(0, cols);
const firstDRow = res.d_values.slice(0, cols);

Performance Analysis

Comparison:
View:
Loading chart...

AMD Ryzen 9 9950X (CPU) | NVIDIA RTX 4090 (GPU) | Benchmarks: 2026-01-05

CUDA note

In our benchmark workload, the Rust CPU implementation is faster than CUDA for this indicator. Prefer the Rust/CPU path unless your workload differs.

Related Indicators