Xem Tiếng Việt
Chương 12Original (EN)

Chapter 12: Market Profile and Support/Resistance Levels With Python


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:

  1. The Behavioral Definition of Support and Resistance: Reframing S/R as price zones where market transactions decelerate, pause, or cluster over time.
  2. From Histograms to Kernel Density Estimation (KDE): Replacing blocky price histograms with smooth Gaussian kernel density functions parameterized by volatility (ATR).
  3. Temporal Weighting: Applying linear decay weights so that recent price action exerts more influence than distant historical observations.
  4. Topographical Peak Prominence: Using signal processing algorithms (scipy.signal.find_peaks) to extract only structurally significant price nodes while filtering noise.
  5. Causal Rolling Implementation: Eliminating look-ahead bias by dynamically updating levels bar-by-bar.
  6. 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:

f(x)=1N⋅h∑i=1NK(x−Xih)f(x) = \frac{1}{N \cdot h} \sum_{i=1}^N K\left(\frac{x - X_i}{h}\right)

Where:

  • XiX_i are the observed logarithmic closing prices ln⁡(Pt)\ln(P_t).
  • KK is the Gaussian kernel.
  • hh is the bandwidth (smoothing parameter).
   Raw Histogram (Blocky)                  Gaussian KDE (Smooth Continuous PDF)
        ┌─┐                                              ╭───╮
      ┌─┘ └─┐ ┌─┐                                      ╭─╯   ╰─╮   ╭─╮
    ┌─┘     └─┘ └─┐                                  ╭─╯       ╰─╮─╯ ╰─╮
────┴─────────────┴────                            ──┴─────────────────┴──

2.2 Volatility-Adaptive Bandwidth

Selecting the bandwidth hh is critical:

  • Too narrow   ⟹  \implies Overfitting, generating hundreds of spurious micro-levels.
  • Too wide   ⟹  \implies 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:

h=ATRlog×ATRmulth = \text{ATR}_{\text{log}} \times \text{ATR}_{\text{mult}}

Where ATRlog\text{ATR}_{\text{log}} is the Average True Range of logarithmic prices over the lookback window. A multiplier of ATRmult=3.0\text{ATR}_{\text{mult}} = 3.0 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 [min⁡(ln⁡P),max⁡(ln⁡P)][\min(\ln P), \max(\ln P)]. 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 wiw_i to each observation i∈[0,N−1]i \in [0, N-1] 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 (w0=0.5w_0 = 0.5, wN−1=1.0w_{N-1} = 1.0).
  • 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):

  1. Identify the maximum prominence across all detected peaks in the current window.
  2. Multiply by a relative threshold prom_thresh (e.g., 0.250.25):

Prominencecutoff=prom_thresh×max⁡(Prominences)\text{Prominence}_{\text{cutoff}} = \text{prom\_thresh} \times \max(\text{Prominences})

  1. Retain only peaks whose prominence exceeds this cutoff.
  2. Exponentiate the grid points at surviving peaks (exp⁡(p)\exp(p)) 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 (Closet−1<L\text{Close}_{t-1} < L and Closet≥L\text{Close}_t \ge L).
  • Short Entry: Price penetrates an active S/R level from above (Closet−1>L\text{Close}_{t-1} > L and Closet≤L\text{Close}_t \le L).
  • Positioning: Always in the market (switching between Long +1+1 and Short −1-1).

6.2 Backtest Performance & The 20% Win Rate Paradox

Over multiple years of daily Bitcoin data (39 total trades):

  • Win Rate (Long): 20%20\%
  • Average Long Winner: +190%+190\%
  • Average Long Loser: −5%-5\%
  • Win Rate (Short): 20%20\%
  • Average Short Winner: +30%+30\%
  • Average Short Loser: −4%-4\%

6.3 Interpretation of the Distribution

While retail traders often obsess over achieving high win rates (e.g., 70%+70\%+), professional trend-following strategies frequently operate with win rates between 20%20\% and 35%35\%.

Because algorithmic Market Profile levels capture major macroeconomic consolidation zones:

  • False breakouts incur modest, tight losses (−4%-4\% to −5%-5\%).
  • Genuine structural breakouts trigger monumental macro trends (+190%+190\%), producing a highly profitable cumulative equity curve through sheer positive expectancy:

E=(0.20×1.90)−(0.80×0.05)=+0.38−0.04=+0.34 per trade\mathbb{E} = (0.20 \times 1.90) - (0.80 \times 0.05) = +0.38 - 0.04 = +0.34 \text{ per trade}


7. Key Takeaways & Practical Extensions — 10:08

  1. Eliminate Discretionary Bias: Market Profile KDE replaces hand-drawn trendlines with a mathematically deterministic, repeatable framework suitable for automated execution.
  2. Dynamic Volatility Scaling: Linking bandwidth directly to the Average True Range ensures the model adapts automatically between calm sideways consolidation and violent trending regimes.
  3. 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.

Nguồn duy nhất: Kênh YouTube chính thức của neurotrader. Nội dung được hệ thống hóa phục vụ học tập & tra cứu — bấm các mốc thời gian trong bài để xem trực tiếp video gốc của tác giả.