-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot_item_graph.py
More file actions
638 lines (566 loc) · 28.8 KB
/
plot_item_graph.py
File metadata and controls
638 lines (566 loc) · 28.8 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
"""
Interactive visualisation of the item conversion graph.
Saves to dashboard/item_graph.html — open in a browser.
Edges are coloured by ROI (revenue/cost − 1) on a continuous diverging scale:
red (max loss) → grey (break-even) → green (max profit).
Edge width scales with |ROI|. Only edges where every item has ≥ LIQUIDITY_MIN_VOL
1h trades are shown; illiquid and unpriced conversions are hidden.
Layout zones (y increases upward):
┌─────────────────────────────────────────────────────────┐ y ≈ 48–52
│ Zone 5 — Armour sets: blessed d'hide | high-end | moon │
│ (set item at top, components in row below) │
├─────────────────────────────────────────────────────────┤ y ≈ 27–38
│ Zone 4 — Jewelry chains: 7 gem tiers × 4 piece types │
│ (uncut → cut → crafted → strung → enchanted) │
├─────────────────────────────────────────────────────────┤ y ≈ 18–23
│ Zone 3 — Godswords (shards→blade→assembled, hilts) │
│ Dragon sq shield (halves→shield) │
├─────────────────────────────────────────────────────────┤ y ≈ 10–14
│ Zone 2 — Armour sets: Barrows | Rune sets | Dragon sets │
│ (set item at top, components in 2×2 below) │
├─────────────────────────────────────────────────────────┤ y ≈ 0–6
│ Zone 1 — Potions: families as columns, dose as rows │
└─────────────────────────────────────────────────────────┘
"""
import re
from collections import defaultdict
from pathlib import Path
import numpy as np
import networkx as nx
import plotly.graph_objects as go
from data.item_graph import ItemGraph
# ── Load ───────────────────────────────────────────────────────────────────────
g = ItemGraph().load()
G = g.graph
# ── Price / volume data ────────────────────────────────────────────────────
import math as _math
from data.api import WikiClient as _WikiClient
print("Fetching price data...", end=" ", flush=True)
try:
_client = _WikiClient()
_mapping = _client.get_mapping() # DataFrame indexed by item_id
_latest = _client.get_latest() # high, highTime, low, lowTime
_agg1h = _client.get_aggregate("1h") # highPriceVolume, lowPriceVolume
print("done")
except Exception as _exc:
print(f"FAILED ({_exc}) — no price data")
_mapping = _latest = _agg1h = None
_name_to_id: dict[str, int] = (
{row["name"]: int(idx) for idx, row in _mapping.iterrows()}
if _mapping is not None else {}
)
def _price(name: str) -> dict:
item_id = _name_to_id.get(name)
if item_id is None:
return {}
d: dict = {"id": item_id}
if _mapping is not None and item_id in _mapping.index:
try: d["buy_limit"] = int(_mapping.loc[item_id, "limit"])
except: pass
if _latest is not None and item_id in _latest.index:
row = _latest.loc[item_id]
d["high"] = row.get("high")
d["low"] = row.get("low")
if _agg1h is not None and item_id in _agg1h.index:
row = _agg1h.loc[item_id]
d["vol"] = int((row.get("highPriceVolume") or 0) + (row.get("lowPriceVolume") or 0))
return d
# ── Categorise nodes ───────────────────────────────────────────────────────────
BARROWS_PREFIXES = ("Ahrim's", "Dharok's", "Guthan's", "Karil's", "Torag's", "Verac's")
DHIDE_COMP = {
"Guthix d'hide body", "Guthix chaps", "Guthix coif", "Guthix bracers",
"Saradomin d'hide body", "Saradomin chaps", "Saradomin coif", "Saradomin bracers",
"Zamorak d'hide body", "Zamorak chaps", "Zamorak coif", "Zamorak bracers",
"Armadyl d'hide body", "Armadyl chaps", "Armadyl coif", "Armadyl bracers",
"Bandos d'hide body", "Bandos chaps", "Bandos coif", "Bandos bracers",
"Ancient d'hide body", "Ancient chaps", "Ancient coif", "Ancient bracers",
}
HIGH_END_PIECES = {
"Armadyl helmet", "Armadyl chestplate", "Armadyl chainskirt",
"Ancestral hat", "Ancestral robe top", "Ancestral robe bottom",
"Inquisitor's great helm", "Inquisitor's hauberk", "Inquisitor's plateskirt",
"Justiciar faceguard", "Justiciar chestguard", "Justiciar legguards",
"Masori mask (f)", "Masori body (f)", "Masori chaps (f)",
"Torva full helm", "Torva platebody", "Torva platelegs",
"Virtus mask", "Virtus robe top", "Virtus robe bottom",
"Oathplate helm", "Oathplate chest", "Oathplate legs",
"Blood moon helm", "Blood moon chestplate", "Blood moon tassets", "Dual macuahuitl",
"Blue moon helm", "Blue moon chestplate", "Blue moon tassets", "Blue moon spear",
"Eclipse moon helm", "Eclipse moon chestplate", "Eclipse moon tassets", "Eclipse atlatl",
}
JEWELRY_ENCHANTED = {
# Zenyte
"Amulet of torture", "Ring of suffering", "Tormented bracelet", "Necklace of anguish",
# Onyx
"Amulet of fury", "Ring of stone", "Berserker necklace", "Regen bracelet",
# Dragonstone
"Amulet of glory", "Ring of wealth(5)", "Skills necklace(4)", "Combat bracelet(4)",
# Diamond
"Amulet of power", "Ring of life", "Phoenix necklace", "Abyssal bracelet(5)",
# Ruby
"Amulet of strength", "Ring of forging", "Digsite pendant(5)", "Inoculation bracelet",
# Emerald
"Amulet of defence", "Ring of dueling(8)", "Binding necklace", "Castle wars bracelet",
# Sapphire
"Amulet of magic", "Ring of recoil", "Games necklace(8)", "Bracelet of clay",
}
JEWELRY_UNENCHANTED = {
# Zenyte
"Zenyte amulet (u)", "Zenyte amulet", "Zenyte ring", "Zenyte bracelet", "Zenyte necklace",
# Onyx
"Onyx amulet (u)", "Onyx amulet", "Onyx ring", "Onyx necklace", "Onyx bracelet",
# Dragonstone
"Dragonstone amulet (u)", "Dragonstone amulet", "Dragonstone ring", "Dragon necklace", "Dragonstone bracelet",
# Diamond
"Diamond amulet (u)", "Diamond amulet", "Diamond ring", "Diamond necklace", "Diamond bracelet",
# Ruby
"Ruby amulet (u)", "Ruby amulet", "Ruby ring", "Ruby necklace", "Ruby bracelet",
# Emerald
"Emerald amulet (u)", "Emerald amulet", "Emerald ring", "Emerald necklace", "Emerald bracelet",
# Sapphire
"Sapphire amulet (u)", "Sapphire amulet", "Sapphire ring", "Sapphire necklace", "Sapphire bracelet",
}
GEMS = {
"Uncut sapphire", "Sapphire",
"Uncut emerald", "Emerald",
"Uncut ruby", "Ruby",
"Uncut diamond", "Diamond",
"Uncut dragonstone", "Dragonstone",
"Uncut onyx", "Onyx",
"Uncut zenyte", "Zenyte",
}
MATERIALS = {
"Gold bar", "Ball of wool",
"Air rune", "Water rune", "Fire rune", "Earth rune", "Cosmic rune",
"Blood rune", "Soul rune",
}
def category(name: str) -> str:
if name in HIGH_END_PIECES:
return "high_end"
if name in DHIDE_COMP:
return "dhide"
if name in JEWELRY_ENCHANTED:
return "jewelry_enchanted"
if name in JEWELRY_UNENCHANTED:
return "jewelry"
if name in GEMS:
return "gem"
if name in MATERIALS:
return "material"
if (name.endswith("armour set") or "armour set (" in name
or name.endswith("robes set") or "dragonhide set" in name.lower()):
return "armour_set"
if any(name.startswith(p) for p in BARROWS_PREFIXES):
return "barrows"
if "godsword" in name.lower() or " hilt" in name.lower() or "shard" in name.lower():
return "godsword"
if any(x in name.lower() for x in ["platebody","platelegs","plateskirt","full helm","kiteshield"]):
return "armour_piece"
if "sq shield" in name.lower() or "left half" in name.lower() or "right half" in name.lower():
return "shield"
if re.search(r'\(\d\)$', name) or any(x in name.lower() for x in
["potion", "brew", "restore", "venom", "antifire"]):
return "potion"
return "other"
PALETTE = {
"armour_set": "#e74c3c",
"barrows": "#e67e22",
"godsword": "#9b59b6",
"armour_piece": "#3498db",
"high_end": "#f39c12",
"dhide": "#27ae60",
"shield": "#1abc9c",
"potion": "#2ecc71",
"jewelry_enchanted": "#fdcb6e",
"jewelry": "#fd79a8",
"gem": "#a29bfe",
"material": "#636e72",
"other": "#95a5a6",
}
cat_map = {n: category(n) for n in G.nodes}
# ── Layout ─────────────────────────────────────────────────────────────────────
def build_layout(g: ItemGraph) -> dict[str, np.ndarray]:
"""
Explicit, non-overlapping positions for every node.
Zone 1 — Potions (y 0–6): family columns × dose rows.
Zone 2 — Armour sets (y 10–14): Barrows columns then Rune/Dragon with shared-component handling.
Zone 3 — Godswords & shield (y 18–23): shards→blade→assembled, hilts below assembled.
"""
pos: dict[str, np.ndarray] = {}
# ── Zone 1: Potions ───────────────────────────────────────────────────────
X_SP = 2.2
Y_SP = 2.0
for fam_idx, fam in enumerate(g._dose_families):
prefix = fam["prefix"]
max_dose = fam.get("max_dose", 4)
for dose in range(1, max_dose + 1):
pos[f"{prefix}({dose})"] = np.array([fam_idx * X_SP, (dose - 1) * Y_SP])
# ── Zone 2: Armour sets ───────────────────────────────────────────────────
Y_SET = 14.0 # set items
Y_C1 = 12.0 # first component row
Y_C2 = 10.0 # second component row
BARROWS = [
("Ahrim's armour set", ["Ahrim's hood", "Ahrim's robetop", "Ahrim's robeskirt", "Ahrim's staff"]),
("Dharok's armour set", ["Dharok's helm", "Dharok's platebody", "Dharok's platelegs", "Dharok's greataxe"]),
("Guthan's armour set", ["Guthan's helm", "Guthan's platebody", "Guthan's chainskirt", "Guthan's warspear"]),
("Karil's armour set", ["Karil's coif", "Karil's leathertop", "Karil's leatherskirt", "Karil's crossbow"]),
("Torag's armour set", ["Torag's helm", "Torag's platebody", "Torag's platelegs", "Torag's hammers"]),
("Verac's armour set", ["Verac's helm", "Verac's brassard", "Verac's plateskirt", "Verac's flail"]),
]
COL_W = 3.6
COMP = [(-0.85, Y_C1), (0.85, Y_C1), (-0.85, Y_C2), (0.85, Y_C2)]
for col, (sname, comps) in enumerate(BARROWS):
xc = col * COL_W
pos[sname] = np.array([xc, Y_SET])
for comp, (dx, cy) in zip(comps, COMP):
pos[comp] = np.array([xc + dx, cy])
# Rune sets — shared components centred between the two set items
XR = 22.5
pos["Rune armour set (lg)"] = np.array([XR, Y_SET])
pos["Rune armour set (sk)"] = np.array([XR + 3.6, Y_SET])
pos["Rune platebody"] = np.array([XR + 1.8, Y_C1])
pos["Rune full helm"] = np.array([XR + 0.9, Y_C2])
pos["Rune kiteshield"] = np.array([XR + 2.7, Y_C2])
pos["Rune platelegs"] = np.array([XR - 0.9, Y_C2])
pos["Rune plateskirt"] = np.array([XR + 4.5, Y_C2])
# Dragon sets — same structure, offset right
XD = 31.0
pos["Dragon armour set (lg)"] = np.array([XD, Y_SET])
pos["Dragon armour set (sk)"] = np.array([XD + 3.6, Y_SET])
pos["Dragon platebody"] = np.array([XD + 1.8, Y_C1])
pos["Dragon full helm"] = np.array([XD + 0.9, Y_C2])
pos["Dragon kiteshield"] = np.array([XD + 2.7, Y_C2])
pos["Dragon platelegs"] = np.array([XD - 0.9, Y_C2])
pos["Dragon plateskirt"] = np.array([XD + 4.5, Y_C2])
# ── Zone 3: Godswords & Dragon sq shield ─────────────────────────────────
Y_ASSEMBLED = 23.0
Y_HILT = 21.3
Y_BLADE = 19.5
Y_SHARDS = 18.0
GS = [
("Armadyl godsword", "Armadyl hilt"),
("Bandos godsword", "Bandos hilt"),
("Saradomin godsword","Saradomin hilt"),
("Zamorak godsword", "Zamorak hilt"),
]
X_GS = 4.0
GS_SP = 4.5
for i, (gsname, hname) in enumerate(GS):
xg = X_GS + i * GS_SP
pos[gsname] = np.array([xg, Y_ASSEMBLED])
pos[hname] = np.array([xg, Y_HILT])
x_blade = X_GS + 1.5 * GS_SP # centred under all 4 assembled swords
pos["Godsword blade"] = np.array([x_blade, Y_BLADE])
pos["Godsword shard 1"] = np.array([x_blade - 1.1, Y_SHARDS])
pos["Godsword shard 2"] = np.array([x_blade, Y_SHARDS])
pos["Godsword shard 3"] = np.array([x_blade + 1.1, Y_SHARDS])
# Dragon sq shield — right of godswords, same y zone
XS = 26.0
pos["Dragon sq shield"] = np.array([XS, Y_ASSEMBLED])
pos["Shield left half"] = np.array([XS - 1.1, Y_BLADE])
pos["Shield right half"]= np.array([XS + 1.1, Y_BLADE])
# ── Zone 4: Jewelry chains — 7 tiers × 4 piece types ─────────────────────
Y_MAT = 27.0 # materials row
Y_UNCUT = 30.0 # uncut gems
Y_CUT = 32.0 # cut gems
Y_U = 34.0 # crafted unenchanted (amulet(u) / ring / necklace / bracelet)
Y_STR = 36.0 # strung amulets only
Y_ENC = 38.0 # enchanted jewelry
# Materials: compact row at y=27
for i, mat in enumerate(["Gold bar", "Ball of wool",
"Air rune", "Water rune", "Fire rune",
"Earth rune", "Cosmic rune",
"Blood rune", "Soul rune"]):
pos[mat] = np.array([i * 1.5, Y_MAT])
# Tier definitions: (uncut, cut, amulet_u, amulet_str, amulet_enc,
# ring, ring_enc, necklace, necklace_enc, bracelet, bracelet_enc)
TIERS = [
("Uncut sapphire", "Sapphire",
"Sapphire amulet (u)", "Sapphire amulet", "Amulet of magic",
"Sapphire ring", "Ring of recoil",
"Sapphire necklace","Games necklace(8)",
"Sapphire bracelet","Bracelet of clay"),
("Uncut emerald", "Emerald",
"Emerald amulet (u)", "Emerald amulet", "Amulet of defence",
"Emerald ring", "Ring of dueling(8)",
"Emerald necklace","Binding necklace",
"Emerald bracelet","Castle wars bracelet"),
("Uncut ruby", "Ruby",
"Ruby amulet (u)", "Ruby amulet", "Amulet of strength",
"Ruby ring", "Ring of forging",
"Ruby necklace", "Digsite pendant(5)",
"Ruby bracelet", "Inoculation bracelet"),
("Uncut diamond", "Diamond",
"Diamond amulet (u)", "Diamond amulet", "Amulet of power",
"Diamond ring", "Ring of life",
"Diamond necklace","Phoenix necklace",
"Diamond bracelet","Abyssal bracelet(5)"),
("Uncut dragonstone", "Dragonstone",
"Dragonstone amulet (u)", "Dragonstone amulet", "Amulet of glory",
"Dragonstone ring", "Ring of wealth(5)",
"Dragon necklace", "Skills necklace(4)",
"Dragonstone bracelet", "Combat bracelet(4)"),
("Uncut onyx", "Onyx",
"Onyx amulet (u)", "Onyx amulet", "Amulet of fury",
"Onyx ring", "Ring of stone",
"Onyx necklace", "Berserker necklace",
"Onyx bracelet", "Regen bracelet"),
("Uncut zenyte", "Zenyte",
"Zenyte amulet (u)", "Zenyte amulet", "Amulet of torture",
"Zenyte ring", "Ring of suffering",
"Zenyte necklace", "Necklace of anguish",
"Zenyte bracelet", "Tormented bracelet"),
]
TIER_X = [4.0, 13.0, 22.0, 31.0, 40.0, 49.0, 58.0]
for xc, (uncut, cut,
am_u, am_s, am_e,
ri, ri_e,
ne, ne_e,
br, br_e) in zip(TIER_X, TIERS):
xa, xr, xn, xb = xc - 2.7, xc - 0.9, xc + 0.9, xc + 2.7
pos[uncut] = np.array([xc, Y_UNCUT])
pos[cut] = np.array([xc, Y_CUT])
pos[am_u] = np.array([xa, Y_U])
pos[am_s] = np.array([xa, Y_STR])
pos[am_e] = np.array([xa, Y_ENC])
pos[ri] = np.array([xr, Y_U])
pos[ri_e] = np.array([xr, Y_ENC])
pos[ne] = np.array([xn, Y_U])
pos[ne_e] = np.array([xn, Y_ENC])
pos[br] = np.array([xb, Y_U])
pos[br_e] = np.array([xb, Y_ENC])
# ── Zone 5: D'hide sets & high-end armour sets ───────────────────────────
Y_SET5 = 52.0
Y_C1_5 = 50.0
BLESSED_DHIDE_SETS = [
("Guthix dragonhide set", "Guthix d'hide body", "Guthix chaps", "Guthix coif", "Guthix bracers"),
("Saradomin dragonhide set", "Saradomin d'hide body", "Saradomin chaps", "Saradomin coif", "Saradomin bracers"),
("Zamorak dragonhide set", "Zamorak d'hide body", "Zamorak chaps", "Zamorak coif", "Zamorak bracers"),
("Armadyl dragonhide set", "Armadyl d'hide body", "Armadyl chaps", "Armadyl coif", "Armadyl bracers"),
("Bandos dragonhide set", "Bandos d'hide body", "Bandos chaps", "Bandos coif", "Bandos bracers"),
("Ancient dragonhide set", "Ancient d'hide body", "Ancient chaps", "Ancient coif", "Ancient bracers"),
]
for col, (sname, c1, c2, c3, c4) in enumerate(BLESSED_DHIDE_SETS):
xc = col * 5.0
pos[sname] = np.array([xc, Y_SET5])
pos[c1] = np.array([xc - 1.5, Y_C1_5])
pos[c2] = np.array([xc - 0.5, Y_C1_5])
pos[c3] = np.array([xc + 0.5, Y_C1_5])
pos[c4] = np.array([xc + 1.5, Y_C1_5])
HIGH_END_LAYOUT = [
("Armadyl armour set", ["Armadyl helmet", "Armadyl chestplate", "Armadyl chainskirt"]),
("Ancestral robes set", ["Ancestral hat", "Ancestral robe top", "Ancestral robe bottom"]),
("Inquisitor's armour set", ["Inquisitor's great helm", "Inquisitor's hauberk", "Inquisitor's plateskirt"]),
("Justiciar armour set", ["Justiciar faceguard", "Justiciar chestguard", "Justiciar legguards"]),
("Masori armour set (f)", ["Masori mask (f)", "Masori body (f)", "Masori chaps (f)"]),
("Torva armour set", ["Torva full helm", "Torva platebody", "Torva platelegs"]),
("Virtus armour set", ["Virtus mask", "Virtus robe top", "Virtus robe bottom"]),
("Oathplate armour set", ["Oathplate helm", "Oathplate chest", "Oathplate legs"]),
("Blood moon armour set", ["Blood moon helm", "Blood moon chestplate", "Blood moon tassets", "Dual macuahuitl"]),
("Blue moon armour set", ["Blue moon helm", "Blue moon chestplate", "Blue moon tassets", "Blue moon spear"]),
("Eclipse moon armour set", ["Eclipse moon helm", "Eclipse moon chestplate", "Eclipse moon tassets","Eclipse atlatl"]),
]
for idx, (sname, comps) in enumerate(HIGH_END_LAYOUT):
xc = 34.0 + idx * 5.5
pos[sname] = np.array([xc, Y_SET5])
n = len(comps)
for i, comp in enumerate(comps):
pos[comp] = np.array([xc - (n - 1) * 0.5 + i * 1.0, Y_C1_5])
return pos
pos = build_layout(g)
# Verify no nodes are missing
missing = [n for n in G.nodes if n not in pos]
if missing:
print(f"WARNING: {len(missing)} nodes have no position: {missing[:10]}")
# ── Profitability & liquidity ──────────────────────────────────────────────────
LIQUIDITY_MIN_VOL = 5 # minimum 1h trades per item to consider liquid
def _conv_stats(c) -> tuple[float | None, bool]:
"""(roi, all_liquid) where roi = (revenue - cost) / cost.
Assumes worst-case execution:
inputs bought at insta-buy price (high = lowest active ask)
outputs sold at insta-sell price (low = highest active bid), minus 2% GE tax
Returns (None, False) if any item has no price data or cost == 0.
all_liquid = True iff every item has 1h vol >= LIQUIDITY_MIN_VOL.
"""
cost = revenue = 0.0
liquid = True
for item, qty in c.inputs.items():
pd = _price(item)
h = pd.get("high")
if not h:
return None, False
cost += h * qty
if (pd.get("vol") or 0) < LIQUIDITY_MIN_VOL:
liquid = False
for item, qty in c.outputs.items():
pd = _price(item)
lo = pd.get("low")
if not lo:
return None, False
tax = min(int(lo * 0.02), 5_000_000)
revenue += (lo - tax) * qty
if (pd.get("vol") or 0) < LIQUIDITY_MIN_VOL:
liquid = False
if cost == 0:
return None, False
return (revenue - cost) / cost, liquid
_cstats: dict[str, tuple] = {c.id: _conv_stats(c) for c in g.conversions}
# ── Profit → colour / width ────────────────────────────────────────────────
_COLOR_LOSS = "#e74c3c" # bright red (max loss)
_COLOR_NEUTRAL = "#4a4a6a" # dark grey (break-even)
_COLOR_GAIN = "#2ecc71" # bright green (max profit)
def _lerp_hex(c1: str, c2: str, t: float) -> str:
r1, g1, b1 = int(c1[1:3],16), int(c1[3:5],16), int(c1[5:7],16)
r2, g2, b2 = int(c2[1:3],16), int(c2[3:5],16), int(c2[5:7],16)
return "#{:02x}{:02x}{:02x}".format(
int(r1 + t*(r2-r1)), int(g1 + t*(g2-g1)), int(b1 + t*(b2-b1))
)
# Normalise linearly on ROI — already a dimensionless ratio
_rois = [r for r, liq in _cstats.values() if r is not None and liq]
_vmax = max((abs(v) for v in _rois), default=0.01) or 0.01
def _profit_color(roi: float | None) -> str:
if roi is None:
return _COLOR_NEUTRAL
t = max(-1.0, min(1.0, roi / _vmax))
if t >= 0:
return _lerp_hex(_COLOR_NEUTRAL, _COLOR_GAIN, t)
else:
return _lerp_hex(_COLOR_NEUTRAL, _COLOR_LOSS, -t)
def _profit_width(roi: float | None) -> float:
if roi is None:
return 0.6
t = min(1.0, abs(roi) / _vmax)
return 0.6 + t * 2.6 # 0.6 (break-even) → 3.2 (max |ROI|)
# ── Edge traces ────────────────────────────────────────────────────────────────
def conv_label(c) -> str:
ins = " + ".join(f"{q}×{k}" if q > 1 else k for k, q in c.inputs.items())
outs = " + ".join(f"{q}×{k}" if q > 1 else k for k, q in c.outputs.items())
return f"{ins} → {outs}"
# Include _rev conversions so both directions of reversible conversions are shown.
# Only include edges where every item is liquid.
edge_groups: dict[tuple, list] = defaultdict(list)
for c in g.conversions:
_, liquid = _cstats.get(c.id, (None, False))
if not liquid:
continue
for u in c.inputs:
for v in c.outputs:
if u in pos and v in pos:
edge_groups[(u, v)].append(c)
edge_traces = []
for (u, v), convs in edge_groups.items():
for c in convs:
profit, _ = _cstats.get(c.id, (None, False))
color = _profit_color(profit)
width = _profit_width(profit)
opacity = 0.90 if profit is not None and profit != 0 else 0.50
if profit is not None:
sign = "+" if profit > 0 else ""
label = f"<b>{conv_label(c)}</b><br>ROI: {sign}{profit*100:.2f}%<br><i>{c.note}</i>"
else:
label = f"<b>{conv_label(c)}</b><br><i>{c.note}</i>"
x0, y0 = pos[u]
x1, y1 = pos[v]
ts = [i / 8 for i in range(9)]
xs = [x0 + t*(x1-x0) for t in ts] + [None]
ys = [y0 + t*(y1-y0) for t in ts] + [None]
edge_traces.append(go.Scatter(
x=xs, y=ys,
mode="lines",
line=dict(width=width, color=color),
hoverinfo="text",
text=[label]*9 + [""],
showlegend=False,
opacity=opacity,
))
# ── Node traces ────────────────────────────────────────────────────────────────
node_traces = []
for cat, colour in PALETTE.items():
nodes_in_cat = [n for n, c in cat_map.items() if c == cat and n in pos]
if not nodes_in_cat:
continue
nx_ = [pos[n][0] for n in nodes_in_cat]
ny_ = [pos[n][1] for n in nodes_in_cat]
hover = []
sizes = []
for n in nodes_in_cat:
pd = _price(n)
high = pd.get("high")
low = pd.get("low")
vol = pd.get("vol")
bl = pd.get("buy_limit")
lines = [f"<b>{n}</b>"]
if high and low:
spread = high - low
tax = min(int(high * 0.02), 5_000_000)
net = spread - tax
margin = 100.0 * net / low if low else 0.0
lines.append(f"High: {high:,} | Low: {low:,}")
lines.append(f"Spread: {spread:,} → net {net:,} ({margin:.1f}%)")
elif pd:
lines.append("<i>no current price</i>")
stat_parts = []
if vol is not None: stat_parts.append(f"1h vol: {vol:,}")
if bl is not None: stat_parts.append(f"buy limit: {bl:,}")
if stat_parts:
lines.append(" | ".join(stat_parts))
produced = [conv_label(c) for c in g.producing(n) if not c.id.endswith("_rev")]
consumed = [conv_label(c) for c in g.consuming(n) if not c.id.endswith("_rev")]
if produced:
lines.append("produced by:<br> " + "<br> ".join(produced))
if consumed:
lines.append("consumed in:<br> " + "<br> ".join(consumed))
hover.append("<br>".join(lines))
# Node size: log-scale on 1h volume; 5 (no data) … 16 (>100k vol)
raw_vol = vol or 0
sizes.append(max(5, min(16, 4 + _math.log10(raw_vol + 1) * 2)))
node_traces.append(go.Scatter(
x=nx_, y=ny_,
mode="markers+text",
marker=dict(size=sizes, color=colour, line=dict(width=1, color="white")),
text=nodes_in_cat,
textposition="top center",
textfont=dict(size=6),
hoverinfo="text",
hovertext=hover,
name=cat.replace("_", " ").title(),
))
# ── Figure ─────────────────────────────────────────────────────────────────────
n_profitable = sum(
1 for c in g.conversions
if (_cstats.get(c.id, (None, False))[0] or -1) > 0
and _cstats.get(c.id, (None, False))[1]
)
n_liquid = sum(1 for c in g.conversions if _cstats.get(c.id, (None, False))[1])
fig = go.Figure(
data=edge_traces + node_traces,
layout=go.Layout(
title=dict(
text=(
"OSRS Item Conversion Graph — "
"<span style='color:#2ecc71'>■ green = max ROI</span> "
"<span style='color:#4a4a6a'>■ grey = break-even</span> "
"<span style='color:#e74c3c'>■ red = max loss</span> "
"(only liquid edges shown; width ∝ |ROI|)"
),
font=dict(size=14),
),
showlegend=True,
hovermode="closest",
margin=dict(b=20, l=5, r=5, t=60),
xaxis=dict(showgrid=False, zeroline=False, showticklabels=False),
yaxis=dict(showgrid=False, zeroline=False, showticklabels=False,
scaleanchor="x", scaleratio=1),
paper_bgcolor="#1a1a2e",
plot_bgcolor="#1a1a2e",
font=dict(color="white"),
legend=dict(bgcolor="#16213e", bordercolor="#444"),
height=1600,
),
)
out = Path("dashboard/item_graph.html")
out.parent.mkdir(exist_ok=True)
fig.write_html(str(out))
print(f"Saved → {out}")
print(f"Nodes: {G.number_of_nodes()} positioned: {len(pos)} missing: {len(missing)}")
print(f"Conversions: {len(g.conversions)} total | {n_liquid} liquid | {n_profitable} profitable")