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 vector_ta::indicators::stochf::{stochf, StochfInput, StochfParams};
use vector_ta::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 vector_ta::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 vector_ta 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 vector_ta 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 vector_ta 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 helpers are available when the Python package is built with CUDA support. Inputs must be float32; outputs are device arrays (DLPack / __cuda_array_interface__ compatible).

import numpy as np
from vector_ta import stochf_cuda_batch_dev, stochf_cuda_many_series_one_param_dev

# One series (float32)
high_f32 = np.asarray(load_high(), dtype=np.float32)
low_f32 = np.asarray(load_low(), dtype=np.float32)
close_f32 = np.asarray(load_close(), dtype=np.float32)

dev = stochf_cuda_batch_dev(
    high_f32=high_f32,
    low_f32=low_f32,
    close_f32=close_f32,
    fastk_range=(2, 20, 2),
    fastd_range=(2, 20, 2),
    device_id=0,
)

# Many series (time-major)
high_tm_f32 = np.asarray(load_high_time_major_matrix(), dtype=np.float32)
rows, cols = high_tm_f32.shape
high_tm_f32 = high_tm_f32.ravel()
low_tm_f32 = np.asarray(load_low_time_major_matrix(), dtype=np.float32)
low_tm_f32 = low_tm_f32.ravel()
close_tm_f32 = np.asarray(load_close_time_major_matrix(), dtype=np.float32)
close_tm_f32 = close_tm_f32.ravel()

dev_tm = stochf_cuda_many_series_one_param_dev(
    high_tm_f32=high_tm_f32,
    low_tm_f32=low_tm_f32,
    close_tm_f32=close_tm_f32,
    cols=cols,
    rows=rows,
    fastk=14,
    fastd=14,
    fastd_matype=14,
    device_id=0,
)

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

CUDA Bindings (Rust)

use vector_ta::cuda::CudaStochf;
use vector_ta::indicators::stochf::StochfBatchRange;

let cuda = CudaStochf::new(0)?;

let high_f32: [f32] = /* ... */;
let low_f32: [f32] = /* ... */;
let close_f32: [f32] = /* ... */;
let sweep = StochfBatchRange::default();

let out = cuda.stochf_batch_dev(&high_f32, &low_f32, &close_f32, &sweep)?;
let _ = out;

Performance Analysis

Comparison:
View:
Loading chart...

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

Related Indicators