Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Trend-Following Strategy

Python Trend-Following Strategy

The dual moving average in Article 4 is the simplest form of trend following. This article upgrades to the pinnacle of this school - the core of the Turtle trading rules: the Donchian channel breakout.

Build a complete strategy of "20-day breakout entry, 10-day reverse breakout exit" and honestly evaluate its performance on Moutai 2019-2024 data.


The origin of the Turtle strategy

In 1983, trading master Richard Dennis bet that "trading ability can be taught", recruited a group of trainees called "Turtles", and taught them a set of mechanical rules. These rules were later made public and became a required course for quant beginners.

Its core idea is the same as the dual moving average - chase the trend, but with clearer entry and exit:

Stage Rule Logic
Entry Closing price breaks above the past 20-day high Makes a new stage high, a trend may be starting
Exit Closing price falls below the past 10-day low Trend exhaustion signal
Position Adjust by ATR volatility (the original uses a 2% risk rule) Buy less of highly volatile instruments

Note: the full Turtle rules also include pyramiding, stop-loss, and multi-instrument diversification; due to space limits this article implements its core framework; position management (ATR risk rule) is covered in the risk management article.


Donchian channel

The Donchian channel is two lines drawn from "the past N days' highest/lowest prices". There's one key detail in implementation: you must shift(1) forward by one day.

The reason relates to backtest fairness: today's close must be compared with the 20-day high "as of yesterday"; if today is included in the channel, price always breaks out of itself and the strategy is ruined.

Example

import

yfinance

as

yf

close

=

yf.

download

(

"600519.SS"

,

start

=

"2019-01-01"

,

end

=

"2024-12-31"

,

                    progress

=

False

,

multi_level_index

=

False

)

[

"Close"

]

The channel uses data "as of yesterday": after rolling you must shift(1)

upper_ch

=

close.

rolling

(

20

)

.

max

(

)

.

shift

(

1

)

 

Entry reference: 20-day high

lower_ch

=

close.

rolling

(

10

)

.

min

(

)

.

shift

(

1

)

 

Exit reference: 10-day low


Strategy main loop

Iterate day by day; when out of the market check for a break above the upper band, when holding check for a fall below the lower band:

Example

import

pandas

as

pd

position

=

pd.

Series

(

0

,

index

=

close.

index

)

 

Daily position state: 1 holding, 0 out of market

pos

,

trades

=

0

,

0

for

i

in

range

(

1

,

len

(

close

)

)

:

   

if

pos

==

0

and

close.

iloc

[

i

]

upper_ch.

iloc

[

i

]

:

        pos

=

1

       

Break above the 20-day high, enter

        trades +

=

1

   

elif

pos

==

1

and

close.

iloc

[

i

]

<

lower_ch.

iloc

[

i

]

:

        pos

=

0

       

Fall below the 10-day low, exit

    position.

iloc

[

i

]

=

pos

Strategy daily return = yesterday's position x today's change (signals executed the next day, to prevent look-ahead bias)

daily_ret

=

close.

pct_change

(

)

strat_ret

=

position.

shift

(

1

)

.

fillna

(

0

)

fillna

(

0

)

The code structure you saw inBacktesting and Performance Evaluationyou've already seen: the position series shift(1) then multiplied by daily returns; this time only the signal source is changed to channel breakouts.


Backtest and honest evaluation

Example

import

numpy

as

np

cum

=

(

1

)

.

cumprod

(

)

days

=

len

(

strat_ret

)

ann

=

cum.

iloc

[

1

]

**

(

252

/ days

)

1

vol

=

strat_ret.

std

(

)

sqrt

(

252

)

mdd

=

(

cum / cum.

cummax

(

)

1

)

.

min

(

)

sharpe

=

(

ann -

0.03

)

/ vol

bh

=

close.

iloc

[

1

]

/ close.

iloc

[

0

]

1

print

(

f

"Number of trades {trades} | strategy cumulative {cum.iloc[-1]-1:.2%} | buy-and-hold {bh:.2%}"

)

print

(

f

"Annualized {ann:.2%} | volatility {vol:.2%} | max drawdown {mdd:.2%} | Sharpe {sharpe:.2f}"

)

The output is shown below:



交易次数 33 | 策略累计 69.16% | 买入持有 187.58%

年化 9.55% | 波动 18.92% | 最大回撤 -28.53% | 夏普 0.35

Buy-and-hold comparison over the same period (computed on the same data): cumulative 187.58%, annualized 20.12%, max drawdown -47.48%, Sharpe 0.58.

The results deserve careful interpretation, not just looking at the return:

Pointer Turtle strategy Buy-and-hold Interpretation
Cumulative Return 69.16% 187.58% Underperformed significantly - a trend strategy can't capture the whole one-way bull market
Maximum Drawdown -28.53% -47.48% Drawdown greatly reduced - the channel exit provided protection during the decline after 2021
Sharpe Ratio 0.35 0.58 A gap remains after risk adjustment; the strategy isn't a free lunch

Plot the channel and buy/sell points for the 2023-2024 segment and the strategy's behavior is clear at a glance:

Example

import

matplotlib.

pyplot

as

plt

seg

=

close.

loc

[

"2023-01-01"

:

"2024-12-31"

]

fig

,

ax

=

plt.

subplots

(

figsize

=

(

12

,

6

)

)

ax.

plot

(

seg.

index

,

seg.

values

,

color

=

"#1f2933"

,

linewidth

=

1.2

,

label

=

"Close"

)

ax.

plot

(

upper_ch.

loc

[

seg.

index

]

,

color

=

"#14805e"

,

linewidth

=

1.0

,

        linestyle

=

"--"

,

label

=

"20-day High Channel (Entry)"

)

ax.

plot

(

lower_ch.

loc

[

seg.

index

]

,

color

=

"#c0563f"

,

linewidth

=

1.0

,

        linestyle

=

"--"

,

label

=

"10-day Low Channel (Exit)"

)

buy_pts

=

seg

[

(

position.

loc

[

seg.

index

]

.

diff

(

)

==

1

)

]

sell_pts

=

seg

[

(

position.

loc

[

seg.

index

]

.

diff

(

)

==

1

)

]

ax.

scatter

(

buy_pts.

index

,

buy_pts.

values

,

marker

=

"^"

,

           color

=

"#14805e"

,

s

=

110

,

zorder

=

3

,

label

=

"Buy"

)

ax.

scatter

(

sell_pts.

index

,

sell_pts.

values

,

marker

=

"v"

,

           color

=

"#c0563f"

,

s

=

110

,

zorder

=

3

,

label

=

"Sell"

)

ax.

set_title

(

"Maotai: Turtle Breakout (Donchian 20/10) 2023-2024"

)

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:

Turtle Channel Breakout Buy and Sell Points

You can see the channel is like two accompanying "guardrails": buy when price breaks above the upper rail, exit when it falls below the lower rail; all trades are clear on the chart.


The character of trend strategies

Combining the dual moving average backtest from Article 9 (which also underperformed buy-and-hold) with this article's results, we can draw a complete picture of trend strategies:

Market environment Trend strategy performance Reason
One-way rise Makes money but underperforms buy-and-hold Enters only on a breakout, always a half-beat slow; the exit rule also makes it get off early
One-way decline Big gains, or at least avoids the loss Being out of the market is naturally immune, or profits from shorting
Range-bound oscillation Repeated stop-loss losses False breakouts keep triggering false signals

This is not a flaw but a character: trend strategies trade "earning less in bull markets" for "surviving bear markets". Institutions pair trend strategies with mean-reversion strategies precisely for complementarity - and mean reversion is the star of the next article.