Chapter 12: Market Profile and Support/Resistance Levels With Python
- Source: Market Profile and Support/Resistance Levels With Python
- Channel: NeuroTrader
- Duration: 10:26
- Language: English
Chapter Overview — 00:00
Support and resistance (S/R) levels are among the most universal concepts in technical analysis. Conventional retail chartists typically identify them by drawing horizontal lines by eye across discretionary swing highs and swing lows. However, discretionary drawing lacks mathematical objectivity, cannot be rigorously backtested, and introduces severe hindsight bias.
This chapter presents a data-driven, algorithmic framework for extracting objective support and resistance levels from the Market Profile using Python:
- The Behavioral Definition of Support and Resistance: Reframing S/R as price zones where market transactions decelerate, pause, or cluster over time.
- From Histograms to Kernel Density Estimation (KDE): Replacing blocky price histograms with smooth Gaussian kernel density functions parameterized by volatility (ATR).
- Temporal Weighting: Applying linear decay weights so that recent price action exerts more influence than distant historical observations.
- Topographical Peak Prominence: Using signal processing algorithms (
scipy.signal.find_peaks) to extract only structurally significant price nodes while filtering noise. - Causal Rolling Implementation: Eliminating look-ahead bias by dynamically updating levels bar-by-bar.
- Empirical Strategy Demonstration: Backtesting a pure breakout system on daily Bitcoin data that demonstrates extreme positive skewness (20% win rate, but 190% average winning trade).
1. Redefining Support and Resistance via Market Profile — 00:46
1.1 The Core Thesis
Rather than viewing support and resistance as magic price numbers, we define them mechanically:
Support and resistance are price levels where price movement is slowed, halted, or revisited repeatedly.
Under this definition, an asset's price distribution through time directly reveals its structural boundaries. Where price lingers and consolidates, market participants have reached temporary consensus (high liquidity, high trading activity). Where price moves rapidly, market participants rejected the price.
1.2 The Market Profile Histogram
In classic floor trading (developed by J. Peter Steidlmayer), Market Profile measures the amount of time spent at each price level.
If we plot a simple histogram of closing prices (e.g., across 2022 Bitcoin hourly data):
- The x-axis represents price bins.
- The y-axis represents the frequency of bars closing within that bin.
- Peaks represent high-volume acceptance zones; valleys represent rejection zones.
However, standard histograms have a major defect: binning distortion. Changing the bin width shifts the location and height of peaks, making precise level identification arbitrary and jagged.
2. Kernel Density Estimation (KDE) on Log Prices — 01:16
2.1 Smooth Probability Density Function (PDF)
To replace discrete bins with a smooth, continuous distribution, we employ Gaussian Kernel Density Estimation (scipy.stats.gaussian_kde). KDE places a Gaussian bell curve over each data point and sums their contributions to produce a smooth continuous estimate of the underlying price distribution:
Where:
- are the observed logarithmic closing prices .
- is the Gaussian kernel.
- is the bandwidth (smoothing parameter).
Raw Histogram (Blocky) Gaussian KDE (Smooth Continuous PDF)
┌─┐ ╭───╮
┌─┘ └─┐ ┌─┐ ╭─╯ ╰─╮ ╭─╮
┌─┘ └─┘ └─┐ ╭─╯ ╰─╮─╯ ╰─╮
────┴─────────────┴──── ──┴─────────────────┴──
2.2 Volatility-Adaptive Bandwidth
Selecting the bandwidth is critical:
- Too narrow Overfitting, generating hundreds of spurious micro-levels.
- Too wide Oversmoothing, obliterating genuine multi-touch structural levels.
Instead of a fixed mathematical rule (like Scott's or Silverman's rule), we anchor the bandwidth directly to market volatility:
Where is the Average True Range of logarithmic prices over the lookback window. A multiplier of provides an optimal balance between filtering noise and capturing significant structural turning points.
2.3 Evaluation Grid
The continuous KDE function is evaluated across a uniform grid of 200 points spanning . Because calculations occur in log-space, each grid step represents a constant percentage return increment.
3. Time Weighting: Prioritizing Recent Price Action — 03:36
3.1 The Decay Problem
In a rolling lookback window (e.g., 365 days or 168 hours), unweighted KDE treats a bar from the distant past with identical importance to the bar that closed 1 hour ago. However, market memory decays: participants are far more reactive to levels tested yesterday than levels tested six months ago.
3.2 Linear Weighting Formulation
To incorporate recency, we assign weights to each observation governed by the parameter first_w:
first_w = 1.0: Uniform weighting across all bars.first_w = 0.5: The oldest price in the window receives half the weight of the latest price (, ).first_w = 0.0: The oldest observation has zero weight, increasing linearly to full weight at the current bar.
Observation Weight
▲
1.0 ┼ /
│ /
│ /
first_w ┼───────────/
│
└─────────────┴──────────► Time (Past -> Present)
Negative values are floored at 0, and weights are supplied directly to gaussian_kde(dataset, weights=weights).
4. Peak Prominence in Topographical Signal Processing — 05:10
4.1 What Is Prominence?
Finding local maxima of the KDE PDF is insufficient; minor ripples create local peaks that do not represent true structural support or resistance.
To filter peaks objectively, we borrow the topographical concept of topographic prominence:
- The prominence of a peak measures how high the peak rises above the lowest contour line connecting it to a higher peak on either side.
- Mathematically, it evaluates the vertical drop from the peak to the highest local valley (saddle point) between it and any neighboring higher peak.
Peak A (Major S/R)
▲
/ \ Peak B (Noise Peak)
/ \ ▲
/ \ / \
/ \ Valleys / \
/ \_/\_________ / \
/ \
──────────────┴─────────────────────────────────┴─────────────
4.2 Thresholding with SciPy
Using scipy.signal.find_peaks(pdf, prominence=min_prominence):
- Identify the maximum prominence across all detected peaks in the current window.
- Multiply by a relative threshold
prom_thresh(e.g., ):
- Retain only peaks whose prominence exceeds this cutoff.
- Exponentiate the grid points at surviving peaks () to map back to nominal price levels.
These prominence values can additionally serve as an objective metric to rank support/resistance levels by relative structural importance.
5. Causal Rolling Implementation & Code — 06:59
To prevent look-ahead bias in backtesting and live trading, the entire estimation must be computed causally inside a rolling lookback window.
import numpy as np
import pandas as pd
from scipy.stats import gaussian_kde
from scipy.signal import find_peaks
def find_sr_levels(
log_prices: np.ndarray,
atr_log: float,
first_w: float = 0.5,
atr_mult: float = 3.0,
prom_thresh: float = 0.25,
grid_size: int = 200
) -> list:
"""
Extracts support and resistance levels from KDE-based market profile.
"""
n = len(log_prices)
# 1. Linear time-weighting
weights = np.linspace(max(0.0, first_w), 1.0, n)
# 2. Gaussian KDE with ATR-scaled bandwidth
bandwidth = atr_log * atr_mult
# In scipy, bandwidth factor is bw / std(data)
std_data = np.std(log_prices)
bw_factor = bandwidth / std_data if std_data > 0 else 0.1
kde = gaussian_kde(log_prices, weights=weights, bw_method=bw_factor)
# 3. Evaluate PDF across uniform log price grid
p_min, p_max = np.min(log_prices), np.max(log_prices)
price_grid = np.linspace(p_min, p_max, grid_size)
pdf = kde.evaluate(price_grid)
# 4. Find peaks and filter by prominence
raw_peaks, properties = find_peaks(pdf, prominence=0.0)
prominences = properties['prominences']
if len(prominences) == 0:
return []
min_prom = np.max(prominences) * prom_thresh
filtered_peaks, _ = find_peaks(pdf, prominence=min_prom)
# 5. Convert log prices back to nominal currency prices
levels = np.exp(price_grid[filtered_peaks])
return sorted(levels.tolist())
6. Systematic Breakout Strategy & Empirical Results — 08:02
6.1 Strategy Rules
To test the predictive validity of these algorithmic S/R levels, a simple trend-following breakout strategy was constructed on daily Bitcoin (BTC/USDT) data:
- Lookback Window: 365 days (1 year of daily closes).
- Parameters:
first_w = 1.0,prom_thresh = 0.25,atr_mult = 3.0. - Long Entry: Price penetrates an active S/R level from below ( and ).
- Short Entry: Price penetrates an active S/R level from above ( and ).
- Positioning: Always in the market (switching between Long and Short ).
6.2 Backtest Performance & The 20% Win Rate Paradox
Over multiple years of daily Bitcoin data (39 total trades):
- Win Rate (Long):
- Average Long Winner:
- Average Long Loser:
- Win Rate (Short):
- Average Short Winner:
- Average Short Loser:
6.3 Interpretation of the Distribution
While retail traders often obsess over achieving high win rates (e.g., ), professional trend-following strategies frequently operate with win rates between and .
Because algorithmic Market Profile levels capture major macroeconomic consolidation zones:
- False breakouts incur modest, tight losses ( to ).
- Genuine structural breakouts trigger monumental macro trends (), producing a highly profitable cumulative equity curve through sheer positive expectancy:
7. Key Takeaways & Practical Extensions — 10:08
- Eliminate Discretionary Bias: Market Profile KDE replaces hand-drawn trendlines with a mathematically deterministic, repeatable framework suitable for automated execution.
- Dynamic Volatility Scaling: Linking bandwidth directly to the Average True Range ensures the model adapts automatically between calm sideways consolidation and violent trending regimes.
- Prominence as Level Strength: The prominence score of each peak provides an objective metric to grade support/resistance levels into primary, secondary, and tertiary zones for stop placement, profit taking, or position sizing.