| 1 | """Entity-level Polymarket selection: which events a topic keeps, how they rank, |
| 2 | and which market each one headlines. |
| 3 | |
| 4 | The fixtures under ``fixtures/polymarket`` are live Gamma ``public-search`` |
| 5 | events from 2026-11-16, trimmed to the fields the parser reads. Prices are the |
| 6 | ones Polymarket displays (see ``_quoted_price``): the midpoint of a tight book, |
| 7 | otherwise the last trade. |
| 8 | """ |
| 9 | |
| 10 | import copy |
| 11 | import json |
| 12 | import math |
| 13 | from pathlib import Path |
| 14 | |
| 15 | import pytest |
| 16 | |
| 17 | from lib import normalize, polymarket, render |
| 18 | |
| 19 | FIXTURES = Path(__file__).parent / "fixtures" / "polymarket" |
| 20 | TO_DATE = "2026-11-16" |
| 21 | |
| 22 | |
| 23 | def _fixture(name): |
| 24 | return json.loads((FIXTURES / f"{name}.json").read_text()) |
| 25 | |
| 26 | |
| 27 | def _parse(topic, *events, to_date=TO_DATE, cap=None, **hints): |
| 28 | response = {"events": list(events)} |
| 29 | if cap is not None: |
| 30 | response["_cap"] = cap |
| 31 | return polymarket.parse_polymarket_response( |
| 32 | response, topic=topic, to_date=to_date, |
| 33 | hints=polymarket.PolymarketHints.coerce(hints or None), |
| 34 | ) |
| 35 | |
| 36 | |
| 37 | def _by_title(items): |
| 38 | return {item["title"]: item for item in items} |
| 39 | |
| 40 | |
| 41 | def _market(question, label, yes, volume, end="2027-03-01", **extra): |
| 42 | return { |
| 43 | "id": f"m-{label}", "question": question, "groupItemTitle": label, |
| 44 | "outcomes": '["Yes", "No"]', "outcomePrices": json.dumps([str(yes), str(round(1 - yes, 4))]), |
| 45 | "volume": str(volume), "volumeNum": volume, "liquidity": "5000", |
| 46 | "endDate": f"{end}T00:00:00Z", "active": True, "closed": False, **extra, |
| 47 | } |
| 48 | |
| 49 | |
| 50 | def _event(event_id, title, markets, neg_risk=False, volume1mo=1000): |
| 51 | return { |
| 52 | "id": event_id, "title": title, "slug": event_id, "active": True, "closed": False, |
| 53 | "negRisk": neg_risk, "volume1mo": volume1mo, "liquidity": 10000, |
| 54 | "updatedAt": "2026-11-16T00:00:00Z", "markets": markets, |
| 55 | } |
| 56 | |
| 57 | |
| 58 | NFL_CHAMPION = "Pro Football: 2027 Champion" |
| 59 | NBA_CHAMPION = "NBA: 2027 Champion" |
| 60 | ROOKIE = "NBA: 2026-27 Rookie of the Year" |
| 61 | WIN_TOTAL = "Pro Football: 49ers 2026 Win Total" |
| 62 | |
| 63 | |
| 64 | # --- Headline: the entity's own market --- |
| 65 | |
| 66 | |
| 67 | def test_champion_event_headlines_the_entitys_own_outcome(): |
| 68 | [item] = _parse("49ers", _fixture("pro_football_2027_champion")) |
| 69 | |
| 70 | assert item["title"] == NFL_CHAMPION |
| 71 | assert item["matched_market"]["label"] == "San Francisco 49ers" |
| 72 | assert item["headline"]["price"] == 0.145 |
| 73 | assert item["question"] == "Will the San Francisco 49ers win the 2027 NFL league championship?" |
| 74 | assert item["price_movement"] == "up 1.8% this month" |
| 75 | assert item["end_date"] == "2027-04-01" |
| 76 | assert item["outcome_prices"][0] == ("San Francisco 49ers", 0.145) |
| 77 | matched = item["matched_market"] |
| 78 | assert (matched["label"], matched["rank"], matched["contender"]) == ("San Francisco 49ers", 1, True) |
| 79 | assert "Chargers" not in item["question"] |
| 80 | |
| 81 | |
| 82 | def test_near_settled_win_total_ranks_after_the_live_champion_market(): |
| 83 | win_total = _fixture("pro_football_49ers_2026_win_total") |
| 84 | win_total["markets"] = [m for m in win_total["markets"] if m["groupItemTitle"] == "8.5+ Wins"] |
| 85 | |
| 86 | items = _parse("49ers", win_total, _fixture("pro_football_2027_champion")) |
| 87 | |
| 88 | assert [item["title"] for item in items] == [NFL_CHAMPION, WIN_TOTAL] |
| 89 | assert [item["selection_tier"] for item in items] == [1, 0] |
| 90 | |
| 91 | |
| 92 | def test_value_ladder_headlines_the_live_rung_closest_to_even(): |
| 93 | items = _parse("49ers", _fixture("pro_football_49ers_2026_win_total"), |
| 94 | _fixture("pro_football_2027_champion")) |
| 95 | |
| 96 | assert items[0]["title"] == NFL_CHAMPION |
| 97 | win_total = _by_title(items)[WIN_TOTAL] |
| 98 | assert win_total["selection_tier"] == 1 |
| 99 | assert win_total["matched_market"]["label"] == "12.5+ Wins" |
| 100 | assert win_total["headline"]["price"] == 0.775 |
| 101 | |
| 102 | |
| 103 | # --- Price floors --- |
| 104 | |
| 105 | |
| 106 | def test_long_shot_in_a_huge_race_ranks_after_a_smaller_live_market(): |
| 107 | items = _parse("Elon Musk", _fixture("republican_presidential_nominee_2028"), |
| 108 | _fixture("who_will_trump_pardon_before_2027")) |
| 109 | |
| 110 | assert [item["title"] for item in items] == [ |
| 111 | "Who will Trump pardon before 2027?", "Republican Presidential Nominee 2028", |
| 112 | ] |
| 113 | pardon, nominee = items |
| 114 | assert pardon["selection_tier"] == 1 |
| 115 | assert pardon["matched_market"]["label"] == "Elon Musk" |
| 116 | # 0.25% with $32M on it: under the 0.5% race floor. |
| 117 | assert nominee["selection_tier"] == 0 |
| 118 | assert nominee["matched_market"]["price"] == 0.0025 |
| 119 | |
| 120 | |
| 121 | def test_largest_company_race_is_kept_for_the_leader_and_a_long_shot(): |
| 122 | [apple] = _parse("Apple", _fixture("largest_company_end_of_december_2026")) |
| 123 | assert apple["selection_tier"] == 1 |
| 124 | assert apple["matched_market"]["label"] == "Apple" |
| 125 | assert apple["headline"]["price"] == 0.9055 |
| 126 | assert apple["matched_market"]["contender"] is True |
| 127 | |
| 128 | items = _by_title(_parse("Microsoft", _fixture("largest_company_end_of_december_2026"), |
| 129 | _fixture("third_largest_company_end_of_december_2026"))) |
| 130 | largest = items["Largest Company end of December 2026?"] |
| 131 | third = items["3rd Largest Company end of December 2026?"] |
| 132 | # 0.55% sits just above the race floor; fourth of eight is no contender. |
| 133 | assert (largest["selection_tier"], largest["matched_market"]["rank"]) == (1, 4) |
| 134 | assert largest["matched_market"]["contender"] is False |
| 135 | assert largest["selection_score"] == pytest.approx(math.log1p(1335787.56), abs=0.01) |
| 136 | # 35.5% and first of nine: the contender bonus. |
| 137 | assert (third["matched_market"]["rank"], third["matched_market"]["contender"]) == (1, True) |
| 138 | assert third["selection_score"] == pytest.approx(math.log1p(38086.96) + 1, abs=0.01) |
| 139 | |
| 140 | |
| 141 | def test_team_title_odds_count_down_to_the_race_floor(): |
| 142 | [item] = _parse("Warriors", _fixture("nba_2027_champion")) |
| 143 | assert item["selection_tier"] == 1 |
| 144 | assert item["matched_market"]["label"] == "Golden State Warriors" |
| 145 | assert item["headline"]["price"] == 0.0225 |
| 146 | assert item["matched_market"]["rank"] == 13 |
| 147 | |
| 148 | |
| 149 | def test_a_teams_biggest_race_has_no_floor_when_the_host_says_team(): |
| 150 | # The Wizards at 0.25% are under the 0.5% race floor. |
| 151 | [plain] = _parse("Washington Wizards", _fixture("nba_2027_champion")) |
| 152 | assert plain["selection_tier"] == 0 |
| 153 | [team] = _parse("Washington Wizards", _fixture("nba_2027_champion"), kind="team") |
| 154 | assert team["selection_tier"] == 1 |
| 155 | assert team["matched_market"]["label"] == "Washington Wizards" |
| 156 | |
| 157 | |
| 158 | # --- Related names and the contender bonus --- |
| 159 | |
| 160 | LENDEBORG = {"name": "Yaxel Lendeborg", "relation": "player"} |
| 161 | |
| 162 | |
| 163 | def test_related_name_leading_a_race_brings_the_race_in(): |
| 164 | items = _parse("Warriors", _fixture("nba_2027_champion"), |
| 165 | _fixture("nba_2026_27_rookie_of_the_year"), |
| 166 | kind="team", related=[LENDEBORG]) |
| 167 | |
| 168 | assert [item["title"] for item in items] == [NBA_CHAMPION, ROOKIE] |
| 169 | rookie = items[1] |
| 170 | assert rookie["matched_market"]["label"] == "Yaxel Lendeborg" |
| 171 | # A 10.7-cent spread: Polymarket shows the last trade. |
| 172 | assert rookie["headline"]["price"] == 0.346 |
| 173 | matched = rookie["matched_market"] |
| 174 | assert (matched["related_name"], matched["rank"], matched["contender"]) == ( |
| 175 | "Yaxel Lendeborg", 1, True, |
| 176 | ) |
| 177 | assert rookie["selection_score"] == pytest.approx(math.log1p(49097.83) + 1, abs=0.01) |
| 178 | |
| 179 | |
| 180 | def test_race_with_no_entity_or_related_name_is_not_matched(): |
| 181 | assert _parse("Warriors", _fixture("nba_2026_27_rookie_of_the_year")) == [] |
| 182 | |
| 183 | |
| 184 | def test_related_name_outside_the_top_three_contributes_nothing(): |
| 185 | # Darryn Peterson is fourth at 8.4% with $45k traded. |
| 186 | assert _parse("Warriors", _fixture("nba_2026_27_rookie_of_the_year"), |
| 187 | related=[{"name": "Darryn Peterson", "relation": "player"}]) == [] |
| 188 | |
| 189 | |
| 190 | def test_related_name_wins_a_large_sparse_race(): |
| 191 | [item] = _parse("Memphis Grizzlies", _fixture("nba_2026_27_most_improved_player"), |
| 192 | kind="team", related=[{"name": "Ty Jerome", "relation": "player"}]) |
| 193 | assert item["matched_market"]["label"] == "Ty Jerome" |
| 194 | assert item["matched_market"]["contender"] is True |
| 195 | |
| 196 | |
| 197 | def _placeholder_race(volume): |
| 198 | markets = [_market("Will Acme be the top lab?", "Acme", 0.5, volume)] + [ |
| 199 | _market(f"Will Lab {n} be the top lab?", f"Lab {n}", 0.1, 50000) for n in range(1, 5) |
| 200 | ] |
| 201 | return _event("race", "Top lab end of 2026?", markets, neg_risk=True) |
| 202 | |
| 203 | |
| 204 | def test_untraded_favorite_earns_no_contender_bonus(): |
| 205 | [item] = _parse("Acme", _placeholder_race(volume=400)) |
| 206 | assert item["matched_market"]["rank"] == 1 |
| 207 | assert item["matched_market"]["contender"] is False |
| 208 | assert item["selection_score"] == pytest.approx(math.log1p(400)) |
| 209 | assert _parse("Widgets", _placeholder_race(volume=400), |
| 210 | related=[{"name": "Acme", "relation": "product"}]) == [] |
| 211 | |
| 212 | |
| 213 | # --- Large events contribute one market --- |
| 214 | |
| 215 | |
| 216 | def test_game_sheet_contributes_only_its_largest_live_entity_market(): |
| 217 | props = [ |
| 218 | _market(f"Benfica to score {n}+ goals?", f"Benfica {n}+", 0.3, 1000 * n, end="2026-11-26") |
| 219 | for n in range(1, 34) |
| 220 | ] |
| 221 | other = _market("Exact Score: Any Other Score?", "Any Other Score", 0.2, 900000, end="2026-11-26") |
| 222 | event = _event("game", "FC Viktoria Plzen vs. Sport Lisboa e Benfica - More Markets", |
| 223 | props + [other]) |
| 224 | |
| 225 | [item] = _parse("Benfica", event) |
| 226 | |
| 227 | assert item["matched_market"]["label"] == "Benfica 33+" |
| 228 | assert item["selection_score"] == pytest.approx(math.log1p(33000)) |
| 229 | |
| 230 | |
| 231 | def test_live_exact_score_sheet_cannot_ride_its_any_other_score_prop(): |
| 232 | # Every score line names Benfica but none has a price or a trade; only |
| 233 | # "Any Other Score" (Benfica not in its own question) has $35.7k traded. |
| 234 | [item] = _parse("Benfica", _fixture("plzen_vs_benfica_exact_score")) |
| 235 | assert item["selection_tier"] == 0 |
| 236 | assert item["matched_market"]["label"] != "Any Other Score" |
| 237 | assert item["selection_score"] == 0.0 |
| 238 | assert item["headline"] is None |
| 239 | |
| 240 | |
| 241 | def test_title_level_topic_takes_one_market_from_a_league_wide_race(): |
| 242 | [item] = _parse("NFL", _fixture("pro_football_2027_champion")) |
| 243 | # NFL is no outcome of the race, so the 3% floor applies: the Buccaneers |
| 244 | # at 0.75% ($4.7M) are out, the Jaguars at 12.55% ($2.2M) lead. |
| 245 | assert item["matched_market"]["label"] == "Jacksonville Jaguars" |
| 246 | assert item["selection_score"] == pytest.approx(math.log1p(2243591.73), abs=0.01) |
| 247 | |
| 248 | |
| 249 | def test_best_ai_model_race_is_matched_on_the_outcome(): |
| 250 | [item] = _parse("Anthropic", _fixture("best_ai_model_end_of_2026")) |
| 251 | assert item["matched_market"]["label"] == "Anthropic" |
| 252 | assert item["headline"]["price"] == 0.18 |
| 253 | assert item["matched_market"]["rank"] == 2 |
| 254 | |
| 255 | |
| 256 | # --- Reference date and cap --- |
| 257 | |
| 258 | |
| 259 | def test_days_to_close_count_from_the_runs_end_date(): |
| 260 | event = _event("soon", "Will Acme ship by November 21?", |
| 261 | [_market("Will Acme ship by November 21?", "", 0.4, 5000, end="2026-11-21")]) |
| 262 | [late] = _parse("Acme", event, to_date="2026-11-16") |
| 263 | assert late["selection_tier"] == 0 |
| 264 | [early] = _parse("Acme", event, to_date="2026-11-06") |
| 265 | assert early["selection_tier"] == 1 |
| 266 | |
| 267 | |
| 268 | def test_quick_cap_keeps_the_top_scored_event(): |
| 269 | minor = [ |
| 270 | _event(f"minor{n}", f"Will the 49ers sign free agent {n}?", |
| 271 | [_market(f"Will the 49ers sign free agent {n}?", "", 0.4, 500)], |
| 272 | volume1mo=50_000_000) |
| 273 | for n in range(8) |
| 274 | ] |
| 275 | items = _parse("49ers", *minor, _fixture("pro_football_2027_champion"), cap=5) |
| 276 | assert len(items) == 5 |
| 277 | assert items[0]["title"] == NFL_CHAMPION |
| 278 | |
| 279 | |
| 280 | # --- Re-checking saved claims --- |
| 281 | |
| 282 | |
| 283 | def _refetch(monkeypatch, event, key): |
| 284 | monkeypatch.setattr(polymarket.http, "request", lambda *_a, **_k: event) |
| 285 | item = type("Item", (), {"metadata": {"event_id": event["id"]}, "url": "", "item_id": ""})() |
| 286 | return polymarket.refetch_datum(item, key)["value"] |
| 287 | |
| 288 | |
| 289 | def _champion_with_niners_at(price): |
| 290 | event = _fixture("pro_football_2027_champion") |
| 291 | for market in event["markets"]: |
| 292 | if market["groupItemTitle"] == "San Francisco 49ers": |
| 293 | market.update(outcomePrices=json.dumps([str(price), str(round(1 - price, 4))]), |
| 294 | bestBid=price - 0.001, bestAsk=price + 0.001, spread=0.002) |
| 295 | return event |
| 296 | |
| 297 | |
| 298 | def test_refetch_keeps_an_outcome_that_has_since_settled(monkeypatch): |
| 299 | event = _champion_with_niners_at(0.98) |
| 300 | assert _refetch(monkeypatch, event, "San Francisco 49ers") == 0.98 |
| 301 | |
| 302 | |
| 303 | def test_refetch_resolves_a_claim_saved_under_the_old_label(monkeypatch): |
| 304 | event = _champion_with_niners_at(0.145) |
| 305 | assert _refetch(monkeypatch, copy.deepcopy(event), "the San Francisco 49ers") == 0.145 |
| 306 | |
| 307 | |
| 308 | # --- Title-named brackets are not race outcomes --- |
| 309 | |
| 310 | |
| 311 | def _ipo_brackets(*prices): |
| 312 | labels = ["<500B", "500B-750B", "750B-1T", ">1T"] |
| 313 | markets = [ |
| 314 | _market(f"OpenAI IPO closing market cap {label}?", label, price, 90000) |
| 315 | for label, price in zip(labels, prices) |
| 316 | ] |
| 317 | return _event("ipo", "OpenAI IPO Closing Market Cap", markets, neg_risk=True) |
| 318 | |
| 319 | |
| 320 | def test_title_named_bracket_takes_the_yes_no_floor(): |
| 321 | # 1-2% clears the race floor but not the 3% floor of a yes/no or ladder |
| 322 | # market: the event title names the subject, no outcome does. |
| 323 | [item] = _parse("OpenAI", _ipo_brackets(0.01, 0.02, 0.01, 0.02)) |
| 324 | assert item["matched_market"]["in_band"] is False |
| 325 | assert item["selection_tier"] == 0 |
| 326 | |
| 327 | |
| 328 | def test_title_named_bracket_is_never_a_contender(): |
| 329 | [item] = _parse("OpenAI", _ipo_brackets(0.2, 0.35, 0.3, 0.15)) |
| 330 | matched = item["matched_market"] |
| 331 | assert matched["rank"] is None |
| 332 | assert matched["contender"] is False |
| 333 | assert item["selection_score"] == pytest.approx(math.log1p(4 * 90000)) |
| 334 | |
| 335 | |
| 336 | def test_race_outcome_keeps_its_headline_when_the_race_sums_over_one(): |
| 337 | # The race's Yes prices sum well over 1, so no distribution is shown, |
| 338 | # but Ty Jerome's own market has a real quote. |
| 339 | event = _fixture("nba_2026_27_most_improved_player") |
| 340 | event["markets"] += [ |
| 341 | _market(f"Will Player {n} win the 2026-27 NBA Most Improved Player?", f"Player {n}", |
| 342 | 0.3, 50, end="2027-07-01", negRisk=True) |
| 343 | for n in range(3) |
| 344 | ] |
| 345 | [item] = _parse("Memphis Grizzlies", event, |
| 346 | kind="team", related=[{"name": "Ty Jerome", "relation": "player"}]) |
| 347 | assert item["odds"] is None |
| 348 | assert item["headline"] is not None |
| 349 | assert "Ty Jerome" in item["headline"]["question"] |
| 350 | assert item["headline"]["price"] == item["matched_market"]["price"] |
| 351 | |
| 352 | |
| 353 | def _win_total(team, line, over, volume): |
| 354 | return _market( |
| 355 | f"Will the {team} win more than {line} games in the 2026 NFL Regular Season?", |
| 356 | team, over, volume, outcomes=json.dumps([f"O {line}", f"U {line}"]), |
| 357 | ) |
| 358 | |
| 359 | |
| 360 | def test_matched_line_speaks_for_the_matched_market_not_the_busiest(): |
| 361 | # The Ravens' over/under has the most money; the 49ers' is the match. |
| 362 | event = _event("totals", "Pro Football: 2026 Regular Season Win Totals", [ |
| 363 | _win_total("Baltimore Ravens", "11.5", 0.0585, 8806.7), |
| 364 | _win_total("San Francisco 49ers", "10.5", 0.935, 3555.76), |
| 365 | ]) |
| 366 | [item] = _parse("49ers", event, kind="team", aliases=["San Francisco 49ers"]) |
| 367 | question = "Will the San Francisco 49ers win more than 10.5 games in the 2026 NFL Regular Season?" |
| 368 | assert item["matched_market"]["question"] == question |
| 369 | assert item["odds"]["subject"] == question |
| 370 | assert item["outcome_prices"][0] == ("O 10.5", 0.935) |
| 371 | assert "Ravens" not in render._polymarket_odds_line( |
| 372 | normalize.normalize_source_items("polymarket", [item], "2026-10-17", TO_DATE)[0], "2026", |
| 373 | ) |
| 374 |