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

Chapter 8: Volume Spread Analysis with Python (Algorithmic Trading Indicator)


Chapter Overview — 00:00

Volume Spread Analysis (VSA) is a classic technical analysis methodology originally popularized by Richard Wyckoff and Tom Williams. Its core premise is that volume confirms price: under normal market conditions, the trading range (spread) of a price bar should be roughly proportional to the trading volume executed during that period.

However, standard discretionary VSA relies on rigid, static categorizations that break down in algorithmic workflows. Furthermore, raw financial price ranges and trading volumes are non-stationary over multi-year horizons, making direct comparisons mathematically invalid.

This chapter presents an adaptive, quantitative reformulation of VSA using Python:

  1. Stationary Relative Measures: Normalizing raw candle range via Average True Range (ATR\text{ATR}) and raw volume via rolling medians.
  2. Empirical Correlation: Demonstrating the linear baseline relationship (r≈0.81r \approx 0.81 on hourly Bitcoin data).
  3. The Four Classic VSA Scenarios: Deconstructing normal confirmation versus market anomalies (absorption and liquidity vacuums).
  4. Adaptive Rolling Regression Engine: Replacing manual quadrant rules with a rolling Ordinary Least Squares (OLS) model to measure range deviations.
  5. Practical Trading Implications: Interpreting positive and negative standard deviations for trend exhaustion and volatility breakouts.

1. The Non-Stationarity Challenge & Normalization — 00:15

1.1 Why Raw Price Range and Volume Fail

Examining hourly Bitcoin data from 2018 to 2023 demonstrates clear statistical obstacles:

  • Raw Volume: Volume spikes irregularly across exchange cycles, bull markets, and structural shifts. Its mean and variance do not hover around a constant baseline.
  • Raw Candle Range (High−LowHigh - Low): Candle range expands proportionally as the nominal price of the underlying asset rises (e.g., Bitcoin at $60,000 naturally produces larger dollar ranges than at $4,000).

Because neither series is stationary, computing direct correlations or setting static thresholds produces severe historical bias.

Raw Series (Non-Stationary)
  Range = High - Low  ──► Drifts higher with nominal asset price
  Volume              ──► Drifts across market regimes

        │ Normalization Step
        ▼
Relative Series (Stationary, Commensurate Scale)
  Relative Range  = Range / ATR(168)
  Relative Volume = Volume / RollingMedian(Volume, 168)

1.2 Defining Relative Range and Relative Volume — 00:46

To make both metrics stationary and scale-comparable, we normalize them against a rolling 1-week benchmark (168 hourly periods):

Relative Ranget=Hight−LowtATR168(t)\text{Relative Range}_t = \frac{\text{High}_t - \text{Low}_t}{\text{ATR}_{168}(t)}

Relative Volumet=VolumetMedian168(Volume)(t)\text{Relative Volume}_t = \frac{\text{Volume}_t}{\text{Median}_{168}(\text{Volume})(t)}

When plotted together, these normalized measures fluctuate around a comparable scale. On hourly Bitcoin, their scatter plot shows a tight linear clustering with a Pearson correlation coefficient of r=0.81r = 0.81. This statistically confirms the fundamental assumption: range is generally proportional to volume.


2. Deconstructing the Four Classic VSA Scenarios — 01:19

The true value of volume spread analysis lies not in confirming the linear baseline, but in detecting anomalous deviations where price and volume decouple. Traditional technical analysis partitions the price-volume space into four quadrants:

ScenarioVolumeRange (Spread)Market MechanismClassical Interpretation
1. Standard ExpansionHighLargeHigh participation driving significant price movementTrend confirmation / Healthy momentum
2. Standard ContractionLowSmallLow market activity resulting in minimal displacementQuiet market / Low-volatility consolidation
3. AbsorptionHighSmallImmense transaction volume trapped inside a narrow price barInstitutional absorption (large limit orders halting price progress)
4. Liquidity VacuumLowLargePrice travels far on minimal volumeLack of order book depth (absence of counter-liquidity)

