write a stochastic indicator in python
- User
write a stochastic indicator in python
- Assistant
write a stochastic indicator in python
Certainly! The Stochastic Oscillator is a popular momentum indicator in technical analysis that compares a particular closing price of a security to a range of its prices over a specific period. It helps identify overbought and oversold conditions in the market.
Here's a step-by-step guide to implementing the Stochastic Oscillator in Python using the pandas library. We'll also include a simple visualization using matplotlib.
Make sure you have the following Python libraries installed:
pip install pandas matplotlib yfinance
The Stochastic Oscillator consists of two lines:
%K Line: Measures the current closing price relative to the high-low range over a specific period (commonly 14 periods).
[ %K = \left( \frac{\text{Current Close} - \text{Lowest Low}}{\text{Highest High} - \text{Lowest Low}} \right) \times 100 ]
%D Line: A moving average of the %K line (commonly a 3-period SMA).
Here's a complete Python script that:
yfinance.import pandas as pd
import matplotlib.pyplot as plt
import yfinance as yf
def stochastic_oscillator(df, period=14, smooth_k=3, smooth_d=3):
"""
Calculate the Stochastic Oscillator (%K and %D).
Parameters:
- df: pandas DataFrame with 'High', 'Low', 'Close' columns.
- period: look-back period for calculation (default=14).
- smooth_k: smoothing period for %K (default=3).
- smooth_d: smoothing period for %D (default=3).
Returns:
- df: DataFrame with additional '%K' and '%D' columns.
"""
# Calculate Lowest Low and Highest High over the specified period
df['Lowest Low'] = df['Low'].rolling(window=period, min_periods=1).min()
df['Highest High'] = df['High'].rolling(window=period, min_periods=1).max()
# Calculate %K
df['%K'] = ((df['Close'] - df['Lowest Low']) / (df['Highest High'] - df['Lowest Low'])) * 100
# Smooth %K with a moving average
df['%K_SMA'] = df['%K'].rolling(window=smooth_k, min_periods=1).mean()
# Calculate %D as the moving average of %K_SMA
df['%D'] = df['%K_SMA'].rolling(window=smooth_d, min_periods=1).mean()
return df
def plot_stochastic(df, ticker):
"""
Plot the Closing Price and Stochastic Oscillator (%K and %D).
Parameters:
- df: DataFrame containing 'Close', '%K', and '%D'.
- ticker: Stock ticker symbol for the title.
"""
plt.figure(figsize=(14, 10))
# Plot Closing Price
ax1 = plt.subplot(2, 1, 1)
ax1.plot(df.index, df['Close'], label='Close Price')
ax1.set_title(f'{ticker} Close Price')
ax1.set_ylabel('Price')
ax1.legend()
ax1.grid(True)
# Plot Stochastic Oscillator
ax2 = plt.subplot(2, 1, 2)
ax2.plot(df.index, df['%K'], label='%K', color='blue')
ax2.plot(df.index, df['%D'], label='%D', color='orange')
ax2.axhline(80, color='red', linestyle='--', label='Overbought (80)')
ax2.axhline(20, color='green', linestyle='--', label='Oversold (20)')
ax2.set_title('Stochastic Oscillator')
ax2.set_ylabel('Oscillator Value')
ax2.set_xlabel('Date')
ax2.legend()
ax2.grid(True)
plt.tight_layout()
plt.show()
def main():
# Parameters
ticker = 'AAPL'
period = 14
smooth_k = 3
smooth_d = 3
start_date = '2022-01-01'
end_date = '2023-12-31'
# Fetch historical data using yfinance
df = yf.download(ticker, start=start_date, end=end_date)
# Check if data is fetched
if df.empty:
print("No data fetched. Please check the ticker symbol and date range.")
return
# Calculate Stochastic Oscillator
df = stochastic_oscillator(df, period, smooth_k, smooth_d)
# Drop intermediate columns if desired
df = df.drop(columns=['Lowest Low', 'Highest High', '%K_SMA'])
# Display the last few rows
print(df[['Close', '%K', '%D']].tail())
# Plot the indicator
plot_stochastic(df, ticker)
if __name__ == "__main__":
main()
Data Fetching:
yfinance to download historical stock data for a specified ticker (e.g., Apple Inc. with ticker AAPL).Calculating the Stochastic Oscillator:
period days.period days.%K over smooth_k periods to smooth out the line.%K_SMA over smooth_d periods.Visualization:
Output:
Close, %K, and %D columns.ticker variable to analyze a different stock.start_date and end_date variables to fetch data for a different time span.period, smooth_k, and smooth_d to customize the oscillator's sensitivity.After running the script, you might see output similar to:
Close %K %D
Date
2023-12-20 176.060013 55.172414 54.197395
2023-12-21 176.600006 58.666398 56.919906
2023-12-22 176.720001 67.326667 60.400035
2023-12-27 176.039993 59.750000 61.042050
2023-12-28 172.699997 30.769231 43.705063
And a plot window showing the closing prices along with the %K and %D lines of the Stochastic Oscillator.
High, Low, or Close values. You might need to handle NaNs appropriately.If you're interested in using libraries that already have technical indicators implemented, consider:
TA-Lib: A popular library that provides a wide range of technical indicators.
pip install TA-Lib
import talib
# Assuming df has 'High', 'Low', 'Close' columns
df['%K'], df['%D'] = talib.STOCH(df['High'], df['Low'], df['Close'],
fastk_period=14,
slowk_period=3,
slowk_matype=0,
slowd_period=3,
slowd_matype=0)
Pandas TA: A pandas extension for technical analysis.
pip install pandas-ta
import pandas_ta as ta
df.ta.stoch(high='High', low='Low', close='Close', k=14, d=3, append=True)
These libraries can simplify the process and offer additional customization options.
By following the steps above, you can effectively implement and visualize the Stochastic Oscillator in Python. This indicator can be a valuable addition to your technical analysis toolkit, helping you identify potential buy and sell signals based on market momentum.
Not yet included in a published release.