import polars as pl
import pytimetk as tk
= tk.load_dataset("stocks_daily", parse_dates=["date"])
df
# Pandas example (engine inferred)
= df.groupby("symbol").augment_stochastic_oscillator(
stoch_df ="date",
date_column="high",
high_column="low",
low_column="close",
close_column=[14, 21],
k_periods=[3, 9],
d_periods
)
# Polars example (method chaining)
= (
stoch_pl "symbol == 'AAPL'"))
pl.from_pandas(df.query(
.tk.augment_stochastic_oscillator(="date",
date_column="high",
high_column="low",
low_column="close",
close_column=14,
k_periods=[3],
d_periods
) )
augment_stochastic_oscillator
augment_stochastic_oscillator(
data,
date_column,
high_column,
low_column,
close_column,=14,
k_periods=3,
d_periods=False,
reduce_memory='auto',
engine )
Calculate Stochastic Oscillator (%K and %D) using pandas or polars backends.
Parameters
Name | Type | Description | Default |
---|---|---|---|
data | DataFrame or GroupBy(pandas or polars) | Input financial data. Grouped inputs are processed per group before the indicators are appended. | required |
date_column | str | Name of the column containing date information. | required |
high_column | str | Column containing high prices. | required |
low_column | str | Column containing low prices. | required |
close_column | str | Column containing closing prices. Resulting columns are prefixed with this name. | required |
k_periods | int, tuple, or list | Lookback window(s) for the %K calculation. Accepts a single integer, an inclusive tuple range, or an explicit list. Defaults to 14 . |
14 |
d_periods | int or list | Lookback window(s) for the %D smoothing calculation. Defaults to 3 . |
3 |
reduce_memory | bool | Attempt to reduce memory usage when operating on pandas data. If a polars input is supplied a warning is emitted and no conversion occurs. | False |
engine | (auto, pandas, polars) | Execution engine. "auto" (default) infers the backend from the input data while allowing explicit overrides. |
"auto" |
Returns
Name | Type | Description |
---|---|---|
DataFrame | DataFrame with %K and %D columns appended for every combination of k_periods and d_periods . The return type matches the input backend. |
Notes
%K is defined as 100 * (Close - LowestLow) / (HighestHigh - LowestLow)
where LowestLow/HighestHigh span the specified lookback window. %D is the rolling mean of %K over d_periods
. Division-by-zero scenarios yield NaN
values to match the pandas behaviour.