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

Summary:
Breadth measures tend to be overlooked by traders and investors, receiving little more than a cursory glance when compared to the attention garnered by price, volume, fundamental data, and traditional technical indicators. However, market breadth provides valuable insight into the underlying strength or weakness of a market, by measuring the level of participation behind the price move. Today we will explore how we can combine the Accumulation Distribution Line with the Ulcer Index indicator to more effectively to identify the market trend in play.
For our trading vehicle we have picked the Nasdaq 100 index ETF (QQQ), with 10 years worth of daily OHLC bars downloaded and stored in a dataframe named df, and the backtest itself is run using the backtesting.py library. We are going to show you how to calculate the Accumulation Distribution Line (ADL), construct the Ulcer Index, apply that to the ADL, 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 Indicators
The Accumulation Distribution Line (ADL) is a volume-based breadth indicator used to measure underlying buying and selling pressure within a market. The casual user of this breadth measure would check to see the ADL is following price exactly, making new highs or lows in lock-step, with variation categorised as ‘divergence’ and deemed an omen of an impending price reversal.
We have found that divergence can be quite ephemeral, and those using it to govern their trading or investing decisions are likely to get unstuck either selling the rally too soon, or worse getting short before a new leg higher. The strategy today will employ a different methodology to create buy/sell signals, with far greater accuracy and very solid results.
To create ADL we combine price movement with trading volume, analysing where price closes within a -1 to +1 range (termed the Money Flow Multiplier), which is then multiplied by volume for the period (termed the Money Flow Volume).
We then create a cumulative sum of these values, and use that to track whether capital is flowing into or out of an asset over time. Rising ADL values suggest accumulation and strengthening demand, while falling values indicate distribution and weakening market participation.
Code as follows:
def ADL(data): MFM = ((data['Close'] - data['Low']) - (data['High'] - data['Close'])) / (data['High'] - data['Low']) MFV = MFM * data['Volume'] ADL = MFV.cumsum() return ADLThe Ulcer Index is a downside volatility indicator designed to measure the depth and duration of drawdowns from recent highs. Unlike traditional volatility measures that treat upward and downward movement equally, the Ulcer Index focuses specifically on sustained declines, making it useful for evaluating risk.
It is calculated by measuring the percentage drawdown from a rolling maximum, squaring these drawdowns, averaging them over a chosen lookback period, and then taking the square root of the result.
Typically we would use Close prices to create the indicator, but for the strategy today we will be using the newly created ADL values in their place. In effect we are measuring the depth and persistence of drawdowns in market participation rather than in price itself, allowing us to quantify periods where breadth is deteriorating beneath the surface, even if the market index remains relatively stable.
The code looks like this:
def Ulcer(data, n): pd = ((data['ADL'] - data['ADL'].rolling(n).max()) / data['ADL'].rolling(n).max()) * 100 sa = (pd ** 2).rolling(n).mean() ui = sa.apply(np.sqrt) return uiThe chart below shows you what our Accumulation Distribution Line and newly created ADL Ulcer indicator looks like:

Signal Generation
A buy signal is generated when our ADL Ulcer indicator (termed ‘UI’ in our code) turns up, indicating a breadth turn is in play with potential for bullish momentum. This pivot is detected using .iloc indexing, where we compare the previous two UI values to confirm that the ADL Ulcer Indicator was falling and has now turned upward (UI[i-1] < UI[i-2]) and (UI[I] > UI[i-1]).
A sell signal is much simpler to calculate, and defined as our ADL Ulcer Indicator dropping below zero signalling weakening momentum. Again we use .iloc indexing to track whether yesterdays value (UI[i-1]) is above zero, and today’s value (UI[I]) is back below. If neither condition is 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.
Signal code as follows:
def signal(data): signal = [0] * len(data) for i in range(2,len(data)): if (data.UI.iloc[i] > data.UI.iloc[i-1]) and (data.UI.iloc[i-1] < data.UI.iloc[i-2]): signal[i] = 1 elif (data.UI.iloc[i-1] > 0) and (data.UI.iloc[i] < 0): signal[i] = 2 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 close any open short positions and buy shares in QQQ with the amount set to 99% of our available balance (size=0.99), and set a profit target of 5% (tp=1.05*price). If the signal equals 2 we check for an open long position and close it, then short shares in QQQ with the amount set to 99% of our available balance (size=0.99), and set a profit target of 5% (tp=0.95*price) and a stop loss at 3% (sl=1.03*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 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.05*price) elif self.signal==2: if self.position.is_long or not self.position: self.position.close() self.sell(size=0.99, sl=1.03*price, tp=0.95*price) bt = Backtest(df, MyStrat, cash=100_000, margin=1, exclusive_orders=True, commission=0.0005)stats = bt.run()statsStrategy Results
The strategy exposure time of 78.50% reduces market participation slightly compared to buy-and-hold, while beating the return in absolute return terms. It did so with 65.52% win rate and a far lower drawdown, over 116 trades, suggesting it has real viability. Stats are as follows:

In order to visualise that 17.49% max drawdown, a profit and loss graph is included below. Unexpectedly the drawdown did not come during the 2021-2022 bear market period in QQQ, and the strategy actually performs exceptionally well during sustained market downtrends.

The 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 strong bottom left to top right profile, with very little variance in the lines, suggesting relative safety in the strategy:

Overall the strategy appears to be fairly effective at getting you long during strong bullish momentum phases, but crucially avoids prolonged drawdowns by capitalising on downside price moves. This one deserves further attention and fine tuning.
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.

01-Dec-2026

30-Nov-2026

21-Nov-2026

14-Nov-2026

07-Nov-2026

04-Nov-2026

02-Nov-2026

01-Nov-2026

28-Oct-2026

24-Oct-2026

17-Oct-2026

14-Oct-2026

10-Oct-2026

07-Oct-2026

03-Oct-2026

01-Oct-2026

30-Sept-2026

01-Sept-2026

21-Jun-2026

21-Jun-2026

14-Jun-2026

08-Jun-2026

24-May-2026

17-May-2026

10-May-2026

03-May-2026

26-Apr-2026