2.1 The Mechanics of Absorption (High Volume, Small Range) — 01:51

When a candle generates exceptionally heavy trading volume but fails to produce a wide spread, aggressive market orders are being matched against massive passive limit orders standing on one side of the order book. Even though volume is massive, price cannot advance. This dynamic—known as absorption—frequently indicates institutional accumulation or distribution and often precedes the stall or reversal of an existing trend.

2.2 The Mechanics of Liquidity Vacuums (Low Volume, Large Range) — 02:07

Conversely, when volume is subdued but the candle spread is abnormally wide, there is an acute deficit of limit orders opposing the move. With little resting liquidity to absorb market orders, even modest transaction volume pushes price rapidly across price levels.


3. Designing an Adaptive Rolling Regression Indicator — 02:22

Rigid four-box categorization works well for discretionary traders reviewing individual charts, but algorithmic execution requires continuous, adaptive mathematical outputs.

3.1 The Model Formulation

Rather than applying arbitrary thresholds, we fit a rolling Ordinary Least Squares (OLS) regression over the previous W=168W = 168 hourly bars:

Relative Range^t=β0+β1⋅Relative Volumet\widehat{\text{Relative Range}}_t = \beta_0 + \beta_1 \cdot \text{Relative Volume}_t

The VSA Indicator is defined as the residual deviation between the actual relative range and the predicted relative range:

VSA Indicatort=Relative Ranget−Relative Range^t\text{VSA Indicator}_t = \text{Relative Range}_t - \widehat{\text{Relative Range}}_t

Relative Range
      ▲
      │                    * Actual Range
      │                   /│
      │                  / │  Positive Residual: Actual > Expected
      │                 /  ▼  (Liquidity Vacuum / Wide Spread)
      │                /───• Expected Range (from Regression Line)
      │               /
      │   OLS Line   /
      │  (slope β₁) /  • Expected Range
      │            /   ▲
      │           /    │  Negative Residual: Actual < Expected
      │          /     │  (Absorption / High Volume Bottleneck)
      │         /      * Actual Range
      └────────/─────────────────────────────► Relative Volume

3.2 Interpreting Residual Values

  • Residual>0\text{Residual} > 0 (Positive Extreme): The current candle's range is significantly wider than predicted by its volume. Price is moving with unusually little friction.
  • Residual≈0\text{Residual} \approx 0 (Baseline): Range matches volume expectations perfectly based on the recent 168-hour regime.
  • Residual<0\text{Residual} < 0 (Negative Extreme): The candle spread is significantly narrower than expected given the heavy volume. Strong absorption is actively suppressing price movement.

4. Python Implementation — 03:09

The indicator requires a two-step lookback window:

  1. One lookback period (WW) to compute rolling ATR and rolling median volume.
  2. A second lookback period (WW) of normalized values to fit the rolling regression.

Consequently, calculation begins at index 2×W2 \times W.

import numpy as np
import pandas as pd
from scipy.stats import linregress

def compute_atr(df: pd.DataFrame, window: int = 168) -> pd.Series:
    """Compute Average True Range over a specified rolling window."""
    high_low = df['high'] - df['low']
    high_close = (df['high'] - df['close'].shift(1)).abs()
    low_close = (df['low'] - df['close'].shift(1)).abs()
    true_range = pd.concat([high_low, high_close, low_close], axis=1).max(axis=1)
    return true_range.rolling(window=window).mean()

