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

**Introduction**

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***, and*

**start***. We initialize our class in the second green rectangle; the initial values inserted in*

**end***are stored in the variables*

**__init__***,*

**self.etf_name***, and*

**self._start***. This procedure is the initialization process.*

**self.end**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

*to*

**self***.*

**etf_name**With the previous explanation, it is time to elucidate the role of * __init__* and

*. The*

**self***function initializes our class with the initial values (*

**__init__***,*

**name***and*

**“2020-01-01”***). Albeit there are four arguments in*

**“2023-10-23”***, namely, (*

**__init__***,*

**self***,*

**name***and*

**“2020-01-01”***), you do not replace*

**“2023-10-23”***with any value. The term*

**self****self**is a convention to refer to the elements of the class, inside of the

*function, it is necessary to use the prefix*

**download_data***to call the elements from the*

**self***function.*

**__init__**The following image shows the class * TradingStrategy* with three functions:

*,*

**__init__***, and*

**download_data***. We initialize the class in*

**get_stochastic_oscillator***; next, we implement the*

**TradingStrategy(etf_name, ‘2020-01-01’, “2023-10-23”)***function to get*

**download_data***. Subsequently, we use the*

**result***function with parameters*

**get_stochastic_oscillator***and*

**data=result***; inside*

**window=14***and*

**StochasticOscillator***calculate the values from the stochastic oscillator.*

**.stoch**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

*; next, we calculate the stochastic oscillator in*

**result = mystrategy.download_data()***. Finally, we implement the*

**stochastic = mystrategy.get_stochastic_oscillator(result, 14)***function with arguments*

**get_D***and*

**result***, and we obtain a 3-day moving average using the values from the stochastic oscillator.*

**“SO”**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

*and*

**data***; in the example, we pass*

**ticker***and*

**result***to the function and get:*

**etf_name**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*:

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

*; this function gets the pandas data frame*

**TradingSignals***and iterates over each row with*

**self.data***; in every iteration, you will have*

**.iterrows()***and*

**index***, the*

**values***variable is the date and*

**index***are the values from each row in the data frame. Subsequently, we implement the buy condition*

**values***, the sell condition*

**so > 80 and so_sma > 80***; also, two other conditions to close the position when the indicator has arrived at 50%.*

**so < 20 and so_sma < 20**Now let’s calculate the returns and plot the 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:

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

## FAQ:

**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%.