forked from WW-shan/poly_strategy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_exhaustive_groups.py
More file actions
457 lines (405 loc) · 16.6 KB
/
test_exhaustive_groups.py
File metadata and controls
457 lines (405 loc) · 16.6 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
import json
import tempfile
import unittest
from pathlib import Path
from poly_strategy.exhaustive_groups import (
potential_exhaustive_group_candidates,
promote_exhaustive_groups,
promotion_candidate_count,
result_to_row,
)
class ExhaustiveGroupTests(unittest.TestCase):
def test_potential_exhaustive_group_candidates_from_near_miss(self):
with tempfile.TemporaryDirectory() as tmp:
snapshots_path, rules_path, _ = _write_candidate_fixture(Path(tmp))
candidates = potential_exhaustive_group_candidates(snapshots_path, rules_path, min_net_edge=0.0, top_n=5)
self.assertEqual(len(candidates), 1)
self.assertEqual(candidates[0]["market_ids"], ["a", "b", "c"])
self.assertAlmostEqual(candidates[0]["net_edge_per_share"], 0.10)
def test_promote_exhaustive_groups_adds_verified_group(self):
client = FakeVerifier(
{
"verdict": "exhaustive_group",
"confidence": 0.99,
"trade_allowed": True,
"risk_flags": [],
"reason": "same event and full candidate set",
}
)
with tempfile.TemporaryDirectory() as tmp:
snapshots_path, rules_path, gamma_path = _write_candidate_fixture(Path(tmp))
out_path = Path(tmp) / "rules-with-groups.json"
result = promote_exhaustive_groups(
gamma_path,
rules_path,
out_path,
snapshots_path,
client,
min_net_edge=0.0,
top_n=5,
min_confidence=0.95,
)
row = json.loads(out_path.read_text())
self.assertEqual(client.market_ids_seen, [["a", "b", "c"]])
self.assertEqual(result.added_count, 1)
self.assertEqual(result.rejected_count, 0)
self.assertEqual(row["exhaustive_groups"][0]["market_ids"], ["a", "b", "c"])
self.assertEqual(row["exhaustive_groups"][0]["source_relation"], "llm_exhaustive_group_verification")
self.assertEqual(result_to_row(result)["type"], "exhaustive_group_promotion")
def test_promote_exhaustive_groups_rejects_risky_verification(self):
client = FakeVerifier(
{
"verdict": "uncertain",
"confidence": 0.80,
"trade_allowed": False,
"risk_flags": ["incomplete_outcome_set"],
"reason": "could be missing a candidate",
}
)
with tempfile.TemporaryDirectory() as tmp:
snapshots_path, rules_path, gamma_path = _write_candidate_fixture(Path(tmp))
out_path = Path(tmp) / "rules-with-groups.json"
result = promote_exhaustive_groups(
gamma_path,
rules_path,
out_path,
snapshots_path,
client,
min_net_edge=0.0,
top_n=5,
min_confidence=0.95,
)
row = json.loads(out_path.read_text())
self.assertEqual(result.added_count, 0)
self.assertEqual(result.rejected_count, 1)
self.assertEqual(row["exhaustive_groups"], [])
def test_promote_exhaustive_groups_uses_semantic_client_after_non_tradeable_primary(self):
primary = FakeVerifier(
{
"verdict": "uncertain",
"confidence": 0.80,
"trade_allowed": False,
"risk_flags": ["insufficient_information"],
"reason": "primary could not prove completeness",
}
)
semantic = FakeVerifier(
{
"verdict": "exhaustive_group",
"confidence": 0.99,
"trade_allowed": True,
"risk_flags": [],
"reason": "semantic pass verified the full outcome set",
}
)
with tempfile.TemporaryDirectory() as tmp:
snapshots_path, rules_path, gamma_path = _write_candidate_fixture(Path(tmp))
out_path = Path(tmp) / "rules-with-groups.json"
result = promote_exhaustive_groups(
gamma_path,
rules_path,
out_path,
snapshots_path,
primary,
min_net_edge=0.0,
top_n=5,
min_confidence=0.95,
semantic_client=semantic,
)
row = json.loads(out_path.read_text())
self.assertEqual(primary.market_ids_seen, [["a", "b", "c"]])
self.assertEqual(semantic.market_ids_seen, [["a", "b", "c"]])
self.assertEqual(result.added_count, 1)
self.assertEqual(result.rejected_count, 0)
self.assertEqual(result.rows[0]["verification_provider"], "semantic")
self.assertEqual(row["exhaustive_groups"][0]["market_ids"], ["a", "b", "c"])
def test_promote_exhaustive_groups_keeps_primary_rejection_uncached_when_semantic_fails(self):
primary = FakeVerifier(
{
"verdict": "uncertain",
"confidence": 0.80,
"trade_allowed": False,
"risk_flags": ["insufficient_information"],
"reason": "primary could not prove completeness",
}
)
semantic = FailingVerifier(TimeoutError("semantic timeout"))
with tempfile.TemporaryDirectory() as tmp:
snapshots_path, rules_path, gamma_path = _write_candidate_fixture(Path(tmp))
out_path = Path(tmp) / "rules-with-groups.json"
state_path = Path(tmp) / "promotion-state.json"
with self.assertRaisesRegex(TimeoutError, "semantic timeout"):
promote_exhaustive_groups(
gamma_path,
rules_path,
out_path,
snapshots_path,
primary,
min_net_edge=0.0,
top_n=5,
min_confidence=0.95,
state_path=state_path,
semantic_client=semantic,
)
self.assertFalse(state_path.exists())
def test_promote_exhaustive_groups_rejects_incomplete_known_neg_risk_group(self):
client = FakeVerifier(
{
"verdict": "exhaustive_group",
"confidence": 0.99,
"trade_allowed": True,
"risk_flags": [],
"reason": "same event and full candidate set",
}
)
with tempfile.TemporaryDirectory() as tmp:
snapshots_path, rules_path, gamma_path = _write_candidate_fixture(Path(tmp))
with gamma_path.open("a") as handle:
handle.write(json.dumps(_gamma_row("d")) + "\n")
out_path = Path(tmp) / "rules-with-groups.json"
result = promote_exhaustive_groups(
gamma_path,
rules_path,
out_path,
snapshots_path,
client,
min_net_edge=0.0,
top_n=5,
min_confidence=0.95,
)
self.assertEqual(client.market_ids_seen, [])
self.assertEqual(result.added_count, 0)
self.assertEqual(result.rejected_count, 1)
self.assertEqual(result.rows[0]["status"], "incomplete_known_neg_risk_group")
self.assertEqual(result.rows[0]["extra_known_market_ids"], ["d"])
def test_promote_exhaustive_groups_uses_state_to_skip_recent_rejections(self):
client = FakeVerifier(
{
"verdict": "uncertain",
"confidence": 0.80,
"trade_allowed": False,
"risk_flags": ["incomplete_outcome_set"],
"reason": "could be missing a candidate",
}
)
with tempfile.TemporaryDirectory() as tmp:
snapshots_path, rules_path, gamma_path = _write_candidate_fixture(Path(tmp))
out_path = Path(tmp) / "rules-with-groups.json"
state_path = Path(tmp) / "promotion-state.json"
first = promote_exhaustive_groups(
gamma_path,
rules_path,
out_path,
snapshots_path,
client,
min_net_edge=0.0,
top_n=5,
min_confidence=0.95,
state_path=state_path,
)
second = promote_exhaustive_groups(
gamma_path,
rules_path,
out_path,
snapshots_path,
client,
min_net_edge=0.0,
top_n=5,
min_confidence=0.95,
state_path=state_path,
)
self.assertEqual(first.rejected_count, 1)
self.assertEqual(second.rejected_count, 0)
self.assertEqual(second.skipped_existing_count, 1)
self.assertEqual(second.rows[0]["status"], "skipped_cached")
self.assertEqual(client.market_ids_seen, [["a", "b", "c"]])
def test_promote_exhaustive_groups_does_not_cache_added_as_active_rule(self):
client = FakeVerifier(
{
"verdict": "exhaustive_group",
"confidence": 0.99,
"trade_allowed": True,
"risk_flags": [],
"reason": "same event and full candidate set",
}
)
with tempfile.TemporaryDirectory() as tmp:
snapshots_path, rules_path, gamma_path = _write_candidate_fixture(Path(tmp))
out_path = Path(tmp) / "rules-with-groups.json"
state_path = Path(tmp) / "promotion-state.json"
first = promote_exhaustive_groups(
gamma_path,
rules_path,
out_path,
snapshots_path,
client,
min_net_edge=0.0,
top_n=5,
min_confidence=0.95,
state_path=state_path,
)
second = promote_exhaustive_groups(
gamma_path,
rules_path,
out_path,
snapshots_path,
client,
min_net_edge=0.0,
top_n=5,
min_confidence=0.95,
state_path=state_path,
)
self.assertEqual(first.added_count, 1)
self.assertEqual(second.added_count, 1)
self.assertEqual(client.market_ids_seen, [["a", "b", "c"], ["a", "b", "c"]])
def test_promotion_candidate_count_counts_near_miss_groups(self):
with tempfile.TemporaryDirectory() as tmp:
snapshots_path, rules_path, _ = _write_candidate_fixture(Path(tmp))
count = promotion_candidate_count(snapshots_path, rules_path, min_net_edge=0.0, top_n=5)
self.assertEqual(count, 1)
def test_promotion_candidate_count_can_use_gamma_neg_risk_groups(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
snapshots_path = root / "snapshots.ndjson"
rules_path = root / "rules.json"
gamma_path = root / "gamma.ndjson"
snapshots_path.write_text(
"\n".join(json.dumps(row) for row in [_snapshot("a", 0.20), _snapshot("b", 0.30), _snapshot("c", 0.40)])
+ "\n"
)
rules_path.write_text("{}")
gamma_path.write_text("\n".join(json.dumps(_gamma_row(market_id)) for market_id in ["a", "b", "c"]) + "\n")
count = promotion_candidate_count(
snapshots_path,
rules_path,
min_net_edge=0.0,
top_n=5,
gamma_path=gamma_path,
)
self.assertEqual(count, 1)
def test_promotion_candidate_count_skips_ordered_range_group_missing_tail(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
snapshots_path = root / "snapshots.ndjson"
rules_path = root / "rules.json"
gamma_path = root / "gamma.ndjson"
out_path = root / "rules-with-groups.json"
snapshots_path.write_text(
"\n".join(json.dumps(row) for row in [_snapshot("a", 0.01), _snapshot("b", 0.01), _snapshot("c", 0.01)])
+ "\n"
)
rules_path.write_text(
json.dumps(
{
"mutually_exclusive": [
{"first": "a", "second": "b", "confidence": 0.99},
{"first": "a", "second": "c", "confidence": 0.99},
{"first": "b", "second": "c", "confidence": 0.99},
]
}
)
)
gamma_path.write_text(
"\n".join(
json.dumps(row)
for row in [
_range_gamma_row("a", "65°F or below", "0"),
_range_gamma_row("b", "66-67°F", "1"),
_range_gamma_row("c", "68-69°F", "2"),
]
)
+ "\n"
)
client = FakeVerifier({"trade_allowed": True})
count = promotion_candidate_count(
snapshots_path,
rules_path,
min_net_edge=0.0,
top_n=5,
gamma_path=gamma_path,
)
result = promote_exhaustive_groups(
gamma_path,
rules_path,
out_path,
snapshots_path,
client,
min_net_edge=0.0,
top_n=5,
)
self.assertEqual(count, 0)
self.assertEqual(result.candidates_found, 0)
self.assertEqual(client.market_ids_seen, [])
class FakeVerifier:
def __init__(self, response):
self.response = response
self.market_ids_seen = []
def verify_group(self, markets):
self.market_ids_seen.append([market.market_id for market in markets])
return dict(self.response)
class FailingVerifier:
def __init__(self, exc):
self.exc = exc
self.market_ids_seen = []
def verify_group(self, markets):
self.market_ids_seen.append([market.market_id for market in markets])
raise self.exc
def _write_candidate_fixture(root: Path):
snapshots_path = root / "snapshots.ndjson"
rules_path = root / "rules.json"
gamma_path = root / "gamma.ndjson"
snapshots_path.write_text("\n".join(json.dumps(row) for row in [_snapshot("a", 0.20), _snapshot("b", 0.30), _snapshot("c", 0.40)]) + "\n")
rules_path.write_text(
json.dumps(
{
"mutually_exclusive": [
{"first": "a", "second": "b", "confidence": 0.99},
{"first": "a", "second": "c", "confidence": 0.99},
{"first": "b", "second": "c", "confidence": 0.99},
]
}
)
)
gamma_path.write_text("\n".join(json.dumps(_gamma_row(market_id)) for market_id in ["a", "b", "c"]) + "\n")
return snapshots_path, rules_path, gamma_path
def _snapshot(market_id: str, yes_price: float):
return {
"ts": "2026-05-09T00:00:00Z",
"type": "binary_snapshot",
"venue": "polymarket",
"market_id": market_id,
"fee_rate": 0.0,
"yes": {"token_id": f"{market_id}-yes", "asks": [[yes_price, 100]], "bids": []},
"no": {"token_id": f"{market_id}-no", "asks": [[1.0 - yes_price, 100]], "bids": []},
}
def _gamma_row(market_id: str):
return {
"ts": "2026-05-09T00:00:00Z",
"type": "raw_polymarket_gamma_market",
"market_id": market_id,
"raw": {
"id": market_id,
"question": f"Will candidate {market_id.upper()} win the final?",
"description": "Resolves based on the final winner.",
"outcomes": json.dumps(["Yes", "No"]),
"clobTokenIds": json.dumps([f"{market_id}-yes", f"{market_id}-no"]),
"endDate": "2026-06-01T00:00:00Z",
"category": "sports",
"slug": f"candidate-{market_id}-wins",
"negRisk": True,
"negRiskMarketID": "final-winner",
"groupItemTitle": market_id.upper(),
"groupItemThreshold": "",
},
}
def _range_gamma_row(market_id: str, group_item_title: str, group_item_threshold: str):
row = _gamma_row(market_id)
raw = row["raw"]
raw["question"] = f"Will the highest temperature be {group_item_title}?"
raw["description"] = "Resolves based on the daily high temperature."
raw["groupItemTitle"] = group_item_title
raw["groupItemThreshold"] = group_item_threshold
raw["slug"] = f"temperature-{market_id}"
return row
if __name__ == "__main__":
unittest.main()