Algorithmic Trading & Indicators
Beginner
Donchian Channel 20-Day Turtle Trading Breakout Strategy in Python
Implement Richard Dennis's classic Turtle Trading 20-period Donchian Channel high/low breakout system in Python using Pandas.
#pandas#numpy
Problem Statement
Capturing multi-week positional trends requires objective breakout rules. This script computes rolling N-period highs and lows (shifted by 1 bar to prevent lookahead bias) for clean breakout signals.
Formula / Core Logic
Upper_Channel = Max(High, 20)_{t-1}
Lower_Channel = Min(Low, 20)_{t-1}
Long Entry when Close_t > Upper_Channel
Installation
pip install pandas numpy
donchian-channel-turtle-trading-breakout-python.py
import pandas as pd
import numpy as np
def donchian_breakout(df, entry_window=20, exit_window=10):
df = df.copy()
df['Upper_20'] = df['High'].rolling(entry_window).max().shift(1)
df['Lower_20'] = df['Low'].rolling(entry_window).min().shift(1)
df['Exit_Low_10'] = df['Low'].rolling(exit_window).min().shift(1)
df['Long_Entry'] = np.where(df['Close'] > df['Upper_20'], 1, 0)
df['Long_Exit'] = np.where(df['Close'] < df['Exit_Low_10'], 1, 0)
return df
Get the Complete 100+ Python Quant & Automation Bundle
Instant lifetime access to all production-ready scripts, valuation models, and trading bots ($19).
Buy Full Bundle on Gumroad ($19) →Frequently Asked Questions
Q: Why is `.shift(1)` mandatory on rolling highs?
Without `.shift(1)`, today's high can never strictly exceed the rolling maximum that already includes today's high.