We collect cookies to improve your browsing experience. By using our site, you agree to ourPrivacy Policy andTerms of Service.

Ratio Oscillator Trading Strategy
Bubble Analytics Research08-Jun-2026

Ratio Oscillator Trading Strategy

Summary:

Ticker:SPX
Timeframe:Daily
Backtest Window:10yrs
Time Invested:70.75%
# Trades:96
Win Rate:79.17%
Total Return:292.39%
Max Drawdown:-13.36%
Sharpe Ratio:1.12
Profit Factor:2.42

This week we are going to construct something we call a Ratio Oscillator. In essence we take ratio data and create a stochastic oscillator from that, then look to see if it is effective at generating solid market timing signals. The inputs for your ratio data can be anything, but for best results you should pick correlated opposites for your trading pairs. Stocks vs bonds, or SPX vs Vix, are both good examples to which this methodology can be easily applied.

For our ratio data we have picked the 3xBull and 3xBear S&P500 ETFs (SPXL / SPXS), and we are going to use that ratio data to trade the S&P500 itself (SPX). 10 years worth of daily OHLC bars were downloaded for each and the backtest itself is run using the backtesting.py library. We are going to show you how to calculate the Ratio Oscillator, generate trading signals, then run a full backtest and output the results.

The completed codebook along with our backtesting template can be downloaded for free via our GitHub profile, and for more detailed coding instruction you can refer to the video on our YouTube channel which shows you how to construct it from start to finish. Please note that the article strategy is for infotainment purposes only and should not be construed as financial advice.

Creating the Oscillator

Our ratio today is based on leveraged ETF products. Our more than likely naive view is that due to the highly leveraged and therefore quite risky nature of the ETFs, the people buying and selling it will be industry professionals, or at least those who know what they are doing, and not retail speculators looking to turn a couple of months' wages into a lottery win (you scoundrels know who you are).

Given the triple leveraged nature, and assuming they really are utilised by people in the know, there is potential for these products to give us a window into the short-term future, with a rising ratio value showing bullish appetite for the market is starting to appear (and vice-versa) just prior to the actual market turns.

For our historical market data we downloaded SPX into a variable called df, SPXL into df1, and SPXS into df2, then calculated the ratio by taking the values in the Open High Low Close columns for df1 and dividing that by their corresponding row values in the Close column for df2. We use the Close column here to keep the oscillator bounded between 0 and 100, and save the resulting ratio data into a new variable called df3.

Once we have our ratio data in OHLC format, we then create the Full Stochastic oscillator by calculating the highest high over a given lookback period; the lowest low over that lookback period, then calculate 'K' which is the (Close - lowest low / highest high - lowest low) * 100. From K we use a simple moving average to smooth the values twice to form our oscillator lines.

Code as follows:

def Full_STO(data, n1, n2, n3):
hi = data.High.rolling(n1).max()
lo = data.Low.rolling(n1).min()
k = ((data.Close - lo) / (hi - lo)) * 100
kx = k.rolling(n3).mean()
d = kx.rolling(n2).mean()
return kx, d
df3["Full_K"], df3["Full_D"] = Full_STO(df3, 10, 4, 4)

At this point in the codebook, our ratio data and oscillator values are in df3, but for chart creation and backtesting purposes we are going to need to take the oscillator values and combine them into one dataframe along with our historical OHLC data for SPX which we earlier stored in a dataframe called df.

To do that we first tidy up the columns in df3, deleting Open High Low and Close, to leave just the Date column and our Oscillator values columns in place. We then use the merge function to combine df3 with df using the Date column as the common key, matching rows that share the same date.

The how="left" argument ensures that all rows from df are retained, while any matching values from df3 are appended as new columns. After the merge, dropna(inplace=True) removes any rows containing missing values, which occurs when a date exists in df but not in df3. Finally, evaluating df displays the cleaned and merged dataframe containing only dates where data exists in both datasets.

The code looks like this:

del df3['Open'], df3['High'], df3['Low'], df3['Close']
df = df.merge(df3, on="Date", how="left")
df.dropna(inplace=True)
df

