Stochastic Indicator: Python Implementation

Stochastic Osillator

The stochastic indicator is a popular momentum oscillator used in technical analysis to identify overbought and oversold conditions in asset prices. It consists of two components: the %K line and the %D line. The %K line compares the closing price to the high-low range over a specified period, while the %D line is a moving average of the %K line. Traders use the stochastic indicator to generate buy and sell signals based on the crossovers and divergences between the %K and %D lines, helping them make informed trading decisions.

In this article, we’ll learn how to implement the stochastic oscillator using Python.

Recommended: Maximizing Cost Savings Through Offshore Development: A Comprehensive Guide

Recommended: Empirical Distribution in Python: Histograms, CDFs, and PMFs

Understanding the Stochastic Indicator: %K Line and %D Line

The stochastic indicator is a momentum oscillator and works on price action. This indicator also helps with finding out any trend reversals. This indicator has two components – %K Line and %D Line. These two lines help us determine whether to trade on the signal. Swing traders generally trade on the strength of the Stochastic Indicator.

%K Line essentially gives us the relative closing price concerning price over a given time which is generally 14 days.

K Line Formula
%K Line Formula

The other component of the stochastic indicator is the %D Line. It is a simple moving average of period 3 of %K. It essentially helps us to find out easier trends. Let us look at the formula for the %D Line.

D Line Formula
%D Line Formula

The stochastic oscillator ranges from 0 to 100. A reading above 80 tells us the asset is overbought and might fall soon. Similarly, when the reading is below 20, the asset appears oversold, and the price might rise soon.

The %K line is often referred to as the “fast stochastic,” as it responds quickly to changes in price. The %D line, on the other hand, is known as the “slow stochastic” because it smooths out the %K line by taking a moving average. This helps to filter out noise and provide a clearer picture of the overall trend. Traders typically look for crossovers between the %K and %D lines, as well as divergences between the stochastic indicator and the price action, to generate trading signals.

In the next segment, we will discuss how this concept can be implemented in Python.

Implementing the Stochastic Indicator in Python: A Step-by-Step Guide

In the code below, we have coded the stochastic indicator. Essentially, we randomly generate 500 price data points. Thereafter we plot the stochastic oscillator on the price movement to generate different types of signals for trading.

import numpy as np
import matplotlib.pyplot as plt

def stochastic_oscillator(data, period=14):
    highs = data[:, 0]
    lows = data[:, 1]
    closes = data[:, 2]

    highs_max = np.maximum.accumulate(highs)
    lows_min = np.minimum.accumulate(lows)

    fast_k = 100 * ((closes - lows_min) / (highs_max - lows_min))

    slow_k = np.zeros_like(fast_k)
    for i in range(period, len(fast_k)):
        slow_k[i] = np.mean(fast_k[i-period:i])

    return fast_k, slow_k

# Generating random data
np.random.seed(0)  # for reproducibility
data_points = 500
data = np.random.rand(data_points, 3) * 100  # High, Low, Close

# Calculate stochastic oscillator
fast_k, slow_k = stochastic_oscillator(data)

# Plotting
plt.figure(figsize=(14, 7))
plt.plot(data[:, 2], label='Close Price')
plt.plot(fast_k, label='%K', color='b')
plt.plot(slow_k, label='%D', color='r')
plt.title('Stochastic Oscillator')
plt.xlabel('Data Points')
plt.ylabel('Value')
plt.legend()
plt.grid(True)
plt.show()

Let us now look at the output of the code above.

Stochastic Oscillator Output
Stochastic Oscillator Output

From the above plot, we can see the close price of the asset and the stochastic indicator in action. Generally, traders use an Excel or CSV file to plot the stock price movement and technical indicators. Therefore, we created a code accepting an Excel and CSV file input. We can download this file from Yahoo Finance.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

def stochastic_oscillator(data, period=14):
    highs = data['High']
    lows = data['Low']
    closes = data['Close']

    highs_max = highs.rolling(window=period).max()
    lows_min = lows.rolling(window=period).min()

    fast_k = 100 * ((closes - lows_min) / (highs_max - lows_min))

    slow_k = fast_k.rolling(window=3).mean()

    return fast_k, slow_k

# Read data from CSV
file_path = 'your_file_path.csv'  # Update with your CSV file path
data = pd.read_csv(file_path)

# Calculate stochastic oscillator
fast_k, slow_k = stochastic_oscillator(data)

# Plotting
plt.figure(figsize=(14, 7))
plt.plot(data['Close'], label='Close Price')
plt.plot(fast_k, label='%K', color='b')
plt.plot(slow_k, label='%D', color='r')
plt.title('Stochastic Oscillator')
plt.xlabel('Data Points')
plt.ylabel('Value')
plt.legend()
plt.grid(True)
plt.show()

Conclusion

With the stochastic indicator under your belt, you now have a powerful tool to analyze momentum and identify potential trading opportunities.
The stochastic indicator’s %K and %D lines work in harmony to provide insights into overbought and oversold conditions, helping you make informed decisions about when to enter or exit a trade. After combining the stochastic indicator with other technical analysis techniques and indicators, you can develop a robust trading strategy tailored to your goals and risk tolerance.

Remember, success in trading requires continuous learning, discipline, and adaptability. As you apply the stochastic indicator to your trading arsenal, keep an open mind and be willing to refine your approach based on market conditions and your own experiences.

So, what’s next on your trading journey? Will you dive deeper into advanced technical analysis techniques, or perhaps explore the world of fundamental analysis? The possibilities are endless, and the key is never to stop learning and growing as a trader.

Are you ready to take your trading skills to new heights?

Recommended: How to Scrape Yahoo Finance Data in Python using Scrapy

Recommended: Understanding Capital Asset Pricing Model (CAPM)