How I Made a Profitable Stochastic Oscillator Strategy with Python(Explanation)


This tutorial has two goals, the first is to teach you how to backtest a strategy using the Stochastic Oscillator, and the second is to introduce the Object Oriented Programming (OOP) approach.

Related reading: –Python Code for Trading Strategies (Backtesting, Code, List, And Plenty of Coding Examples)

Stochastic Oscillator

The Stochastic Oscillator is an indicator that measures momentum and the speed in the security price. It measures in percentage terms how far the closing price is from its low and high. George Lane discovered this indicator in the late 1950s, and he used it to find reversals.

The calculation has two parts:

The following image shows the Stochastic Oscillator calculation:

To get the Stochastic Oscillator of day five, we implement:

The previous implementation takes the difference between the closing price of day five (15) and the minimum value of Low from the last five days [min(18,20,20,17,15) = 15]; the result is 15-15=0. Then, it subtracts the High of day five (17) minus the minimum value of the variable Low from the last five days (15), yielding 17-15=2. Finally, the division between zero and any number is zero.

The estimation of is a simple moving average; in the example, we estimated it using a 3-day window length. The calculation for the day 7 is =(0+66.7+100)/3=55.6.

Other articles

This article takes part of its code from other articles on our website. In case you have any doubts about Python codeing, please check out our landing page which contains tens of articles:

Data to Use for this Stochastic Oscillator Strategy

The following image shows the financial instruments to use:

The start and end periods to use are 2020-01-01 and 2023-10-23, respectively.

Stochastic Oscillator in Python

The first step is to download the Python libraries:

In the previous image, we import StochasticOscillator from ta.momentum that computes the Stochastic Oscillator.

Part of the aim of this tutorial is to introduce Object Oriented Programming (OOP) because it is a VERY IMPORTANT aspect of Python. There are so many benefits; you will learn to reuse your code, to code clean, and to use trading codes on the web using this programming approach.

The following image explains how a Python class works:

The previous image shows the class TradingStrategy, it has three parameters: etf_name, start, and end. We initialize our class in the second green rectangle; the initial values inserted in __init__ are stored in the variables self.etf_name, self._start, and self.end. This procedure is the initialization process.

In the second blue rectangle, we implement the download_data function. We can see in the white rectangles the prefix self. Then we print the results and see them at the button of the image.

If we implement the example_sef function located in the yellow rectangle, Python will generate an error because we need to add the prefix self to etf_name.

With the previous explanation, it is time to elucidate the role of __init__ and self. The __init__ function initializes our class with the initial values (name, “2020-01-01” and “2023-10-23”). Albeit there are four arguments in __init__, namely, (self, name, “2020-01-01” and “2023-10-23”), you do not replace self with any value. The term self is a convention to refer to the elements of the class, inside of the download_data function, it is necessary to use the prefix self to call the elements from the __init__ function.

The following image shows the class TradingStrategy with three functions: __init__, download_data, and get_stochastic_oscillator. We initialize the class in TradingStrategy(etf_name, ‘2020-01-01’, “2023-10-23”); next, we implement the download_data function to get result. Subsequently, we use the get_stochastic_oscillator function with parameters data=result and window=14; inside StochasticOscillator and .stoch calculate the values from the stochastic oscillator.

Finally, we return the values in return soscillator_values.

The following image shows the result from the previous implementation:

Now, let’s add the get_D function that calculates %D to the class TradingStregy:

In the previous image, we initialize our class in mystrategy = TradingStrategy(etf_name, ‘2020-01-01’, “2023-10-23”); next, we download the data to obtain result = mystrategy.download_data(); next, we calculate the stochastic oscillator in stochastic = mystrategy.get_stochastic_oscillator(result, 14). Finally, we implement the get_D function with arguments result and “SO”, and we obtain a 3-day moving average using the values from the stochastic oscillator.

These are the results:

The following image shows the code to implement a function to plot our chart:

The plot_data function takes two arguments data and ticker; in the example, we pass result and etf_name to the function and get:

Stochastic Oscillator Strategy

In the previous function, we see the historical price from the ETF, and at the button, the stochastic oscillator with its simple moving average (%D) and two bands to get the 20% and 80% intervals, respectively.

Stochastic Trading Strategy

We will implement the following trading strategy:

  • Buy when the %K and %D rise below the 80% line
  • Sell when the %K and %D fall below the 20% line

A value of %K and %D over 80% indicates an overbought situation; looking at the chart, it seems a likely possibility of retracement in the stock price at this level. Meanwhile, a value of %K and %D under 20% indicates an oversold situation; looking at the chart, it seems a likely possibility of an increase in the stock price at this level.

To calculate in Python the previous trading signals, we will implement the class TradingSignals:

Stochastic Trading Strategy

The previous class has only one parameter data; we initialize the class in signals = TradingSignals(result).

Next, we implement the get_signals function from the class TradingSignals; this function gets the pandas data frame and iterates over each row with .iterrows(); in every iteration, you will have index and values, the index variable is the date and values are the values from each row in the data frame. Subsequently, we implement the buy condition so > 80 and so_sma > 80, the sell condition so < 20 and so_sma < 20; also, two other conditions to close the position when the indicator has arrived at 50%.

Now let’s calculate the returns and plot the equity curve:

Stochastic Oscillator Strategy equity curve

The previous chart shows us the equity curve from our strategy and its benchmark (the ETF); we can see how our strategy started to outperform the IJH ETF in 2022. The total return from our strategy is around 160%. The other important aspect is that our strategy has less volatility.

QQQ Implementation

In this section, we will implement the previous classes and functions inside a function. The idea is to give you a function in which you insert the name of your financial instrument, the initial and end dates, and will make all the operations to plot the equity curve. The following image shows such a function:

The equity curve for this stochastic trading strategy is:

Stochastic Oscillator Strategy equity curve

In the last chart, we can see an equity curve for QQQ lower than its benchmark but with lower volatility.


What is the Stochastic Oscillator and how does it measure momentum in security prices?

The Stochastic Oscillator is an indicator that measures the momentum and speed of a security’s price movement. It calculates the percentage difference between the closing price and the high/low range. George Lane developed this indicator in the late 1950s to identify potential reversals in the market.

Why is Object Oriented Programming (OOP) important in Python, and how is it utilized in the provided tutorial?

OOP is crucial in Python for code reusability, cleanliness, and versatility. The tutorial introduces OOP through a class named TradingStrategy, demonstrating the initialization process, the download_data function, and the application of OOP in creating modular and efficient Python code.

How does the TradingSignals class help in generating trading signals?

The TradingSignals class generates signals based on the Stochastic Oscillator (%K) and its moving average (%D). Buying signals occur when both %K and %D rise above the 80% line, while selling signals are triggered when both fall below the 20% line. Additionally, positions are closed when the indicator reaches 50%.

Similar Posts