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

Chapter 7: Applying Graph Theory to Algorithmic Trading (Time Series Visibility Graphs)


Chapter Overview — 00:00

Time series analysis and graph (network) theory are traditionally distinct scientific domains. Time series analysis models sequences of observations ordered chronologically, while graph theory analyzes topological networks of nodes and relational links.

Visibility graphs create a mathematical bridge between these two disciplines by converting a sequential financial time series into a complex topological network. Once converted, the full analytical arsenal of network science—such as degree distributions, assortativity, clustering coefficients, and shortest path lengths—can be applied to financial prices.

Because the vast majority of algorithmic traders rely on standard indicators (moving averages, oscillators, order book heatmaps), visibility graph metrics represent an under-exploited quantitative domain with minimal algorithmic crowding. This chapter covers:

  1. Converting price series into Natural Visibility Graphs (NVG) and Horizontal Visibility Graphs (HVG).
  2. Resolving topological asymmetry by constructing dual positive and inverted price graphs (PP vs. −P-P).
  3. Measuring market structure via the Average Shortest Path Length using Python's ts2vg and networkx.
  4. Deploying a walk-forward indicator trading rule that generates alpha during regimes where traditional strategies fail.

1. Transforming Time Series into Graphs — 01:33

1.1 Geometric Line-of-Sight Intuition

Visualizing price bars as vertical pillars on a landscape reveals the core mechanism:

  • Each price bar xix_i at time tit_i represents a node in the graph.
  • An edge (link) connects node ii and node jj if and only if there is an uninterrupted straight line of sight between the tops of the two bars.
  • If any intermediate bar xkx_k (where ti<tk<tjt_i < t_k < t_j) protrudes above the line connecting bar ii and bar jj, the line of sight is blocked, and no edge exists.
 Price
   ▲
 8 │         [Bar 3]
 7 │            │
 6 │   [Bar 1]  │  • • Line of sight blocked by Bar 3 • •  [Bar 5]
 5 │      │     │                                              │
 4 │      │   [Bar 2]                                       [Bar 4]
 3 │      │     │                                              │
───┴──────┴─────┴──────────────────────────────────────────────┴─────► Time
       Node 1 ── Node 2 (Visible)
       Node 1 ── Node 3 (Visible)
       Node 1 ── Node 5 (BLOCKED by Bar 3 -> No edge)

Formally, for a Natural Visibility Graph (NVG), two data points (ta,ya)(t_a, y_a) and (tb,yb)(t_b, y_b) share an edge if every intermediate point (tc,yc)(t_c, y_c) satisfies:

yc<yb+(ya−yb)tb−tctb−tay_c < y_b + (y_a - y_b) \frac{t_b - t_c}{t_b - t_a}

1.2 Mathematical Encoding: The Adjacency Matrix — 02:37

The resulting network is an undirected graph encoded as a symmetric N×NN \times N adjacency matrix AA:

  • Ai,j=1A_{i, j} = 1 if node ii and node jj have clear visibility.
  • Ai,j=0A_{i, j} = 0 if visibility is occluded.
  • Adjacent sequential bars (j=i±1j = i \pm 1) always have an edge (Ai,i+1=1A_{i, i+1} = 1) because no intermediate bar can exist between them.

1.3 High-Performance Implementation with ts2vg — 03:06

Pure Python graph construction scales as O(N2)O(N^2) and is too slow for rolling backtests. The C-optimized Cython package ts2vg provides near-instant conversion:

import numpy as np
from ts2vg import NaturalVG

# Sample price series
prices = np.array([2.5, 3.1, 1.8, 4.0, 2.2, 3.5])

# Build graph and export adjacency matrix
vg = NaturalVG()
vg.build(prices)
adj_matrix = vg.adjacency_matrix()

1.4 Natural vs. Horizontal Visibility Graphs — 04:26

  • Natural Visibility Graph (NVG): Uses tilted sightlines following exact linear geometry. Retains subtle slope dynamics.
  • Horizontal Visibility Graph (HVG): Requires a purely horizontal line of sight (yc<min⁡(ya,yb)y_c < \min(y_a, y_b)). Faster to compute and analytically simpler, but prunes long-distance diagonal sightlines across trending phases.

2. Resolving Topological Asymmetry: Dual Inverted Graphs — 04:55

Standard visibility graphs construct lines of sight exclusively from above looking across peaks:

  • High price spikes act as dominant "hubs" that see far across the series.
  • Deep market dips (troughs, capitulation wicks) are occluded and remain structurally isolated.

This produces an incomplete, upside-biased picture of market structure.

The Negative Series Solution

To measure trough geometry and support structures, invert the price series prior to graph construction:

