|
| 1 | +from typing import Union, Optional |
| 2 | +import pandas as pd |
| 3 | +import polars as pl |
| 4 | + |
| 5 | + |
| 6 | +def stochastic_oscillator( |
| 7 | + data: Union[pd.DataFrame, pl.DataFrame], |
| 8 | + high_column: str = "High", |
| 9 | + low_column: str = "Low", |
| 10 | + close_column: str = "Close", |
| 11 | + k_period: int = 14, |
| 12 | + k_slowing: int = 3, |
| 13 | + d_period: int = 3, |
| 14 | + result_column: Optional[str] = None |
| 15 | +) -> Union[pd.DataFrame, pl.DataFrame]: |
| 16 | + """ |
| 17 | + Calculate the Stochastic Oscillator (%K and %D) for a given DataFrame. |
| 18 | + The Stochastic Oscillator is a momentum indicator comparing |
| 19 | + a particular closing price of a security to a range of its |
| 20 | + prices over a certain period. |
| 21 | +
|
| 22 | + Args: |
| 23 | + data (Union[pd.DataFrame, pl.DataFrame]): Input DataFrame |
| 24 | + containing the high, low, and close prices. |
| 25 | + high_column (str): Name of the column containing high prices. |
| 26 | + low_column (str): Name of the column containing low prices. |
| 27 | + close_column (str): Name of the column containing close prices. |
| 28 | + k_period (int): The period for %K calculation. |
| 29 | + d_period (int): The period for %D calculation. |
| 30 | + k_slowing (int): The period for smoothing the %K line. |
| 31 | + result_column (Optional[str]): Optional prefix for result |
| 32 | + columns. If None, defaults to "%K" and "%D". |
| 33 | +
|
| 34 | + Returns: |
| 35 | + Union[pd.DataFrame, pl.DataFrame]: DataFrame |
| 36 | + with %K and %D columns. |
| 37 | + """ |
| 38 | + |
| 39 | + k_col = f"{result_column}_%K" if result_column else "%K" |
| 40 | + d_col = f"{result_column}_%D" if result_column else "%D" |
| 41 | + |
| 42 | + if isinstance(data, pd.DataFrame): |
| 43 | + # Fast %K |
| 44 | + low_min = data[low_column].rolling( |
| 45 | + window=k_period, min_periods=k_period |
| 46 | + ).min() |
| 47 | + high_max = data[high_column].rolling( |
| 48 | + window=k_period, min_periods=k_period |
| 49 | + ).max() |
| 50 | + |
| 51 | + fast_k = 100 * (data[close_column] - low_min) / (high_max - low_min) |
| 52 | + |
| 53 | + # Slow %K (smoothed Fast %K) |
| 54 | + slow_k = fast_k.rolling(window=k_slowing, min_periods=k_slowing).mean() |
| 55 | + |
| 56 | + # %D (smoothed Slow %K) |
| 57 | + d = slow_k.rolling(window=d_period, min_periods=d_period).mean() |
| 58 | + |
| 59 | + data[k_col] = slow_k |
| 60 | + data[d_col] = d |
| 61 | + |
| 62 | + return data |
| 63 | + |
| 64 | + elif isinstance(data, pl.DataFrame): |
| 65 | + # Compute Fast %K |
| 66 | + low_min = pl.col(low_column).rolling_min(k_period) |
| 67 | + high_max = pl.col(high_column).rolling_max(k_period) |
| 68 | + |
| 69 | + fast_k_expr = ((pl.col(close_column) - low_min) / |
| 70 | + (high_max - low_min)) * 100 |
| 71 | + |
| 72 | + # Compute Slow %K and %D in steps |
| 73 | + df = data.with_columns([ |
| 74 | + fast_k_expr.alias("_fast_k") |
| 75 | + ]) |
| 76 | + |
| 77 | + df = df.with_columns([ |
| 78 | + pl.col("_fast_k").rolling_mean(k_slowing).alias(k_col) |
| 79 | + ]) |
| 80 | + |
| 81 | + df = df.with_columns([ |
| 82 | + pl.col(k_col).rolling_mean(d_period).alias(d_col) |
| 83 | + ]) |
| 84 | + |
| 85 | + return df.drop("_fast_k") |
| 86 | + |
| 87 | + else: |
| 88 | + raise TypeError("Input data must be a pandas or polars DataFrame.") |
0 commit comments