def volume_spread_indicator(df: pd.DataFrame, lookback: int = 168) -> pd.Series:
    """
    Computes an adaptive Volume Spread Analysis residual indicator.
    
    Parameters:
        df: DataFrame containing 'open', 'high', 'low', 'close', 'volume'
        lookback: Window size for ATR, rolling median volume, and regression (default 168)
        
    Returns:
        pd.Series containing the VSA deviation indicator.
    """
    # 1. Compute rolling normalizers
    atr = compute_atr(df, window=lookback)
    vol_median = df['volume'].rolling(window=lookback).median()
    
    # 2. Derive relative measures
    raw_range = df['high'] - df['low']
    rel_range = (raw_range / atr).to_numpy()
    rel_volume = (df['volume'] / vol_median).to_numpy()
    
    n_candles = len(df)
    vsa_out = np.zeros(n_candles, dtype=float)
    
    # Start after 2 * lookback to ensure full warm-up
    start_idx = lookback * 2
    
    for i in range(start_idx, n_candles):
        # Extract the lookback window of relative values
        vol_window = rel_volume[i - lookback : i]
        range_window = rel_range[i - lookback : i]
        
        # Fit linear regression: range = slope * volume + intercept
        reg = linregress(vol_window, range_window)
        slope = reg.slope
        intercept = reg.intercept
        r_squared = reg.rvalue ** 2
        
        # Sanity checks: must be positively correlated and statistically valid
        if slope <= 0 or r_squared < 0.10:
            vsa_out[i] = 0.0
            continue
            
        current_vol = rel_volume[i]
        current_range = rel_range[i]
        
        # Predict expected range given current relative volume
        predicted_range = slope * current_vol + intercept
        
        # Residual difference: Actual - Predicted
        vsa_out[i] = current_range - predicted_range
        
    return pd.Series(vsa_out, index=df.index, name="vsa_indicator")

4.1 Statistical Checks and Hygiene

  • Negative Slope & Low R2R^2 Guard: The physical expectation of the market is that volume and range correlate positively. If regime shifts or localized noise produce a negative slope or an R2R^2 below threshold, the model flags the relationship as degenerate and assigns an indicator output of 0.00.0.
  • Stationarity & Distribution — 04:26: The raw output series is stationary with a symmetric, bell-shaped distribution centered precisely at zero.
  • Outlier Taming: Because market shocks can create extreme kurtosis, passing the raw residual through a non-linear squashing function—such as the hyperbolic tangent (tanh⁡\tanh) or normal cumulative distribution function (Φ(z)\Phi(z))—is recommended before feeding it into machine learning models.

5. Practical Trading Applications & Limitations — 04:41

5.1 Negative Extremes: Identifying Trend Exhaustion and Absorption — 04:56

When the indicator registers an extreme negative value (e.g., ≤−1.0\le -1.0), trading range has compressed despite massive trading volume:

  • At Downtrend Lows: Suggests large institutional limit buy orders are absorbing aggressive panic selling, frequently marking the terminus of the sell-off followed by sideways accumulation.
  • At Uptrend Highs: Suggests aggressive buyers are running into heavy passive ask liquidity (institutional distribution), halting upward momentum.
  • Rule of Thumb: Negative extremes do not predict immediate sharp reversals; they predict a loss of velocity or temporary halt of the prevailing trend.

5.2 Positive Extremes: Identifying Breakouts and Liquidity Gaps — 05:28

When the indicator generates an extreme positive value:

  • The candle expanded aggressively on disproportionately low volume.
  • These events frequently appear at the start of sudden trend thrusts (where price punches through an empty order book) or at trend blow-off tops.

5.3 Critical Caveats — 05:43

  1. Non-Directional Metric: The indicator models candle spread (High−Low\text{High} - \text{Low}), not directional displacement (Close−Open\text{Close} - \text{Open}). A wide candle has a large positive range regardless of whether it closed green or red. Directional context must be imported from external trend filters or candle polarity.
  2. Not a Standalone Trading Signal: Extreme readings mark points of structural interest, not deterministic entry triggers. Trends can still grind through absorption blocks or liquidity gaps. Use the metric as a regime feature or confluence trigger alongside order flow and market structure.

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ả.