Ppos=P⟺Pneg=−PP_{\text{pos}} = P \quad \Longleftrightarrow \quad P_{\text{neg}} = -P

Building separate visibility graphs for PposP_{\text{pos}} and PnegP_{\text{neg}} yields two fundamentally distinct adjacency topologies:

  • G(Ppos)G(P_{\text{pos}}) quantifies resistance visibility and peak clustering.
  • G(Pneg)G(P_{\text{neg}}) quantifies support visibility and trough clustering.

3. Network Metric: Average Shortest Path Length — 05:32

The shortest path length d(i,j)d(i, j) between node ii and node jj is the minimum number of edges required to traverse from one to the other:

  • If a direct sightline exists: d(i,j)=1d(i, j) = 1.
  • If traversing requires an intermediate hub: d(i,j)=2d(i, j) = 2.

The Average Shortest Path Length (LL) averages this distance across all unique node pairs:

L=1N(N−1)∑i≠jd(i,j)L = \frac{1}{N(N-1)} \sum_{i \ne j} d(i, j)

import networkx as nx

# Convert ts2vg graph to NetworkX
nx_graph = vg.as_networkx()
avg_path_length = nx.average_shortest_path_length(nx_graph)

Structural Meaning of Path Extremes — 07:32

Path Length MetricTopological StructurePrice Action Interpretation
Max LL (e.g., 3.543.54)Highly sparse graph with minimal leapfrogging links; traverses chain-like from node to node.Convex trend profile where intermediate bars block sightlines between distant extremes.
Min LL (e.g., 1.121.12)Dense "small-world" network; virtually every node connects directly to central hubs.Concave consolidation or bowl shape where a dominant peak/trough is visible to nearly all bars.

4. Constructing a Visibility Trading Strategy — 08:04

       Hourly Prices ──► Rolling Window (12 bars)
                             │
            ┌────────────────┴────────────────┐
            ▼                                 ▼
       $G(P_{\text{pos}})$             $G(P_{\text{neg}})$
            │                                 │
            ▼                                 ▼
     $L_{\text{pos}}$                  $L_{\text{neg}}$
            │                                 │
            └────────────────┬────────────────┘
                             ▼
                Signal = Long if $L_{\text{pos}} > L_{\text{neg}}$
                         Short if $L_{\text{pos}} < L_{\text{neg}}$

4.1 System Rules & Signal Formulation

Using hourly Bitcoin (BTC/USD) data with a rolling lookback window of 12 candles:

  1. Compute LposL_{\text{pos}} from the rolling 12-bar window of raw closing prices.
  2. Compute LnegL_{\text{neg}} from the rolling 12-bar window of inverted closing prices.
  3. Execution Rule: Signalt={+1 (Long)if Lpos>Lneg−1 (Short)if Lpos≤Lneg\text{Signal}_t = \begin{cases} +1 \text{ (Long)} & \text{if } L_{\text{pos}} > L_{\text{neg}} \\ -1 \text{ (Short)} & \text{if } L_{\text{pos}} \le L_{\text{neg}} \end{cases}

4.2 Empirical Findings & Performance Characteristics — 08:35

  • Stationarity: Unlike raw prices, both LposL_{\text{pos}} and LnegL_{\text{neg}} oscillate within stable bounded regimes, behaving as stationary technical indicators.
  • Regime Diversity: The strategy exhibits robust performance during sideways or choppy market phases where standard momentum and trend-following strategies suffer repeated whipsaws.
  • Parameter Sensitivity: Evaluating a heat map of lookback windows confirms that the 12-period setting is stable across neighboring lookbacks (8 to 16). At excessively large lookbacks (>40> 40), performance decays as short-term graph visibility becomes diluted by distant historical bars.

[!WARNING] This prototype system is always 100% invested and does not include execution slippage or maker/taker fees. It is not intended as a plug-and-play retail strategy, but rather as an alpha-generating indicator for multi-factor models.


5. Key Takeaways & Practical Implementation Rules

  1. Bridge Time Series and Network Science: Visibility graphs map non-linear sequential price dynamics into well-defined topological networks.
  2. Always Pair Positive and Negative Graphs: Natural visibility from above misses support and valley structures; evaluating G(P)G(P) alongside G(−P)G(-P) provides complete structural symmetry.
  3. Short Path Length = Dense Hub Visibility: Low path lengths signal broad visibility across a central anchor point; high path lengths indicate segmented, monotonic drift.
  4. Optimal Lookbacks are Compact: Use short rolling windows (e.g., 10–20 bars on hourly data) to preserve local geometric relevance.
  5. Vast Unexplored Feature Space: Beyond average shortest path length, network science provides degree centrality, modularity, assortativity, and clustering coefficients as novel features for quantitative machine learning pipelines.

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