Lesson 2: Breakouts versus bands

Three classic strategies from your QuantResearch folder, and the one question that decides which of them works: does a move tend to continue or to snap back?

1. The question behind every strategy

Imagine a stock that has just risen 10% in two weeks. You can think one of two things:

Both views have made people rich, and both have made people poor. Neither is "correct". Each is correct in a market with the right personality. In Lesson 1 our moving-average rule was a gentle trend-follower. Today we meet three strategies and test them on three kinds of market.

StrategyPhilosophyFile in your folder
TurtleBreakout: buy a new highbacktest/turtle.py
Bollinger BandsMean reversion: fade a stretched pricebacktest/bollinger_bands.py
Dual ThrustBreakout around today's openbacktest/dual_thrust.py

Many people assume Bollinger Bands are a trend tool. In your folder's code they are a mean-reversion tool: it buys when the price bounces back up from the lower band. That makes it the opposite of the other two, which is why we study them together.

2. Turtle: buy a new high

The story

In the 1980s the trader Richard Dennis trained a group of beginners, nicknamed the "Turtles", with a fixed set of rules. The rules were mechanical, so nobody needed instinct. The version in your folder is the classic idea.

The rules, in plain English

  1. Entry: if today's price is above the highest price of the last 20 days, buy. A new 20-day high says "the market is going somewhere".
  2. Exit: if the price drops below the lowest price of the last 10 days, sell. The exit window is shorter so you leave sooner than you entered.
  3. Stop-loss: if the price falls 2 ATRs below your entry price, sell no matter what.
  4. Size: buy so that a one-ATR move against you costs about 1% of your capital.
Turtle breakout on a trending market

Green line: the entry line. Red line: the exit line. Look at how the exit line trails the price upward like a ratchet, and notice the quick buy-then-sell pairs where a breakout failed. Those failed breakouts are called whipsaws, and they are the price you pay to catch the big trends.

New word: ATR (Average True Range)

ATR is a ruler for how much a stock normally moves in a day, in rupees (or dollars). A "true range" for one day is the biggest of three numbers: high minus low, the gap from yesterday's close up to today's high, and the gap from yesterday's close down to today's low. ATR is the average of that over 14 days.

Why not just high minus low? Take yesterday's close of 100. Today the stock opens at 106 with a high of 107 and a low of 105. High minus low is only 2, but the stock really moved 7 from yesterday. The gap measures are there to catch overnight jumps.

Worked example: sizing and stops

Capital ₹1,00,000. A stock costs ₹100 and its ATR is ₹2.

This is the clever bit of the Turtle system. A volatile stock has a big ATR, so you buy fewer shares. A calm stock has a small ATR, so you buy more. Every trade risks about the same amount. This idea is called volatility-based position sizing, and it matters as much as the entry rule.

A likely bug in the repo. In turtle.py, the line labelled "10d low" reads don_low = max(df_hist.High.iloc[-10-1:-1]). That takes the maximum of the highs, not the minimum of the lows. As written, the strategy would sell at the first pullback below the recent highs, not on a real breakdown. It looks like a typo. My version uses the intended rule (lowest low of the last 10 days). If you run the original, expect very twitchy behaviour.

3. Bollinger Bands: bet on the snap-back

The idea

Compute the 20-day average price. Then compute how spread-out the last 20 prices are (the standard deviation). Draw a band two standard deviations above and below the average. If prices were roughly bell-shaped, about 95% of days would sit inside the band. A price outside is unusually stretched, so the bet is that it returns to the average.

Example: average 100, standard deviation 2. Upper band 104, lower band 96. The price drops to 94 (stretched) and then climbs back to 96.5. Your code treats that as a "bounce back above the lower band" and buys, aiming for the middle line at 100.

Bollinger bands with buy and short signals on a mean-reverting market

The price keeps getting pulled back toward the dashed average. Buys happen after dips, shorts after spikes, and trades close when the price reaches the middle.

The rules in your folder

The danger. In a strong trend, price can "walk the band": it keeps riding the upper band while the band itself moves up. A Bollinger trader who keeps shorting that is fighting the trend, and it hurts. The next section shows exactly how much.

