Python Mean Reversion Strategy
Mean reversion is the mirror image of trend following: instead of chasing rallies and selling dips, it bets that prices "will come back after straying too far".
This chapter implements two classic mean-reversion approaches: Bollinger Band reversion trading and pairs trading, continuing this tutorial's honest tradition by presenting the pairs-trading demo results truthfully, including losses.
The Logic and Premise of Mean Reversion
Trend strategies fear choppy markets; mean reversion loves them: when prices swing repeatedly within a range, "buy after a big drop, sell after a big rise" has the highest win rate.
| School | Core Assumption | Nemesis |
|---|---|---|
| Trend following | Price trends will continue | Choppy markets (false breakouts) |
| Mean reversion | Price deviations will revert | One-sided markets (buying ever lower) |
So the two types are naturally complementary, and many funds run both to hedge against regime risk.
Bollinger Band Reversion Strategy
Chapter 14 already plotted Bollinger Bands; now turn it into a strategy: buy when price falls below the lower band (oversold), sell when it returns to the middle band (the mean).
Example
import
yfinance
as
yf
import
pandas
as
pd
Choppy-market sample: Moutai 2023-2024 (buy-and-hold has a negative return)
close
=
yf.
download
(
"600519.SS"
,
start
=
"2023-01-01"
,
end
=
"2024-12-31"
,
progress
=
False
,
multi_level_index
=
False
)
[
"Close"
]
mid
=
close.
rolling
(
20
)
.
mean
(
)
std
=
close.
rolling
(
20
)
.
std
(
)
lower
=
mid -
2
- std
Lower band: the oversold line
position
=
pd.
Series
(
0
,
index
=
close.
index
)
p
=
0
for
i
in
range
(
20
,
len
(
close
)
)
:
Let the moving average warm up for the first 20 days
if
p
==
0
and
close.
iloc
[
i
]
<
lower.
iloc
[
i
]
:
p
=
1
Fall below the lower band, bet on reversion
elif
p
==
1
and
close.
iloc
[
i
]
=
mid.
iloc
[
i
]
:
p
=
0
Return to the middle band, take profit
position.
iloc
[
i
]
=
p
ret
=
close.
pct_change
(
)
strat_ret
=
position.
shift
(
1
)
.
fillna
(
0
)
- ret.
fillna
(
0
)
(
f
"Number of openings {int((position.diff() == 1).sum())}"
)
Add the familiar performance calculation:
Example
import
numpy
as
np
def
perf
(
strat
,
name
)
:
cum
=
(
1
- strat
)
.
cumprod
(
)
ann
=
cum.
iloc
[
1
]
**
(
252
/
len
(
strat
)
)
1
vol
=
strat.
std
(
)
- np.
sqrt
(
252
)
mdd
=
(
cum / cum.
cummax
(
)
1
)
.
min
(
)
(
f
"{name}: cumulative {cum.iloc[-1]-1:.2%} | annualized {ann:.2%} | "
f
"volatility {vol:.2%} | max drawdown {mdd:.2%} | Sharpe {(ann-0.03)/vol:.2f}"
)
perf
(
strat_ret
,
"Bollinger Band Strategy"
)
perf
(
ret.
fillna
(
0
)
,
"Buy and Hold"
)
The output is shown below:
开仓次数 10
布林带策略: 累计 19.49% | 年化 9.73% | 波动 13.27% | 最大回撤 -8.65% | 夏普 0.51
买入持有: 累计 -6.14% | 年化 -3.25% | 波动 24.41% | 最大回撤 -31.37% | 夏普 -0.26
A dramatic result: same stock, same period, trend-style buy-and-hold lost 6%, mean reversion gained 19.5%, with only a quarter of the drawdown.
This is a vivid demonstration of "strategy personality": choppy markets are mean reversion's home turf. Plot the signals to see what it is doing:
Example
import
matplotlib.
pyplot
as
plt
fig
,
ax
=
plt.
subplots
(
figsize
=
(
12
,
6
)
)
ax.
plot
(
close.
index
,
close.
values
,
color
=
"#1f2933"
,
linewidth
=
1.2
,
label
=
"Close"
)
ax.
plot
(
mid.
index
,
mid.
values
,
color
=
"#e0a458"
,
linewidth
=
1.1
,
label
=
"Middle Band"
)
ax.
plot
(
lower.
index
,
lower.
values
,
color
=
"#14805e"
,
linewidth
=
0.9
,
linestyle
=
"--"
,
label
=
"Lower Band"
)
buy_pts
=
close
[
(
position.
diff
(
)
==
1
)
]
sell_pts
=
close
[
(
position.
diff
(
)
==
1
)
]
ax.
scatter
(
buy_pts.
index
,
buy_pts.
values
,
marker
=
"^"
,
color
=
"#14805e"
,
s
=
100
,
zorder
=
3
,
label
=
"Buy"
)
ax.
scatter
(
sell_pts.
index
,
sell_pts.
values
,
marker
=
"v"
,
color
=
"#c0563f"
,
s
=
100
,
zorder
=
3
,
label
=
"Sell"
)
ax.
set_title
(
"Maotai: Bollinger Band Mean Reversion (20, 2)"
)
ax.
set_xlabel
(
"Date"
)
ax.
set_ylabel
(
"Price (CNY)"
)
ax.
legend
(
)
ax.
grid
(
alpha
=
0.25
)
plt.
show
(
)
Run the code above and the output chart is as follows:

