Skip to content

Instantly share code, notes, and snippets.

@palewire
Created October 30, 2024 17:20
Show Gist options
  • Save palewire/045717b87e210867f70f71f0015609d4 to your computer and use it in GitHub Desktop.
Save palewire/045717b87e210867f70f71f0015609d4 to your computer and use it in GitHub Desktop.
def stochastic_oscillator(
series: pd.Series,
sample_window: int = 200,
smoothing_window: int = 3,
) -> pd.Series:
"""Calculate the stochastic oscillator.
Args:
series: The series to calculate the oscillator for. Must be in chronological order.
sample_window: The window to sample over. Default is 200.
smoothing_window: The window to smooth over. Default is 3.
Returns:
The 'D' line of the stochastic oscillator.
"""
# Get the minimum value over that rolling time period
min_series = series.rolling(sample_window).min()
# Get the maximum value over that rolling time period
max_series = series.rolling(sample_window).max()
# Calculate the 'K' line of a stochastic oscillator over that range
k_series = (series - min_series) * 100 / (max_series - min_series)
# Calculate the 'D' line over that range using the smoothing window
d_series = k_series.rolling(smoothing_window).mean()
# Round the number to 1 decimal place
d_series = d_series.round(1)
# Return the 'D' line
return d_series
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment