QuantLearn
Trading Strategies
Bollinger Bands Pattern Recognition
Volatility bands for pattern recognition trading
W-Pattern Recognition Results
Demonstrates algorithmic W-bottom pattern detection with expansion/contraction cycle analysis for GBP/USD currency pair.

Bollinger Bands Trading Positions
Long entry signal at W-pattern completion with price breaking above upper band, and exit during band contraction phase.

W-Bottom Pattern Visualization
Mathematical identification of five-node W-pattern with expansion/contraction phases clearly marked for entry and exit timing.
Volatility Channel Theory
Bollinger Bands consist of a middle band (20-day SMA) and two outer bands (±2 standard deviations) creating dynamic support and resistance.
Bands expand during high volatility periods and contract during low volatility, providing market structure insights.
Price tends to bounce between the bands, with breaks indicating strong trends or potential reversals.
The strategy focuses on algorithmic W-bottom pattern recognition rather than subjective visual identification.
Uses mathematical conditions to identify five key nodes: left peak, first bottom, middle peak, second bottom, and breakout point.
Combines pattern recognition with volatility analysis for both entry and exit timing.
Strategy employs expansion/contraction cycles to time entries during volatility expansion and exits during contraction.
Mathematical Foundation
1Simple Moving Average (Middle Band)
20-period simple moving average forming the middle band and baseline for volatility measurement.
2Rolling Standard Deviation
20-period rolling standard deviation measuring price volatility around the moving average.
3Upper Bollinger Band
Upper band positioned 2 standard deviations above the middle band, acting as dynamic resistance.
4Lower Bollinger Band
Lower band positioned 2 standard deviations below the middle band, acting as dynamic support.
5Band Width (Volatility Measure)
Normalized band width measuring relative volatility. Low values indicate contraction, high values indicate expansion.
6W-Pattern Node Proximity Condition
Alpha tolerance parameter determining how close price must be to a band to qualify as a pattern node.
7W-Pattern Detection Logic
Four mathematical conditions for W-bottom pattern: first bottom (k), middle peak (j), second bottom (m), breakout (i).
8Volatility Contraction Exit Signal
Exit position when volatility (standard deviation) falls below beta threshold, indicating momentum exhaustion.
W-Pattern Recognition Algorithm
Advanced algorithmic pattern detection using mathematical conditions to identify W-bottom formations with precise entry and exit rules.
Bollinger Bands Calculation
def bollinger_bands(df):
data = copy.deepcopy(df)
data['std'] = data['price'].rolling(window=20, min_periods=20).std()
data['mid band'] = data['price'].rolling(window=20, min_periods=20).mean()
data['upper band'] = data['mid band'] + 2 * data['std']
data['lower band'] = data['mid band'] - 2 * data['std']
return dataCreates dynamic support/resistance bands using 20-period moving average ± 2 standard deviations.
W-Pattern Detection Logic
# Five-node W-pattern detection (l,k,j,m,i)
for i in range(period, len(df)):
# Condition 4: Price breaks above upper band
if (df['price'][i] > df['upper band'][i]) and (df['cumsum'][i] == 0):
# Condition 2: Find middle peak near mid band
for j in range(i, i-period, -1):
if (abs(df['mid band'][j] - df['price'][j]) < alpha) and \
(abs(df['mid band'][j] - df['upper band'][i]) < alpha):
# Condition 1: Find first bottom near lower band
for k in range(j, i-period, -1):
if abs(df['lower band'][k] - df['price'][k]) < alpha:
threshold = df['price'][k]
# Condition 3: Find second bottom above first
for m in range(i, j, -1):
if (df['price'][m] - df['lower band'][m] < alpha) and \
(df['price'][m] > df['lower band'][m]) and \
(df['price'][m] < threshold):
df.at[i, 'signals'] = 1Systematically identifies W-pattern using five nodes with mathematical proximity conditions (alpha tolerance) to band levels.
Volatility-Based Exit Strategy
# Exit on band contraction (volatility decrease)
if (df['cumsum'][i] != 0) and (df['std'][i] < beta) and (moveon == False):
df.at[i, 'signals'] = -1
df['cumsum'] = df['signals'].cumsum()Exits positions when volatility contracts (standard deviation < beta threshold), indicating momentum exhaustion.
Implementation Steps
- 1Calculate 20-period moving average and standard deviation for band construction
- 2Set alpha parameter (price proximity to bands) and beta parameter (volatility threshold)
- 3Use 75-period lookback window for W-pattern detection (3-month horizon)
- 4Scan for condition 4: price breakout above upper Bollinger Band
- 5Verify condition 2: identify middle peak (j) near mid band within lookback period
- 6Confirm condition 1: locate first bottom (k) touching lower band before middle peak
- 7Validate condition 3: find second bottom (m) above lower band but below first bottom
- 8Generate long signal when all five nodes (l,k,j,m,i) form valid W-pattern
- 9Exit position when band contraction occurs (standard deviation falls below beta)
- 10Store pattern coordinates for visualization and analysis
Key Metrics
Risk Considerations
Practice Implementation
Prerequisites
Mathematical Background
- • Linear regression and OLS estimation
- • Time series analysis (stationarity, unit roots)
- • Hypothesis testing and p-values
- • Basic econometrics (error correction models)
Technical Skills
- • Python programming (pandas, numpy)
- • Statistical libraries (statsmodels)
- • Data visualization (matplotlib)
- • Financial data handling (yfinance)
Complete Implementation
Access the full Python implementation from the original quantitative trading repository:
# Complete pair trading implementation
git clone https://github.com/je-suis-tm/quant-trading.git
cd quant-trading
python "Pair trading backtest.py"
# Modify tickers and parameters for your own analysisLearning Checkpoints
Understand Cointegration
Can you explain why two assets might be cointegrated and what breaks this relationship?
Interpret Statistical Tests
Practice reading ADF test results and understanding when to accept/reject cointegration.
Signal Generation
Implement Z-score calculations and understand threshold selection (±1σ vs ±2σ).
Risk Management
Understand position sizing, monitoring regime changes, and exit strategies.
Recommended Learning Path
Immediate Actions
- Download and run the Python script
- Test with different asset pairs
- Experiment with threshold parameters
Advanced Studies
- Learn Johansen cointegration test
- Study Vector Error Correction Models
- Explore multiple asset pair trading
Important Disclaimer
This strategy involves significant risk. Historical cointegration relationships can break permanently. Always use proper risk management, position sizing, and never risk more than you can afford to lose. Paper trade extensively before using real capital.