Sub topic 17
Application: Finding Currency Arbitrage with Logarithmic Weights
This chapter assumes you already know how Bellman-Ford relaxes edges, why the extra pass after V-1 rounds detects a negative cycle, and how predecessor arrays work. The goal here is to apply that machinery to a real problem. Exchange rates multiply along a path. Bellman-Ford adds weights along a path. A logarithm turns the first into the second.
The Problem: Profitable Loops of Trades
Currency arbitrage is a sequence of exchanges that starts and ends in the same currency and leaves you with more than you started with. Suppose 1 USD buys 0.9 EUR, 1 EUR buys 0.87 GBP, and 1 GBP buys 1.30 USD. Converting 1 USD around that loop gives:
1 × 0.9 × 0.87 × 1.30 = 1.0179 USD
That is a 1.79% profit with no risk, as long as the quotes are real and you can trade at them.
Model the market as a weighted directed graph:
- Each currency is a vertex.
- Each quoted rate r(a, b), meaning "1 unit of a buys r units of b", is a directed edge from a to b.
- A cycle is an arbitrage opportunity exactly when the product of its rates is greater than 1.
Turning Products into Sums
Bellman-Ford knows nothing about products. It detects cycles whose weight sum is negative. The reduction uses two facts about logarithms:
- log(x × y) = log x + log y, so a product of rates becomes a sum of logs.
- The logarithm is strictly increasing, so a product is greater than 1 exactly when its log is greater than 0.
Set each edge weight to w(a, b) = −log r(a, b). For a cycle with rates r₁, …, rₖ:
r₁ × … × rₖ > 1 ⟺ log r₁ + … + log rₖ > 0 ⟺ (−log r₁) + … + (−log rₖ) < 0
An arbitrage loop becomes a negative cycle. The negation matters. Without it you would be looking for positive cycles, and no algorithm in this tutorial does that.
| Rate on edge | −log(rate) | Meaning |
|---|---|---|
| r > 1 | negative | the trade gains units |
| r = 1 | 0 | neutral |
| r < 1 | positive | the trade loses units |
| cycle product > 1 | cycle sum < 0 | arbitrage |
Any logarithm base works, because changing the base scales every weight by the same positive constant and keeps every sign. The natural log is the usual choice.
Detecting a Cycle Anywhere, Not Just from One Source
Standard Bellman-Ford only finds negative cycles reachable from its source. A trader wants any profitable loop in the market. The usual fix is a virtual source: add a new vertex s with a zero-weight edge to every currency and run Bellman-Ford from s. Every vertex is now reachable, so every negative cycle is too.
You don't need to build s. After the first round from s, every real vertex has distance 0. So you can start with dist = [0.0] * n and treat that as round one already done. The augmented graph has n + 1 vertices, so it needs n rounds in total. Since one is already done, n − 1 further rounds are enough, and an n-th pass that still changes something proves a negative cycle exists.
Extracting the Cycle Itself
Knowing that a cycle exists is not enough. You need the trades. Take the vertex x that was relaxed during the n-th pass and follow predecessors back n times. A chain of n predecessor steps across n vertices must repeat a vertex, so after n steps you are on a cycle of the predecessor graph. Any cycle in the predecessor graph has negative total weight. Then walk predecessors from that vertex until you return to it, and reverse the list to get the trades in forward order.
import math
def find_arbitrage(currencies, rates, eps=1e-12):
"""Return one arbitrage cycle as a list of currency codes, or None.
rates maps (from_code, to_code) -> units of to_code per unit of from_code.
"""
index = {c: i for i, c in enumerate(currencies)}
n = len(currencies)
edges = [(index[a], index[b], -math.log(r)) for (a, b), r in rates.items()]
dist = [0.0] * n # same as one round from a virtual source
pred = [None] * n
x = None
for _ in range(n): # n-1 normal rounds plus one detection pass
x = None
for u, v, w in edges:
if dist[u] + w < dist[v] - eps:
dist[v] = dist[u] + w
pred[v] = u
x = v
if x is None: # nothing changed: no negative cycle
return None
# x was relaxed in the n-th pass; step back n times to land on the cycle
for _ in range(n):
x = pred[x]
cycle = [x]
v = pred[x]
while v != x:
cycle.append(v)
v = pred[v]
cycle.append(x)
cycle.reverse()
return [currencies[i] for i in cycle]
def cycle_product(cycle, rates):
product = 1.0
for a, b in zip(cycle, cycle[1:]):
product *= rates[(a, b)]
return product
currencies = ["USD", "EUR", "GBP", "JPY"]
rates = {
("USD", "EUR"): 0.9, ("EUR", "USD"): 1.1,
("EUR", "GBP"): 0.87, ("GBP", "EUR"): 1.14,
("GBP", "USD"): 1.30, ("USD", "GBP"): 0.76,
("USD", "JPY"): 150, ("JPY", "USD"): 0.0066,
}
cycle = find_arbitrage(currencies, rates)
print(cycle) # ['USD', 'EUR', 'GBP', 'USD']
print(round(cycle_product(cycle, rates), 4)) # 1.0179
rates[("GBP", "USD")] = 1.27 # remove the opportunity
print(find_arbitrage(currencies, rates)) # NoneThe early exit from the earlier chapter appears here as return None. If a full pass changes nothing, distances are final and no negative cycle exists.
Using Floyd-Warshall Instead
With only a few dozen currencies, Floyd-Warshall on the same −log weights also works. After it runs, any vertex i with dist[i][i] < 0 lies on an arbitrage loop. The cost is O(V³) against Bellman-Ford's O(V·E). A full rate table is a dense graph with E ≈ V², so Bellman-Ford costs about O(V³) as well and the asymptotic difference disappears. Floyd-Warshall gives you every pairwise best conversion rate as a by-product. Extracting a clean cycle from its next-hop matrix is awkward, though, because the earlier chapter's warning applies: next-hop paths are unreliable once a negative cycle exists. Bellman-Ford's predecessor walk is the simpler way to get the actual trades.
Gotchas in Practice
Floating-point noise
Logarithms of real-world rates are not exact. A cycle whose true product is exactly 1 can come out with a log sum of −1e-16, which looks like an arbitrage. That is why the code compares against dist[v] - eps. Choose eps to match the smallest profit worth acting on. A threshold tied to transaction costs, such as 1e-6, is often more useful than a value near machine precision.
Fees and spreads
Quoted mid-market rates overstate what you can get. Use the actual executable rate for each direction: the bid in one direction and the ask in the other, after fees. A flat percentage fee f multiplies each rate by (1 − f), which adds −log(1 − f) to every edge weight. This positive penalty grows with cycle length, so it removes long, thin opportunities first.
Which cycle you get
The algorithm returns some negative cycle, not the most profitable one. Finding the most profitable simple cycle is as hard as the longest simple path problem, which is NP-hard. Cycle detection is still the right tool when the goal is to spot that a market is mispriced.
Stale and partial data
Rates change by the millisecond, and a missing pair simply means a missing edge. Detection is only as good as the snapshot it runs on. The extra relaxation pass costs little compared with the cost of acting on an outdated quote.
Exercises
Exercise
Why must the edge weight be −log(rate) rather than log(rate) for Bellman-Ford to find arbitrage?
Show answer
An arbitrage cycle has a rate product greater than 1, so the sum of log(rate) around it is positive. Bellman-Ford detects negative cycles, not positive ones. Negating each log flips the sign, so a profitable cycle has a negative total weight and the standard detection pass finds it.
Exercise
The code starts with dist = [0.0] * n and loops n times instead of n − 1. Explain why that loop count is correct.
Show answer
Zero initial distances are what you get after one round from a virtual source with zero-weight edges to every currency. The augmented graph has n + 1 vertices and needs n rounds. One is already done, so n − 1 rounds remain, and the n-th iteration is the detection pass. A change during that pass means a negative cycle.
Exercise
A three-trade cycle has a mid-market product of 1.004, and each trade charges a 0.2% fee. Is it still profitable?
Show answer
No. The effective product is 1.004 × 0.998³ ≈ 1.004 × 0.99401 ≈ 0.99801, which is less than 1. In log terms, the fee adds about 3 × 0.002 = 0.006 to the cycle weight, which outweighs the −log(1.004) ≈ −0.004 gain.