Chapter 11: Self-Exciting Behavior and Detecting the End of Price Trends
- Source: Self-Exciting Behavior and Detecting the End of Price Trends | Algorithmic Trading Strategy
- Channel: NeuroTrader
- Duration: 8:20
- Language: English
Chapter Overview — 00:00
A persistent challenge in algorithmic trend following is timing the exit: exiting too early leaves significant profit on the table, while exiting too late surrenders gains during violent trend reversals. Standard lagging indicators (such as moving average crosses) react too slowly, while fixed take-profit targets fail to adapt to expanding volatility regimes.
This chapter presents an exit methodology rooted in point processes and probability theory: the Hawkes process. Originally formulated to model earthquake aftershocks, a Hawkes process is a self-exciting point process where the occurrence of an event increases the probability of future events in the near term. In financial markets, this phenomenon manifests as volatility clustering and volume bursts.
Key topics covered:
- Mathematical Intuition of Self-Exciting Processes: Why volatility clusters and how the Hawkes process formalizes event clustering.
- Normalized Volatility Metric: Measuring candle range normalized by a long-term Average True Range (ATR).
- Discrete Hawkes Process Implementation: Recursive decay formulation using parameter .
- Dynamic Regime Thresholds: Establishing rolling quantiles ( and ) to detect trend ignition and trend exhaustion.
- Momentum Strategy & Robustness: Backtesting a complete system on Bitcoin hourly data across 25 parameter permutations.
1. Self-Exciting Processes and Volatility Clustering — 00:15
1.1 What Is a Self-Exciting Process?
In statistics and point process theory, a process is defined as self-exciting if the arrival of an event increases the conditional intensity (the instantaneous arrival rate) of subsequent events.
In financial time series, price movements do not conform to independent identically distributed (i.i.d.) random walks. Instead, two primary variables display pronounced self-excitation:
- Trading Volume: Large orders trigger market reactions, liquidity cascades, and algorithmic execution programs.
- Volatility: A large price displacement (shock) tends to be followed by further large price displacements, a stylized empirical fact known as Mandelbrot's volatility clustering.
Low Volatility Regime Shock / Cluster Decay / Mean Reversion
- - - - - - - - - - - -> [ | | | | | | | ] - - - - - > - - - - - - - - - -
Self-Excitation Exhaustion
When a sustained price trend develops, volatility spikes rapidly as momentum builds. As the trend matures and exhausts itself, volatility decays gradually before reverting to baseline noise. By modeling this excitation and subsequent decay, traders can systematically capture trend expansions and exit as the impulse dissipates.
2. Computing the Normalized Candle Range — 00:47
To supply a continuous input signal to the Hawkes process, we compute a normalized measure of bar volatility on logarithmic prices.
2.1 Formulation
- Data: 1-hour OHLCV candles (tested on Bitcoin).
- Logarithmic True Range: Compute the Average True Range (ATR) on log-transformed prices using a long lookback period (e.g., 2 weeks or 336 candles on the 1-hour timeframe) to reflect the baseline regime.
- Normalized Range ():
2.2 Empirical Behavior
During market tranquility, hovers near lower values. When an impulse occurs (such as the March 2020 liquidity cascade), large spikes in cluster densely together. As the selloff or rally subsides, the frequency and magnitude of large ranges taper off.
3. The Hawkes Process Formulation and Python Implementation — 01:51
3.1 Recursive Discrete Formulation
While the theoretical continuous Hawkes process involves intensity functions and integral kernels, in discrete algorithmic trading it can be evaluated as an autoregressive exponential decay model:
Where:
- is the normalized input range .
- (Kappa) is the decay parameter controlling memory length.
- represents the single-step decay factor ().
- An optional scale multiplier normalizes the output across differing parameter choices: .
3.2 Impact of the Parameter
- Small (e.g., ): Slower decay rate, longer memory, smoother trajectory, but higher lag.
- Large (e.g., ): Rapid decay rate, sensitive response to instantaneous spikes, less persistent smoothing.
Hawkes Output
▲
│ /\
│ / \ <- Fast rise on shock
│ / \
│ / \......
│ / \.... <- Slow exponential decay (Alpha = exp(-Kappa))
└──┴───────────────────────► Time
3.3 Python Implementation
import numpy as np
def hawkes_process(data: np.ndarray, kappa: float) -> np.ndarray:
"""
Computes a discrete recursive Hawkes process on an input series.
:param data: 1D numpy array of normalized input values (e.g., normalized range)
:param kappa: Decay velocity parameter
:return: 1D numpy array of Hawkes process values
"""
alpha = np.exp(-kappa)
out = np.empty(len(data))
out[:] = np.nan
for i in range(len(data)):
if np.isnan(out[i - 1]):
out[i] = data[i]
else:
# Recursive decay + new event arrival
out[i] = out[i - 1] * alpha + data[i]
# Loosely normalizes output range across different kappa values
return out * kappa
(Note: Credit is given to quant blogger "Trader with an 8", who pioneered applying Hawkes processes to signed order volume).
4. Regime Detection with Rolling Quantiles — 03:43
Raw Hawkes process values fluctuate with broader market cycles. To dynamically adapt to shifting baseline volatility, we apply rolling quantiles over a lookback window (e.g., 1 week / 168 hours):
- Upper Threshold (): 95th percentile of the Hawkes series over the lookback window. Crossing above indicates rapid volatility expansion and trend ignition.
- Lower Threshold (): 5th percentile of the Hawkes series over the lookback window. Crossing below indicates volatility exhaustion and trend conclusion.
Hawkes Value
▲
95% ┼- - - - - - - - - - - - - - - - - - - - - - (Trend Trigger: Long/Short Entry)
│ /‾‾‾\
│ / \
│ / \
5% ┼- - - -/ - - - - \- - - - - - - - - - - - - (Exit Trigger: Close Position)
│ / \________
└─────┴─────────────────────┴────────────► Time
5. End-to-End Trading Strategy & Logic — 04:14
5.1 Trading Rules
- Track Prior Consolidation: Continuously store
last_below, the timestamp index where the Hawkes process was most recently below the lower threshold. - Entry Trigger: When the Hawkes process crosses strictly above the upper threshold:
- Calculate cumulative price displacement: .
- If : Enter Long ().
- If : Enter Short ().
- Exit Trigger: When the Hawkes process crosses strictly below the lower threshold:
- Flatten position to Cash ().
- Update
last_belowto current index.
5.2 Python Strategy Engine
import numpy as np
import pandas as pd
def hawkes_trading_strategy(
close: np.ndarray,
hawkes: np.ndarray,
lookback: int = 168
) -> np.ndarray:
"""
Generates position signals based on Hawkes volatility breakouts and exhaustion exits.
"""
n = len(close)
signal = np.zeros(n)
# Calculate rolling 5% and 95% quantiles
hawkes_series = pd.Series(hawkes)
q_low = hawkes_series.rolling(lookback).quantile(0.05).to_numpy()
q_high = hawkes_series.rolling(lookback).quantile(0.95).to_numpy()
last_below = -1
for i in range(1, n):
# Position tracking and lower boundary registration
if hawkes[i] < q_low[i]:
signal[i] = 0
last_below = i
continue
# Check breakout above upper boundary
cross_above = (hawkes[i] >= q_high[i]) and (hawkes[i - 1] < q_high[i - 1])
if cross_above and last_below > 0:
price_diff = close[i] - close[last_below]
if price_diff > 0:
signal[i] = 1 # Long
elif price_diff < 0:
signal[i] = -1 # Short
else:
signal[i] = signal[i - 1] # Carry forward existing position
return signal
6. Backtest Results & Parameter Robustness — 06:19
6.1 Baseline Performance (1-Hour Bitcoin)
Tested using baseline parameters (, Quantile Lookback = hours):
- Overall Profit Factor:
- Long Win Rate: (Average trade return: )
- Short Win Rate: (Average trade return: )
- Market Exposure: Only in market of total time, preserving capital during non-trending chop.
6.2 Robustness Matrix (25 Variations)
To assess whether profitability was an artifact of curve fitting, a parameter grid was evaluated:
- values: 5 steps spanning slow to fast decay.
- Quantile Lookback: 5 steps spanning short to long horizons.
Key Finding: All 25 out of 25 parameter variations achieved a Profit Factor . This widespread stability across parameter space confirms genuine statistical edge rather than overfitted optimization.
7. Key Takeaways & Practical Recommendations — 07:35
- The Primary Edge Is in the Exit: While the Hawkes breakout entry is effective, the greatest utility of the Hawkes process lies in its exhaustion exit. As volatility decays below the lower quantile, the self-exciting impulse has expired; remaining in the position exposes capital to adverse mean reversion.
- Decouple Entry from Exit: The simple price change heuristic () can be replaced with superior trend-detection filters (e.g., Donchian breakouts, Kalman filters, or multi-scale order flow), while retaining the Hawkes lower-quantile cross as the dedicated exit engine.
- Versatility of Point Processes: Beyond candle range, the Hawkes process can be applied to order book imbalance, trade tick frequency, signed volume bursts, or liquidation flow to detect market microstructure state changes.