Last Updated on April 30, 2023 by mishou

I. Using yfinance + dictionary + matplotlib

I.1. Getting historic pricing data using yfinance

Load the data and get the pricing data for NASDAQ:

!pip install yfinance
import yfinance as yf
import pandas as pd
import datetime
# set the start and end dates
start_date = '2022-01-01'
end_date = datetime.date.today().strftime('%Y-%m-%d')
# load the data and create a dictionary
# list the ticker symbols
ticker_ls = ["^IXIC", "^DJI", "^GSPC"]
# create a dictionary for each data frame
dic_df = {}
for ticker in ticker_ls:
    dic_df[ticker] = yf.download(tickers=ticker, start=start_date, end=end_date, interval="1d")
nasdaq = dic_df['^IXIC']

I.2. Creating a stochastic oscillator function from scratch

You can learn the code from the tutorial linked below:

Create a stochastic oscillator in Python

def add_stochastic_oscillator(df, periods=14):
    copy = df.copy()
    
    high_roll = copy["High"].rolling(periods).max()
    low_roll = copy["Low"].rolling(periods).min()
    
    # Fast stochastic indicator
    num = copy["Close"] - low_roll
    denom = high_roll - low_roll
    copy["%K"] = (num / denom) * 100
    
    # Slow stochastic indicator
    copy["%D"] = copy["%K"].rolling(3).mean()
    
    return copy

Adding %K and %D to NASDAQ prices:

nasdaq_kd = add_stochastic_oscillator(nasdaq, periods=14)
nasdaq_kd
table of nasdaq_kd

I.3. Creating Stochastic Oscillator plot using matplotlib

import datetime
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
today = datetime.datetime.now()
date_pattern = "%Y-%m-%d"
today_str = today.strftime(date_pattern)
date_ranges = {
    "1M": (today - datetime.timedelta(days=30)).strftime(date_pattern),
    "3M": (today - datetime.timedelta(days=90)).strftime(date_pattern),
    "6M": (today - datetime.timedelta(days=180)).strftime(date_pattern),
    "1Y": (today - datetime.timedelta(days=365)).strftime(date_pattern),
    "2Y": (today - datetime.timedelta(days=2*365)).strftime(date_pattern),
}
def plot_stochastic_oscillator(df, symbol, rng, periods=14):
    start = date_ranges[rng]
    end = today_str
    temp_df = df[start:end]
    
    fig, ax = plt.subplots(nrows=2, ncols=1, sharex=True, tight_layout=True, figsize=(12, 6))

    ax[0].set_title(f"{symbol} price, {rng}")
    ax[0].plot(temp_df["Close"], color="tab:blue")

    ax[1].set_title(f"{symbol} Stochastic Oscillator ({periods}-day period), {rng}")
    ax[1].set_ylim(-10, 110)
    ax[1].plot(temp_df["%K"], color="tab:blue") # fast
    ax[1].plot(temp_df["%D"], color="tab:orange") # slow

    ax[1].axhline(80, color="tab:red", ls="--")
    ax[1].axhline(20, color="tab:green", ls="--")

    custom_lines = [
        Line2D([0], [0], color="tab:blue", lw=4),
        Line2D([0], [0], color="tab:orange", lw=4),
        Line2D([0], [0], color="tab:red", lw=4),
        Line2D([0], [0], color="tab:green", lw=4),
    ]
    ax[1].legend(custom_lines, ["%K", "%D", "Overbought", "Oversold"], loc="best")

Show the plot:

II. Using finance, pandas_ta, and plotly.graph_objects

You can learn the code here:

Using the Stochastic Oscillator in Python for Algorithmic Trading

plot created with plotly.graph_objects

You can see all the code above here on Google Colaboratory:

https://colab.research.google.com/drive/1N5mFsAFqV2RHODIxoWUgDiVnOVbgS4po?usp=sharing

By mishou

Leave a Reply

Your email address will not be published. Required fields are marked *