Chapter 8: Volume Spread Analysis with Python (Algorithmic Trading Indicator)
- Source: Volume Spread Analysis with Python | Algorithmic Trading Indicator
- Channel: NeuroTrader
- Duration: 6:12
- Language: English
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:
- Stationary Relative Measures: Normalizing raw candle range via Average True Range () and raw volume via rolling medians.
- Empirical Correlation: Demonstrating the linear baseline relationship ( on hourly Bitcoin data).
- The Four Classic VSA Scenarios: Deconstructing normal confirmation versus market anomalies (absorption and liquidity vacuums).
- Adaptive Rolling Regression Engine: Replacing manual quadrant rules with a rolling Ordinary Least Squares (OLS) model to measure range deviations.
- 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 (): 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):
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 . 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:
| Scenario | Volume | Range (Spread) | Market Mechanism | Classical Interpretation |
|---|---|---|---|---|
| 1. Standard Expansion | High | Large | High participation driving significant price movement | Trend confirmation / Healthy momentum |
| 2. Standard Contraction | Low | Small | Low market activity resulting in minimal displacement | Quiet market / Low-volatility consolidation |
| 3. Absorption | High | Small | Immense transaction volume trapped inside a narrow price bar | Institutional absorption (large limit orders halting price progress) |
| 4. Liquidity Vacuum | Low | Large | Price travels far on minimal volume | Lack 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 hourly bars:
The VSA Indicator is defined as the residual deviation between the actual relative range and the predicted relative range:
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
- (Positive Extreme): The current candle's range is significantly wider than predicted by its volume. Price is moving with unusually little friction.
- (Baseline): Range matches volume expectations perfectly based on the recent 168-hour regime.
- (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:
- One lookback period () to compute rolling ATR and rolling median volume.
- A second lookback period () of normalized values to fit the rolling regression.
Consequently, calculation begins at index .
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 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 below threshold, the model flags the relationship as degenerate and assigns an indicator output of .
- 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 () or normal cumulative distribution function ()—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., ), 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
- Non-Directional Metric: The indicator models candle spread (), not directional displacement (). 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.
- 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.