4. Dual Thrust: the day's own open sets the line

Both strategies above look at closing prices. Dual Thrust uses the open, so it needs open, high and low prices. Every morning it draws two trigger lines around the day's open, and the distance depends on how big the recent range has been.

Step 1: measure the recent range

Look at the previous n days (4 by default). Find: HH = highest high, LL = lowest low, HC = highest close, LC = lowest close. Then range = max(HH − LC, HC − LL). Taking the larger of two measures makes the range more robust.

Example: HH = 105, LC = 99, HC = 103, LL = 98. Then HH − LC = 6 and HC − LL = 5, so the range is 6.

Step 2: set the triggers

buy trigger = open + 0.5 × range and sell trigger = open − 0.5 × range. If today's open is 101, the buy trigger is 104 and the sell trigger is 98.

Step 3: trade the break

If the price touches the buy trigger, go long. If it touches the sell trigger, go short (the two numbers k1 and k2 let you make one side more sensitive than the other).

Dual Thrust illustration with trigger lines around the open

An illustration, not real data. The price reaches the buy trigger and we go long right there.

Notice it is a breakout idea again, just measured from today's open instead of from a 20-day high. It is designed for intraday data. On daily bars like ours it only makes sense if you know the day's high and low, so I simulated those.

In the repo, the range window iloc[-n:] includes the latest bar. I use the previous n days, which is the standard way and rules out any chance of peeking.

5. So which one wins?

I built three kinds of fake market where I know the personality, then ran all three strategies on each. For each type I used 120 different markets.

Average Sharpe by strategy and market type

Bars show the average Sharpe ratio (from Lesson 1). The black whiskers are a 95% margin of error. A bar whose whisker doesn't cross zero is a real difference, not luck.

TrendingRandomMean-reverting
Turtle0.21 (62% of markets profit)−0.03 (47%)−0.94 (0%)
Bollinger−0.34 (23%)−0.05 (47%)1.07 (100%)
Dual Thrust0.12 (60%)−0.04 (52%)−0.51 (9%)

Buy & hold shows about +0.07 in every market. It is zero by design; the small positive is a quirk of how percentage returns compound, so treat it as zero.

What to take from it

  1. Opposite strategies, opposite results. The breakout strategies lose money in the mean-reverting market, and Bollinger loses money in the trending one. Nothing is "the best".
  2. The random market is the sanity check. All three sit near zero there. That tells us the profits elsewhere come from the market's personality, not from a bug in my simulator.
  3. The catch. In real life nobody hands you a label saying "this market is mean-reverting". Markets switch between personalities. That is the hard part of quant trading, and it is why Lesson 3 teaches tools to measure a market's personality (the Hurst exponent and half-life from your folder's mean_reversion.py).

Play with it: choose the market's personality

Move the slider from strongly mean-reverting on the left to strongly trending on the right. Each position shows the average Sharpe over 60 simulated markets.

Try these:

  1. Put the slider in the middle (random). Everything is close to zero.
  2. Slide right. Turtle and Dual Thrust climb while Bollinger falls.
  3. Slide left. Bollinger climbs and the breakout strategies sink. Notice the left side moves further from zero than the right side.

Honest limits of this experiment.

6. The code, explained

Lesson 1's ideas (rolling, shift(1), cumprod) all return. Today adds three new ideas.

New ideaWhat it does
.rolling(20).max() / .min()Highest / lowest value of the last 20 rows. This builds the Turtle channel.
pd.concat([...], axis=1).max(axis=1)Line up several columns side by side, then take the biggest in each row. This builds the "true range".
A loop with memoryGo day by day, remembering whether you are holding, and at what price. Some rules depend on history ("sell if 2 ATR below my entry"), so they cannot be written as one vectorised line.

The channel and the "no cheating" shift

highest = df.High.rolling(20).max().shift(1)
lowest  = df.Low.rolling(10).min().shift(1)
The highest High of the 20 days, computed for every day. Then shift(1) slides it down one row, so that today's channel is built only from yesterday and before. Without it, today's high is inside its own 20-day window, and "price above the 20-day high" could never fire properly. Same principle as Lesson 1: only use what was known at the time.