The chart below shows you the S&P500 price above, with our newly created Ratio Oscillator below:

Section 19

Signal Generation

A buy signal is generated when the smoothest of our oscillator lines (termed ‘Full_D’ in our code) turns up, indicating a turn is in play with potential for short term bullish momentum. This pivot is detected using .iloc indexing, where we compare the previous two D values to confirm that the line was falling and has now turned upward (D[i-1] < D[i-2]) and (D[I] > D[i-1]).

Today we will be using stop loss levels and profit targets to exit our trades, but a sell signal could be defined as our D line dropping out of overbought territory signalling weakening momentum. If you wanted to do that, you would use .iloc indexing to track whether yesterdays value (D[i-1]) is above 80, and today’s value (D[I]) is back below.

The signal function loops through each row of the dataframe and assigns a value of 1 (buy), or 0 (do nothing) into a ‘signal’ column.

Signal code as follows:

def signal(data):
signal = [0] * len(data)
for i in range(0,len(data)):
if (data.Full_D.iloc[i-2] > data.Full_D.iloc[i-1]) &\
(data.Full_D.iloc[i] > data.Full_D.iloc[i-1]):
signal[i] = 1
else:
signal[i] = 0
data["signal"] = signal
signal(df)

Running the Backtest

Once our signal column values are populated, we can then run the backtest. We define a SIGNAL function to take in the values of our signal column, then create a strategy class called MyStrat. Within MyStrat we initialise the SIGNAL function, create a ‘price’ reference point we can key off to set stop losses and profit targets, then use if statements to tell the backtesting program what action to take when a buy or sell signal is found.

In this case, if the signal equals 1 we buy shares in SPX with the amount set to 99% of our available balance (size=0.99), and set a profit target of 3.5% (tp=1.035*price), and a stop loss equivalent to 5% (sl=0.95*price).

When we come to run the backtest, we tell it where to find our signal column values (df), which strategy class we want to run (MyStrat), define the starting capital allocation (cash=100_000), set it to use no leverage (margin=1), set a rule whereby we can only have one open position at a time (exclusive_orders=True), and tell it to factor in a 0.05% commission fee on the buy and sell (commission=0.0005) for total fees per completed trade of 0.1%.

def SIGNAL():
return df.signal
class MyStrat(Strategy):
def init(self):
super().init()
self.signal = self.I(SIGNAL)
def next(self):
super().next()
price = self.data.Close[-1]
if self.signal==1:
if self.position.is_short or not self.position:
self.position.close()
self.buy(size=0.99, sl=0.95*price, tp=1.035*price)
bt = Backtest(df, MyStrat, cash=100_000, margin=1, exclusive_orders=True, commission=0.0005)
stats = bt.run()
stats

Strategy Results

The strategy exposure time of 70.75% reduces market participation slightly compared to buy-and-hold, while beating the return in absolute return terms (292% vs 262%). It did so with an excellent 79.17% win rate and a far lower drawdown, over 96 trades, suggesting it has real viability. Stats are as follows:

Stats 33

In order to visualise that 13.36% max drawdown, a profit and loss graph is included below. The strategy actually performs exceptionally well, even during sustained market downtrends.

Section 35

A MonteCarlo simulation creates a cumulative return based on percent gain or loss per trade, and randomises the trade order 100 times before displaying each equity curve on the chart. This one shows a decent bottom left to top right profile suggesting relative safety in the strategy, although more trades would be needed to confirm that:

Section 37

Overall the strategy appears to be fairly effective at getting you long just before we experienced bullish momentum, but more crucially avoids prolonged drawdowns, hinting that leverage could be employed to juice overall returns. This one deserves further attention and fine tuning.

Looking for algorithmic trading signals? Bubble Analytics provides real-time trade notifications generated by systematically tested strategies, complete with detailed performance statistics, trade histories and risk metrics. Explore our live trading signals and start your free 30-day trial today. ->

As always, further parameter optimisation, regime filtering, or volatility targeting may improve performance. This article strategy is presented for educational purposes only and should not be considered financial advice. For a detailed run through of the codebook, please watch the video below.

Share this article:

Explore our services

Recent Articles

Browse all articles