What will we cover?
In this tutorial we will show how to calculate the Stochastic Oscillator with Pandas DataFrames.
Step 1: Retrieve the Data from CSV file with Pandas DataFrames
We first need to read the data from a CSV file into a DataFrame. You can get the CSV file from here or directly from Yahoo! Finance.
Alternatively you can you PandasDataframes as described in this tutorial.
import pandas as pd import matplotlib.pyplot as plt %matplotlib notebook data = pd.read_csv("AAPL.csv", index_col=0, parse_dates=True)
Step 2: Calculate the Stochastic Oscillator with Pandas DataFrames
The Stochastic Oscillator is defined as follows.
- 14-high: Maximum of last 14 trading days
- 14-low: Minimum of last 14 trading days
- %K: (Last Close – 14-low)*100 / (14-high – 14-low)
- %D: Simple Moving Average of %K
That can be done as follows.
high14 = data['High'].rolling(14).max() low14 = data['Low'].rolling(14).min() data['%K'] = (data['Close'] - low14)*100/(high14 - low14) data['%D'] = data['%K'].rolling(3).mean()
Notice, we only keep the %K and %D. The high14 and low14 are temporary variables to make our calculations easier to read.
Step 3: Visualize the Stochastic Oscillator with Matplotlib
To visualize it.
fig, ax = plt.subplots() data[['%K', '%D']].loc['2020-11-01':].plot(ax=ax) ax.axhline(80, c='r', alpha=0.3) ax.axhline(20, c='r', alpha=0.3) data['Close'].loc['2020-11-01':].plot(ax=ax, alpha=0.3, secondary_y=True)
Resulting in the following.
Want to learn more?
This is part of the FREE online course on my page. No signup required and 2 hours of free video content with code and Jupyter Notebooks available on GitHub.
Follow the link and read more.