Note the late-September 2024 surge: the strategy exited early and perfectly avoided the subsequent sharp pullback, but for the same reason it missed one-sided trends like 2022. Methods are not good or bad, only suited or unsuited.
Warning: mean reversion's worst fear is "catching a falling knife" in a one-sided decline. Moutai 2023-2024 happened to be choppy; swap in a persistent slide like 2018 and a strategy that keeps buying as price breaks the lower band will keep bleeding. Live trading must include a stop-loss.
Pairs Trading: A Market-Neutral Version of Mean Reversion
The Bollinger strategy is always exposed to market direction risk. Pairs trading uses "one long, one short" to hedge market moves, earning only from the reversion of the spread between two stocks.
The full workflow was laid out inStatistical Foundations: cointegration tests, the hedge ratio (beta=2.8141, estimated with 2022 data), spread and z-score. Now turn the z-score into trading rules:
Example
import
numpy
as
np
Spread and 60-day rolling z-score (z indicates how many standard deviations the spread is from its mean)
spread
=
px
[
"000333.SZ"
]
- beta * px
[
"000651.SZ"
]
Midea - 2.81 x Gree
z
=
(
spread - spread.
rolling
(
60
)
.
mean
(
)
)
/ spread.
rolling
(
60
)
.
std
(
)
Trade only in the out-of-sample period (2023-2024)
z_trade
=
z.
loc
[
"2023-01-01"
:
]
position_p
=
pd.
Series
(
0
,
index
=
z_trade.
index
)
p
=
0
for
i
in
range
(
len
(
z_trade
)
)
:
v
=
z_trade.
iloc
[
i
]
if
p
==
0
and
v
<
2
:
p
=
1
Spread below -2 standard deviations: go long the spread
elif
p
==
1
and
abs
(
v
)
<
0.5
:
p
=
0
Spread reverts near 0: close the position
position_p.
iloc
[
i
]
=
p
(
f
"Opened {int((position_p.diff() == 1).sum())} times | final position {int(position_p.iloc[-1])}"
)
There are only two rules: open a position betting on reversion when z is below -2, and close when z returns within +/-0.5. The opening/closing points (z values) after execution are as follows:
开仓 5 次 | 期末持仓 0
Date
2023-02-02 -2.02 <- 开仓
2023-07-03 0.42 <- 平仓
2023-07-28 -2.08 <- 开仓
2023-08-21 0.22 <- 平仓
2024-02-20 -2.09 <- 开仓
2024-03-26 -0.49 <- 平仓
2024-05-06 -2.15 <- 开仓
2024-05-16 -0.22 <- 平仓
2024-08-05 -2.12 <- 开仓
2024-10-31 -0.02 <- 平仓
All five openings came from the spread falling below -2 sigma, and all successfully waited for reversion; the signal mechanism worked exactly as designed.
Example
import
matplotlib.
pyplot
as
plt
fig
,
ax
=
plt.
subplots
(
figsize
=
(
12
,
6
)
)
ax.
plot
(
z_trade.
index
,
z_trade.
values
,
color
=
"#1f2933"
,
linewidth
=
1.1
,
label
=
"Z-Score"
)
ax.
axhline
(
2
,
color
=
"#c0563f"
,
linewidth
=
1.0
,
linestyle
=
"--"
)
ax.
axhline
(
2
,
color
=
"#14805e"
,
linewidth
=
1.0
,
linestyle
=
"--"
)
ax.
axhline
(
0
,
color
=
"#8a95a1"
,
linewidth
=
0.8
)
ax.
fill_between
(
z_trade.
index
,
2
,
2
,
color
=
"#14805e"
,
alpha
=
0.05
)
open_pts
=
z_trade
[
(
position_p.
diff
(
)
==
1
)
]
close_pts
=
z_trade
[
(
position_p.
diff
(
)
==
1
)
]
ax.
scatter
(
open_pts.
index
,
open_pts.
values
,
marker
=
"^"
,
color
=
"#14805e"
,
s
=
100
,
zorder
=
3
,
label
=
"Open"
)
ax.
scatter
(
close_pts.
index
,
close_pts.
values
,
marker
=
"v"
,
color
=
"#e0a458"
,
s
=
100
,
zorder
=
3
,
label
=
"Close"
)
ax.
set_title
(
"Midea/Gree Spread Z-Score with Entry (-2) and Exit (0) Levels"
)
ax.
set_xlabel
(
"Date"
)
ax.
set_ylabel
(
"Z-Score (60d)"
)
ax.
legend
(
)
ax.
grid
(
alpha
=
0.25
)
plt.
show
(
)
Run the code above and the output chart is as follows:

An Honest Ending: This Pair Lost Money
Compute strategy returns from the relative change of the spread (excluding securities-lending costs):
配对价差多头: 累计 -8.65% | 年化 -4.61% | 波动 31.59% | 最大回撤 -46.41%
All five reversions were caught, yet it ultimately lost 8.65%, because drift in the spread itself (Midea's center rising relative to Gree) ate up all the reversion profit.
Returning to theCointegration Test: this pair has p=0.0617 and did not pass the 5% significance test. Statistically, "not cointegrated" precisely means "the spread will drift"; this loss is the honest fulfillment of the test result, not bad luck.
Conclusion: no step in pairs trading can be skipped: the cointegration test is the ticket in, the hedge ratio must avoid look-ahead bias, lending costs must be included, and the portfolio must be diversified across multiple pairs. Cut corners anywhere and the result can be like this demo: "every signal right, the outcome all wrong".