Objective
Represent a graph appropriately, pick the right search for the question (BFS, DFS, topological order, Dijkstra, Bellman–Ford), state its complexity in and , and apply Bellman–Ford to the classic quant question: is there an arbitrage cycle in this table of exchange rates?
Representations
| Adjacency list | Adjacency matrix | |
|---|---|---|
| Space | ||
| Is there an edge ? | , or with a set per node | |
| Iterate neighbours of | ||
| Best for | sparse graphs, almost everything | dense graphs, small , all-pairs algorithms |
In Python an adjacency list is dict[node, list[node]], or list[(neighbour, weight)] for weighted edges. A matrix of exchange rates among 10 currencies is naturally dense (), whereas a graph of instruments and their dependencies is sparse.
BFS and DFS
Breadth-first search explores in rings of increasing distance using a queue. In an unweighted graph the first time BFS reaches a node is along a shortest path, so it computes hop distances in .
from collections import deque
def bfs_dist(adj, src):
dist = {src: 0}
q = deque([src])
while q:
u = q.popleft()
for v in adj[u]:
if v not in dist: # mark when enqueued, not when popped
dist[v] = dist[u] + 1
q.append(v)
return dist
adj = {"A": ["B", "C"], "B": ["D"], "C": ["D", "E"], "D": ["F"], "E": ["F"], "F": []}
print(bfs_dist(adj, "A")) # {'A': 0, 'B': 1, 'C': 1, 'D': 2, 'E': 2, 'F': 3}
Depth-first search goes as deep as possible before backtracking (recursion, or an explicit stack). It is the tool for connectivity, counting components (islands in a grid), and cycle detection in a directed graph: colour nodes white, grey (on the current path) and black (finished); meeting a grey node means a back edge, hence a cycle. Also . For deep graphs in Python, use an explicit stack: the default recursion limit is about 1000.
Topological sort
A DAG (directed acyclic graph) of dependencies, such as "the vol surface needs prices and rates; risk needs the vol surface", must be evaluated in an order where every node comes after everything it depends on. Kahn's algorithm: count each node's incoming edges, start with the nodes that have none, and each time you output a node, decrement its successors' counts and release any that reach zero.
from collections import defaultdict, deque
def topo_sort(deps):
"""deps[u] = nodes that need u (edges u -> v)."""
indeg = defaultdict(int)
for u in deps:
for v in deps[u]:
indeg[v] += 1
ready = deque(u for u in deps if indeg[u] == 0)
order = []
while ready:
u = ready.popleft()
order.append(u)
for v in deps[u]:
indeg[v] -= 1
if indeg[v] == 0:
ready.append(v)
if len(order) < len(deps):
raise ValueError("cycle: no valid order")
return order
deps = {"prices": ["returns", "vol_surface"], "returns": ["risk"],
"rates": ["vol_surface", "risk"], "vol_surface": ["risk"],
"risk": ["report"], "report": []}
print(topo_sort(deps))
# ['prices', 'rates', 'returns', 'vol_surface', 'risk', 'report']
. If some nodes never reach in-degree zero, they lie on or behind a cycle, so no valid order exists, which doubles as a cycle detector. The order is generally not unique; any order consistent with the edges is correct. Build systems, spreadsheet recalculation and pricing graphs all run on this.
Dijkstra's algorithm
With non-negative edge weights, the unsettled node with the smallest tentative distance cannot be improved later: any other route to it passes through a node at least as far away and only adds non-negative weight. Dijkstra repeatedly settles that node and relaxes its edges. A heap finds it; Python's heapq has no decrease-key, so push a fresh entry and skip stale ones on pop (lazy deletion).
import heapq, math
def dijkstra(graph, src):
"""graph[u] = list of (v, weight) with weight >= 0."""
dist = {src: 0}
heap = [(0, src)]
while heap:
d, u = heapq.heappop(heap)
if d > dist[u]:
continue # stale entry
for v, w in graph[u]:
nd = d + w
if nd < dist.get(v, math.inf):
dist[v] = nd
heapq.heappush(heap, (nd, v))
return dist
g = {"S": [("A", 4), ("B", 1)], "B": [("A", 2), ("C", 5)], "A": [("C", 1)], "C": []}
print(dijkstra(g, "S")) # {'S': 0, 'A': 3, 'B': 1, 'C': 4}
The direct edge to A costs 4, but costs 3, and then gives 4, beating at 6. Cost: each edge pushes at most once, so .
Negative edges break it. Take weight 2, weight 3, weight , weight 1. Dijkstra settles A at distance 2 before it ever looks at B, and reports C at 3. The true distances are A and C . (The lazy-deletion code above happens to repair this small case by expanding A a second time, but in general re-expansion can take exponential time, and the correctness argument no longer holds.) For negative weights use Bellman–Ford; for a DAG, relax edges in topological order, which handles negative weights in .
Bellman–Ford and negative cycles
Bellman–Ford relaxes every edge, times. A shortest path with no cycles has at most edges, and after round every shortest path of at most edges is correct, so rounds suffice: in total. If a further round still improves some distance, the graph has a negative cycle reachable from the source, because without one nothing could improve.
From arbitrage to negative cycles. Let be the units of currency one unit of buys. A round trip is profitable when the product of the rates exceeds 1. Taking logs turns products into sums, and negating flips the inequality:
So give each edge weight : an arbitrage cycle is exactly a negative cycle. Starting every distance at 0 (as if a virtual source had a zero-weight edge to every node) finds a negative cycle anywhere in the graph. To recover it, record predecessors; a node improved in round leads back into the cycle after predecessor steps.
Worked example
finding a currency cycle
Rates (units received per unit given): USD→EUR 0.92, EUR→USD 1.08, EUR→GBP 0.86, GBP→EUR 1.16, GBP→USD 1.27, USD→GBP 0.78, USD→JPY 150, JPY→USD 0.0066. Is there an arbitrage? Find it with Bellman–Ford.
Show solutionHide solution
Two-legged round trips first. USD↔EUR gives , EUR↔GBP , USD↔GBP , USD↔JPY : all below 1, as the bid–ask spread guarantees.
Run Bellman–Ford on rates.
import math
def find_arbitrage(currencies, rates):
"""rates[(a, b)] = units of b per unit of a. Returns a profitable cycle, or None."""
idx = {c: i for i, c in enumerate(currencies)}
n = len(currencies)
edges = [(idx[a], idx[b], -math.log(r)) for (a, b), r in rates.items()]
dist, pred = [0.0] * n, [-1] * n # virtual source: every node at 0
for _ in range(n - 1):
for u, v, w in edges:
if dist[u] + w < dist[v] - 1e-12:
dist[v], pred[v] = dist[u] + w, u
for u, v, w in edges: # round n: any improvement => negative cycle
if dist[u] + w < dist[v] - 1e-12:
pred[v] = u
x = v
for _ in range(n): # step back n times to land on the cycle
x = pred[x]
cycle, y = [x], pred[x]
while y != x:
cycle.append(y)
y = pred[y]
cycle.append(x)
return [currencies[i] for i in reversed(cycle)]
return None
rates = {("USD", "EUR"): 0.92, ("EUR", "USD"): 1.08, ("EUR", "GBP"): 0.86,
("GBP", "EUR"): 1.16, ("GBP", "USD"): 1.27, ("USD", "GBP"): 0.78,
("USD", "JPY"): 150.0, ("JPY", "USD"): 0.0066}
print(find_arbitrage(["USD", "EUR", "GBP", "JPY"], rates))
# ['USD', 'EUR', 'GBP', 'USD']
Check. : one dollar becomes about 1.0048 dollars, a 48 basis-point edge before costs. In log terms the cycle weight is . The reverse loop, , loses. If GBP→USD were 1.25 instead, the cycle product would be and the function would return None.
What to add out loud. The tolerance stops floating-point noise from reporting fake cycles. Real arbitrage must survive fees, the time to execute each leg and size limits. And with currencies and a full rate table, , so Bellman–Ford is , which is trivial for a few dozen currencies.
Knowledge check
You need the fewest trades (hops) to convert one asset into another, where every allowed conversion counts as one hop. Which algorithm is the natural choice?
Knowledge check
Why are arbitrage edges weighted by rather than by or ?
Knowledge check
Kahn's algorithm finishes having output only 7 of a graph's 10 nodes. What can you conclude?
Knowledge check
What is the complexity of Bellman–Ford with V nodes and E edges, including the extra round that detects negative cycles?
Key takeaways
- Adjacency lists ( space) suit sparse graphs; matrices suit dense ones such as a full rate table.
- BFS gives unweighted shortest paths; DFS gives connectivity and, with grey/black colouring, directed cycle detection; both are .
- Kahn's topological sort orders a dependency DAG in and reports a cycle when nodes are left over.
- Dijkstra needs non-negative weights and runs in with a lazy heap; one negative edge can make it wrong.
- Bellman–Ford is and detects negative cycles; with weights , a negative cycle is a currency arbitrage.
Finished reading?
Answer the 4 knowledge checks to complete this lesson (0 done).