-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathArbitrage.py
51 lines (38 loc) · 1.08 KB
/
Arbitrage.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import GraphLib
from BaseClassLib import GraphBase
import DirectedEdge, ShortestPath
import math
with open('rates.txt', 'r') as f:
V = int(f.readline().strip())
text = f.read()
f.close()
lines = text.split('\n')
table = []
for line in lines:
if len(line) < V+1: continue
l = line.split()
name = l[0]
table.append([name])
for i in range(1, V+1):
rate = float(l[i])
table[-1].append(rate)
# name is vertex-indexed list
name = [table[i][0] for i in range(V)]
#G = GraphLib.EdgeWeightedDigraph(V)
class EWDG(GraphBase):
pass
G = EWDG.graphfactory(V, directed=True, weighted=True)
for v in range(V):
for w in range(V):
if w != v:
G.addEdge(DirectedEdge.DEdge(v, w, -math.log(table[v][w+1])))
spt = ShortestPath.BellmanFordSP(G, 0)
if (spt.hasNegativeCycle()):
stake = 1000.00 # the money we want to invest in arbitrage
for e in spt.negativeCycle():
# the first negative cycle found
print "{:10.5f} {:s} ".format(stake, name[e.src()]),
stake *= math.exp(-e.weight())
print "= {:10.5f} {:s} ".format(stake, name[e.sink()])
else:
print "No arbitrage opportunity."