ATR

prev_close = df.Close.shift(1)
true_range = pd.concat([df.High - df.Low,
                        (df.High - prev_close).abs(),
                        (df.Low  - prev_close).abs()], axis=1).max(axis=1)
atr = true_range.rolling(14).mean()
Three columns: today's range, the gap up from yesterday's close, the gap down. axis=1 means "across the columns, row by row", so .max(axis=1) picks the largest of the three for each day. The 14-day average of that is ATR.

A loop with memory (the heart of Turtle)

holding, entry_price, size = False, 0.0, 0.0
for t in range(len(df)):
    if not holding and close[t] > hi[t]:             # flat and a breakout appears
        holding, entry_price = True, close[t]
        size = min(1.0, risk * close[t] / a[t])      # volatility-based size
    elif holding and (close[t] < lo[t] or close[t] < entry_price - 2 * a[t]):
        holding = False                              # channel exit or stop-loss
    out[t] = size if holding else 0.0                # what we want to hold at today's close
Three variables carry the memory from one day to the next: whether we hold, the price we bought at, and the size. Each day we ask: "am I flat and is there a breakout?" (buy), or "am I holding and did the exit or stop trigger?" (sell). The last line records what we want to own at the close. Then to_returns shifts that by a day, exactly like Lesson 1, so today's decision earns tomorrow's return. close, hi, lo and a are plain arrays (.values), which makes loops about ten times faster than indexing a pandas Series each time.

Bollinger in three lines

mid   = df.Close.rolling(20).mean()
sd    = df.Close.rolling(20).std(ddof=0)
upper, lower = mid + 2 * sd, mid - 2 * sd
The middle line is the 20-day average. sd measures how spread out those 20 prices are. The bands are two spreads above and below. Everything else in bollinger_signal is a loop with memory like Turtle's, using the crossing conditions listed in section 3.

All of this lives in strategies.py (the three strategies), markets.py (the fake markets) and sim.py (charts and the experiment).

Your turn (try these before looking at my code)

  1. Make a Series of 10 closing prices. Compute .rolling(3).max() and print it beside the prices. Then add .shift(1) and describe the difference.
  2. Compute the 5-day average and 5-day standard deviation. Build the upper and lower bands by hand.
  3. Write a loop over the prices that sets holding = True when the price beats its previous 3-day high, and prints the day it happens.
  4. Change Turtle's entry from 20 to 55 days. Predict: more or fewer trades? Then run it and count.
How to run it yourself
python3 -m venv venv
source venv/bin/activate        # fish shell: source venv/bin/activate.fish
pip install numpy pandas matplotlib
python sim.py                   # draws the charts and runs the experiment (about 80 seconds)

7. Check your understanding

1. Why do Turtle and Bollinger lose money in each other's favourite markets?

They are opposite bets. Turtle buys strength expecting it to continue. Bollinger sells strength expecting a snap-back. In a trending market the snap-back doesn't come; in a mean-reverting market the continuation doesn't come.

2. A stock has ATR ₹5, price ₹200, capital ₹2,00,000, and risk 1%. How many shares does Turtle buy?

Risk per ATR = 1% × ₹2,00,000 = ₹2,000. Shares = ₹2,000 ÷ ₹5 = 400 shares (₹80,000, which is 40% of capital).

3. Why did the random market matter in the experiment?

It is a control. No strategy should make money there. When a strategy did (Dual Thrust in my first version), it exposed a bug in the simulator. Always test on data with no edge before trusting a result.

4. If you could not tell which regime a market is in, what would you worry about?

That you pick the wrong strategy, and the right strategy for the opposite regime is the one that loses the most. This is why measuring the regime (Lesson 3) matters.

All data here is simulated for teaching. Educational content, not investment advice. The strategies follow turtle.py, bollinger_bands.py and dual_thrust.py from the open-source QuantResearch repo by Letian Wang (MIT license).

← Lesson 1 · All strategy lessons · Next: Lesson 3, Mean reversion and how to measure it