Currency Arbitrage Detection and Cycle Recovery
Medium · Software Engineering Fundamentals · Software Engineer · Onsite
Problem Statement
Foreign-exchange venues publish directed spot quotes as (source, target, rate) tuples, where selling 1 unit of currency source yields rate units of currency target. A currency arbitrage loop is a closed walk of directed conversions that begins with 1 unit of some currency, steps through one or more quoted pairs, and returns to that initial currency holding strictly more than 1 unit.
Implement two functions over a batch of quotes:
has_arbitrage(quotes: List[Quote], margin: float = DEFAULT_MARGIN) -> bool— ReturnTrueif at least one qualifying profitable conversion loop exists anywhere in the market, andFalseotherwise.find_arbitrage(quotes: List[Quote], margin: float = DEFAULT_MARGIN) -> Optional[List[str]]— Return one qualifying simple conversion loop as currency tickers in execution order[c_0, c_1, ..., c_L]withc_0 == c_Land distinct intermediate currenciesc_0, ..., c_{L-1}, orNonewhen no qualifying loop exists.
Your implementation must obey these market and numerical rules:
- Directed quotes only: A tuple
(A, B, r)permits exchangingAintoBat multiplierr; never synthesize a reverse trade(B, A, 1 / r)unless(B, A, ...)is explicitly present inquotes. - Zero flat fees and best-venue selection: Trades scale linearly for any notional size without fixed per-trade charges. When
quotescontains multiple entries for the same directed pair(A, B), always use the largest quotedrate. - Per-hop numerical tolerance (
margin): To prevent IEEE-754 rounding noise on fair cross-rates from registering as phantom profit, a simple loop ofLconversions with best ratesr_1, r_2, ..., r_Lqualifies only when bothr_1 * r_2 * ... * r_L > exp(L * margin)(defaultDEFAULT_MARGIN = 1e-9) and the true product strictly exceeds1.0. - Whole-market search and clean cycle output: Detect winning loops even in disconnected currency islands that cannot be reached from the first currency in
quotes. Any returned list[c_0, c_1, ..., c_0]must contain strictly the simple cycle itself—no entry path leading into the loop and no dead-end tail branching out of it. When multiple loops or cyclic rotations qualify, returning any one of them is valid. - Input validation: Raise
ValueErrorifmarginis not a strictly positive finite float (0 < margin < inf) or if any quote has aratethat is zero, negative,NaN, or infinite.
Examples
Example 1
quotes = [
("CAD", "AUD", 0.80),
("AUD", "SGD", 0.95),
("SGD", "CAD", 1.40),
("AUD", "CAD", 1.20),
("SGD", "AUD", 1.02),
("CAD", "SGD", 0.70),
]
has_arbitrage(quotes) # True
find_arbitrage(quotes) # ["CAD", "AUD", "SGD", "CAD"] (or a cyclic rotation in the same order)
Walk-through: Trading 1 CAD -> 0.80 AUD -> 0.80 * 0.95 = 0.76 SGD -> 0.76 * 1.40 = 1.064 CAD produces a 6.4% gain, easily clearing exp(3 * 1e-9). Every two-leg round trip (0.96, 0.969, 0.98) and the opposite three-leg direction (0.70 * 1.02 * 1.20 = 0.8568) lose money.
Example 2
quotes = [
("CHF", "NOK", 12.0),
("NOK", "SEK", 0.98),
("CHF", "SEK", 11.5),
("SEK", "CHF", 0.084),
]
has_arbitrage(quotes) # False
find_arbitrage(quotes) # None
Walk-through: Only two directed cycles exist: CHF -> NOK -> SEK -> CHF multiplies to 12.0 * 0.98 * 0.084 = 0.98784 < 1, and CHF -> SEK -> CHF multiplies to 11.5 * 0.084 = 0.966 < 1. Reverse quotes such as SEK -> NOK are absent and cannot be inferred.
Example 3
quotes = [
("MXN", "BRL", 0.30),
("NZD", "DKK", 4.10),
("NZD", "DKK", 4.25),
("DKK", "NZD", 0.24),
]
has_arbitrage(quotes) # True
find_arbitrage(quotes) # ["NZD", "DKK", "NZD"] (or ["DKK", "NZD", "DKK"])
Walk-through: Although "MXN" appears first and leads only to a dead end "BRL", the separate NZD/DKK island has two quotes for NZD -> DKK. Picking the stronger quote 4.25 gives 4.25 * 0.24 = 1.02 > 1.0, and "MXN"/"BRL" do not appear in the returned cycle.
Constraints
0 <= len(quotes) <= 10^4, with up to several hundred distinct currency tickers.- Currency tickers are non-empty strings.
- Valid
rateandmarginvalues are finite floats strictly greater than0.0(including extreme positive floats that may approach IEEE-754 exponent bounds); non-positive,NaN, or infinite numbers must raiseValueError. - Target time complexity is
O(Q + V * E)forQquotes,Vdistinct currencies, andEdistinct directed pairs.
Step-by-step walkthrough
Pin down the market rules and function contract
Before writing code, settle every boundary condition in the specification:
- Directed quotes only: A quote
("CAD", "AUD", 0.80)lets us exchange1CAD for0.80AUD, and implies nothing about trading AUD back into CAD. Synthesizing a reverse quote1 / 0.80 = 1.25ignores dealer spreads and fabricates nonexistent trades. - Zero flat fees, linear scaling: Every conversion scales proportionally for any notional size without fixed per-hop charges.
- Duplicate directed pairs: When several venues quote the same pair
src -> dst, retain only the largest rate because a rational trader always picks the highest payout on that leg. - Per-hop floating-point margin: Require every leg to clear a small positive
margin(default1e-9) so IEEE-754 log-rounding noise never triggers phantom arbitrage. - Clean simple cycle output: Return any simple winning loop
[c0, c1, ..., c0]in forward execution order with zero lead-in prefix or trailing branch, orNonewhen none exists. - Scale and validation: With
Vcurrencies andEunique directed pairs (E <= V^2), anO(V * E)pass comfortably handles hundreds of currencies in Python. Non-positive,NaN, or infinite rates or margins raiseValueError.
- Directed quotes only: A quote
Turn rate multiplication into additive edge weights
Represent each currency as a vertex in a directed graph and each quote
(src, dst, rate)as a directed edgesrc -> dst. Starting with1unit ofc0and trading around a loopc0 -> c1 -> ... -> cL = c0with ratesr1, r2, ..., rLproduces an ending balance equal to the productr1 * r2 * ... * rL. Arbitrage exists whenever that product exceeds1.Why not enumerate all simple directed cycles and multiply their rates directly? On a dense market of
Vcurrencies, the count of simple directed cycles issum_{k=2..V} C(V, k) * (k - 1)!— already1.1million atV = 10and2.6 * 10^11atV = 15.Shortest-path algorithms combine edges by addition, not multiplication. Taking the natural logarithm converts products into sums, and negating flips
> 0into< 0:r1 * r2 * ... * rL > 1 <=> log(r1 * r2 * ... * rL) > log(1) = 0 <=> log(r1) + log(r2) + ... + log(rL) > 0 <=> (-log(r1)) + (-log(r2)) + ... + (-log(rL)) < 0Assigning each directed edge
u -> vthe weightw = -log(rate)turns a winning currency loop into a negative-weight cycle (a closed directed loop whose edge weights sum to less than zero):Quotes: CAD -> AUD (0.80) AUD -> SGD (0.95) SGD -> CAD (1.40) Weights: -log(0.80) = +0.2231 -log(0.95) = +0.0513 -log(1.40) = -0.3365 Cycle sum: 0.2231 + 0.0513 - 0.3365 = -0.0620 < 0 True gain: 0.80 * 0.95 * 1.40 = 1.064 = exp(+0.0620) > 1 (a 6.4% profit!)Filter out floating-point rounding noise with a per-hop margin
64-bit floating-point logarithms round at roughly
1e-16. Watch what happens on a completely fair, break-even pair0.80and1.25:0.80 * 1.25 == 1.0 (exact zero profit) -log(0.80) + (-log(1.25)) == -5.5511e-17 < 0 (phantom negative cycle!)Without a numerical buffer, a strict
< 0cycle check would claimCAD -> AUD -> CADprints free money!Adding a small positive
margin(1e-9by default) to every edge weight eliminates rounding false positives:weight = -log(rate) + marginAround a loop of
Lconversions, the shifted weights sum below0if and only if:sum(-log(r_i) + margin) < 0 <=> sum(log(r_i)) > L * margin <=> r1 * r2 * ... * rL > exp(L * margin) ≈ 1 + L * 1e-9Think of
marginas a tiny1e-9proportional haircut per hop: seven orders of magnitude above 64-bit rounding error (~1e-16), yet five orders of magnitude smaller than one basis point (1e-4=0.01%).Build the currency graph and keep best venue rates
Graph arrays are cleanest when vertices are indexed
0 .. V - 1rather than strings._build_graphvalidates each rate, assigns integer IDs in order of first appearance, and retains the maximum rate per(src_id, dst_id)pair:from typing import Dict, List, Optional, Tuple import math Quote = Tuple[str, str, float] DEFAULT_MARGIN = 1e-9 def _build_graph(quotes: List[Quote]) -> Tuple[List[str], Dict[Tuple[int, int], float]]: """Assign integer IDs 0..V-1 to currencies and keep the highest rate per directed pair.""" # currency_names: list[str] mapping integer vertex ID -> currency code, e.g. ["CAD", "AUD"] currency_names: List[str] = [] # currency_to_id: dict[str, int] mapping currency code -> integer vertex ID currency_to_id: Dict[str, int] = {} # best_rate: dict[(src_id, dst_id), float] storing the highest quoted rate per directed edge best_rate: Dict[Tuple[int, int], float] = {} for src, dst, rate in quotes: # rate > 0 is also False for NaN, and isfinite rejects +inf. if not (rate > 0 and math.isfinite(rate)): raise ValueError( f"rate for {src}->{dst} must be a positive finite number, got {rate!r}" ) for code in (src, dst): if code not in currency_to_id: currency_to_id[code] = len(currency_names) currency_names.append(code) directed_pair = (currency_to_id[src], currency_to_id[dst]) # If multiple venues quote the same directed pair, a trader always takes the highest rate. if directed_pair not in best_rate or rate > best_rate[directed_pair]: best_rate[directed_pair] = rate return currency_names, best_rateFind negative cycles across all components with Bellman-Ford
Dijkstra's algorithm breaks here because
-log(rate)is negative wheneverrate > 1. Instead we run the Bellman-Ford algorithm, repeatedly relaxing every edge (if dist[u] + weight < dist[v]: dist[v] = dist[u] + weight).Watch out for a classic pitfall: textbook Bellman-Ford sets
dist[0] = 0anddist[others] = +inf, which only explores vertices reachable from vertex0. In Example 3,MXN -> BRLis a dead-end component whileNZD <-> DKKforms an isolated profitable island — starting only atMXNwould missNZD <-> DKKcompletely!Initializing
dist = [0.0] * num_currenciesfor every vertex simultaneously acts like attaching a virtual start nodeSwith a0-weight edge to every currency:0 [MXN] ──> [BRL] +───> [S] ─+ [NZD] ──> [DKK] +───> ^ | 0 +─────────+ (isolated winning loop still reached from S!)Every simple path from
Straverses at mostV - 1currency edges. When no negative cycle exists, all distances settle withinV - 1passes. If any vertex still drops during passV, a negative cycle must exist — and if an earlier pass changes nothing, we returnNoneimmediately.Step off any outgoing tail to isolate the cycle
When pass
Vlowersdist[last_updated], mustlast_updatedlie on the negative cycle itself? No! Look at what happens when a losing chain branches out of a profitableCAD <-> AUDloop:+────── (-0.18) ──────+ v | [CAD] ─── (+0.05) ───> [AUD] ──> [SGD] ──> [CHF] ──> [SEK] |<─── negative cycle ───>| |<── outgoing tail ──>|Each lap around
CAD <-> AUDlowersdist[AUD], and that decrease cascades down the tail intoSGD,CHF, andSEK. In pass5,last_updatedcan beSEK— even thoughSEKhas zero outgoing edges!Notice where the
predecessorpointers lead (SEK -> CHF -> SGD -> AUD <-> CAD): they walk backward against the trade arrows, straight back into the negative cycle that fed the drop. WithVvertices total, stepping backwardVtimes fromlast_updatedis guaranteed (by the pigeonhole principle) to exit any tail and land on a vertexcycle_startinside the cycle.From
cycle_start, followpredecessoruntil returning tocycle_start, then.reverse()the list into forward conversion order. Finally,_is_cycle_profitablemultiplies the actual quoted rates around the loop to verify a product strictly above1.0— falling back tomath.frexp(rate = mantissa * 2^exp) if extreme magnitudes like1e-200 * 1e-200would underflow 64-bit floats mid-loop:from typing import Dict, List, Tuple import math def _is_cycle_profitable( best_rate: Dict[Tuple[int, int], float], cycle: List[int] ) -> bool: """Return True if multiplying the quoted rates around `cycle` yields strictly more than 1.""" product = 1.0 for i in range(len(cycle) - 1): product *= best_rate[(cycle[i], cycle[i + 1])] # Fast path for normal rates where intermediate multiplication neither underflows nor overflows. if 0.0 < product < math.inf: return product > 1.0 # Fallback for extreme rates (e.g. 1e-200 * 1e-200 underflows float64 to 0.0 even if later # legs multiply by 2e200 * 2e200 = 4.0): track mantissa in [0.5, 1.0) and exact base-2 exponent. mantissa = 1.0 total_exp = 0 for i in range(len(cycle) - 1): rate = best_rate[(cycle[i], cycle[i + 1])] rate_mantissa, rate_exp = math.frexp(rate) mantissa, step_exp = math.frexp(mantissa * rate_mantissa) total_exp += rate_exp + step_exp return total_exp > 1 or (total_exp == 1 and mantissa > 0.5)Trace Example 1 pass by pass
Trace the winning three-currency loop from Example 1:
[("CAD", "AUD", 0.80), ("AUD", "SGD", 0.95), ("SGD", "CAD", 1.40)]. HereV = 3(0: CAD, 1: AUD, 2: SGD), with edge weights-log(rate) + 1e-9approximately+0.2231,+0.0513, and-0.3365:Initial: dist = [CAD: 0.0000, AUD: 0.0000, SGD: 0.0000] pred = [-1, -1, -1] Pass 1: CAD->AUD: 0 + 0.2231 = 0.2231 (not < 0) AUD->SGD: 0 + 0.0513 = 0.0513 (not < 0) SGD->CAD: 0 - 0.3365 = -0.3365 < 0 --> dist[CAD] = -0.3365, pred[CAD] = SGD, last_updated = CAD Pass 2: CAD->AUD: -0.3365 + 0.2231 = -0.1133 < 0 --> dist[AUD] = -0.1133, pred[AUD] = CAD AUD->SGD: -0.1133 + 0.0513 = -0.0620 < 0 --> dist[SGD] = -0.0620, pred[SGD] = AUD SGD->CAD: -0.0620 - 0.3365 = -0.3985 < -0.3365 --> dist[CAD] = -0.3985, pred[CAD] = SGD Pass 3 (the V-th pass!): Every vertex drops by another 0.0620 (the cycle's negative weight); last_updated = CAD Reconstruct: 1. Walk V = 3 steps back from CAD: CAD -> SGD -> AUD -> CAD (cycle_start = CAD) 2. Collect backward around pred: [CAD, SGD, AUD, CAD] 3. Reverse to forward trade order: ["CAD", "AUD", "SGD", "CAD"] 4. Verify product: 0.80 * 0.95 * 1.40 = 1.064 > 1.0 (valid!)Complete solution
Putting
_build_graph,_find_negative_cycle,_is_cycle_profitable,find_arbitrage, andhas_arbitragetogether:from typing import Dict, List, Optional, Tuple import math Quote = Tuple[str, str, float] # A cycle of L conversions counts as profitable only if the product of its rates # exceeds exp(L * margin), about 1 + L * 1e-9 with this default. DEFAULT_MARGIN = 1e-9 def _build_graph(quotes: List[Quote]) -> Tuple[List[str], Dict[Tuple[int, int], float]]: """Assign integer IDs 0..V-1 to currencies and keep the highest rate per directed pair.""" # currency_names: list[str] mapping integer vertex ID -> currency code, e.g. ["CAD", "AUD"] currency_names: List[str] = [] # currency_to_id: dict[str, int] mapping currency code -> integer vertex ID currency_to_id: Dict[str, int] = {} # best_rate: dict[(src_id, dst_id), float] storing the highest quoted rate per directed edge best_rate: Dict[Tuple[int, int], float] = {} for src, dst, rate in quotes: # rate > 0 is also False for NaN, and isfinite rejects +inf. if not (rate > 0 and math.isfinite(rate)): raise ValueError( f"rate for {src}->{dst} must be a positive finite number, got {rate!r}" ) for code in (src, dst): if code not in currency_to_id: currency_to_id[code] = len(currency_names) currency_names.append(code) directed_pair = (currency_to_id[src], currency_to_id[dst]) # If multiple venues quote the same directed pair, a trader always takes the highest rate. if directed_pair not in best_rate or rate > best_rate[directed_pair]: best_rate[directed_pair] = rate return currency_names, best_rate def _find_negative_cycle( num_currencies: int, edges: List[Tuple[int, int, float]] ) -> Optional[List[int]]: """Run Bellman-Ford from a virtual source; return a negative cycle [v, ..., v] or None.""" if num_currencies == 0: return None # Starting every vertex at dist = 0.0 acts like adding a virtual source with a 0-weight # edge to every currency, so we find negative cycles even in disconnected components. dist = [0.0] * num_currencies # predecessor[v] stores the vertex u whose edge u -> v most recently lowered dist[v]. predecessor = [-1] * num_currencies last_updated = -1 # Shortest simple paths from the virtual source use at most num_currencies - 1 real edges. # Any improvement in round num_currencies proves a negative-weight cycle exists. for _ in range(num_currencies): last_updated = -1 for u, v, weight in edges: candidate_dist = dist[u] + weight if candidate_dist < dist[v]: dist[v] = candidate_dist predecessor[v] = u last_updated = v # Early exit: if a full pass changed nothing, no future pass can change anything either. if last_updated == -1: return None # Phase 2: Walk backward num_currencies steps from last_updated. # Why: last_updated may sit on an outgoing tail fed by the cycle rather than on the cycle # itself; across num_currencies steps among num_currencies vertices, we must enter the cycle. cycle_start = last_updated for _ in range(num_currencies): cycle_start = predecessor[cycle_start] # Phase 3: Trace around the cycle until we return to cycle_start, then reverse so # vertices appear in forward conversion order instead of backward predecessor order. backward_cycle = [cycle_start] curr = predecessor[cycle_start] while curr != cycle_start: backward_cycle.append(curr) curr = predecessor[curr] backward_cycle.append(cycle_start) backward_cycle.reverse() return backward_cycle def _is_cycle_profitable( best_rate: Dict[Tuple[int, int], float], cycle: List[int] ) -> bool: """Return True if multiplying the quoted rates around `cycle` yields strictly more than 1.""" product = 1.0 for i in range(len(cycle) - 1): product *= best_rate[(cycle[i], cycle[i + 1])] # Fast path for normal rates where intermediate multiplication neither underflows nor overflows. if 0.0 < product < math.inf: return product > 1.0 # Fallback for extreme rates (e.g. 1e-200 * 1e-200 underflows float64 to 0.0 even if later # legs multiply by 2e200 * 2e200 = 4.0): track mantissa in [0.5, 1.0) and exact base-2 exponent. mantissa = 1.0 total_exp = 0 for i in range(len(cycle) - 1): rate = best_rate[(cycle[i], cycle[i + 1])] rate_mantissa, rate_exp = math.frexp(rate) mantissa, step_exp = math.frexp(mantissa * rate_mantissa) total_exp += rate_exp + step_exp # Since 0.5 <= mantissa < 1.0, mantissa * 2**total_exp > 1.0 iff total_exp > 1, # or total_exp == 1 and 2 * mantissa > 1.0 (i.e. mantissa > 0.5). return total_exp > 1 or (total_exp == 1 and mantissa > 0.5) def find_arbitrage( quotes: List[Quote], margin: float = DEFAULT_MARGIN ) -> Optional[List[str]]: """Return a simple winning conversion loop such as ["CAD", "AUD", "SGD", "CAD"], or None.""" # Reject 0, negatives, NaN, and +inf; with margin == 0, rounded logs of 0.8 and 1.25 # sum to -5.55e-17 and would falsely report arbitrage on a break-even pair. if not (margin > 0 and math.isfinite(margin)): raise ValueError("margin must be a positive finite number") currency_names, best_rate = _build_graph(quotes) # Convert multiplicative gains (r1 * r2 * ... > exp(L * margin)) into negative-weight cycles: # sum(-log(rate) + margin) < 0. edges: List[Tuple[int, int, float]] = [] for (u, v), rate in best_rate.items(): weight = -math.log(rate) + margin edges.append((u, v, weight)) cycle = _find_negative_cycle(len(currency_names), edges) if cycle is None: return None # Defense-in-depth check: verify the reconstructed cycle truly multiplies to > 1.0 # (guards against caller-supplied ultra-tiny margins below float64 log rounding). if not _is_cycle_profitable(best_rate, cycle): return None result: List[str] = [] for vertex_id in cycle: result.append(currency_names[vertex_id]) return result def has_arbitrage(quotes: List[Quote], margin: float = DEFAULT_MARGIN) -> bool: """Return True iff at least one simple conversion loop clears `margin` and multiplies > 1.""" return find_arbitrage(quotes, margin) is not None✅ Submit now — all tests should pass.
Intuition & how it works
Imagine walking past three airport exchange counters where 1 CAD buys 0.80 AUD, 1 AUD buys 0.95 SGD, and 1 SGD buys 1.40 CAD: trading around that triangle turns 1 CAD into 0.80 * 0.95 * 1.40 = 1.064 CAD — 6.4 cents of riskless profit! Because classic shortest-path algorithms add edge costs rather than multiplying exchange rates, we transform each rate r into an additive weight w = -log(r) + margin: since log(a * b) = log(a) + log(b), a loop whose rates multiply past 1 becomes a negative-weight cycle (a closed loop in a directed graph whose edge weights sum below zero). We then run the Bellman-Ford algorithm (a shortest-path method that repeatedly checks every directed edge u -> v to see if routing through u lowers the cost to reach v, an operation called edge relaxation) starting with distance 0 at every currency so isolated currency islands are searched too.
Why do simpler ideas fall short? Enumerating all simple loops and multiplying their rates blows up factorially — just 15 currencies can form over 260 billion directed cycles! Meanwhile, Dijkstra's shortest-path algorithm breaks whenever an edge weight is negative (rate > 1 yields -log(rate) < 0), and running Bellman-Ford on bare -log(rate) without a tolerance fails on floating-point rounding because exact break-even rates like 0.80 and 1.25 have rounded logs summing to -5.55e-17 < 0.
Let's trace Example 1's winning loop CAD -> AUD (0.80), AUD -> SGD (0.95), SGD -> CAD (1.40) with weights +0.2231, +0.0513, and -0.3365:
Start: dist = [CAD: 0.0000, AUD: 0.0000, SGD: 0.0000] pred = [-1, -1, -1]
Pass 1: SGD->CAD lowers CAD to -0.3365 pred[CAD] = SGD
Pass 2: CAD->AUD lowers AUD to -0.1133 (pred=CAD), AUD->SGD lowers SGD to -0.0620 (pred=AUD),
SGD->CAD lowers CAD again to -0.3985 (pred=SGD)
Pass 3: Distances still drop in pass V=3! Walk back 3 steps from CAD -> lands on CAD,
trace pred [CAD, SGD, AUD, CAD], reverse -> ["CAD", "AUD", "SGD", "CAD"] (gain 1.064 > 1)
Complexity
Let Q be the number of input quotes, V be the number of distinct currencies, and E be the number of distinct directed currency pairs (E <= min(Q, V^2)).
- Time:
O(Q + V * E)._build_graphscans theQquotes once usingO(1)average dictionary lookups to assign vertex IDs and retain each pair's highest rate; Bellman-Ford then runs at mostVpasses across allEunique edges (O(V * E)), and stepping backwardVtimes plus reversing the cycle takesO(V). When no arbitrage exists, the early-exit check typically finishes in far fewer thanVpasses. - Space:
O(V + E). We storeVcurrency tickers,Vslots indistandpredecessor, andEentries inbest_rateandedges.
Edge cases
- Empty quote list or one-way chain (
CHF -> NOK -> SEK): No closed loop exists because reverse quotes are never synthesized; Bellman-Ford settles in at mostV - 1passes and returnsNone. - Disconnected profitable island: In Example 3,
MXN -> BRLis a dead-end component whileNZD <-> DKKmakes money; initializingdist = [0.0] * Vacts as a virtual source connected to every component, soNZD <-> DKKis still found. - Lead-in prefixes and outgoing tails: When
CAD <-> AUDis profitable andAUD -> SGD -> CHF -> SEKbranches off it,SEKmay be the last vertex updated in passV; walkingVsteps backward alongpredecessorsteps off the tail and ontoCAD <-> AUDbefore collecting the loop. - Duplicate quotes on the same directed pair:
_build_graphkeeps the maximum rate, matching best-execution venue selection. - Consistent fair cross rates (
rate(a, b) = price[a] / price[b]): Every cycle's true product is1.0, and addingmargin = 1e-9per hop prevents1e-16log-rounding noise from triggering false positives. - Extreme magnitudes (
1e-200and2e200) or ultra-tiny callermargin: Logs remain moderate (|-log(1e-200)| ≈ 460.5), and_is_cycle_profitablefalls back tomath.frexp(splitting a float into a normalized[0.5, 1.0)fraction and an exact integer power of2) so intermediate products like1e-200 * 1e-200neither underflow to0.0nor falsely pass on+inf. - Invalid inputs: Zero, negative,
NaN, or infinite rates or margins raiseValueError.
Common mistakes
- Starting Bellman-Ford from a single vertex (
dist[0] = 0, others+inf): Any winning loop unreachable from currency0(such asNZD <-> DKKin Example 3) is silently missed. - Tracing the loop directly from
last_updatedwithout steppingVhops back first: Whenlast_updatedsits on an outgoing tail rather than on the cycle itself,while curr != last_updatedloops forever inside the cycle and never terminates! - Forgetting
.reverse()on the predecessor chain: Becausepredecessor[v]points to where we came from to reachv, followingpredecessorwalks against the conversion arrows — returning the money-losing reverse loop instead of the winning forward order. - Using
+log(rate)instead of-log(rate)(or zero tolerance): Searching for a negative sum of+log(rate)finds a losing cycle (product < 1), while omittingmarginmakes break-even pairs like0.80and1.25register as arbitrage due to rounding. - Inventing reciprocal quotes: Treating
CAD -> AUDat0.80as implyingAUD -> CADat1.25ignores dealer spreads and fabricates nonexistent trades.
Alternative approaches
- Floyd-Warshall all-pairs shortest paths: Maintain a
V x Vmatrix of minimum log-weights inO(V^3)time andO(V^2)space; anydist[i][i] < 0indicates a negative cycle passing throughi. Very concise on dense graphs (E ≈ V^2), though slower than early-exit Bellman-Ford on sparse markets. - Queue-based Bellman-Ford (SPFA — Shortest Path Faster Algorithm): Maintain a FIFO queue of vertices whose
distjust dropped so only outgoing edges of improved vertices are relaxed, tracking hop counts (hops[v] >= V) to detect cycles. Faster on average, with the sameO(V * E)worst case.
Follow-up questions
- What makes locating the single highest-return simple cycle fundamentally harder than finding an arbitrary winning loop, and what practical workarounds exist? Without size limits you could repeat any winning loop indefinitely, so "highest return" is only well-defined over simple cycles (visiting no currency twice). Finding the simple cycle with the largest rate product (minimum total
-logweight) is NP-hard (no known polynomial-time algorithm exists), because giving every edge weight-1reduces Hamiltonian cycle (whether a cycle visits allVvertices) directly to checking for a cycle of weight-V. In practice, trading desks either compute the cycle with the best geometric-mean return per hop inO(V * E)time via Karp's minimum-mean-cycle algorithm, or cap execution toK <= 4legs and evaluate bounded-hop walks by dynamic programming inO(K * V * E)time. - How does the graph formulation change when venues charge transaction fees or quote separate buy and sell prices? Separate buy and sell quotes (bid/ask spreads, the gap between a dealer's lower buy price and higher sell price) already fit naturally into our directed graph: AUD/CAD quoted at
0.9000 / 0.9004simply becomesAUD -> CADat0.9000andCAD -> AUDat1 / 0.9004 = 1.1106. A proportional feef(such as0.001for0.1%) multiplies the effective rate by(1 - f), which adds-log(1 - f)to that edge's weight with zero algorithmic changes. A flat per-trade fee (like$5) or depth-dependent order-book slippage breaks scale invariance, requiring a fixed starting trade size (or searching over(currency, quantity)states) rather than multiplying unit rates. - When exchange rates stream in one tick at a time, how can you incrementally test for new arbitrage without rerunning full Bellman-Ford on every tick? Cache the settled distances from the previous arbitrage-free state as vertex potentials
p[v](baseline offsets satisfyingp[u] + w(u, v) - p[v] >= 0on every edge). When a quote worsens (ratedecreases, sow(u, v)grows), no negative cycle can appear andpstays valid inO(1)time. When a quoteu -> vimproves tow_new, any newly created negative cycle must traverseu -> v, so we run Dijkstra's algorithm fromvtouover non-negative reduced weightsw'(x, y) = w(x, y) + p[x] - p[y] >= 0inO(E log V)time and check whethershortest_path(v -> u) + w_new + p[u] - p[v] < 0. - Why can a cycle that looks profitable in your market-data feed still lose money when executed on live exchanges? Network latency makes incoming quotes slightly stale (quote staleness), and competing low-latency participants race for the same mispricing so top-of-book liquidity often disappears before your order arrives. Worse, firing a three-leg loop sequentially exposes you to leg risk: leg 1 (
CAD -> AUD) fills, and then leg 2 moves against you before executing, leaving you holding unhedged AUD at a loss. Thin order-book depth, dealer "last-look" rejections on indicative FX streams, and venue fees can easily turn a small theoretical edge into a net loss.
Follow-up questions
- What makes locating the single highest-return simple cycle fundamentally harder than finding an arbitrary winning loop, and what practical workarounds exist?
- How does the graph formulation change when venues charge transaction fees or quote separate buy and sell prices?
- When exchange rates stream in one tick at a time, how can you incrementally test for new arbitrage without rerunning full Bellman-Ford on every tick?
- Why can a cycle that looks profitable in your market-data feed still lose money when executed on live exchanges?
Similar questions
- Domain Contracts for Trade Reconciliation
- Designing an Exact Top-Ten Trade Selector
- Progressive C++ Concurrent Queue: Mutex, Spinlock, and Atomic Ring
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination