W

WquGuru·QuantLearn

VolatilityIntermediate

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

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

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

1
Simple Moving Average (Middle Band)

SMA20,t=120i=019PricetiSMA_{20,t} = \frac{1}{20} \sum_{i=0}^{19} Price_{t-i}

20-period simple moving average forming the middle band and baseline for volatility measurement.

2
Rolling Standard Deviation

σ20,t=120i=019(PricetiSMA20,t)2\sigma_{20,t} = \sqrt{\frac{1}{20} \sum_{i=0}^{19} (Price_{t-i} - SMA_{20,t})^2}

20-period rolling standard deviation measuring price volatility around the moving average.

3
Upper Bollinger Band

UpperBandt=SMA20,t+2×σ20,tUpperBand_t = SMA_{20,t} + 2 \times \sigma_{20,t}

Upper band positioned 2 standard deviations above the middle band, acting as dynamic resistance.

4
Lower Bollinger Band

LowerBandt=SMA20,t2×σ20,tLowerBand_t = SMA_{20,t} - 2 \times \sigma_{20,t}

Lower band positioned 2 standard deviations below the middle band, acting as dynamic support.

5
Band Width (Volatility Measure)

BandWidtht=UpperBandtLowerBandtSMA20,t=4×σ20,tSMA20,tBandWidth_t = \frac{UpperBand_t - LowerBand_t}{SMA_{20,t}} = \frac{4 \times \sigma_{20,t}}{SMA_{20,t}}

Normalized band width measuring relative volatility. Low values indicate contraction, high values indicate expansion.

6
W-Pattern Node Proximity Condition

PricetBandt<α|Price_t - Band_t| < \alpha

Alpha tolerance parameter determining how close price must be to a band to qualify as a pattern node.

7
W-Pattern Detection Logic

Condition1:PricekLowerBandk<αCondition2:PricejSMA20,j<αCondition3:PricemLowerBandm<αPricem<PricekCondition4:Pricei>UpperBandi\begin{align} Condition_1: &\quad |Price_k - LowerBand_k| < \alpha \\ Condition_2: &\quad |Price_j - SMA_{20,j}| < \alpha \\ Condition_3: &\quad |Price_m - LowerBand_m| < \alpha \land Price_m < Price_k \\ Condition_4: &\quad Price_i > UpperBand_i \end{align}

Four mathematical conditions for W-bottom pattern: first bottom (k), middle peak (j), second bottom (m), breakout (i).

8
Volatility Contraction Exit Signal

ExitSignalt=(σ20,t<β)(Positiont10)ExitSignal_t = (\sigma_{20,t} < \beta) \land (Position_{t-1} \neq 0)

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

python
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 data

Creates dynamic support/resistance bands using 20-period moving average ± 2 standard deviations.

W-Pattern Detection Logic

python
# 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'] = 1

Systematically identifies W-pattern using five nodes with mathematical proximity conditions (alpha tolerance) to band levels.

Volatility-Based Exit Strategy

python
# 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

  1. 1Calculate 20-period moving average and standard deviation for band construction
  2. 2Set alpha parameter (price proximity to bands) and beta parameter (volatility threshold)
  3. 3Use 75-period lookback window for W-pattern detection (3-month horizon)
  4. 4Scan for condition 4: price breakout above upper Bollinger Band
  5. 5Verify condition 2: identify middle peak (j) near mid band within lookback period
  6. 6Confirm condition 1: locate first bottom (k) touching lower band before middle peak
  7. 7Validate condition 3: find second bottom (m) above lower band but below first bottom
  8. 8Generate long signal when all five nodes (l,k,j,m,i) form valid W-pattern
  9. 9Exit position when band contraction occurs (standard deviation falls below beta)
  10. 10Store pattern coordinates for visualization and analysis

Key Metrics

W-pattern detection frequency and accuracy rate
Alpha tolerance parameter effectiveness (pattern proximity to bands)
Beta threshold optimization for volatility-based exits
Average holding period from expansion to contraction cycles
Breakout success rate after W-pattern completion
Band width dynamics and volatility cycle timing
Pattern coordinate accuracy and visual confirmation

Risk Considerations

Alpha parameter sensitivity - too small misses patterns, too large generates false signals
Beta parameter calibration affects exit timing and can lead to premature or late exits
Pattern recognition requires sufficient volatility expansion periods to be effective
False W-patterns can form during range-bound markets without genuine breakout potential
Strategy performance depends heavily on parameter tuning (alpha/beta values)
Band compression periods may result in whipsaw exits if volatility threshold is too sensitive
Requires 75-period minimum data for pattern detection, limiting early signal generation

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:

bash
# 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 analysis

Learning Checkpoints

1

Understand Cointegration

Can you explain why two assets might be cointegrated and what breaks this relationship?

2

Interpret Statistical Tests

Practice reading ADF test results and understanding when to accept/reject cointegration.

3

Signal Generation

Implement Z-score calculations and understand threshold selection (±1σ vs ±2σ).

4

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.

Quick Navigation