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?
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.
| Strategy | Philosophy | File in your folder |
|---|---|---|
| Turtle | Breakout: buy a new high | backtest/turtle.py |
| Bollinger Bands | Mean reversion: fade a stretched price | backtest/bollinger_bands.py |
| Dual Thrust | Breakout around today's open | backtest/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.
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.
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.
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.
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.
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.
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 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.
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.
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.
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.
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).
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.
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.
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.
| Trending | Random | Mean-reverting | |
|---|---|---|---|
| Turtle | 0.21 (62% of markets profit) | −0.03 (47%) | −0.94 (0%) |
| Bollinger | −0.34 (23%) | −0.05 (47%) | 1.07 (100%) |
| Dual Thrust | 0.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.
mean_reversion.py).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:
Honest limits of this experiment.
Lesson 1's ideas (rolling, shift(1), cumprod) all return. Today adds three new ideas.
| New idea | What 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 memory | Go 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. |
highest = df.High.rolling(20).max().shift(1)
lowest = df.Low.rolling(10).min().shift(1)
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()
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.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
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.mid = df.Close.rolling(20).mean()
sd = df.Close.rolling(20).std(ddof=0)
upper, lower = mid + 2 * sd, mid - 2 * sd
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).
.rolling(3).max() and print it beside the prices. Then add .shift(1) and describe the difference.holding = True when the price beats its previous 3-day high, and prints the day it happens.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)
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.
Risk per ATR = 1% × ₹2,00,000 = ₹2,000. Shares = ₹2,000 ÷ ₹5 = 400 shares (₹80,000, which is 40% of capital).
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.
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