Chapter 7: Applying Graph Theory to Algorithmic Trading (Time Series Visibility Graphs)
- Source: Applying Graph Theory to Algorithmic Trading | Time Series Visibility Graphs
- Channel: NeuroTrader
- Duration: 9:52
- Language: English
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:
- Converting price series into Natural Visibility Graphs (NVG) and Horizontal Visibility Graphs (HVG).
- Resolving topological asymmetry by constructing dual positive and inverted price graphs ( vs. ).
- Measuring market structure via the Average Shortest Path Length using Python's
ts2vgandnetworkx. - 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 at time represents a node in the graph.
- An edge (link) connects node and node if and only if there is an uninterrupted straight line of sight between the tops of the two bars.
- If any intermediate bar (where ) protrudes above the line connecting bar and bar , 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 and share an edge if every intermediate point satisfies:
1.2 Mathematical Encoding: The Adjacency Matrix — 02:37
The resulting network is an undirected graph encoded as a symmetric adjacency matrix :
- if node and node have clear visibility.
- if visibility is occluded.
- Adjacent sequential bars () always have an edge () because no intermediate bar can exist between them.
1.3 High-Performance Implementation with ts2vg — 03:06
Pure Python graph construction scales as 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 (). 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:
Building separate visibility graphs for and yields two fundamentally distinct adjacency topologies:
- quantifies resistance visibility and peak clustering.
- quantifies support visibility and trough clustering.
3. Network Metric: Average Shortest Path Length — 05:32
The shortest path length between node and node is the minimum number of edges required to traverse from one to the other:
- If a direct sightline exists: .
- If traversing requires an intermediate hub: .
The Average Shortest Path Length () averages this distance across all unique node pairs:
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 Metric | Topological Structure | Price Action Interpretation |
|---|---|---|
| Max (e.g., ) | 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 (e.g., ) | 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:
- Compute from the rolling 12-bar window of raw closing prices.
- Compute from the rolling 12-bar window of inverted closing prices.
- Execution Rule:
4.2 Empirical Findings & Performance Characteristics — 08:35
- Stationarity: Unlike raw prices, both and 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 (), 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
- Bridge Time Series and Network Science: Visibility graphs map non-linear sequential price dynamics into well-defined topological networks.
- Always Pair Positive and Negative Graphs: Natural visibility from above misses support and valley structures; evaluating alongside provides complete structural symmetry.
- Short Path Length = Dense Hub Visibility: Low path lengths signal broad visibility across a central anchor point; high path lengths indicate segmented, monotonic drift.
- Optimal Lookbacks are Compact: Use short rolling windows (e.g., 10–20 bars on hourly data) to preserve local geometric relevance.
- 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.