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

Chapter 11: Self-Exciting Behavior and Detecting the End of Price Trends


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:

  1. Mathematical Intuition of Self-Exciting Processes: Why volatility clusters and how the Hawkes process formalizes event clustering.
  2. Normalized Volatility Metric: Measuring candle range normalized by a long-term Average True Range (ATR).
  3. Discrete Hawkes Process Implementation: Recursive decay formulation using parameter κ\kappa.
  4. Dynamic Regime Thresholds: Establishing rolling quantiles (5%5\% and 95%95\%) to detect trend ignition and trend exhaustion.
  5. 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

  1. Data: 1-hour OHLCV candles (tested on Bitcoin).
  2. 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.
  3. Normalized Range (RnormR_{\text{norm}}):

Rnorm(t)=ln⁡(Hight)−ln⁡(Lowt)ATR336(t)R_{\text{norm}}(t) = \frac{\ln(\text{High}_t) - \ln(\text{Low}_t)}{\text{ATR}_{336}(t)}

2.2 Empirical Behavior

During market tranquility, RnormR_{\text{norm}} hovers near lower values. When an impulse occurs (such as the March 2020 liquidity cascade), large spikes in RnormR_{\text{norm}} 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:

yt=α⋅yt−1+xty_t = \alpha \cdot y_{t-1} + x_t

Where:

  • xtx_t is the normalized input range Rnorm(t)R_{\text{norm}}(t).
  • κ\kappa (Kappa) is the decay parameter controlling memory length.
  • α=e−κ\alpha = e^{-\kappa} represents the single-step decay factor (0<α<10 < \alpha < 1).
  • An optional scale multiplier κ\kappa normalizes the output across differing parameter choices: Ht=κ⋅ytH_t = \kappa \cdot y_t.

3.2 Impact of the κ\kappa Parameter

  • Small κ\kappa (e.g., 0.050.05): Slower decay rate, longer memory, smoother trajectory, but higher lag.
  • Large κ\kappa (e.g., 0.200.20): 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 (Q0.95Q_{0.95}): 95th percentile of the Hawkes series over the lookback window. Crossing above indicates rapid volatility expansion and trend ignition.
  • Lower Threshold (Q0.05Q_{0.05}): 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

  1. Track Prior Consolidation: Continuously store last_below, the timestamp index where the Hawkes process was most recently below the 5%5\% lower threshold.
  2. Entry Trigger: When the Hawkes process crosses strictly above the 95%95\% upper threshold:
    • Calculate cumulative price displacement: ΔP=Closet−Closelast_below\Delta P = \text{Close}_t - \text{Close}_{\text{last\_below}}.
    • If ΔP>0\Delta P > 0: Enter Long (+1+1).
    • If ΔP<0\Delta P < 0: Enter Short (−1-1).
  3. Exit Trigger: When the Hawkes process crosses strictly below the 5%5\% lower threshold:
    • Flatten position to Cash (00).
    • Update last_below to 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 (κ=0.1\kappa = 0.1, Quantile Lookback = 168168 hours):

  • Overall Profit Factor: 1.071.07
  • Long Win Rate: 58%58\% (Average trade return: +2.9%+2.9\%)
  • Short Win Rate: 49%49\% (Average trade return: +1.1%+1.1\%)
  • Market Exposure: Only in market ∼50%\sim 50\% 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 5×55 \times 5 parameter grid was evaluated:

  • κ\kappa 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 >1.00> 1.00. This widespread stability across parameter space confirms genuine statistical edge rather than overfitted optimization.


7. Key Takeaways & Practical Recommendations — 07:35

  1. 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.
  2. Decouple Entry from Exit: The simple price change heuristic (Closet−Closelast_below\text{Close}_t - \text{Close}_{\text{last\_below}}) 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.
  3. 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.

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