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

The CCI & Schaff Trend Cycle Strategy
Bubble Analytics Research17-May-2026

The CCI & Schaff Trend Cycle Strategy

Summary:

Ticker:QQQ
Timeframe:Daily
Backtest Window:10yrs
Time Invested:76.71%
# Trades:235
Win Rate:37.45%
Total Return:351.19%
Max Drawdown:-19.22%
Sharpe Ratio:0.91
Profit Factor:1.74

This week we are taking a look at a dual-indicator strategy built using the Commodity Channel Index (CCI) and the Schaff Trend Cycle (STC). Both indicators are momentum-based, but they measure different aspects of price behaviour. CCI focuses on price deviation from its statistical mean, while STC uses using MACD logic combined with stochastic smoothing to identify cyclical turning points within broader trends. The aim of the strategy is to use STC to identify the trend and CCI to trigger entry and exit points.

In terms of strategy construction we have picked the Nasdaq 100 index (QQQ), with 10 years worth of daily OHLC bars downloaded from Yahoo Finance into a dataframe named df, and the backtest itself is run using the backtesting.py library. As usual, we will show you how to calculate the indicators, apply them to price, generate trading signals, then run a full backtest.

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 Indicators

The CCI starts by calculating the “typical price,” which is simply the average of the High, Low, and Close for each bar (tp). It then computes a rolling average of this typical price over a chosen lookback period (ma).

Next, we calculate the mean deviation (md), which measures how much price typically deviates from that rolling average by taking the average of the absolute differences over the same window.

We then compare the current deviation (tp − ma) to this average deviation. Finally, the result is scaled by a constant (0.015) so that most values fall roughly between -100 and +100, and a column of daily CCI values is added into our dataframe.

In essence, the mean deviation (md) quantifies the average fluctuation of price around its rolling mean, while CCI shows how extreme the current price move is relative to that normal level of fluctuation.

The code looks like this:

def CCI(data, n):
tp = (data["High"] + data["Low"] + data["Close"]) / 3
ma = tp.rolling(n).mean()
md = tp.rolling(n).apply(lambda x: np.mean(np.abs(x - x.mean())), raw=True)
cci = (tp - ma) / (0.015 * md)
return cci
df["CCI"] = CCI(df, 20)

For the Schaff Trend Cycle, we start by calculating two exponential moving averages of price with different lookback periods (fast & slow). The difference between these two averages forms the MACD line, which represents underlying trend momentum (macd).

We then calculate the highest and lowest MACD values over a rolling window (lomac & himac) and measure where the current MACD reading sits within that range, expressing it as a percentage between its recent minimum and maximum values which converts it into a bounded oscillator (stc). Standard indicator settings are 23, 50, 10, but we will be amending these to 23, 50 and 26 today.

Readings above 80 typically suggest strong bullish momentum while readings below 20 indicate bearish or oversold conditions. Rather than hitting the top and signalling exhaustion, we tend to see sustained periods above 80 or below 20 reflecting trend persistence, helping us distinguish between short-term pullbacks and genuine shifts in trend.

The code looks like this:

def stc(data, n1, n2, n3):
fast = data.Close.ewm(n1).mean()
slow = data.Close.ewm(n2).mean()
macd = fast-slow
lomac = macd.rolling(n3).min()
himac = macd.rolling(n3).max()
stc = ((macd - lomac) / (himac - lomac)) * 100
return stc
df['STC'] = stc(df, 23, 50, 26)

The chart below shows you what both indicators look like:

Section 19

Signal Generation

A buy signal is generated when STC is above 20, indicating bullish momentum is forming, and CCI forms a short-term turn to the upside. This pivot is detected using .iloc indexing, where we compare the previous two CCI values to confirm that CCI was falling and has now turned upward (CCI[i-1] < CCI[i-2]) and (CCI[I] > CCI[i-1]).

A sell signal is generated where STC is trading below 20 and CCI turns down (signal = 2). To maximise our use of the indicator, we are adding an additional buy signal where STC crosses above 20 from below (signal = 3). If none of our conditions are met, the signal remains 0, meaning no trade action is taken.

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

Our signal code looks like this:

def signal(data):
signal = [0] * len(df)
for i in range(2,len(df)):
if (data.STC.iloc[i] > 20) &\
(data.CCI.iloc[i] > data.CCI.iloc[i-1]) &\
(data.CCI.iloc[i-1] < data.CCI.iloc[i-2]):
signal[i] = 1
elif (data.STC.iloc[i] < 20) &\
(data.CCI.iloc[i] < data.CCI.iloc[i-1]) &\
(data.CCI.iloc[i-1] > data.CCI.iloc[i-2]):
signal[i] = 2
elif (data.STC.iloc[i-1] < 20) and (data.STC.iloc[i] > 20) :
signal[i] = 3
else:
signal[i] = 0
df["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 close any open short positions and buy with an amount equal to 99% of our available balance, and set a profit target of 4.5% and a stop loss of 5%; for our secondary buy signal (signal=3) we buy with 99% of available balance and set a target of 5% and a stop at 2%; if signal equals 2 we close any open long position then get short with a profit target of 6% and a stop at 1%.

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 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, tp=1.045*price, sl=0.95*price)
elif self.signal==3:
if self.position.is_short or not self.position:
self.position.close()
self.buy(size=0.99, tp=1.05*price, sl=0.98*price)
elif self.signal==2:
if self.position.is_long or not self.position:
self.position.close()
self.sell(size=0.99, tp=0.94*price, sl=1.01*price)
bt = Backtest(df, MyStrat, cash=100_000, margin=1/2, exclusive_orders=True, commission=0.0005)
stats = bt.run()
stats

Strategy Results

The strategy exposure time of 76.71% means our market participation is only marginally reduced compared to buy-and-hold, and although it underperformed passive exposure in absolute return terms, it did so with a far lower drawdown suggesting it has some viability. Stats are as follows:

Stats 33

In order to visualise that 19.22% max drawdown, a profit and loss graph is included below. While fairly choppy, the overall trajectory is decent and the strategy is profitable. With stops for each signal type in place, the more aggressive may apply some leverage here.

Section 35

With more than enough trades for statistical relevance, we have run a montecarlo simulation and the results are below:

Section 37

Overall the strategy appears to be fairly effective at getting you long during strong bullish momentum phases, makes the most of short term upside swings, and avoids prolonged drawdowns.

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