Algorithmic Trading & Indicators
Intermediate
Bollinger Band & Keltner Channel Volatility Squeeze Scanner in Python
Scan stocks for TTM Volatility Squeeze setups in Python using Pandas where Bollinger Bands contract inside Keltner Channels before explosive breakouts.
#pandas#numpy
Problem Statement
Identifying low-volatility consolidation zones across 500+ stocks manually is impossible. This scanner flags exact candles where 20-period Bollinger Bands compress inside 1.5x ATR Keltner Channels.
Formula / Core Logic
Squeeze_On = (BB_Upper < KC_Upper) and (BB_Lower > KC_Lower)
Breakout occurs when Squeeze_On turns False and Close > BB_Upper.
Installation
pip install pandas numpy
bollinger-band-squeeze-breakout-scanner-python.py
import pandas as pd
import numpy as np
def detect_volatility_squeeze(df, length=20, bb_mult=2.0, kc_mult=1.5):
df = df.copy()
df['SMA'] = df['Close'].rolling(length).mean()
df['StdDev'] = df['Close'].rolling(length).std()
df['BB_Upper'] = df['SMA'] + (bb_mult * df['StdDev'])
df['BB_Lower'] = df['SMA'] - (bb_mult * df['StdDev'])
tr = pd.concat([df['High'] - df['Low'], (df['High'] - df['Close'].shift(1)).abs(), (df['Low'] - df['Close'].shift(1)).abs()], axis=1).max(axis=1)
atr = tr.rolling(length).mean()
df['KC_Upper'] = df['SMA'] + (kc_mult * atr)
df['KC_Lower'] = df['SMA'] - (kc_mult * atr)
df['In_Squeeze'] = (df['BB_Lower'] > df['KC_Lower']) & (df['BB_Upper'] < df['KC_Upper'])
df['Bull_Breakout'] = (~df['In_Squeeze']) & (df['In_Squeeze'].shift(1)) & (df['Close'] > df['BB_Upper'])
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 combine Keltner Channels with Bollinger Bands?
Comparing standard deviation (Bollinger) against True Range (Keltner) normalizes volatility compression across any asset class.