| 1 | """Polymarket prediction market search via Gamma API (free, no auth required). |
| 2 | |
| 3 | Uses gamma-api.polymarket.com for event/market discovery. |
| 4 | No API key needed - public read-only API. |
| 5 | """ |
| 6 | |
| 7 | import datetime |
| 8 | import json |
| 9 | import math |
| 10 | import re |
| 11 | import sys |
| 12 | import time |
| 13 | from concurrent.futures import ThreadPoolExecutor |
| 14 | from dataclasses import dataclass, field |
| 15 | from typing import Any, Dict, List, Optional, Tuple |
| 16 | from urllib.parse import quote, urlencode |
| 17 | |
| 18 | from . import http, log |
| 19 | |
| 20 | GAMMA_SEARCH_URL = "https://gamma-api.polymarket.com/public-search" |
| 21 | GAMMA_EVENTS_URL = "https://gamma-api.polymarket.com/events" |
| 22 | |
| 23 | SEARCH_LIMIT = { |
| 24 | "quick": 10, |
| 25 | "default": 20, |
| 26 | "deep": 50, |
| 27 | } |
| 28 | # Gamma answers bursts with 429s that carry no Retry-After, so searches run |
| 29 | # two at a time and a rate-limited call is retried with backoff. |
| 30 | _SEARCH_WORKERS = 2 |
| 31 | _SEARCH_ATTEMPTS = 3 |
| 32 | # Most aliases and related names a plan may give (planner.py validates it). |
| 33 | HINT_CAP = 5 |
| 34 | |
| 35 | # Max events to return after merge + dedup + re-ranking |
| 36 | RESULT_CAP = { |
| 37 | "quick": 5, |
| 38 | "default": 15, |
| 39 | "deep": 25, |
| 40 | } |
| 41 | |
| 42 | # The selection rule. A market is live ("in band") under PRICE_CEILING with |
| 43 | # MIN_DAYS_TO_CLOSE or more days left and at or above its floor: |
| 44 | # RACE_PRICE_FLOOR when the subject (or a related name) is itself an outcome |
| 45 | # of a mutually exclusive race of RACE_MIN_OUTCOMES or more live outcomes, |
| 46 | # PRICE_FLOOR for anything else, including the brackets of a race the event |
| 47 | # title names the subject in ("OpenAI IPO Closing Market Cap"). An |
| 48 | # event scores ln(1 + money traded on its live entity markets), plus |
| 49 | # CONTENDER_BONUS when one of them is a top-CONTENDER_TOP outcome of such a |
| 50 | # race with at least CONTENDER_MIN_VOLUME traded on its own market. An event |
| 51 | # of more than GAME_SHEET_MARKETS markets contributes one market. |
| 52 | PRICE_CEILING = 0.97 |
| 53 | PRICE_FLOOR = 0.03 |
| 54 | RACE_PRICE_FLOOR = 0.005 |
| 55 | RACE_MIN_OUTCOMES = 4 |
| 56 | MIN_DAYS_TO_CLOSE = 7 |
| 57 | CONTENDER_TOP = 3 |
| 58 | CONTENDER_MIN_VOLUME = 1000.0 |
| 59 | CONTENDER_BONUS = 1.0 |
| 60 | GAME_SHEET_MARKETS = 30 |
| 61 | |
| 62 | |
| 63 | def _log(msg: str): |
| 64 | log.source_log("PM", msg, tty_only=False) |
| 65 | |
| 66 | |
| 67 | def _extract_core_subject(topic: str) -> str: |
| 68 | """Extract core subject from topic string. |
| 69 | |
| 70 | Strips common prefixes like 'last 7 days', 'what are people saying about', etc. |
| 71 | """ |
| 72 | topic = topic.strip() |
| 73 | # Remove common leading phrases |
| 74 | prefixes = [ |
| 75 | r"^last \d+ days?\s+", |
| 76 | r"^what(?:'s| is| are) (?:people saying about|happening with|going on with)\s+", |
| 77 | r"^how (?:is|are)\s+", |
| 78 | r"^tell me about\s+", |
| 79 | r"^research\s+", |
| 80 | ] |
| 81 | for pattern in prefixes: |
| 82 | topic = re.sub(pattern, "", topic, flags=re.IGNORECASE) |
| 83 | return topic.strip() |
| 84 | |
| 85 | |
| 86 | # Words that are too generic to serve as the sole topic-match signal. |
| 87 | # If ALL core words from the topic are in this set, we skip filtering (can't meaningfully filter). |
| 88 | # But if some words are informative and some are generic, we require at least one informative word. |
| 89 | _NOISE_WORDS = frozenset({ |
| 90 | # Articles, prepositions, conjunctions |
| 91 | "the", "a", "an", "in", "on", "at", "of", "for", "and", "or", "to", "is", "are", |
| 92 | "was", "were", "will", "be", "by", "with", "from", "as", "it", "its", "not", "no", |
| 93 | "but", "if", "so", "do", "has", "had", "have", "this", "that", "what", "who", |
| 94 | # Directional / geographic terms that cause false matches |
| 95 | "west", "east", "north", "south", "central", "southern", "northern", "eastern", "western", |
| 96 | # Common sports / category terms |
| 97 | "champion", "championship", "league", "division", "conference", "cup", "series", |
| 98 | "team", "game", "match", "season", "win", "winner", "finals", |
| 99 | # Common geographic / place nouns that cause false matches |
| 100 | # "club" -> Athletic Club, Racing Club; "island" -> Epstein's Island, Rhode Island |
| 101 | "club", "island", "city", "park", "hill", "lake", "bay", "beach", "valley", |
| 102 | "river", "mountain", "county", "state", "village", "town", "point", "creek", |
| 103 | "springs", "heights", "ridge", "bridge", "harbor", "port", "station", "center", |
| 104 | "square", "field", "forest", "garden", "tower", "school", "church", "camp", |
| 105 | "ranch", "crossing", "shore", "rock", "summit", "falls", "grove", "haven", |
| 106 | # Generic tech terms — see _DOMAIN_WORDS below, which is folded in here |
| 107 | # Generic prediction market terms |
| 108 | "market", "odds", "prediction", "forecast", "chance", "probability", |
| 109 | # Comparison-query conjunctions — should not count as informative filter tokens |
| 110 | # when the topic is "X vs Y vs Z" |
| 111 | "vs", "versus", |
| 112 | }) |
| 113 | |
| 114 | # Generic tech terms that match too broadly to be the sole signal for a NARROW |
| 115 | # topic ("cli" -> any CLI tool market; "ai" -> every AI market), but which ARE |
| 116 | # the subject when the topic is a domain sweep rather than one product. Kept |
| 117 | # separate from the rest of _NOISE_WORDS — the directional/sports/place words |
| 118 | # there exist to PREVENT false matches ("NFC West" vs a "Kanye West" search), |
| 119 | # so they must never be used as a positive signal. |
| 120 | _DOMAIN_WORDS = frozenset({ |
| 121 | "cli", "mcp", "protocol", "tool", "app", "code", "model", "ai", "api", |
| 122 | "software", "plugin", "skill", "agent", "bot", "search", "research", |
| 123 | }) |
| 124 | |
| 125 | # Soft residue left after stripping domain words from a sweep topic |
| 126 | # ("AI frontier developments"). Domain-word fallback may fire when these are |
| 127 | # the only informative leftovers. Distinctive terms like "benchmark" block it. |
| 128 | _SWEEP_RESIDUE = frozenset({ |
| 129 | "frontier", "developments", "development", "news", "trends", "trend", |
| 130 | "latest", "industry", "space", "ecosystem", "landscape", "overview", |
| 131 | "updates", "update", "future", "outlook", "sector", "field", "world", |
| 132 | }) |
| 133 | |
| 134 | _NOISE_WORDS = _NOISE_WORDS | _DOMAIN_WORDS |
| 135 | |
| 136 | |
| 137 | def _domain_stem(word: str) -> str | None: |
| 138 | """Return the canonical domain token if ``word`` is a domain term or plural. |
| 139 | |
| 140 | Exact-set membership alone treats ``models`` as a hard narrowing term even |
| 141 | though ``model`` is a domain word — which blocked soft AI sweeps and broke |
| 142 | ``AI models`` → ``New AI prediction``. |
| 143 | """ |
| 144 | if word in _DOMAIN_WORDS: |
| 145 | return word |
| 146 | if word.endswith("ies") and len(word) > 4: |
| 147 | stem = word[:-3] + "y" |
| 148 | if stem in _DOMAIN_WORDS: |
| 149 | return stem |
| 150 | if len(word) > 3 and word.endswith("es") and word[:-2] in _DOMAIN_WORDS: |
| 151 | return word[:-2] |
| 152 | if len(word) > 2 and word.endswith("s") and word[:-1] in _DOMAIN_WORDS: |
| 153 | return word[:-1] |
| 154 | return None |
| 155 | |
| 156 | |
| 157 | def _informative_words(core_words: list[str]) -> list[str]: |
| 158 | """Topic words that are neither noise nor (possibly plural) domain terms.""" |
| 159 | return [ |
| 160 | w for w in core_words |
| 161 | if w not in _NOISE_WORDS and _domain_stem(w) is None |
| 162 | ] |
| 163 | |
| 164 | |
| 165 | def _domain_word_fallback_allows(core_words: list[str], informative: list[str], |
| 166 | title_lower: str, title_words: set[str]) -> bool: |
| 167 | """Allow domain-word title matches only for pure/soft domain sweeps. |
| 168 | |
| 169 | Blocks mixed topics like \"MCP protocol benchmark\" from accepting a Kyoto |
| 170 | Protocol market via the shared domain token \"protocol\" when the distinctive |
| 171 | informative word (\"benchmark\") missed. |
| 172 | """ |
| 173 | hard_informative = [w for w in informative if w not in _SWEEP_RESIDUE] |
| 174 | if hard_informative: |
| 175 | return False |
| 176 | domain_stems = [] |
| 177 | seen: set[str] = set() |
| 178 | for w in core_words: |
| 179 | stem = _domain_stem(w) |
| 180 | if stem and stem not in seen: |
| 181 | seen.add(stem) |
| 182 | domain_stems.append(stem) |
| 183 | if not domain_stems: |
| 184 | return False |
| 185 | for word in domain_stems: |
| 186 | if word in title_words or f"{word}s" in title_words or f"{word}es" in title_words: |
| 187 | return True |
| 188 | if len(word) >= 4 and word in title_lower: |
| 189 | return True |
| 190 | return False |
| 191 | |
| 192 | |
| 193 | _UPPERCASE_ACRONYM_RE = re.compile(r"(?<!\w)[A-Z]{3,}(?!\w)") |
| 194 | |
| 195 | |
| 196 | def _uppercase_acronyms(text: Any) -> frozenset[str]: |
| 197 | """Extract original-case all-caps 3+ letter acronym tokens before casefolding.""" |
| 198 | return frozenset(_UPPERCASE_ACRONYM_RE.findall(str(text or ""))) |
| 199 | |
| 200 | |
| 201 | def _acronym_credit(core_words: list[str], title_acronyms: set[str] | frozenset[str]) -> int: |
| 202 | """Credit matches when the title abbreviates a phrase the topic spells out. |
| 203 | |
| 204 | Prediction-market titles use shorthand ("AGI by 2030?") while topics arrive |
| 205 | spelled out ("artificial general intelligence"), so word overlap scores zero |
| 206 | on a title that is squarely on topic. For each run of 3+ consecutive |
| 207 | informative words, build its initialism and, if the original-case title |
| 208 | carries it as an all-caps whole word (excluding noise words even in all-caps |
| 209 | titles), credit one match per abbreviated word. Requiring at least three |
| 210 | letters avoids treating ambiguous tokens such as "ML" as expanded phrases. |
| 211 | """ |
| 212 | informative_set = set(_informative_words(core_words)) |
| 213 | credit = 0 |
| 214 | run: list[str] = [] |
| 215 | for word in core_words + [""]: |
| 216 | if word in informative_set: |
| 217 | run.append(word) |
| 218 | continue |
| 219 | if len(run) >= 3: |
| 220 | acronym = "".join(w[0] for w in run) |
| 221 | if ( |
| 222 | len(acronym) >= 3 |
| 223 | and acronym not in _NOISE_WORDS |
| 224 | and acronym.upper() in title_acronyms |
| 225 | ): |
| 226 | credit = max(credit, len(run)) |
| 227 | run = [] |
| 228 | return credit |
| 229 | |
| 230 | |
| 231 | @dataclass(frozen=True) |
| 232 | class RelatedName: |
| 233 | """A person or thing tied to the subject (a team's player, a company's CEO).""" |
| 234 | |
| 235 | name: str |
| 236 | relation: str = "" |
| 237 | |
| 238 | |
| 239 | @dataclass(frozen=True) |
| 240 | class PolymarketHints: |
| 241 | """What the host planner knows about the subject and Gamma cannot say. |
| 242 | |
| 243 | ``kind`` is the subject's kind ("team", "company", "person", "product", |
| 244 | "other"); only "team" changes selection. ``aliases`` name the subject |
| 245 | itself ("F1" for "Formula 1") and are searched and matched like the topic. |
| 246 | ``related`` names count only when they lead a race. Every field is |
| 247 | optional: with none, the topic text alone drives search and matching. |
| 248 | """ |
| 249 | |
| 250 | kind: Optional[str] = None |
| 251 | aliases: Tuple[str, ...] = () |
| 252 | related: Tuple[RelatedName, ...] = () |
| 253 | |
| 254 | @classmethod |
| 255 | def coerce(cls, value: Any) -> "PolymarketHints": |
| 256 | """Hints from None, a ``PolymarketHints``, a plan dict, or an object |
| 257 | with ``kind``/``aliases``/``related`` attributes.""" |
| 258 | if isinstance(value, cls): |
| 259 | return value |
| 260 | if value is None: |
| 261 | return cls() |
| 262 | |
| 263 | def get(key: str) -> Any: |
| 264 | if isinstance(value, dict): |
| 265 | return value.get(key) |
| 266 | return getattr(value, key, None) |
| 267 | |
| 268 | kind = str(get("kind") or "").strip().casefold() or None |
| 269 | aliases = tuple( |
| 270 | alias.strip() for alias in get("aliases") or [] |
| 271 | if isinstance(alias, str) and alias.strip() |
| 272 | ) |
| 273 | related = [] |
| 274 | for entry in get("related") or []: |
| 275 | if isinstance(entry, dict): |
| 276 | name, relation = entry.get("name"), entry.get("relation") |
| 277 | else: |
| 278 | name, relation = getattr(entry, "name", None), getattr(entry, "relation", None) |
| 279 | name = str(name or "").strip() |
| 280 | if name: |
| 281 | related.append(RelatedName(name, str(relation or "").strip())) |
| 282 | return cls(kind, aliases, tuple(related)) |
| 283 | |
| 284 | |
| 285 | def _match_text(text: Any) -> str: |
| 286 | """Text as the entity matcher compares it: casefolded, possessive "'s" |
| 287 | dropped, punctuation turned to spaces.""" |
| 288 | text = str(text or "").casefold().replace("’", "'") |
| 289 | text = re.sub(r"'s\b", "", text) |
| 290 | return " ".join(re.sub(r"[^\w\s]", " ", text).split()) |
| 291 | |
| 292 | |
| 293 | def _has_word(word: str, words: set) -> bool: |
| 294 | """Whether ``words`` holds ``word`` or its simple plural or singular form |
| 295 | ("rate" and "rates", "tax" and "taxes").""" |
| 296 | if word in words or f"{word}s" in words or f"{word}es" in words: |
| 297 | return True |
| 298 | if word.endswith("es") and word[:-2] in words: |
| 299 | return True |
| 300 | return word.endswith("s") and word[:-1] in words |
| 301 | |
| 302 | |
| 303 | class _Term: |
| 304 | """One name the matcher looks for, as a whole phrase.""" |
| 305 | |
| 306 | def __init__(self, name: str): |
| 307 | self.phrase = re.sub(r"^the\s+", "", _match_text(name)) |
| 308 | self.pattern = ( |
| 309 | re.compile(rf"(?<!\w){re.escape(self.phrase)}(?!\w)") if self.phrase else None |
| 310 | ) |
| 311 | self.words = [word for word in self.phrase.split() if len(word) > 1] |
| 312 | self.informative = _informative_words(self.words) |
| 313 | |
| 314 | def found_in( |
| 315 | self, |
| 316 | text: str, |
| 317 | *, |
| 318 | acronyms: Optional[frozenset[str] | set[str]] = None, |
| 319 | ) -> bool: |
| 320 | """Whether ``text`` (already through ``_match_text``) names this term: |
| 321 | the whole phrase at word boundaries, an all-caps initialism of a |
| 322 | spelled-out phrase ("AGI"), every informative word of a descriptive |
| 323 | topic in any order ("Nvidia earnings"), or, for a soft domain sweep |
| 324 | ("AI frontier developments"), its domain word.""" |
| 325 | if self.pattern is None: |
| 326 | return False |
| 327 | if self.pattern.search(text): |
| 328 | return True |
| 329 | words = set(text.split()) |
| 330 | title_acronyms = _uppercase_acronyms(text) if acronyms is None else acronyms |
| 331 | if title_acronyms and _acronym_credit(self.words, title_acronyms): |
| 332 | return True |
| 333 | if len(self.informative) >= 2 and all(_has_word(word, words) for word in self.informative): |
| 334 | return True |
| 335 | return _domain_word_fallback_allows(self.words, self.informative, text, words) |
| 336 | |
| 337 | |
| 338 | def _topic_sides(topic: str) -> List[str]: |
| 339 | """Each side of a "vs" topic, or the topic's core subject alone.""" |
| 340 | return re.split(r"\s+(?:vs\.?|versus)\s+", _extract_core_subject(topic), flags=re.IGNORECASE) |
| 341 | |
| 342 | |
| 343 | def _prepare_match_text(raw: Any) -> Tuple[str, frozenset[str]]: |
| 344 | return (_match_text(raw), _uppercase_acronyms(raw)) |
| 345 | |
| 346 | |
| 347 | def _names_any( |
| 348 | terms: List[_Term], |
| 349 | texts: List[str | Tuple[str, frozenset[str]]], |
| 350 | ) -> bool: |
| 351 | """Whether any of ``terms`` is found in any non-empty text of ``texts``.""" |
| 352 | for entry in texts: |
| 353 | if isinstance(entry, tuple): |
| 354 | text, acronyms = entry |
| 355 | else: |
| 356 | text, acronyms = entry, None |
| 357 | if not text: |
| 358 | continue |
| 359 | if any(term.found_in(text, acronyms=acronyms) for term in terms): |
| 360 | return True |
| 361 | return False |
| 362 | |
| 363 | |
| 364 | def _entity_terms(topic: str, aliases: Tuple[str, ...] = ()) -> List[str]: |
| 365 | """The names that stand for the subject: each side of a "vs" topic, then |
| 366 | each alias, once each.""" |
| 367 | sides = _topic_sides(topic or "") |
| 368 | terms: List[str] = [] |
| 369 | seen: set = set() |
| 370 | for term in [*sides, *aliases]: |
| 371 | term = term.strip() |
| 372 | key = _Term(term).phrase |
| 373 | if key and key not in seen: |
| 374 | seen.add(key) |
| 375 | terms.append(term) |
| 376 | return terms |
| 377 | |
| 378 | |
| 379 | def _json_list(value: Any) -> List[Any]: |
| 380 | if isinstance(value, str): |
| 381 | try: |
| 382 | value = json.loads(value) |
| 383 | except (json.JSONDecodeError, TypeError): |
| 384 | return [] |
| 385 | return list(value) if isinstance(value, (list, tuple)) else [] |
| 386 | |
| 387 | |
| 388 | def _market_texts(market: Dict[str, Any]) -> List[str]: |
| 389 | """A market's own text: its question, its ``groupItemTitle`` and its |
| 390 | outcome labels other than Yes and No.""" |
| 391 | labels = [ |
| 392 | str(outcome) for outcome in _json_list(market.get("outcomes")) |
| 393 | if str(outcome).strip().casefold() not in ("yes", "no") |
| 394 | ] |
| 395 | return [str(market.get("question") or ""), str(market.get("groupItemTitle") or ""), *labels] |
| 396 | |
| 397 | |
| 398 | @dataclass(frozen=True) |
| 399 | class EntityMatch: |
| 400 | """How a market names the subject. |
| 401 | |
| 402 | ``field`` is "market" when the market's own question, label or outcome |
| 403 | names it and "title" when only its event title does. ``related`` is the |
| 404 | related name that matched, None when the subject (or an alias) did. |
| 405 | """ |
| 406 | |
| 407 | field: str |
| 408 | related: Optional[str] = None |
| 409 | relation: str = "" |
| 410 | |
| 411 | |
| 412 | class EntityMatcher: |
| 413 | """Decides whether a market names the research subject. |
| 414 | |
| 415 | The topic and each alias match as whole phrases, ignoring a leading "the" |
| 416 | and a possessive "'s", in a market's question, ``groupItemTitle``, |
| 417 | non-Yes/No outcome labels, or its event title. A related name matches |
| 418 | only the market's own text, and only when the subject does not. |
| 419 | """ |
| 420 | |
| 421 | def __init__(self, topic: str, hints: Any = None): |
| 422 | self.hints = PolymarketHints.coerce(hints) |
| 423 | self.terms = [_Term(term) for term in _entity_terms(topic, self.hints.aliases)] |
| 424 | self.related = [(entry, _Term(entry.name)) for entry in self.hints.related] |
| 425 | |
| 426 | def match( |
| 427 | self, |
| 428 | market: Dict[str, Any], |
| 429 | event_title: str = "", |
| 430 | *, |
| 431 | title_text: Optional[str] = None, |
| 432 | title_acronyms: Optional[frozenset[str]] = None, |
| 433 | ) -> Optional[EntityMatch]: |
| 434 | """``title_text``, when given, is ``event_title`` already through |
| 435 | ``_match_text``, so a caller matching many markets of one event |
| 436 | normalizes the title once.""" |
| 437 | own = [_prepare_match_text(text) for text in _market_texts(market)] |
| 438 | if _names_any(self.terms, own): |
| 439 | return EntityMatch("market") |
| 440 | title_pair = ( |
| 441 | _match_text(event_title) if title_text is None else title_text, |
| 442 | _uppercase_acronyms(event_title) if title_acronyms is None else title_acronyms, |
| 443 | ) |
| 444 | if _names_any(self.terms, [title_pair]): |
| 445 | return EntityMatch("title") |
| 446 | for entry, term in self.related: |
| 447 | if _names_any([term], own): |
| 448 | return EntityMatch("market", entry.name, entry.relation) |
| 449 | return None |
| 450 | |
| 451 | def outcome_kind( |
| 452 | self, |
| 453 | market: Dict[str, Any], |
| 454 | match: EntityMatch, |
| 455 | event_title: str = "", |
| 456 | *, |
| 457 | title_text: Optional[str] = None, |
| 458 | title_acronyms: Optional[frozenset[str]] = None, |
| 459 | ) -> Optional[str]: |
| 460 | """How the subject (or the related name) is an outcome of the event: |
| 461 | "label" when the market's ``groupItemTitle`` names it and, for the |
| 462 | subject, the event title does not; "outcome" when only a non-Yes/No |
| 463 | outcome label names the subject; None when the market is about the |
| 464 | subject without the subject being one of the event's outcomes (a |
| 465 | bracket of "OpenAI IPO Closing Market Cap"). ``title_text`` is as for |
| 466 | ``match``.""" |
| 467 | label = _prepare_match_text(market.get("groupItemTitle")) |
| 468 | if match.related: |
| 469 | terms = [term for entry, term in self.related if entry.name == match.related] |
| 470 | return "label" if label[0] and _names_any(terms, [label]) else None |
| 471 | title_pair = ( |
| 472 | _match_text(event_title) if title_text is None else title_text, |
| 473 | _uppercase_acronyms(event_title) if title_acronyms is None else title_acronyms, |
| 474 | ) |
| 475 | if _names_any(self.terms, [title_pair]): |
| 476 | return None |
| 477 | if label[0] and _names_any(self.terms, [label]): |
| 478 | return "label" |
| 479 | if _names_any(self.terms, [_prepare_match_text(market.get("question"))]): |
| 480 | return None |
| 481 | return "outcome" if self.matched_outcome(market, match) is not None else None |
| 482 | |
| 483 | def matched_outcome(self, market: Dict[str, Any], match: EntityMatch) -> Optional[str]: |
| 484 | """The non-Yes/No outcome label that names the subject (or the related |
| 485 | name that matched), for a market whose outcomes are names.""" |
| 486 | terms = ( |
| 487 | [term for entry, term in self.related if entry.name == match.related] |
| 488 | if match.related else self.terms |
| 489 | ) |
| 490 | for outcome in _json_list(market.get("outcomes")): |
| 491 | name = str(outcome) |
| 492 | if name.strip().casefold() in ("yes", "no"): |
| 493 | continue |
| 494 | if _names_any(terms, [_prepare_match_text(name)]): |
| 495 | return name |
| 496 | return None |
| 497 | |
| 498 | |
| 499 | def _item_matches(matcher: "EntityMatcher", item: Any) -> bool: |
| 500 | """Whether a parsed or normalized item names what ``matcher`` looks for. |
| 501 | |
| 502 | Reads the event title, the matched market's question and label, the |
| 503 | headline market's question and label, and the item's own question. A raw |
| 504 | parse dict carries these at the top level, a ``SourceItem`` in metadata. |
| 505 | """ |
| 506 | if isinstance(item, dict): |
| 507 | fields = {**(item.get("metadata") or {}), **item} |
| 508 | else: |
| 509 | fields = {**(getattr(item, "metadata", None) or {}), "title": getattr(item, "title", "")} |
| 510 | matched = fields.get("matched_market") if isinstance(fields.get("matched_market"), dict) else {} |
| 511 | headline = fields.get("headline") if isinstance(fields.get("headline"), dict) else {} |
| 512 | market = { |
| 513 | "question": str(matched.get("question") or fields.get("question") or ""), |
| 514 | "groupItemTitle": str(matched.get("label") or ""), |
| 515 | "outcomes": [ |
| 516 | str(text) for text in ( |
| 517 | headline.get("question"), headline.get("label"), fields.get("question"), |
| 518 | ) if text |
| 519 | ], |
| 520 | } |
| 521 | return matcher.match(market, str(fields.get("title") or "")) is not None |
| 522 | |
| 523 | |
| 524 | def filter_items_against_topic(topic: str, items: List[Any], hints: Any = None) -> List[Any]: |
| 525 | """Keep the items whose market names the research topic, by ``EntityMatcher``. |
| 526 | |
| 527 | The Polymarket topic bar, called post-merge from pipeline.py on the stable |
| 528 | research topic and the run's hints. The event title alone is not enough: |
| 529 | "Pro Football: 2027 Champion" names the 49ers only in its matched market, |
| 530 | and a related player's award market only through a host-supplied name. |
| 531 | Each side of a "vs" topic counts, so a market naming one compared entity |
| 532 | stays. |
| 533 | |
| 534 | Accepts raw parse dicts or SourceItem-like objects and returns the kept |
| 535 | items in the same order. |
| 536 | """ |
| 537 | if not topic: |
| 538 | return items |
| 539 | matcher = EntityMatcher(topic, hints) |
| 540 | filtered = [item for item in items if _item_matches(matcher, item)] |
| 541 | |
| 542 | dropped = len(items) - len(filtered) |
| 543 | if dropped: |
| 544 | _log(f"Post-merge topic filter dropped {dropped} Polymarket items against full topic '{topic}'") |
| 545 | |
| 546 | return filtered |
| 547 | |
| 548 | |
| 549 | def filter_items_against_keywords(items: List[Any], keywords: List[str]) -> List[Any]: |
| 550 | """Keep only items whose market names at least one keyword, by ``EntityMatcher``. |
| 551 | |
| 552 | Intended for disambiguating ambiguous single-token topics like 'Warriors' |
| 553 | via --polymarket-keywords (e.g., 'nba,gsw,golden-state') to filter out |
| 554 | Glasgow Warriors rugby, Honor of Kings Rogue Warriors markets that share |
| 555 | the 'Warriors' token but are not the target entity. Each keyword matches |
| 556 | as a whole phrase, any case, in the same fields as the topic filter. |
| 557 | """ |
| 558 | normalized_keywords = [kw.strip() for kw in keywords or [] if kw and kw.strip()] |
| 559 | if not normalized_keywords: |
| 560 | return items |
| 561 | matcher = EntityMatcher("", PolymarketHints(aliases=tuple(normalized_keywords))) |
| 562 | filtered = [item for item in items if _item_matches(matcher, item)] |
| 563 | |
| 564 | dropped = len(items) - len(filtered) |
| 565 | if dropped: |
| 566 | _log( |
| 567 | f"Keyword filter dropped {dropped} Polymarket items; " |
| 568 | f"kept {len(filtered)} matching {normalized_keywords}" |
| 569 | ) |
| 570 | |
| 571 | return filtered |
| 572 | |
| 573 | |
| 574 | def _search_term(term: str, limit: int, deadline: Optional[float] = None) -> Dict[str, Any]: |
| 575 | """One volume-sorted public-search for one term, retries included, ending |
| 576 | by ``deadline`` (a ``time.monotonic()`` value) when one is given.""" |
| 577 | params = { |
| 578 | "q": term, |
| 579 | "sort": "volume", |
| 580 | "events_status": "active", |
| 581 | "keep_closed_markets": "0", |
| 582 | "limit_per_type": str(limit), |
| 583 | } |
| 584 | url = f"{GAMMA_SEARCH_URL}?{urlencode(params)}" |
| 585 | try: |
| 586 | return http.request( |
| 587 | "GET", url, timeout=15, |
| 588 | retries=_SEARCH_ATTEMPTS, max_429_retries=_SEARCH_ATTEMPTS, |
| 589 | deadline_monotonic=deadline, |
| 590 | ) |
| 591 | except Exception as e: |
| 592 | _log(f"Search failed for '{term}': {e}") |
| 593 | return {"events": [], "error": str(e)} |
| 594 | |
| 595 | |
| 596 | def _run_searches( |
| 597 | terms: List[str], limit: int, events: Dict[str, Dict[str, Any]], errors: List[str], |
| 598 | deadline: Optional[float] = None, |
| 599 | ) -> None: |
| 600 | """Search each term, adding open events to ``events`` by id. An event |
| 601 | found by an earlier term keeps that term's copy.""" |
| 602 | if not terms: |
| 603 | return |
| 604 | with ThreadPoolExecutor(max_workers=min(_SEARCH_WORKERS, len(terms))) as executor: |
| 605 | futures = [ |
| 606 | http.submit_with_context(executor, _search_term, term, limit, deadline) for term in terms |
| 607 | ] |
| 608 | for future in futures: |
| 609 | try: |
| 610 | response = future.result() |
| 611 | except Exception as e: |
| 612 | errors.append(str(e)) |
| 613 | continue |
| 614 | if response.get("error"): |
| 615 | errors.append(str(response["error"])) |
| 616 | for event in response.get("events") or []: |
| 617 | event_id = str(event.get("id") or "") |
| 618 | # events_status=active can still return a closed event. |
| 619 | if event_id and not event.get("closed") and event_id not in events: |
| 620 | events[event_id] = event |
| 621 | |
| 622 | |
| 623 | def search_polymarket( |
| 624 | topic: str, |
| 625 | from_date: str, |
| 626 | to_date: str, |
| 627 | depth: str = "default", |
| 628 | hints: Any = None, |
| 629 | deadline: Optional[float] = None, |
| 630 | ) -> Dict[str, Any]: |
| 631 | """Search Polymarket for the subject's events, biggest money first. |
| 632 | |
| 633 | One volume-sorted public-search per subject name (the topic, each side of |
| 634 | a "vs" topic, each host alias). Then each related name the merged events |
| 635 | not already an outcome of a race in the merged events is searched on its |
| 636 | own. |
| 637 | |
| 638 | Args: |
| 639 | topic: Search topic |
| 640 | from_date: Start date (YYYY-MM-DD); Gamma searches open events, so unused |
| 641 | to_date: End date (YYYY-MM-DD); unused for the same reason |
| 642 | depth: 'quick', 'default', or 'deep' |
| 643 | hints: Optional ``PolymarketHints`` (or a plan dict of the same shape) |
| 644 | deadline: Optional ``time.monotonic()`` value every search, retries |
| 645 | included, must finish by; the related-name searches are skipped |
| 646 | once it has passed. |
| 647 | |
| 648 | Returns: |
| 649 | Dict with 'events' list, plus 'error' when any search failed and |
| 650 | 'partial' when some searches failed but others returned events. |
| 651 | """ |
| 652 | hints = PolymarketHints.coerce(hints) |
| 653 | limit = SEARCH_LIMIT.get(depth, SEARCH_LIMIT["default"]) |
| 654 | cap = RESULT_CAP.get(depth, RESULT_CAP["default"]) |
| 655 | terms = _entity_terms(topic, hints.aliases) |
| 656 | |
| 657 | _log(f"Searching for '{topic}' with terms: {terms} (limit={limit})") |
| 658 | |
| 659 | events: Dict[str, Dict[str, Any]] = {} |
| 660 | errors: List[str] = [] |
| 661 | _run_searches(terms, limit, events, errors, deadline) |
| 662 | |
| 663 | # A related name is searched unless the pool already holds a race it is |
| 664 | # an outcome of; a game prop naming the player is no award race. |
| 665 | race_labels = [] |
| 666 | for event in events.values(): |
| 667 | live = _live_markets(event) |
| 668 | if _is_race(event, live): |
| 669 | race_labels += [_prepare_match_text(market.get("groupItemTitle")) for market in live] |
| 670 | related_terms = [ |
| 671 | entry.name for entry in hints.related[:HINT_CAP] |
| 672 | if not _names_any([_Term(entry.name)], race_labels) |
| 673 | ] |
| 674 | if related_terms and deadline is not None and time.monotonic() >= deadline: |
| 675 | errors.append(f"skipped related-name searches {related_terms}: deadline passed") |
| 676 | related_terms = [] |
| 677 | if related_terms: |
| 678 | _log(f"Searching related names: {related_terms}") |
| 679 | _run_searches(related_terms, limit, events, errors, deadline) |
| 680 | |
| 681 | merged_events = list(events.values()) |
| 682 | _log(f"Found {len(merged_events)} unique events across {len(terms) + len(related_terms)} searches") |
| 683 | |
| 684 | result = {"events": merged_events, "_cap": cap} |
| 685 | if errors: |
| 686 | result["error"] = "; ".join(errors[:2]) |
| 687 | if merged_events: |
| 688 | result["partial"] = True |
| 689 | return result |
| 690 | |
| 691 | |
| 692 | def _format_price_movement(market: Dict[str, Any]) -> Optional[str]: |
| 693 | """Pick the most significant price change and format it. |
| 694 | |
| 695 | Returns string like 'down 11.7% this month' or None if no significant change. |
| 696 | """ |
| 697 | changes = [ |
| 698 | (abs(market.get("oneDayPriceChange") or 0), market.get("oneDayPriceChange"), "today"), |
| 699 | (abs(market.get("oneWeekPriceChange") or 0), market.get("oneWeekPriceChange"), "this week"), |
| 700 | (abs(market.get("oneMonthPriceChange") or 0), market.get("oneMonthPriceChange"), "this month"), |
| 701 | ] |
| 702 | |
| 703 | # Pick the largest absolute change |
| 704 | changes.sort(key=lambda x: x[0], reverse=True) |
| 705 | abs_change, raw_change, period = changes[0] |
| 706 | |
| 707 | # Skip if change is less than 1% (noise) |
| 708 | if abs_change < 0.01: |
| 709 | return None |
| 710 | |
| 711 | direction = "up" if raw_change > 0 else "down" |
| 712 | pct = abs_change * 100 |
| 713 | return f"{direction} {pct:.1f}% {period}" |
| 714 | |
| 715 | |
| 716 | def _price_movement_points(market: Dict[str, Any]) -> Optional[List[Any]]: |
| 717 | """The same change ``_format_price_movement`` words, as ``[points, period]``. |
| 718 | |
| 719 | Gamma's ``oneDayPriceChange`` / ``oneWeekPriceChange`` / |
| 720 | ``oneMonthPriceChange`` are differences between two prices on the 0-to-1 |
| 721 | scale, so times 100 they are percentage points, signed, not a relative |
| 722 | change. None under one point. |
| 723 | """ |
| 724 | changes = [ |
| 725 | (market.get("oneDayPriceChange") or 0, "today"), |
| 726 | (market.get("oneWeekPriceChange") or 0, "this week"), |
| 727 | (market.get("oneMonthPriceChange") or 0, "this month"), |
| 728 | ] |
| 729 | changes = [(c, p) for c, p in changes if isinstance(c, (int, float)) and not isinstance(c, bool)] |
| 730 | if not changes: |
| 731 | return None |
| 732 | # Stable sort: the shorter period wins a tie, as in _format_price_movement. |
| 733 | change, period = sorted(changes, key=lambda pair: -abs(pair[0]))[0] |
| 734 | if abs(change) < 0.01: |
| 735 | return None |
| 736 | return [round(change * 100, 1), period] |
| 737 | |
| 738 | |
| 739 | # Polymarket displays a market's midpoint only while its book is tight: a bid |
| 740 | # and an ask no more than 10 cents apart. A wider or one-sided book shows the |
| 741 | # last trade instead, since the midpoint of an empty book (no bid, ask 0.87) |
| 742 | # is no one's price. |
| 743 | _MAX_MIDPOINT_SPREAD = 0.10 |
| 744 | _BOOK_FIELDS = ("bestBid", "bestAsk", "spread") |
| 745 | # The most a mutually exclusive (negRisk) set's Yes prices may sum to and |
| 746 | # still be shown as one distribution. |
| 747 | _MAX_EXCLUSIVE_YES_TOTAL = 1.10 |
| 748 | |
| 749 | |
| 750 | def _optional_float(val: Any) -> Optional[float]: |
| 751 | """Parse a finite non-bool float, returning None when absent or malformed.""" |
| 752 | if val is None or isinstance(val, bool): |
| 753 | return None |
| 754 | if isinstance(val, str) and not val.strip(): |
| 755 | return None |
| 756 | try: |
| 757 | parsed = float(val) |
| 758 | except (ValueError, TypeError, OverflowError): |
| 759 | return None |
| 760 | return parsed if math.isfinite(parsed) else None |
| 761 | |
| 762 | |
| 763 | def _quoted_price(market: Dict[str, Any], midpoint: float) -> Optional[float]: |
| 764 | """The price Polymarket would display for a market's first (Yes) outcome. |
| 765 | |
| 766 | The midpoint (``outcomePrices``) when the book has a bid and an ask within |
| 767 | ``_MAX_MIDPOINT_SPREAD``; otherwise the last trade; otherwise None (the |
| 768 | market is unpriced). A market served without any book field (older |
| 769 | fixtures, saved replays) and a closed market (its price is the |
| 770 | resolution) keep the midpoint. |
| 771 | """ |
| 772 | if market.get("closed") or all(market.get(field) is None for field in _BOOK_FIELDS): |
| 773 | return midpoint |
| 774 | bid = _optional_float(market.get("bestBid")) |
| 775 | ask = _optional_float(market.get("bestAsk")) |
| 776 | raw_spread = _optional_float(market.get("spread")) |
| 777 | if bid is not None and ask is not None and bid > 0 and ask >= bid: |
| 778 | spread = raw_spread if (raw_spread is not None and raw_spread >= 0) else ask - bid |
| 779 | # Float noise: an ask of 0.13 over a bid of 0.03 is a 0.10 spread. |
| 780 | if round(spread, 6) <= _MAX_MIDPOINT_SPREAD: |
| 781 | return midpoint |
| 782 | last = _optional_float(market.get("lastTradePrice")) |
| 783 | if last is not None and 0 < last < 1: |
| 784 | return last |
| 785 | return None |
| 786 | |
| 787 | |
| 788 | def _parse_outcome_prices(market: Dict[str, Any], *, book_aware: bool = True) -> List[tuple]: |
| 789 | """Parse outcomePrices JSON string into list of (outcome_name, price) tuples. |
| 790 | |
| 791 | ``book_aware`` prices the market the way Polymarket displays it (see |
| 792 | ``_quoted_price``): an unpriced market parses to no outcomes, and a |
| 793 | two-outcome market quoted from its last trade prices its second outcome |
| 794 | as the complement. |
| 795 | """ |
| 796 | outcomes = _json_list(market.get("outcomes")) |
| 797 | prices = _json_list(market.get("outcomePrices")) |
| 798 | |
| 799 | if not prices: |
| 800 | return [] |
| 801 | |
| 802 | result = [] |
| 803 | has_first = False |
| 804 | for i, price in enumerate(prices): |
| 805 | if isinstance(price, bool): |
| 806 | continue |
| 807 | try: |
| 808 | p = float(price) |
| 809 | except (ValueError, TypeError, OverflowError): |
| 810 | continue |
| 811 | if not math.isfinite(p) or p < 0.0 or p > 1.0: |
| 812 | continue |
| 813 | if i == 0: |
| 814 | has_first = True |
| 815 | raw_name = outcomes[i] if i < len(outcomes) else None |
| 816 | name = str(raw_name) if raw_name is not None else f"Outcome {i+1}" |
| 817 | result.append((name, p)) |
| 818 | |
| 819 | if book_aware and result: |
| 820 | if not has_first: |
| 821 | return [] |
| 822 | quoted = _quoted_price(market, result[0][1]) |
| 823 | if quoted is None: |
| 824 | return [] |
| 825 | if quoted != result[0][1]: |
| 826 | result[0] = (result[0][0], quoted) |
| 827 | if len(prices) == 2 and len(result) == 2: |
| 828 | result[1] = (result[1][0], round(1 - quoted, 4)) |
| 829 | |
| 830 | return result |
| 831 | |
| 832 | |
| 833 | # Longest name _shorten_question keeps when a question has no shorter subject. |
| 834 | _MAX_QUESTION_NAME_CHARS = 80 |
| 835 | _UNBROKEN_NAME_CHARS = 40 |
| 836 | |
| 837 | |
| 838 | def _question_subject(q: str) -> Optional[str]: |
| 839 | """The subject of a "Will X win/be/..." question, or None.""" |
| 840 | # Common patterns: "Will X win/be/...", "X wins/loses..." |
| 841 | m = re.match(r"^Will\s+(.+?)\s+(?:win|be|make|reach|have|lose|qualify|advance|strike|agree|pass|sign|get|become|remain|stay|leave|survive|next)\b", q, re.IGNORECASE) |
| 842 | if m: |
| 843 | return m.group(1).strip() |
| 844 | m = re.match(r"^Will\s+(.+?)\s+", q, re.IGNORECASE) |
| 845 | if m and len(m.group(1).split()) <= 4: |
| 846 | return m.group(1).strip() |
| 847 | return None |
| 848 | |
| 849 | |
| 850 | def _shorten_question(question: str) -> str: |
| 851 | """Extract a short display name from a market question. |
| 852 | |
| 853 | 'Will Arizona win the 2026 NCAA Tournament?' -> 'Arizona' |
| 854 | 'Will Duke be a number 1 seed in the 2026 NCAA...' -> 'Duke' |
| 855 | """ |
| 856 | q = question.strip().rstrip("?") |
| 857 | subject = _question_subject(q) |
| 858 | if subject is not None: |
| 859 | return subject |
| 860 | return _whole_question_name(q) |
| 861 | |
| 862 | |
| 863 | def _whole_question_name(q: str) -> str: |
| 864 | """The question itself as a name. Sub-markets of one event often differ |
| 865 | only in their last words ("... by March 31, 2027"), so it is kept whole |
| 866 | and only a very long one is cut, at a word boundary. A leading article is |
| 867 | dropped so the name doesn't read "an"/"the".""" |
| 868 | q = q.strip().rstrip("?") |
| 869 | text = q |
| 870 | if len(q) > _MAX_QUESTION_NAME_CHARS: |
| 871 | head = q[: _MAX_QUESTION_NAME_CHARS + 1] |
| 872 | if " " in head: |
| 873 | text = head.rsplit(" ", 1)[0].rstrip(" ,;:-") |
| 874 | else: |
| 875 | # One unbroken run has no word boundary to cut at. |
| 876 | text = q[:_UNBROKEN_NAME_CHARS] |
| 877 | return re.sub(r"^(?:a|an|the)\s+", "", text, flags=re.I) |
| 878 | |
| 879 | |
| 880 | _ARTICLES = frozenset({"a", "an", "the"}) |
| 881 | |
| 882 | |
| 883 | def _sibling_outcome_labels(sibling_markets: List[Dict[str, Any]]) -> Dict[int, str]: |
| 884 | """Compute unambiguous per-market labels across all child markets in an event. |
| 885 | |
| 886 | Running label disambiguation across the entire event before price filtering |
| 887 | guarantees that a market keeps the same label during display parsing |
| 888 | (``include_all_outcomes=False``) and verification (``include_all_outcomes=True``), |
| 889 | even when a sub-floor sibling shares its ``groupItemTitle`` or another |
| 890 | market's ``groupItemTitle`` collides with its question subject. |
| 891 | """ |
| 892 | questions = [str(market["question"]) for market in sibling_markets] |
| 893 | names = [_shorten_question(q) for q in questions] |
| 894 | subjects = [_question_subject(q.strip().rstrip("?")) is not None for q in questions] |
| 895 | repeats: Dict[str, int] = {} |
| 896 | for name in names: |
| 897 | repeats[name.casefold()] = repeats.get(name.casefold(), 0) + 1 |
| 898 | relabel = [ |
| 899 | is_subject and (repeats.get(name.casefold(), 0) > 1 or name.casefold() in _ARTICLES) |
| 900 | for name, is_subject in zip(names, subjects) |
| 901 | ] |
| 902 | group_titles = [ |
| 903 | " ".join(str(market.get("groupItemTitle") or "").split()) for market in sibling_markets |
| 904 | ] |
| 905 | title_counts: Dict[str, int] = {} |
| 906 | for title in group_titles: |
| 907 | if title: |
| 908 | title_counts[title.casefold()] = title_counts.get(title.casefold(), 0) + 1 |
| 909 | labels = [ |
| 910 | title |
| 911 | if change or (is_subject and title and title_counts.get(title.casefold(), 0) == 1) |
| 912 | else name |
| 913 | for name, change, is_subject, title in zip(names, relabel, subjects, group_titles) |
| 914 | ] |
| 915 | taken: Dict[str, int] = {} |
| 916 | for label in labels: |
| 917 | if label: |
| 918 | taken[label.casefold()] = taken.get(label.casefold(), 0) + 1 |
| 919 | resolved: Dict[int, str] = {} |
| 920 | for market, label, change, question in zip(sibling_markets, labels, relabel, questions): |
| 921 | if ( |
| 922 | not label |
| 923 | or taken.get(label.casefold(), 0) > 1 |
| 924 | or (change and title_counts.get(label.casefold(), 0) > 1) |
| 925 | ): |
| 926 | resolved[id(market)] = _whole_question_name(question) |
| 927 | else: |
| 928 | resolved[id(market)] = label |
| 929 | final_counts: Dict[str, int] = {} |
| 930 | for label in resolved.values(): |
| 931 | if label: |
| 932 | final_counts[label.casefold()] = final_counts.get(label.casefold(), 0) + 1 |
| 933 | for market, question in zip(sibling_markets, questions): |
| 934 | label = resolved[id(market)] |
| 935 | if final_counts.get(label.casefold(), 0) > 1: |
| 936 | resolved[id(market)] = _whole_question_name(question) |
| 937 | return resolved |
| 938 | |
| 939 | |
| 940 | def _own_outcome_labels( |
| 941 | outcome_prices: List[tuple], |
| 942 | outcome_questions: List[Optional[str]], |
| 943 | outcome_markets: List[Dict[str, Any]], |
| 944 | sibling_markets: Optional[List[Dict[str, Any]]] = None, |
| 945 | ) -> List[tuple]: |
| 946 | """Give each sub-market of an event a label of its own. |
| 947 | |
| 948 | ``_shorten_question`` names a sub-market by its question's subject, which |
| 949 | tells teams apart ("Will Arizona win ...") but not the brackets, cities |
| 950 | or prices of one subject: every "Will Waymo operate in N cities ..." |
| 951 | market came out as "Waymo". A subject name is replaced by the label |
| 952 | Polymarket gives that sub-market (``groupItemTitle``: "San Francisco |
| 953 | 49ers", "12-15", "Denver, CO") when that label is its own across the |
| 954 | event's child markets. Any collision across all child markets—whether |
| 955 | from repeated subjects, repeated ``groupItemTitle``s, or a subject |
| 956 | colliding with another market's ``groupItemTitle``—falls back to |
| 957 | ``_whole_question_name``. |
| 958 | |
| 959 | ``sibling_markets`` covers every child market of the event, priced or |
| 960 | above-floor or not, so labels never shift when filtering or verification |
| 961 | changes which markets are kept. |
| 962 | |
| 963 | Only subject names are replaced, and the order is kept, so every name an |
| 964 | older build saved still reads its own market through |
| 965 | ``_legacy_shorten_question``. |
| 966 | """ |
| 967 | if not any(question is not None for question in outcome_questions): |
| 968 | return list(outcome_prices) |
| 969 | pool = ( |
| 970 | sibling_markets |
| 971 | if sibling_markets is not None |
| 972 | else [ |
| 973 | market |
| 974 | for market, question in zip(outcome_markets, outcome_questions) |
| 975 | if question is not None and market.get("question") |
| 976 | ] |
| 977 | ) |
| 978 | resolved = _sibling_outcome_labels(pool) |
| 979 | return [ |
| 980 | ( |
| 981 | resolved[id(market)] |
| 982 | if question is not None and id(market) in resolved |
| 983 | else name, |
| 984 | price, |
| 985 | ) |
| 986 | for (name, price), question, market in zip( |
| 987 | outcome_prices, outcome_questions, outcome_markets, |
| 988 | ) |
| 989 | ] |
| 990 | |
| 991 | |
| 992 | _MONTH_NAMES = ( |
| 993 | "January|February|March|April|May|June|July|August|September|October|" |
| 994 | "November|December|Jan|Feb|Mar|Apr|Jun|Jul|Aug|Sept|Sep|Oct|Nov|Dec" |
| 995 | ) |
| 996 | # "by December 31, 2026", "before March 31": a deadline, not "on" a day. |
| 997 | _DEADLINE = re.compile( |
| 998 | rf"\b(?:by|before)\s+(?:the\s+end\s+of\s+)?({_MONTH_NAMES})\.?\s+(\d{{1,2}})" |
| 999 | r"(?:st|nd|rd|th)?(?:,?\s+(\d{4}))?", |
| 1000 | re.IGNORECASE, |
| 1001 | ) |
| 1002 | _MONTH_NUMBERS = { |
| 1003 | name: number |
| 1004 | for number, name in enumerate( |
| 1005 | ("jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"), 1, |
| 1006 | ) |
| 1007 | } |
| 1008 | |
| 1009 | |
| 1010 | def _deadline_date(question: str, market: Dict[str, Any]) -> Optional[str]: |
| 1011 | """The one deadline a question names, as an ISO date: the date it spells |
| 1012 | out when that has a year, and the market's end date otherwise. None when |
| 1013 | the question names no deadline, or more than one.""" |
| 1014 | found = _DEADLINE.findall(question) |
| 1015 | if len(found) != 1: |
| 1016 | return None |
| 1017 | month, day, year = found[0] |
| 1018 | if year: |
| 1019 | try: |
| 1020 | return datetime.date(int(year), _MONTH_NUMBERS[month[:3].lower()], int(day)).isoformat() |
| 1021 | except ValueError: |
| 1022 | return None |
| 1023 | end = str(market.get("endDate") or "")[:10] |
| 1024 | return end if re.fullmatch(r"\d{4}-\d{2}-\d{2}", end) else None |
| 1025 | |
| 1026 | |
| 1027 | def _deadline_label(question: str) -> Optional[List[Any]]: |
| 1028 | """The deadline a question names, as ``[month, day, year or None]``, the |
| 1029 | way the question spells it (a market's end date is often the day after).""" |
| 1030 | found = _DEADLINE.findall(question) |
| 1031 | if len(found) != 1: |
| 1032 | return None |
| 1033 | month, day, year = found[0] |
| 1034 | return [month[:3].title(), int(day), int(year) if year else None] |
| 1035 | |
| 1036 | |
| 1037 | def _today() -> str: |
| 1038 | return datetime.datetime.now(datetime.timezone.utc).date().isoformat() |
| 1039 | |
| 1040 | |
| 1041 | # A deadline rung priced under this says only that the date is too soon. |
| 1042 | _LIVE_RUNG_PRICE = 0.05 |
| 1043 | |
| 1044 | |
| 1045 | def _ladder_ends( |
| 1046 | outcome_questions: List[Optional[str]], |
| 1047 | outcome_markets: List[Dict[str, Any]], |
| 1048 | ) -> Optional[List[str]]: |
| 1049 | """Each sub-market's deadline as an ISO date when the sub-markets are one |
| 1050 | question asked for several deadlines, else None.""" |
| 1051 | if len(outcome_questions) < 2: |
| 1052 | return None |
| 1053 | stems = set() |
| 1054 | ends: List[str] = [] |
| 1055 | for question, market in zip(outcome_questions, outcome_markets): |
| 1056 | if not question: |
| 1057 | return None |
| 1058 | end = _deadline_date(question, market) |
| 1059 | if end is None: |
| 1060 | return None |
| 1061 | stems.add(" ".join(_DEADLINE.sub("", question).casefold().split())) |
| 1062 | ends.append(end) |
| 1063 | return ends if len(stems) == 1 else None |
| 1064 | |
| 1065 | |
| 1066 | # The most outcomes one odds line carries. |
| 1067 | ODDS_LINE_OUTCOMES = 3 |
| 1068 | |
| 1069 | |
| 1070 | def _market_id(market: Dict[str, Any]) -> str: |
| 1071 | for key in ("id", "conditionId", "slug"): |
| 1072 | value = str(market.get(key) or "").strip() |
| 1073 | if value: |
| 1074 | return value |
| 1075 | question = " ".join(str(market.get("question") or "").split()) |
| 1076 | group = " ".join(str(market.get("groupItemTitle") or "").split()) |
| 1077 | if question and group: |
| 1078 | return f"{question}\x1f{group}" |
| 1079 | return question or group |
| 1080 | |
| 1081 | |
| 1082 | def _parse_clob_token_ids(market: Dict[str, Any]) -> List[str]: |
| 1083 | raw = market.get("clobTokenIds") |
| 1084 | if isinstance(raw, str): |
| 1085 | try: |
| 1086 | raw = json.loads(raw) |
| 1087 | except (json.JSONDecodeError, TypeError): |
| 1088 | return [] |
| 1089 | if not isinstance(raw, list): |
| 1090 | return [] |
| 1091 | return [str(tok).strip() for tok in raw if tok is not None and str(tok).strip()] |
| 1092 | |
| 1093 | |
| 1094 | def _outcome_id(market: Dict[str, Any], outcome_name: Optional[str]) -> str: |
| 1095 | """Stable identifier for one outcome within ``market``. |
| 1096 | |
| 1097 | Uses the matching ``clobTokenIds`` entry when aligned with the market's |
| 1098 | ``outcomes`` list; otherwise falls back to the normalized outcome name. |
| 1099 | """ |
| 1100 | raw_outcomes = market.get("outcomes") |
| 1101 | if isinstance(raw_outcomes, str): |
| 1102 | try: |
| 1103 | raw_outcomes = json.loads(raw_outcomes) |
| 1104 | except (json.JSONDecodeError, TypeError): |
| 1105 | raw_outcomes = [] |
| 1106 | outcomes = [str(name) for name in raw_outcomes] if isinstance(raw_outcomes, list) else [] |
| 1107 | target = outcome_name if outcome_name is not None else (outcomes[0] if outcomes else "") |
| 1108 | tokens = _parse_clob_token_ids(market) |
| 1109 | if target and outcomes and len(tokens) == len(outcomes): |
| 1110 | target_cf = target.casefold() |
| 1111 | for idx, name in enumerate(outcomes): |
| 1112 | if name.casefold() == target_cf: |
| 1113 | return tokens[idx] |
| 1114 | return " ".join(str(target or "").split()) |
| 1115 | |
| 1116 | |
| 1117 | def _odds_summary( |
| 1118 | title: str, |
| 1119 | top_market: Dict[str, Any], |
| 1120 | outcome_prices: List[tuple], |
| 1121 | outcome_questions: List[Optional[str]], |
| 1122 | outcome_markets: List[Dict[str, Any]], |
| 1123 | today: Optional[str] = None, |
| 1124 | ) -> Optional[Dict[str, Any]]: |
| 1125 | """What a one-line odds summary of the event is built from. |
| 1126 | |
| 1127 | ``kind`` is ``ladder`` (one question, several deadlines: the nearest live |
| 1128 | deadlines in date order, each with its date in ``by``), ``outcomes`` |
| 1129 | (brackets, places, candidates: the leading outcomes under their own |
| 1130 | labels) or ``single`` (one Yes/No market: its Yes price). Each part's |
| 1131 | ``move`` is that outcome's own change in points, where the outcome is a |
| 1132 | market of its own. Never a volume. |
| 1133 | """ |
| 1134 | if not outcome_prices: |
| 1135 | return None |
| 1136 | |
| 1137 | def _part_ids(market: Dict[str, Any], outcome_name: Optional[str]) -> Dict[str, Any]: |
| 1138 | extra_ids: Dict[str, Any] = {} |
| 1139 | mid = _market_id(market) |
| 1140 | if mid: |
| 1141 | extra_ids["market_id"] = mid |
| 1142 | oid = _outcome_id(market, outcome_name) |
| 1143 | if oid: |
| 1144 | extra_ids["outcome_id"] = oid |
| 1145 | return extra_ids |
| 1146 | |
| 1147 | def part(index: int, **extra: Any) -> Dict[str, Any]: |
| 1148 | market = outcome_markets[index] |
| 1149 | priced_alone = outcome_questions[index] is not None |
| 1150 | outcome_name = "Yes" if priced_alone else str(outcome_prices[index][0]) |
| 1151 | return { |
| 1152 | "price": outcome_prices[index][1], |
| 1153 | "move": _price_movement_points(market) if priced_alone else None, |
| 1154 | **_part_ids(market, outcome_name), |
| 1155 | **extra, |
| 1156 | } |
| 1157 | |
| 1158 | if outcome_questions[0] is not None: |
| 1159 | prices = [price for _name, price in outcome_prices] |
| 1160 | ends = _ladder_ends(outcome_questions, outcome_markets) |
| 1161 | start = _nearest_deadline(outcome_questions, outcome_markets, prices, today) |
| 1162 | if ends is not None and start is not None: |
| 1163 | rungs = sorted( |
| 1164 | (index for index in range(len(ends)) if ends[index] >= ends[start]), |
| 1165 | key=lambda index: ends[index], |
| 1166 | )[:ODDS_LINE_OUTCOMES] |
| 1167 | return { |
| 1168 | "kind": "ladder", |
| 1169 | "subject": " ".join(_DEADLINE.sub("", outcome_questions[start]).split()), |
| 1170 | "parts": [ |
| 1171 | part(index, by=_deadline_label(outcome_questions[index])) for index in rungs |
| 1172 | ], |
| 1173 | } |
| 1174 | indexes = range(min(len(outcome_prices), ODDS_LINE_OUTCOMES)) |
| 1175 | return { |
| 1176 | "kind": "outcomes", |
| 1177 | "subject": title, |
| 1178 | "parts": [part(index, label=str(outcome_prices[index][0])) for index in indexes], |
| 1179 | } |
| 1180 | question = str(top_market.get("question") or title) |
| 1181 | by_name = {str(name).casefold(): price for name, price in outcome_prices} |
| 1182 | if set(by_name) == {"yes", "no"}: |
| 1183 | yes_label = next( |
| 1184 | (str(name) for name, _price in outcome_prices if str(name).casefold() == "yes"), |
| 1185 | "Yes", |
| 1186 | ) |
| 1187 | return { |
| 1188 | "kind": "single", |
| 1189 | "subject": question, |
| 1190 | "parts": [ |
| 1191 | { |
| 1192 | "price": by_name["yes"], |
| 1193 | "move": _price_movement_points(top_market), |
| 1194 | **_part_ids(top_market, yes_label), |
| 1195 | } |
| 1196 | ], |
| 1197 | } |
| 1198 | return { |
| 1199 | "kind": "outcomes", |
| 1200 | "subject": question, |
| 1201 | "parts": [ |
| 1202 | { |
| 1203 | "label": str(name), |
| 1204 | "price": price, |
| 1205 | "move": None, |
| 1206 | **_part_ids(top_market, str(name)), |
| 1207 | } |
| 1208 | for name, price in outcome_prices[:ODDS_LINE_OUTCOMES] |
| 1209 | ], |
| 1210 | } |
| 1211 | |
| 1212 | |
| 1213 | def _nearest_deadline( |
| 1214 | outcome_questions: List[Optional[str]], |
| 1215 | outcome_markets: List[Dict[str, Any]], |
| 1216 | prices: List[float], |
| 1217 | today: Optional[str] = None, |
| 1218 | ) -> Optional[int]: |
| 1219 | """Index of the nearest deadline that has not passed, for a deadline ladder. |
| 1220 | |
| 1221 | A rung the market gives under 5% is passed over for the next one, so an |
| 1222 | "IPO by" ladder shows the first date traders think is live, not a date |
| 1223 | days away at 0.8%. When every open rung is that low the nearest is kept. |
| 1224 | |
| 1225 | A ladder is one question asked for several deadlines ("... by December 31, |
| 1226 | 2026?", "... by March 31, 2027?"). Its later deadlines always price |
| 1227 | higher, so the highest price is only the furthest date. None when the |
| 1228 | sub-markets are not one question with different deadlines. |
| 1229 | """ |
| 1230 | ends = _ladder_ends(outcome_questions, outcome_markets) |
| 1231 | if ends is None: |
| 1232 | return None |
| 1233 | today = today or _today() |
| 1234 | open_ends = [index for index, end in enumerate(ends) if end >= today] |
| 1235 | live = [index for index in open_ends if prices[index] >= _LIVE_RUNG_PRICE] |
| 1236 | return min(live or open_ends or range(len(ends)), key=lambda index: ends[index]) |
| 1237 | |
| 1238 | |
| 1239 | def _headline_market( |
| 1240 | title: str, |
| 1241 | top_market: Dict[str, Any], |
| 1242 | outcome_prices: List[tuple], |
| 1243 | outcome_questions: List[Optional[str]], |
| 1244 | outcome_markets: List[Dict[str, Any]], |
| 1245 | ) -> Optional[Dict[str, Any]]: |
| 1246 | """The one market and price that stand for an event in a one-line summary. |
| 1247 | |
| 1248 | The question and the price always come from the same market. For an event |
| 1249 | of Yes/No sub-markets that is the nearest open deadline of a deadline |
| 1250 | ladder, and otherwise the first outcome (the topic's own, or the most |
| 1251 | likely). For a single market it is its Yes price, or its leading outcome |
| 1252 | with that outcome's ``label``. |
| 1253 | """ |
| 1254 | if not outcome_prices: |
| 1255 | return None |
| 1256 | if outcome_questions[0] is not None: |
| 1257 | index = _nearest_deadline( |
| 1258 | outcome_questions, outcome_markets, [price for _name, price in outcome_prices], |
| 1259 | ) or 0 |
| 1260 | return {"question": outcome_questions[index], "price": outcome_prices[index][1]} |
| 1261 | question = str(top_market.get("question") or title) |
| 1262 | by_name = {str(name).casefold(): price for name, price in outcome_prices} |
| 1263 | if set(by_name) == {"yes", "no"}: |
| 1264 | return {"question": question, "price": by_name["yes"]} |
| 1265 | name, price = outcome_prices[0] |
| 1266 | return {"question": question, "label": str(name), "price": price} |
| 1267 | |
| 1268 | |
| 1269 | def names_whole_topic(topic: str, *texts: str) -> bool: |
| 1270 | """Whether a market's text names the whole topic, not one word of it. |
| 1271 | |
| 1272 | The event filter keeps a market that shares one informative word with a |
| 1273 | two-word topic, so "Jensen Huang" keeps a table tennis match played by |
| 1274 | another Huang. Every informative word of the topic (of either side of a |
| 1275 | "vs" topic) must appear as a word of its own. A topic with no informative |
| 1276 | word is not checked. |
| 1277 | """ |
| 1278 | def words(text: str) -> List[str]: |
| 1279 | text = re.sub(r"['\u2019]s\b", "", text.casefold()) |
| 1280 | return [word for word in re.sub(r"[^\w\s]", " ", text).split() if len(word) > 1] |
| 1281 | |
| 1282 | found = {word for text in texts for word in words(text or "")} |
| 1283 | sides = _topic_sides(topic) |
| 1284 | checked = False |
| 1285 | for side in sides: |
| 1286 | side_words = words(side) |
| 1287 | informative = _informative_words(side_words) or side_words |
| 1288 | if not informative: |
| 1289 | continue |
| 1290 | checked = True |
| 1291 | if all(word in found for word in informative): |
| 1292 | return True |
| 1293 | return not checked |
| 1294 | |
| 1295 | |
| 1296 | _SERIES_DROP_WORDS = frozenset( |
| 1297 | {name.casefold() for name in _MONTH_NAMES.split("|")} |
| 1298 | | {"will", "the", "a", "an", "in", "on", "by", "from", "to", "of", "between", |
| 1299 | "and", "be", "before", "after", "through", "until", "week", "month"} |
| 1300 | ) |
| 1301 | # A recurring count market: "Elon Musk # tweets November 6 - November 13, |
| 1302 | # 2026?", "How many times will X say ...", "... post 260-279 tweets ...", |
| 1303 | # "What will X say during ...", "X mentions ...". |
| 1304 | _COUNT_SERIES = re.compile( |
| 1305 | r"#\s*(?:of\s+)?(?:tweets|posts|mentions|truths)\b" |
| 1306 | r"|\b(?:how many|number of)\s+(?:times|tweets|posts|mentions)\b" |
| 1307 | r"|\b(?:post|tweet|say|mention)s?\s+[<>]?\d[\d,]*\s*(?:[-–+]\s*\d*[\d,]*)?\+?\s*(?:tweets|posts|times)\b" |
| 1308 | r"|\bmentions?\s+market\b" |
| 1309 | r"|^what will .+ say\b", |
| 1310 | re.IGNORECASE, |
| 1311 | ) |
| 1312 | |
| 1313 | |
| 1314 | def series_key(*texts: str) -> str: |
| 1315 | """A market's question stem with its numbers, dates and brackets removed. |
| 1316 | |
| 1317 | Weekly reruns of one question ("Elon Musk # tweets November 6 - November |
| 1318 | 13, 2026?", "Elon Musk # tweets in November 2026?") share a key, so a |
| 1319 | caller can name the series once. The first non-empty text is used. |
| 1320 | """ |
| 1321 | text = next((t for t in texts if t and t.strip()), "") |
| 1322 | text = re.sub(r"['’]s\b", "", text.casefold()) |
| 1323 | text = re.sub(r"[<>$]?\d[\d,.]*\s*[kmbt%+]?", " ", text) |
| 1324 | words = [w for w in re.sub(r"[^\w\s]", " ", text).split() if w not in _SERIES_DROP_WORDS] |
| 1325 | return " ".join(words) |
| 1326 | |
| 1327 | |
| 1328 | def is_count_series(*texts: str) -> bool: |
| 1329 | """Whether a market is a recurring count bracket (tweets, posts, mentions).""" |
| 1330 | return any(_COUNT_SERIES.search(text or "") for text in texts) |
| 1331 | |
| 1332 | |
| 1333 | def _legacy_shorten_question(question: str) -> str: |
| 1334 | """The name older builds gave a market question; saved reports hold it. |
| 1335 | |
| 1336 | They cut a question with no shorter subject at 40 characters and only |
| 1337 | then dropped a leading article. |
| 1338 | """ |
| 1339 | q = question.strip().rstrip("?") |
| 1340 | subject = _question_subject(q) |
| 1341 | if subject is not None: |
| 1342 | return subject |
| 1343 | return re.sub(r"^(?:a|an|the)\s+", "", q[:40], flags=re.I) |
| 1344 | |
| 1345 | |
| 1346 | def _safe_float(val, default=0.0) -> float: |
| 1347 | """Safely convert a value to float.""" |
| 1348 | if isinstance(val, bool): |
| 1349 | return default |
| 1350 | try: |
| 1351 | parsed = float(val or default) |
| 1352 | except (ValueError, TypeError, OverflowError): |
| 1353 | return default |
| 1354 | return parsed if math.isfinite(parsed) else default |
| 1355 | |
| 1356 | |
| 1357 | def _market_volume(market: Dict[str, Any]) -> float: |
| 1358 | """Money traded on one market over its life.""" |
| 1359 | return _safe_float(market.get("volumeNum")) or _safe_float(market.get("volume")) |
| 1360 | |
| 1361 | |
| 1362 | def _yes_price(market: Dict[str, Any]) -> Optional[float]: |
| 1363 | """The displayed price of a market's first outcome, None when unpriced.""" |
| 1364 | pairs = _parse_outcome_prices(market) |
| 1365 | return pairs[0][1] if pairs else None |
| 1366 | |
| 1367 | |
| 1368 | def _live_markets(event: Dict[str, Any], include_closed: bool = False) -> List[Dict[str, Any]]: |
| 1369 | """An event's open, active markets with liquidity (resolved markets have |
| 1370 | 0 or None). ``include_closed`` keeps every market.""" |
| 1371 | live = [] |
| 1372 | for market in event.get("markets") or []: |
| 1373 | if not include_closed and (market.get("closed") or not market.get("active", True)): |
| 1374 | continue |
| 1375 | if _safe_float(market.get("liquidity")) > 0 or include_closed: |
| 1376 | live.append(market) |
| 1377 | return live |
| 1378 | |
| 1379 | |
| 1380 | def _days_to_close(market: Dict[str, Any], event: Dict[str, Any], today: str) -> Optional[int]: |
| 1381 | end = str(market.get("endDate") or event.get("endDate") or "")[:10] |
| 1382 | try: |
| 1383 | return (datetime.date.fromisoformat(end) - datetime.date.fromisoformat(today)).days |
| 1384 | except ValueError: |
| 1385 | return None |
| 1386 | |
| 1387 | |
| 1388 | @dataclass |
| 1389 | class _EntityMarket: |
| 1390 | """One market of an event that names the subject (or a related name).""" |
| 1391 | |
| 1392 | market: Dict[str, Any] |
| 1393 | match: EntityMatch |
| 1394 | outcome: Optional[str] |
| 1395 | price: Optional[float] |
| 1396 | volume: float |
| 1397 | days: Optional[int] |
| 1398 | rank: Optional[int] = None |
| 1399 | race_size: Optional[int] = None |
| 1400 | race_outcome: bool = False |
| 1401 | in_band: bool = False |
| 1402 | contender: bool = False |
| 1403 | priced_outcome: Optional[str] = None |
| 1404 | |
| 1405 | @property |
| 1406 | def label(self) -> str: |
| 1407 | title = " ".join(str(self.market.get("groupItemTitle") or "").split()) |
| 1408 | return title or self.outcome or _shorten_question(str(self.market.get("question") or "")) |
| 1409 | |
| 1410 | |
| 1411 | @dataclass |
| 1412 | class _EventEntities: |
| 1413 | """The subject's markets in one event, before the selection rule.""" |
| 1414 | |
| 1415 | race: bool |
| 1416 | live_count: int |
| 1417 | named_by_market: bool |
| 1418 | markets: List[_EntityMarket] = field(default_factory=list) |
| 1419 | |
| 1420 | |
| 1421 | def _is_exclusive(event: Dict[str, Any], markets: List[Dict[str, Any]]) -> bool: |
| 1422 | """Whether an event's markets are mutually exclusive (``negRisk``): only |
| 1423 | one of them can resolve Yes.""" |
| 1424 | return bool(event.get("negRisk")) or any(m.get("negRisk") for m in markets) |
| 1425 | |
| 1426 | |
| 1427 | def _is_race(event: Dict[str, Any], live_markets: List[Dict[str, Any]]) -> bool: |
| 1428 | """Whether an event's live markets are a race: mutually exclusive |
| 1429 | (``negRisk``), RACE_MIN_OUTCOMES or more of them, labelled by |
| 1430 | ``groupItemTitle``.""" |
| 1431 | exclusive = _is_exclusive(event, live_markets) |
| 1432 | labelled = sum(1 for m in live_markets if str(m.get("groupItemTitle") or "").strip()) |
| 1433 | return exclusive and len(live_markets) >= RACE_MIN_OUTCOMES and labelled >= 2 |
| 1434 | |
| 1435 | |
| 1436 | def _event_entities( |
| 1437 | event: Dict[str, Any], |
| 1438 | active_markets: List[Dict[str, Any]], |
| 1439 | matcher: EntityMatcher, |
| 1440 | race: bool, |
| 1441 | today: str, |
| 1442 | ) -> _EventEntities: |
| 1443 | """Match each live market of an event and price its entity markets. |
| 1444 | |
| 1445 | Recurring count brackets ("# tweets") are dropped. A market with no |
| 1446 | displayable price is kept but can never be live. In a race (a mutually |
| 1447 | exclusive event of RACE_MIN_OUTCOMES or more live outcomes, labelled by |
| 1448 | ``groupItemTitle``) a market whose outcome is the subject or a related |
| 1449 | name is a race outcome, and when its label names it, it is ranked by |
| 1450 | price among the live outcomes. |
| 1451 | """ |
| 1452 | title = str(event.get("title") or "") |
| 1453 | title_text, title_acronyms = _prepare_match_text(title) |
| 1454 | yes_prices = [_yes_price(market) for market in active_markets] |
| 1455 | found = _EventEntities(race=race, live_count=len(active_markets), named_by_market=False) |
| 1456 | for market in active_markets: |
| 1457 | match = matcher.match( |
| 1458 | market, title, title_text=title_text, title_acronyms=title_acronyms, |
| 1459 | ) |
| 1460 | if match is None: |
| 1461 | continue |
| 1462 | if match.field == "market" and not match.related: |
| 1463 | found.named_by_market = True |
| 1464 | if is_count_series(title, str(market.get("question") or "")): |
| 1465 | continue |
| 1466 | outcome = matcher.matched_outcome(market, match) |
| 1467 | pairs = _parse_outcome_prices(market) |
| 1468 | if outcome is not None: |
| 1469 | price = next((p for name, p in pairs if str(name) == outcome), None) |
| 1470 | priced_outcome = outcome |
| 1471 | else: |
| 1472 | price = pairs[0][1] if pairs else None |
| 1473 | priced_outcome = str(pairs[0][0]) if pairs else None |
| 1474 | entity = _EntityMarket( |
| 1475 | market=market, match=match, outcome=outcome, price=price, |
| 1476 | volume=_market_volume(market), days=_days_to_close(market, event, today), |
| 1477 | priced_outcome=priced_outcome, |
| 1478 | ) |
| 1479 | kind = ( |
| 1480 | matcher.outcome_kind( |
| 1481 | market, match, title, title_text=title_text, title_acronyms=title_acronyms, |
| 1482 | ) |
| 1483 | if race else None |
| 1484 | ) |
| 1485 | entity.race_outcome = kind is not None |
| 1486 | if kind == "label" and price is not None: |
| 1487 | entity.rank = 1 + sum(1 for other in yes_prices if other is not None and other > price) |
| 1488 | entity.race_size = len(active_markets) |
| 1489 | found.markets.append(entity) |
| 1490 | return found |
| 1491 | |
| 1492 | |
| 1493 | def _teams_biggest_race(analyses: Dict[int, _EventEntities]) -> Optional[int]: |
| 1494 | """The race where the team's own outcome has the most money on it, among |
| 1495 | open outcomes the selection rule would otherwise floor.""" |
| 1496 | best: Optional[Tuple[float, int]] = None |
| 1497 | for key, found in analyses.items(): |
| 1498 | for entity in found.markets: |
| 1499 | if entity.match.related or not entity.race_outcome: |
| 1500 | continue |
| 1501 | if entity.price is None or not 0 < entity.price < PRICE_CEILING: |
| 1502 | continue |
| 1503 | if entity.days is not None and entity.days < MIN_DAYS_TO_CLOSE: |
| 1504 | continue |
| 1505 | if best is None or entity.volume > best[0]: |
| 1506 | best = (entity.volume, key) |
| 1507 | return best[1] if best else None |
| 1508 | |
| 1509 | |
| 1510 | def _apply_band(found: _EventEntities, exempt: bool) -> None: |
| 1511 | for entity in found.markets: |
| 1512 | floor = ( |
| 1513 | 0.0 if exempt and not entity.match.related |
| 1514 | else RACE_PRICE_FLOOR if entity.race_outcome else PRICE_FLOOR |
| 1515 | ) |
| 1516 | entity.in_band = ( |
| 1517 | entity.price is not None |
| 1518 | and entity.price < PRICE_CEILING |
| 1519 | and (entity.price > 0 if floor == 0 else entity.price >= floor) |
| 1520 | and (entity.days is None or entity.days >= MIN_DAYS_TO_CLOSE) |
| 1521 | ) |
| 1522 | entity.contender = ( |
| 1523 | entity.rank is not None |
| 1524 | and entity.rank <= CONTENDER_TOP |
| 1525 | and entity.volume >= CONTENDER_MIN_VOLUME |
| 1526 | ) |
| 1527 | |
| 1528 | |
| 1529 | def _chosen_markets(found: _EventEntities) -> List[_EntityMarket]: |
| 1530 | """The entity markets an event contributes. |
| 1531 | |
| 1532 | A related name enters only as a live top contender. An event of more than |
| 1533 | GAME_SHEET_MARKETS markets (a game's prop sheet, a league-wide race) |
| 1534 | contributes one market: its busiest live market that names the subject on |
| 1535 | its own text, or when no market does (the subject is only in the title), |
| 1536 | its busiest live market. |
| 1537 | """ |
| 1538 | entity = [m for m in found.markets if not m.match.related] |
| 1539 | related = [m for m in found.markets if m.match.related and m.in_band and m.contender] |
| 1540 | if found.live_count <= GAME_SHEET_MARKETS: |
| 1541 | return entity + related |
| 1542 | pool = [m for m in entity if m.match.field == "market"] if found.named_by_market else entity |
| 1543 | for group in ([m for m in pool if m.in_band], related, pool): |
| 1544 | if group: |
| 1545 | return [max(group, key=lambda m: m.volume)] |
| 1546 | return [] |
| 1547 | |
| 1548 | |
| 1549 | def _headline_entity(group: List[_EntityMarket], today: str) -> _EntityMarket: |
| 1550 | """The market that stands for the event: the nearest live deadline of a |
| 1551 | date ladder, the rung closest to even of a value ladder ("8.5+ wins", |
| 1552 | "9.5+ wins"), else the likeliest outcome.""" |
| 1553 | priced = [m for m in group if m.price is not None] |
| 1554 | if not priced: |
| 1555 | return max(group, key=lambda m: m.volume) |
| 1556 | if len(priced) > 1: |
| 1557 | questions: List[Optional[str]] = [str(m.market.get("question") or "") for m in priced] |
| 1558 | prices = [m.price for m in priced if m.price is not None] |
| 1559 | index = _nearest_deadline(questions, [m.market for m in priced], prices, today) |
| 1560 | if index is not None: |
| 1561 | return priced[index] |
| 1562 | if len({series_key(question or "") for question in questions}) == 1: |
| 1563 | return min(priced, key=lambda m: abs((m.price or 0) - 0.5)) |
| 1564 | return max(priced, key=lambda m: (m.price or 0, m.volume)) |
| 1565 | |
| 1566 | |
| 1567 | def parse_polymarket_response( |
| 1568 | response: Dict[str, Any], |
| 1569 | topic: str = "", |
| 1570 | *, |
| 1571 | hints: Any = None, |
| 1572 | to_date: Optional[str] = None, |
| 1573 | include_all_outcomes: bool = False, |
| 1574 | include_closed: bool = False, |
| 1575 | ) -> List[Dict[str, Any]]: |
| 1576 | """Parse Gamma API response into normalized item dicts. |
| 1577 | |
| 1578 | Each event becomes one item showing its title and top markets. |
| 1579 | |
| 1580 | With a topic, an event is kept only when one of its markets names the |
| 1581 | subject (``EntityMatcher``), and the item headlines the subject's own |
| 1582 | market. Items are ranked by the selection rule (see PRICE_CEILING): |
| 1583 | events with a live entity market first, by ``selection_score``, then the |
| 1584 | rest by money on the subject. Without a topic (re-checking a saved claim) |
| 1585 | every market is kept and nothing is gated. |
| 1586 | |
| 1587 | Args: |
| 1588 | response: Raw Gamma API response |
| 1589 | topic: Original search topic |
| 1590 | hints: Optional ``PolymarketHints`` (or a plan dict of the same shape) |
| 1591 | to_date: The run's end date, the "now" for days to close and live |
| 1592 | deadlines; today when absent |
| 1593 | |
| 1594 | Returns: |
| 1595 | List of item dicts ready for normalization. |
| 1596 | """ |
| 1597 | events = response.get("events", []) |
| 1598 | today = to_date or _today() |
| 1599 | matcher = EntityMatcher(topic, hints) if topic else None |
| 1600 | |
| 1601 | # Pass one: each event's live markets and, with a topic, its entity markets. |
| 1602 | prepared = [] |
| 1603 | analyses: Dict[int, _EventEntities] = {} |
| 1604 | filtered_count = 0 |
| 1605 | for event in events: |
| 1606 | # Filter: skip closed/resolved events |
| 1607 | if not include_closed: |
| 1608 | if event.get("closed", False): |
| 1609 | continue |
| 1610 | if not event.get("active", True): |
| 1611 | continue |
| 1612 | |
| 1613 | active_markets = _live_markets(event, include_closed) |
| 1614 | if not active_markets: |
| 1615 | continue |
| 1616 | |
| 1617 | mutually_exclusive = _is_exclusive(event, active_markets) |
| 1618 | if matcher is not None: |
| 1619 | found = _event_entities( |
| 1620 | event, active_markets, matcher, |
| 1621 | race=_is_race(event, active_markets), |
| 1622 | today=today, |
| 1623 | ) |
| 1624 | if not found.markets: |
| 1625 | filtered_count += 1 |
| 1626 | continue |
| 1627 | analyses[len(prepared)] = found |
| 1628 | prepared.append((event, active_markets, mutually_exclusive)) |
| 1629 | |
| 1630 | exempt = ( |
| 1631 | _teams_biggest_race(analyses) |
| 1632 | if matcher is not None and matcher.hints.kind == "team" else None |
| 1633 | ) |
| 1634 | |
| 1635 | items = [] |
| 1636 | for index, (event, active_markets, mutually_exclusive) in enumerate(prepared): |
| 1637 | event_id = event.get("id", "") |
| 1638 | title = event.get("title", "") |
| 1639 | slug = event.get("slug", "") |
| 1640 | |
| 1641 | chosen: List[_EntityMarket] = [] |
| 1642 | entity: Optional[_EntityMarket] = None |
| 1643 | tier = 0 |
| 1644 | score = 0.0 |
| 1645 | found = analyses.get(index) |
| 1646 | if found is not None: |
| 1647 | _apply_band(found, exempt=index == exempt) |
| 1648 | chosen = _chosen_markets(found) |
| 1649 | if not chosen: |
| 1650 | filtered_count += 1 |
| 1651 | continue |
| 1652 | live = [m for m in chosen if m.in_band] |
| 1653 | if live: |
| 1654 | tier = 1 |
| 1655 | score = math.log1p(sum(m.volume for m in live)) + ( |
| 1656 | CONTENDER_BONUS if any(m.contender for m in live) else 0.0 |
| 1657 | ) |
| 1658 | else: |
| 1659 | score = math.log1p(sum(m.volume for m in chosen)) |
| 1660 | entity = _headline_entity(live or chosen, today) |
| 1661 | chosen_ids = {id(m.market) for m in chosen} |
| 1662 | |
| 1663 | # Sort markets by volume (most liquid first) |
| 1664 | def market_volume(m): |
| 1665 | try: |
| 1666 | return float(m.get("volume", 0) or 0) |
| 1667 | except (ValueError, TypeError): |
| 1668 | return 0 |
| 1669 | active_markets.sort(key=market_volume, reverse=True) |
| 1670 | |
| 1671 | # Take top market for the event |
| 1672 | top_market = active_markets[0] |
| 1673 | # The market whose outcomes and question the odds show: the subject's |
| 1674 | # own when matched, so a busier sibling with its own outcome labels |
| 1675 | # ("O 11.5" for another team) never speaks for it. |
| 1676 | shown_market = entity.market if entity is not None else top_market |
| 1677 | |
| 1678 | # Parse outcome prices - for multi-market events with Yes/No binary |
| 1679 | # sub-markets, synthesize from market questions to show actual |
| 1680 | # team/entity probabilities instead of a single market's Yes/No |
| 1681 | outcome_prices = _parse_outcome_prices(shown_market) |
| 1682 | # The market question each outcome was named from, None for a label. |
| 1683 | outcome_questions: List[Optional[str]] = [None] * len(outcome_prices) |
| 1684 | # The market each outcome is priced in. |
| 1685 | outcome_markets: List[Dict[str, Any]] = [shown_market] * len(outcome_prices) |
| 1686 | # Whether the sub-markets are Yes/No is read from the raw outcome |
| 1687 | # labels, so a malformed or unpriced top market still leads to its |
| 1688 | # priced siblings. |
| 1689 | raw_top_outcomes = [ |
| 1690 | str(name).strip().lower() |
| 1691 | for name in _json_list(shown_market.get("outcomes")) |
| 1692 | if name is not None and str(name).strip() |
| 1693 | ] |
| 1694 | top_outcomes_are_binary = ( |
| 1695 | len(raw_top_outcomes) == 2 and set(raw_top_outcomes) == {"yes", "no"} |
| 1696 | ) |
| 1697 | impossible_set = False |
| 1698 | sibling_markets: Optional[List[Dict[str, Any]]] = None |
| 1699 | if top_outcomes_are_binary and len(active_markets) > 1: |
| 1700 | sibling_markets = [m for m in active_markets if m.get("question")] |
| 1701 | synth_outcomes = [] |
| 1702 | for m in sibling_markets: |
| 1703 | q = m["question"] |
| 1704 | pairs = _parse_outcome_prices(m) |
| 1705 | yes_price = next((p for name, p in pairs if name.strip().lower() == "yes"), None) |
| 1706 | if yes_price is not None and ( |
| 1707 | include_all_outcomes |
| 1708 | or yes_price >= RACE_PRICE_FLOOR |
| 1709 | or id(m) in chosen_ids |
| 1710 | ): |
| 1711 | synth_outcomes.append((q, yes_price, m)) |
| 1712 | if synth_outcomes: |
| 1713 | synth_outcomes.sort(key=lambda x: x[1], reverse=True) |
| 1714 | outcome_prices = [(_shorten_question(q), p) for q, p, _m in synth_outcomes] |
| 1715 | outcome_questions = [q for q, _p, _m in synth_outcomes] |
| 1716 | outcome_markets = [m for _q, _p, m in synth_outcomes] |
| 1717 | # Only one bracket of a negRisk set can resolve Yes, so its |
| 1718 | # Yes prices sum to about 1. A set still well over 1 after |
| 1719 | # the book check is no distribution to show. |
| 1720 | yes_total = sum(p for _q, p, _m in synth_outcomes) |
| 1721 | if mutually_exclusive and yes_total > _MAX_EXCLUSIVE_YES_TOTAL: |
| 1722 | impossible_set = True |
| 1723 | _log( |
| 1724 | f"Suppressed odds for '{title[:60]}': mutually exclusive " |
| 1725 | f"Yes prices sum to {yes_total:.2f}" |
| 1726 | ) |
| 1727 | |
| 1728 | # The subject's own markets lead the outcome list, in price order. |
| 1729 | if chosen and outcome_prices: |
| 1730 | rows = list(zip(outcome_prices, outcome_questions, outcome_markets)) |
| 1731 | if outcome_questions[0] is not None: |
| 1732 | own = [row for row in rows if id(row[2]) in chosen_ids] |
| 1733 | else: |
| 1734 | own = [row for row in rows if entity is not None and row[0][0] == entity.outcome] |
| 1735 | if own: |
| 1736 | rows = own + [row for row in rows if row not in own] |
| 1737 | outcome_prices = [priced for priced, _q, _m in rows] |
| 1738 | outcome_questions = [q for _priced, q, _m in rows] |
| 1739 | outcome_markets = [m for _priced, _q, m in rows] |
| 1740 | |
| 1741 | # The market the item speaks for: the subject's own with a topic. |
| 1742 | lead_market = entity.market if entity is not None else top_market |
| 1743 | |
| 1744 | # Format price movement |
| 1745 | price_movement = _format_price_movement(lead_market) |
| 1746 | |
| 1747 | # Volume and liquidity - prefer event-level (more stable), fall back to market-level |
| 1748 | event_volume1mo = _safe_float(event.get("volume1mo")) |
| 1749 | event_volume1wk = _safe_float(event.get("volume1wk")) |
| 1750 | event_liquidity = _safe_float(event.get("liquidity")) |
| 1751 | event_competitive = _safe_float(event.get("competitive")) |
| 1752 | volume24hr = _safe_float(event.get("volume24hr")) or _safe_float(top_market.get("volume24hr")) |
| 1753 | liquidity = event_liquidity or _safe_float(top_market.get("liquidity")) |
| 1754 | |
| 1755 | # Event URL |
| 1756 | url = f"https://polymarket.com/event/{slug}" if slug else f"https://polymarket.com/event/{event_id}" |
| 1757 | |
| 1758 | # Date: use updatedAt from event |
| 1759 | updated_at = event.get("updatedAt", "") |
| 1760 | date_str = None |
| 1761 | if updated_at: |
| 1762 | try: |
| 1763 | date_str = updated_at[:10] # YYYY-MM-DD |
| 1764 | except (IndexError, TypeError): |
| 1765 | pass |
| 1766 | |
| 1767 | # End date for the market |
| 1768 | end_date = lead_market.get("endDate") |
| 1769 | if end_date: |
| 1770 | try: |
| 1771 | end_date = end_date[:10] |
| 1772 | except (IndexError, TypeError): |
| 1773 | end_date = None |
| 1774 | |
| 1775 | # Volume signal: log-scaled monthly volume (most stable signal) |
| 1776 | vol_raw = event_volume1mo or event_volume1wk or volume24hr |
| 1777 | vol_score = min(1.0, math.log1p(vol_raw) / 16) # ~$9M = 1.0 |
| 1778 | |
| 1779 | # Liquidity signal |
| 1780 | liq_score = min(1.0, math.log1p(liquidity) / 14) # ~$1.2M = 1.0 |
| 1781 | |
| 1782 | # Price movement: daily weighted more than monthly |
| 1783 | day_change = abs(lead_market.get("oneDayPriceChange") or 0) * 3 |
| 1784 | week_change = abs(lead_market.get("oneWeekPriceChange") or 0) * 2 |
| 1785 | month_change = abs(lead_market.get("oneMonthPriceChange") or 0) |
| 1786 | max_change = max(day_change, week_change, month_change) |
| 1787 | movement_score = min(1.0, max_change * 5) # 20% change = 1.0 |
| 1788 | |
| 1789 | market_quality = ( |
| 1790 | 0.50 * vol_score + |
| 1791 | 0.25 * liq_score + |
| 1792 | 0.15 * movement_score + |
| 1793 | 0.10 * event_competitive |
| 1794 | ) |
| 1795 | # How firmly the event is about the subject: the subject named, then a |
| 1796 | # related name leading a race; an event with no live market counts less. |
| 1797 | if entity is None: |
| 1798 | match_strength = 0.5 |
| 1799 | else: |
| 1800 | match_strength = 1.0 if any(not m.match.related for m in chosen) else 0.8 |
| 1801 | if not tier: |
| 1802 | match_strength *= 0.6 |
| 1803 | relevance = min(1.0, match_strength * (0.75 + 0.25 * market_quality)) |
| 1804 | |
| 1805 | # After the ordering above, which reads the subject names. |
| 1806 | outcome_prices = _own_outcome_labels( |
| 1807 | outcome_prices, |
| 1808 | outcome_questions, |
| 1809 | outcome_markets, |
| 1810 | sibling_markets, |
| 1811 | ) |
| 1812 | if entity is not None and entity.price is None: |
| 1813 | headline = None |
| 1814 | elif entity is not None: |
| 1815 | headline = { |
| 1816 | "question": str(entity.market.get("question") or title), |
| 1817 | "price": entity.price, |
| 1818 | } |
| 1819 | if entity.outcome is not None: |
| 1820 | headline["label"] = entity.outcome |
| 1821 | else: |
| 1822 | headline = _headline_market( |
| 1823 | title, top_market, outcome_prices, outcome_questions, outcome_markets, |
| 1824 | ) |
| 1825 | |
| 1826 | # Normal display payloads stay compact. Verification requests the |
| 1827 | # complete snapshot so topic-promoted outcomes remain re-checkable. |
| 1828 | top_outcomes = outcome_prices if include_all_outcomes else outcome_prices[:3] |
| 1829 | remaining = len(outcome_prices) - 3 |
| 1830 | if remaining < 0: |
| 1831 | remaining = 0 |
| 1832 | odds = _odds_summary( |
| 1833 | title, shown_market, outcome_prices, outcome_questions, outcome_markets, today, |
| 1834 | ) |
| 1835 | if impossible_set: |
| 1836 | # The event stays as evidence, with no odds line or listed |
| 1837 | # outcomes. Verification still sees each market's quote. The |
| 1838 | # subject's own outcome of the race keeps its headline: its price |
| 1839 | # is that market's own quote, not read off the bogus set. |
| 1840 | odds = None |
| 1841 | if entity is None or not entity.race_outcome: |
| 1842 | headline = None |
| 1843 | remaining = 0 |
| 1844 | if not include_all_outcomes: |
| 1845 | top_outcomes = [] |
| 1846 | |
| 1847 | outcome_market_ids = ( |
| 1848 | [_market_id(m) for m in outcome_markets[: len(top_outcomes)]] |
| 1849 | if top_outcomes and outcome_questions and outcome_questions[0] is not None |
| 1850 | else [] |
| 1851 | ) |
| 1852 | item = { |
| 1853 | "event_id": event_id, |
| 1854 | "title": title, |
| 1855 | "question": lead_market.get("question", title), |
| 1856 | "url": url, |
| 1857 | "outcome_prices": top_outcomes, |
| 1858 | "outcome_questions": outcome_questions[: len(top_outcomes)], |
| 1859 | **({"outcome_market_ids": outcome_market_ids} if outcome_market_ids else {}), |
| 1860 | "outcomes_remaining": remaining, |
| 1861 | "headline": headline, |
| 1862 | "odds": odds, |
| 1863 | "price_movement": price_movement, |
| 1864 | "volume24hr": volume24hr, |
| 1865 | "volume1mo": event_volume1mo, |
| 1866 | "liquidity": liquidity, |
| 1867 | "date": date_str, |
| 1868 | "end_date": end_date, |
| 1869 | "relevance": round(relevance, 2), |
| 1870 | "why_relevant": f"Prediction market: {title[:60]}", |
| 1871 | } |
| 1872 | if entity is not None: |
| 1873 | item["selection_score"] = score |
| 1874 | item["selection_tier"] = tier |
| 1875 | matched_payload = { |
| 1876 | "label": entity.label, |
| 1877 | "question": str(entity.market.get("question") or ""), |
| 1878 | "price": entity.price, |
| 1879 | "volume": entity.volume, |
| 1880 | "end_date": end_date, |
| 1881 | "rank": entity.rank, |
| 1882 | "race_size": entity.race_size, |
| 1883 | "contender": entity.contender, |
| 1884 | "in_band": entity.in_band, |
| 1885 | "match_field": entity.match.field, |
| 1886 | "related_name": entity.match.related, |
| 1887 | "relation": entity.match.relation or None, |
| 1888 | } |
| 1889 | matched_mid = _market_id(entity.market) |
| 1890 | if matched_mid: |
| 1891 | matched_payload["market_id"] = matched_mid |
| 1892 | matched_oid = _outcome_id(entity.market, entity.priced_outcome or entity.outcome) |
| 1893 | if matched_oid: |
| 1894 | matched_payload["outcome_id"] = matched_oid |
| 1895 | item["matched_market"] = matched_payload |
| 1896 | items.append(item) |
| 1897 | |
| 1898 | if filtered_count: |
| 1899 | _log(f"Filtered {filtered_count} events that do not name '{topic}'") |
| 1900 | |
| 1901 | if matcher is not None: |
| 1902 | # The selection rule decides the order, and the cap comes after it. |
| 1903 | items.sort(key=lambda x: (x["selection_tier"], x["selection_score"]), reverse=True) |
| 1904 | else: |
| 1905 | items.sort(key=lambda x: x["relevance"], reverse=True) |
| 1906 | |
| 1907 | cap = response.get("_cap", len(items)) |
| 1908 | return items[:cap] |
| 1909 | |
| 1910 | |
| 1911 | def _normalize_snapshot_key(key: str) -> str: |
| 1912 | if "\x1f" in key: |
| 1913 | name, occurrence = key.rsplit("\x1f", 1) |
| 1914 | return f"{name.strip().casefold()}\x1f{occurrence.strip()}" |
| 1915 | return key.strip().casefold() |
| 1916 | |
| 1917 | |
| 1918 | def _has_base_in_map(normalized_values: Dict[str, Any], base: str) -> bool: |
| 1919 | if base in normalized_values: |
| 1920 | return True |
| 1921 | prefix = f"{base}\x1f" |
| 1922 | return any(key.startswith(prefix) for key in normalized_values) |
| 1923 | |
| 1924 | |
| 1925 | def _resolve_value_in_map( |
| 1926 | values: Dict[str, Any], |
| 1927 | datum_key: str, |
| 1928 | *, |
| 1929 | blocked_repeats: frozenset[str] = frozenset(), |
| 1930 | allow_occurrence_zero: bool = True, |
| 1931 | ) -> Any: |
| 1932 | if not values: |
| 1933 | return None |
| 1934 | if datum_key == "end_date" or not allow_occurrence_zero: |
| 1935 | if datum_key in values: |
| 1936 | return values[datum_key] |
| 1937 | target = datum_key.strip().casefold() |
| 1938 | for raw_key, raw_value in values.items(): |
| 1939 | if str(raw_key).strip().casefold() == target: |
| 1940 | return raw_value |
| 1941 | return None |
| 1942 | |
| 1943 | has_suffix = "\x1f" in datum_key |
| 1944 | if has_suffix: |
| 1945 | outcome_name, raw_occurrence = datum_key.rsplit("\x1f", 1) |
| 1946 | raw_occ_stripped = raw_occurrence.strip() |
| 1947 | if not (raw_occ_stripped.isascii() and raw_occ_stripped.isdigit()): |
| 1948 | return None |
| 1949 | try: |
| 1950 | occurrence = int(raw_occ_stripped) |
| 1951 | except ValueError: |
| 1952 | return None |
| 1953 | base = outcome_name.strip().casefold() |
| 1954 | if base in blocked_repeats: |
| 1955 | return None |
| 1956 | target = f"{base}\x1f{occurrence}" |
| 1957 | else: |
| 1958 | base = datum_key.strip().casefold() |
| 1959 | occurrence = 0 |
| 1960 | target = base |
| 1961 | |
| 1962 | if datum_key in values: |
| 1963 | return values[datum_key] |
| 1964 | |
| 1965 | normalized_values: Dict[str, Any] = {} |
| 1966 | for raw_key, raw_value in values.items(): |
| 1967 | normalized_values.setdefault(_normalize_snapshot_key(str(raw_key)), raw_value) |
| 1968 | |
| 1969 | if target in normalized_values: |
| 1970 | return normalized_values[target] |
| 1971 | if not has_suffix and base not in blocked_repeats: |
| 1972 | # Resolve an unsuffixed name against \x1f0 only when no sibling |
| 1973 | # occurrence exists; when multiple occurrences share the label, an |
| 1974 | # unsuffixed name cannot identify which market it came from. |
| 1975 | prefix = f"{base}\x1f" |
| 1976 | occ_keys = [key for key in normalized_values if key.startswith(prefix)] |
| 1977 | if occ_keys == [f"{base}\x1f0"]: |
| 1978 | return normalized_values[occ_keys[0]] |
| 1979 | elif has_suffix and occurrence == 0 and base in normalized_values: |
| 1980 | return normalized_values[base] |
| 1981 | return None |
| 1982 | |
| 1983 | |
| 1984 | def resolve_snapshot_value( |
| 1985 | values: Dict[str, Any], |
| 1986 | datum_key: str, |
| 1987 | *, |
| 1988 | legacy_values: Optional[Dict[str, Any]] = None, |
| 1989 | blocked_repeats: frozenset[str] = frozenset(), |
| 1990 | legacy_blocked_repeats: Optional[frozenset[str]] = None, |
| 1991 | allow_occurrence_zero: bool = True, |
| 1992 | ) -> Any: |
| 1993 | """Resolve ``datum_key`` against current ``values`` first, then ``legacy_values``. |
| 1994 | |
| 1995 | Shared by both ``refetch_datum`` (direct fetch) and ``freshness._lookup_cached_datum`` |
| 1996 | (cached hit) so direct and cached verification always produce identical results |
| 1997 | and legacy cut names never shadow or leak into a current outcome name. |
| 1998 | """ |
| 1999 | value = _resolve_value_in_map( |
| 2000 | values, |
| 2001 | datum_key, |
| 2002 | blocked_repeats=blocked_repeats, |
| 2003 | allow_occurrence_zero=allow_occurrence_zero, |
| 2004 | ) |
| 2005 | if value is not None: |
| 2006 | return value |
| 2007 | if legacy_values and datum_key != "end_date" and allow_occurrence_zero: |
| 2008 | base = ( |
| 2009 | datum_key.rsplit("\x1f", 1)[0].strip().casefold() |
| 2010 | if "\x1f" in datum_key |
| 2011 | else datum_key.strip().casefold() |
| 2012 | ) |
| 2013 | normalized_current = { |
| 2014 | _normalize_snapshot_key(str(k)): v for k, v in values.items() |
| 2015 | } |
| 2016 | if _has_base_in_map(normalized_current, base): |
| 2017 | return None |
| 2018 | return _resolve_value_in_map( |
| 2019 | legacy_values, |
| 2020 | datum_key, |
| 2021 | blocked_repeats=( |
| 2022 | blocked_repeats |
| 2023 | if legacy_blocked_repeats is None |
| 2024 | else legacy_blocked_repeats |
| 2025 | ), |
| 2026 | allow_occurrence_zero=allow_occurrence_zero, |
| 2027 | ) |
| 2028 | return None |
| 2029 | |
| 2030 | |
| 2031 | def _record_outcome_values( |
| 2032 | values: Dict[str, Any], |
| 2033 | pairs: List[tuple], |
| 2034 | *, |
| 2035 | overwrite: bool, |
| 2036 | ) -> None: |
| 2037 | totals: Dict[str, int] = {} |
| 2038 | for name, _price in pairs: |
| 2039 | normalized = str(name).strip().casefold() |
| 2040 | totals[normalized] = totals.get(normalized, 0) + 1 |
| 2041 | existing_norm = {_normalize_snapshot_key(k) for k in values} |
| 2042 | counts: Dict[str, int] = {} |
| 2043 | for name, price in pairs: |
| 2044 | clean_name = str(name).strip() |
| 2045 | normalized = clean_name.casefold() |
| 2046 | occurrence = counts.get(normalized, 0) |
| 2047 | counts[normalized] = occurrence + 1 |
| 2048 | key = f"{clean_name}\x1f{occurrence}" if totals[normalized] > 1 else clean_name |
| 2049 | norm_key = _normalize_snapshot_key(key) |
| 2050 | if overwrite: |
| 2051 | values[key] = price |
| 2052 | existing_norm.add(norm_key) |
| 2053 | elif norm_key not in existing_norm: |
| 2054 | values[key] = price |
| 2055 | existing_norm.add(norm_key) |
| 2056 | |
| 2057 | |
| 2058 | def _saved_outcome_market_id(item: Any, datum_key: str) -> Optional[str]: |
| 2059 | """Return the saved sub-market ID aligned with ``datum_key`` on ``item``, if present.""" |
| 2060 | if datum_key == "end_date": |
| 2061 | return None |
| 2062 | metadata = getattr(item, "metadata", None) |
| 2063 | if not isinstance(metadata, dict): |
| 2064 | return None |
| 2065 | outcome_pairs = metadata.get("outcome_prices") |
| 2066 | outcome_market_ids = metadata.get("outcome_market_ids") |
| 2067 | if ( |
| 2068 | not isinstance(outcome_pairs, (list, tuple)) |
| 2069 | or not isinstance(outcome_market_ids, (list, tuple)) |
| 2070 | or len(outcome_pairs) != len(outcome_market_ids) |
| 2071 | ): |
| 2072 | return None |
| 2073 | valid: List[Tuple[str, str]] = [] |
| 2074 | for pair, raw_mid in zip(outcome_pairs, outcome_market_ids): |
| 2075 | if not isinstance(pair, (list, tuple)) or len(pair) != 2: |
| 2076 | continue |
| 2077 | name, value = pair |
| 2078 | if isinstance(value, bool) or not isinstance(value, (int, float)): |
| 2079 | continue |
| 2080 | try: |
| 2081 | numeric = float(value) |
| 2082 | except OverflowError: |
| 2083 | continue |
| 2084 | if not math.isfinite(numeric): |
| 2085 | continue |
| 2086 | key = str(name).strip() |
| 2087 | if not key: |
| 2088 | continue |
| 2089 | valid.append((key, str(raw_mid or "").strip())) |
| 2090 | counts: Dict[str, int] = {} |
| 2091 | for key, _mid in valid: |
| 2092 | norm = key.casefold() |
| 2093 | counts[norm] = counts.get(norm, 0) + 1 |
| 2094 | seen: Dict[str, int] = {} |
| 2095 | key_to_mid: Dict[str, str] = {} |
| 2096 | for key, mid in valid: |
| 2097 | norm = key.casefold() |
| 2098 | occ = seen.get(norm, 0) |
| 2099 | seen[norm] = occ + 1 |
| 2100 | full_key = f"{norm}\x1f{occ}" if counts[norm] > 1 else norm |
| 2101 | if mid: |
| 2102 | key_to_mid[full_key] = mid |
| 2103 | return key_to_mid.get(_normalize_snapshot_key(datum_key)) |
| 2104 | |
| 2105 | |
| 2106 | def _is_settled_closed_market( |
| 2107 | market: Dict[str, Any], |
| 2108 | pairs: List[tuple], |
| 2109 | ) -> bool: |
| 2110 | """Return True only when a closed market carries a finalized 0/1 settlement. |
| 2111 | |
| 2112 | A market that stopped trading before oracle settlement can still report its |
| 2113 | last pre-close odds (e.g. 60%/40%) while ``closed`` is True. Accepting |
| 2114 | those prices would falsely mark stale saved odds ``current``. |
| 2115 | """ |
| 2116 | if not market.get("closed", False): |
| 2117 | return False |
| 2118 | uma_status = str(market.get("umaResolutionStatus") or "").strip().lower() |
| 2119 | if uma_status and uma_status != "resolved": |
| 2120 | return False |
| 2121 | if len(pairs) < 2: |
| 2122 | return False |
| 2123 | raw_outcomes = [ |
| 2124 | name for name in _json_list(market.get("outcomes")) |
| 2125 | if name is not None and str(name).strip() |
| 2126 | ] |
| 2127 | if raw_outcomes and len(pairs) != len(raw_outcomes): |
| 2128 | return False |
| 2129 | prices = [price for _name, price in pairs] |
| 2130 | return all(price in (0.0, 1.0) for price in prices) and sum( |
| 2131 | 1 for price in prices if price == 1.0 |
| 2132 | ) == 1 |
| 2133 | |
| 2134 | |
| 2135 | class DatumNotFound(KeyError): |
| 2136 | """The event re-fetched, but it no longer prices this one datum. |
| 2137 | |
| 2138 | ``datum_only`` tells verification the failure belongs to this claim, so |
| 2139 | other claims on the same event are still re-checked (a market dropped as |
| 2140 | unpriced must not fail its priced siblings). |
| 2141 | """ |
| 2142 | |
| 2143 | datum_only = True |
| 2144 | snapshot: Optional[Dict[str, Any]] = None |
| 2145 | |
| 2146 | |
| 2147 | def refetch_datum(item: Any, datum_key: str) -> dict[str, Any]: |
| 2148 | """Re-fetch one event datum through the replay-aware HTTP wrapper.""" |
| 2149 | event_id = str(getattr(item, "metadata", {}).get("event_id") or "").strip() |
| 2150 | slug_match = re.search(r"/event/([^/?#]+)", str(getattr(item, "url", ""))) |
| 2151 | cached_item_id = str(getattr(item, "item_id", "") or "").strip() |
| 2152 | # On the slug fallback, a slug can be re-used by a re-created event. When |
| 2153 | # the cached item still carries the original Gamma event id (numeric; the |
| 2154 | # synthetic PM<N> parse fallback carries no identity), the response id |
| 2155 | # must match it too, or the verdict would come from another market. |
| 2156 | expected_id = ( |
| 2157 | cached_item_id |
| 2158 | if not event_id and re.fullmatch(r"\d+", cached_item_id) |
| 2159 | else "" |
| 2160 | ) |
| 2161 | if event_id: |
| 2162 | payload = http.request( |
| 2163 | "GET", f"{GAMMA_EVENTS_URL}/{quote(event_id)}", timeout=10, retries=2, |
| 2164 | ) |
| 2165 | elif slug_match: |
| 2166 | if not expected_id: |
| 2167 | # No event id anywhere: slug equality alone cannot verify event |
| 2168 | # identity, so fail closed (unsupported) instead of re-deriving a |
| 2169 | # verdict from whatever event currently owns the slug. |
| 2170 | raise ValueError( |
| 2171 | "Polymarket item carries no event id; slug equality alone " |
| 2172 | "cannot verify event identity" |
| 2173 | ) |
| 2174 | requested_slug = slug_match.group(1) |
| 2175 | payload = http.request( |
| 2176 | "GET", GAMMA_EVENTS_URL, params={"slug": requested_slug}, |
| 2177 | timeout=10, retries=2, |
| 2178 | ) |
| 2179 | else: |
| 2180 | raise ValueError("Polymarket item has no event id or slug") |
| 2181 | |
| 2182 | requested_slug = slug_match.group(1) if slug_match else None |
| 2183 | |
| 2184 | def _matches_identity(entry: dict) -> bool: |
| 2185 | if str(entry.get("slug") or "").strip() != requested_slug: |
| 2186 | return False |
| 2187 | if expected_id and str(entry.get("id") or "").strip() != expected_id: |
| 2188 | return False |
| 2189 | return True |
| 2190 | |
| 2191 | def _pick_event(events: list) -> Any: |
| 2192 | candidates = [entry for entry in events if isinstance(entry, dict)] |
| 2193 | if requested_slug is None: |
| 2194 | return candidates[0] if candidates else None |
| 2195 | # Verify identity: Gamma slug queries can return multiple or loosely |
| 2196 | # matched events, and verifying a claim against another market's |
| 2197 | # prices would fabricate current/stale verdicts. |
| 2198 | for entry in candidates: |
| 2199 | if _matches_identity(entry): |
| 2200 | return entry |
| 2201 | return None |
| 2202 | |
| 2203 | if isinstance(payload, list): |
| 2204 | event = _pick_event(payload) |
| 2205 | elif isinstance(payload, dict) and isinstance(payload.get("events"), list): |
| 2206 | event = _pick_event(payload.get("events") or []) |
| 2207 | else: |
| 2208 | event = payload |
| 2209 | if ( |
| 2210 | requested_slug is not None |
| 2211 | and isinstance(event, dict) |
| 2212 | and ( |
| 2213 | str(event.get("slug") or "").strip() not in ("", requested_slug) |
| 2214 | or ( |
| 2215 | expected_id |
| 2216 | and str(event.get("id") or "").strip() not in ("", expected_id) |
| 2217 | ) |
| 2218 | ) |
| 2219 | ): |
| 2220 | event = None |
| 2221 | if not isinstance(event, dict): |
| 2222 | raise KeyError("Polymarket event was not found") |
| 2223 | # Mixed events: an active event can carry resolved child markets whose |
| 2224 | # high volume would win the parse and swap the outcome labels. Only fall |
| 2225 | # back to closed markets when nothing is active (fully resolved event - |
| 2226 | # the stale-odds transition verification exists to catch). |
| 2227 | markets = event.get("markets") or [] |
| 2228 | has_active = any( |
| 2229 | isinstance(m, dict) and m.get("active", True) and not m.get("closed", False) |
| 2230 | for m in markets |
| 2231 | ) |
| 2232 | live_event_markets = _live_markets(event, include_closed=not has_active) |
| 2233 | # Build market_values directly from eligible child markets before checking |
| 2234 | # whether parse_polymarket_response produced display rows: if one market |
| 2235 | # resolves while the only open sibling has zero liquidity, or a two-market |
| 2236 | # event drops to one active Yes/No market without outcome_market_ids, |
| 2237 | # saved market_id claims must still verify using the same Yes extraction |
| 2238 | # rule parse_polymarket_response applies when saving multi-market outcomes. |
| 2239 | event_open = event.get("active", True) and not event.get("closed", False) |
| 2240 | all_dict_markets = [m for m in markets if isinstance(m, dict)] |
| 2241 | all_mid_counts: dict[str, int] = {} |
| 2242 | for m in all_dict_markets: |
| 2243 | clean_mid = _market_id(m) |
| 2244 | if clean_mid: |
| 2245 | all_mid_counts[clean_mid] = all_mid_counts.get(clean_mid, 0) + 1 |
| 2246 | market_values: dict[str, Any] = {} |
| 2247 | for m in all_dict_markets: |
| 2248 | is_live_open = ( |
| 2249 | event_open |
| 2250 | and m.get("active", True) |
| 2251 | and not m.get("closed", False) |
| 2252 | and _safe_float(m.get("liquidity")) > 0 |
| 2253 | ) |
| 2254 | if not is_live_open and not m.get("closed", False): |
| 2255 | continue |
| 2256 | clean_mid = _market_id(m) |
| 2257 | if not clean_mid or all_mid_counts.get(clean_mid) != 1: |
| 2258 | continue |
| 2259 | pairs = _parse_outcome_prices(m) |
| 2260 | if not is_live_open and not _is_settled_closed_market(m, pairs): |
| 2261 | continue |
| 2262 | yes_price = next((p for name, p in pairs if name.strip().lower() == "yes"), None) |
| 2263 | if yes_price is not None: |
| 2264 | market_values[clean_mid] = yes_price |
| 2265 | |
| 2266 | parsed = parse_polymarket_response( |
| 2267 | {"events": [event]}, |
| 2268 | include_all_outcomes=True, |
| 2269 | include_closed=not has_active, |
| 2270 | ) |
| 2271 | saved_market_id = ( |
| 2272 | None if datum_key == "end_date" else _saved_outcome_market_id(item, datum_key) |
| 2273 | ) |
| 2274 | if not parsed: |
| 2275 | if not market_values: |
| 2276 | raise KeyError("Polymarket event is closed, unavailable, or malformed") |
| 2277 | snapshot = { |
| 2278 | "values": {}, |
| 2279 | "legacy_values": {}, |
| 2280 | "market_values": market_values, |
| 2281 | "blocked_repeats": [], |
| 2282 | "legacy_blocked_repeats": [], |
| 2283 | "url": str(getattr(item, "url", "")), |
| 2284 | "timestamp": event.get("updatedAt"), |
| 2285 | } |
| 2286 | value = market_values.get(saved_market_id) if saved_market_id else None |
| 2287 | if value is None: |
| 2288 | missing = DatumNotFound(f"Polymarket datum {datum_key!r} was not found") |
| 2289 | missing.snapshot = snapshot |
| 2290 | raise missing |
| 2291 | return {"value": value, **snapshot} |
| 2292 | refreshed = parsed[0] |
| 2293 | values: dict[str, Any] = {} |
| 2294 | outcome_pairs = refreshed.get("outcome_prices") or [] |
| 2295 | _record_outcome_values(values, outcome_pairs, overwrite=True) |
| 2296 | # Reports saved by older builds hold each market under its old cut name. |
| 2297 | # Keep them in a separate map so legacy cut names are tried only after |
| 2298 | # current names (including occurrence-0 collapse on current names). |
| 2299 | questions = refreshed.get("outcome_questions") or [] |
| 2300 | legacy_pairs = [ |
| 2301 | ( |
| 2302 | _legacy_shorten_question(question).strip() if question else str(name).strip(), |
| 2303 | price, |
| 2304 | ) |
| 2305 | for (name, price), question in zip(outcome_pairs, questions) |
| 2306 | ] |
| 2307 | legacy_values: dict[str, Any] = {} |
| 2308 | _record_outcome_values(legacy_values, legacy_pairs, overwrite=True) |
| 2309 | # A repeated name is told apart by its rank among the priced markets. When |
| 2310 | # the book check drops one market carrying that name, the ranks shift and a |
| 2311 | # saved occurrence could read a sibling's price, so repeated names of a |
| 2312 | # dropped market are not answered at all. Track current and legacy dropped |
| 2313 | # labels separately so a dropped market's legacy cut cannot block an |
| 2314 | # unrelated current outcome name. |
| 2315 | sibling_event_markets = [ |
| 2316 | m for m in live_event_markets if isinstance(m, dict) and m.get("question") |
| 2317 | ] |
| 2318 | sibling_labels = ( |
| 2319 | _sibling_outcome_labels(sibling_event_markets) |
| 2320 | if len(sibling_event_markets) > 1 |
| 2321 | else {} |
| 2322 | ) |
| 2323 | dropped_current: set[str] = set() |
| 2324 | dropped_legacy: set[str] = set() |
| 2325 | for market in markets: |
| 2326 | if not isinstance(market, dict) or not market.get("question"): |
| 2327 | continue |
| 2328 | if has_active and (not market.get("active", True) or market.get("closed", False)): |
| 2329 | continue |
| 2330 | if _parse_outcome_prices(market) or not _parse_outcome_prices(market, book_aware=False): |
| 2331 | continue |
| 2332 | question = str(market["question"]) |
| 2333 | is_subject = _question_subject(question.strip().rstrip("?")) is not None |
| 2334 | full_label = sibling_labels.get(id(market)) |
| 2335 | if full_label: |
| 2336 | dropped_current.add(full_label.strip().casefold()) |
| 2337 | else: |
| 2338 | dropped_current.add(_shorten_question(question).strip().casefold()) |
| 2339 | if is_subject: |
| 2340 | group_title = " ".join(str(market.get("groupItemTitle") or "").split()) |
| 2341 | if group_title: |
| 2342 | dropped_current.add(group_title.casefold()) |
| 2343 | dropped_legacy.add(_legacy_shorten_question(question).strip().casefold()) |
| 2344 | # If another child market could have claimed a label via its current label, |
| 2345 | # shortened subject, legacy cut, or groupItemTitle (only when it has a |
| 2346 | # question subject), an older report without outcome_market_ids could have |
| 2347 | # saved that other market under that label. Purge such cross-market |
| 2348 | # ambiguous labels from both values and legacy_values so label-only |
| 2349 | # verification returns unsupported instead of switching markets. |
| 2350 | active_question_markets = [ |
| 2351 | m |
| 2352 | for m in markets |
| 2353 | if isinstance(m, dict) |
| 2354 | and m.get("question") |
| 2355 | and (not has_active or (m.get("active", True) and not m.get("closed", False))) |
| 2356 | ] |
| 2357 | |
| 2358 | ambiguous_current: set[str] = set() |
| 2359 | ambiguous_legacy: set[str] = set() |
| 2360 | if len(active_question_markets) > 1: |
| 2361 | current_owners: dict[str, set[int]] = {} |
| 2362 | legacy_owners: dict[str, set[int]] = {} |
| 2363 | possible_owners: dict[str, set[int]] = {} |
| 2364 | for idx, market in enumerate(active_question_markets): |
| 2365 | question = str(market["question"]) |
| 2366 | current_name = (sibling_labels.get(id(market)) or "").strip().casefold() |
| 2367 | if current_name: |
| 2368 | current_owners.setdefault(current_name, set()).add(idx) |
| 2369 | legacy_name = _legacy_shorten_question(question).strip().casefold() |
| 2370 | if legacy_name: |
| 2371 | legacy_owners.setdefault(legacy_name, set()).add(idx) |
| 2372 | possible_names = { |
| 2373 | current_name, |
| 2374 | legacy_name, |
| 2375 | _shorten_question(question).strip().casefold(), |
| 2376 | } |
| 2377 | if _question_subject(question.strip().rstrip("?")) is not None: |
| 2378 | possible_names.add( |
| 2379 | " ".join(str(market.get("groupItemTitle") or "").split()).casefold() |
| 2380 | ) |
| 2381 | possible_names.discard("") |
| 2382 | for name in possible_names: |
| 2383 | possible_owners.setdefault(name, set()).add(idx) |
| 2384 | ambiguous_current = { |
| 2385 | name |
| 2386 | for name, owners in current_owners.items() |
| 2387 | if possible_owners.get(name, set()) - owners |
| 2388 | } |
| 2389 | ambiguous_legacy = { |
| 2390 | name |
| 2391 | for name, owners in legacy_owners.items() |
| 2392 | if possible_owners.get(name, set()) - owners |
| 2393 | } |
| 2394 | for key in list(values): |
| 2395 | if key == "end_date": |
| 2396 | continue |
| 2397 | base = ( |
| 2398 | key.rsplit("\x1f", 1)[0].strip().casefold() |
| 2399 | if "\x1f" in key |
| 2400 | else key.strip().casefold() |
| 2401 | ) |
| 2402 | if base in ambiguous_current or ("\x1f" in key and base in dropped_current): |
| 2403 | del values[key] |
| 2404 | dropped_current.update(ambiguous_current) |
| 2405 | for key in list(legacy_values): |
| 2406 | base = ( |
| 2407 | key.rsplit("\x1f", 1)[0].strip().casefold() |
| 2408 | if "\x1f" in key |
| 2409 | else key.strip().casefold() |
| 2410 | ) |
| 2411 | if base in ambiguous_legacy or ("\x1f" in key and base in dropped_legacy): |
| 2412 | del legacy_values[key] |
| 2413 | dropped_legacy.update(ambiguous_legacy) |
| 2414 | if refreshed.get("end_date") is not None: |
| 2415 | values["end_date"] = refreshed["end_date"] |
| 2416 | |
| 2417 | blocked_current = frozenset(dropped_current) |
| 2418 | blocked_legacy = frozenset(dropped_legacy) |
| 2419 | if saved_market_id: |
| 2420 | value = market_values.get(saved_market_id) |
| 2421 | else: |
| 2422 | value = resolve_snapshot_value( |
| 2423 | values, |
| 2424 | datum_key, |
| 2425 | legacy_values=legacy_values, |
| 2426 | blocked_repeats=blocked_current, |
| 2427 | legacy_blocked_repeats=blocked_legacy, |
| 2428 | allow_occurrence_zero=(datum_key != "end_date"), |
| 2429 | ) |
| 2430 | snapshot = { |
| 2431 | "values": values, |
| 2432 | "legacy_values": legacy_values, |
| 2433 | "market_values": market_values, |
| 2434 | "blocked_repeats": sorted(blocked_current), |
| 2435 | "legacy_blocked_repeats": sorted(blocked_legacy), |
| 2436 | "url": str(getattr(item, "url", "")), |
| 2437 | "timestamp": event.get("updatedAt"), |
| 2438 | } |
| 2439 | if value is None: |
| 2440 | missing = DatumNotFound(f"Polymarket datum {datum_key!r} was not found") |
| 2441 | # The event was fetched; sibling claims read this snapshot instead of |
| 2442 | # fetching it again. |
| 2443 | missing.snapshot = snapshot |
| 2444 | raise missing |
| 2445 | return {"value": value, **snapshot} |
| 2446 | |
| 2447 | |
| 2448 | def by_selection(items: list) -> list: |
| 2449 | """Markets in the parser's selection order: a live entity market first, |
| 2450 | by ``selection_score``. An item saved before the parser scored markets |
| 2451 | follows, by 30-day volume as before.""" |
| 2452 | def key(item) -> tuple: |
| 2453 | volume = (item.engagement or {}).get("volume") or 0 |
| 2454 | score = item.metadata.get("selection_score") |
| 2455 | if isinstance(score, bool) or not isinstance(score, (int, float)): |
| 2456 | return (0, 0, 0.0, volume) |
| 2457 | return (1, item.metadata.get("selection_tier") or 0, score, volume) |
| 2458 | |
| 2459 | return sorted(items, key=key, reverse=True) |
| 2460 |