Coverage for src/copytrading_engine/parsing/extraction.py: 93%
296 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-16 16:55 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-16 16:55 +0000
1"""The model's reading of a post is untrusted: plain checks hold it to the post's own words."""
3import re
4import unicodedata
5from dataclasses import dataclass
6from decimal import Decimal
7from typing import Literal, Protocol
9from pydantic import BaseModel, ConfigDict
11from copytrading_engine.parsing.diagnostics import ValidationIssue
12from copytrading_engine.parsing.history import RecentCall
13from copytrading_engine.parsing.routes import Route
14from copytrading_engine.shared.reading import (
15 All,
16 Alongside,
17 AtMarket,
18 Batch,
19 Buy,
20 Call,
21 Chatter,
22 Conditional,
23 Dollars,
24 Exact,
25 Fraction,
26 Instruction,
27 Lot,
28 NotGiven,
29 PostReading,
30 Range,
31 ReaderReading,
32 Sell,
33 Stock,
34 Stop,
35 Suggestion,
36 TradeMade,
37)
38from copytrading_engine.shared.signals import same_fraction
39from copytrading_engine.shared.symbols import crypto_pair, is_crypto
41PROMPT_VERSION = "stock-reading-v10"
43# Chinese characters and ASCII letters both count as Unicode word characters.
44# Match complete numeric tokens and bound English words by ASCII letters so
45# half/full next to Chinese still count as allocations.
46EXPLICIT_ALLOCATION = re.compile(
47 r"(?P<chinese>(?:\d+|[一二两三四五六七八九十])分之"
48 r"(?:\d+|[一二两三四五六七八九十]))"
49 r"|(?P<ratio>(?<![\d./])\d+\s*/\s*\d+(?![\d./]))"
50 r"|(?P<percent>(?<![\d.])\d+(?:\.\d+)?%(?![\d]))"
51 r"|(?P<half>一半|半仓|(?<![A-Za-z])half(?![A-Za-z]))"
52 r"|(?P<full>全仓|全部|(?<![A-Za-z])full(?![A-Za-z]))"
53 # "a third", "two thirds", "a quarter", "three quarters", "quarter position". A bare "third"
54 # is an order ("third time") and a bare "quarter" a season ("next quarter"), so both need a
55 # count, or for a quarter the word position or size after it.
56 r"|(?P<english>(?<![A-Za-z])(?:(?:an?|one|two|three|four|[1-9])[\s-]+"
57 r"(?:third|quarter|fourth|fifth|sixth|seventh|eighth|ninth|tenth)s?"
58 r"|quarter(?=[\s-]+(?:position|pos|size)(?![A-Za-z])))(?![A-Za-z]))",
59 re.I,
60)
62_ENGLISH_COUNTS = {"a": 1, "an": 1, "one": 1, "two": 2, "three": 3, "four": 4}
63_ENGLISH_PARTS = {
64 "third": 3,
65 "quarter": 4,
66 "fourth": 4,
67 "fifth": 5,
68 "sixth": 6,
69 "seventh": 7,
70 "eighth": 8,
71 "ninth": 9,
72 "tenth": 10,
73}
76class DecodeError(Exception):
77 """Provider-independent failure; no provider response or secret is retained."""
79 def __init__(
80 self, reason: str, *, retryable: bool, issues: tuple[ValidationIssue, ...] = ()
81 ) -> None:
82 self.reason, self.retryable, self.issues = reason, retryable, issues
83 super().__init__(reason)
86class ReadingOutput(BaseModel):
87 """Anything about stocks or the market: a trade made or to make, a plan, market talk, or a
88 post about a trade that cannot be pinned down. One reading of the post."""
90 model_config = ConfigDict(extra="forbid", frozen=True, hide_input_in_errors=True)
91 reading: ReaderReading
94class JustChat(BaseModel):
95 """Small talk with nothing about stocks or the market: a greeting, a reaction, an emoji,
96 such as "hi", "how's going", "早上好", or "👍"."""
98 model_config = ConfigDict(extra="forbid", frozen=True)
101@dataclass(frozen=True)
102class Answer:
103 """A reading and the model that gave it."""
105 reading: PostReading
106 model: str | None = None
109@dataclass(frozen=True)
110class ReadingInput:
111 """The post as the checks see it, its guru's route, and the guru's recent calls, so a failed
112 check can go back to the model with its reason."""
114 text: str
115 route: Route
116 recent: tuple[RecentCall, ...] = ()
119class Decoder(Protocol):
120 async def answer(self, text: str, route: Route, recent: tuple[RecentCall, ...] = ()) -> Answer:
121 """The post read, and which model answered."""
122 ...
125def playbook_maps(playbook: str, phrase: str, symbol: str) -> bool:
126 """A name resolves to a ticker only when one playbook line states both."""
127 ticker = re.compile(r"(?<![A-Za-z0-9])" + re.escape(symbol) + r"(?![A-Za-z0-9])")
128 return any(phrase in line and ticker.search(line) for line in playbook.splitlines())
131_PLAYBOOK_SIZE = re.compile(
132 r"^\s*(?P<words>.+?)\s+means\s+(?:sell\s+|buy\s+)?(?P<size>\d+/\d+|\d*\.\d+|half|all)\s*$",
133 re.IGNORECASE,
134)
137def playbook_size(playbook: str, words: str) -> Decimal | None:
138 """The size the owner's playbook gives a guru's own words, as in "减仓 means 1/2" or
139 "第二批 means 1/3" (ADR-0010); None when no line names these words."""
140 for line in playbook.splitlines():
141 match = _PLAYBOOK_SIZE.match(line)
142 if match is None or match.group("words").strip().strip('"“”') != words.strip(): 142 ↛ 143line 142 didn't jump to line 143 because the condition on line 142 was never true
143 continue
144 size = match.group("size").lower()
145 if size == "half": 145 ↛ 146line 145 didn't jump to line 146 because the condition on line 145 was never true
146 return Decimal("0.5")
147 if size == "all": 147 ↛ 148line 147 didn't jump to line 148 because the condition on line 147 was never true
148 return Decimal(1)
149 if "/" in size: 149 ↛ 152line 149 didn't jump to line 152 because the condition on line 149 was always true
150 numerator, denominator = (Decimal(part) for part in size.split("/"))
151 return numerator / denominator if denominator else None
152 return Decimal(size)
153 return None
156# What a sell's share counts from: the original buy, or what is left of it (ADR-0010).
157type Basis = Literal["original", "remaining"]
159# The words that name a basis, in a post or a playbook line. Code decides the basis from them;
160# the model only points at them.
161_BASIS_TERMS: dict[Basis, tuple[str, ...]] = {
162 "original": (
163 "原仓",
164 "原始",
165 "原来",
166 "原有",
167 "初始",
168 "最初",
169 "总仓",
170 "original",
171 "initial",
172 "whole position",
173 "full position",
174 "total position",
175 ),
176 "remaining": ("剩", "余下", "其余", "rest", "remain", "left"),
177}
179# A playbook habit line: "Sell fractions count from the original buy", "卖出比例按原仓计算".
180_PLAYBOOK_BASIS = re.compile(
181 r"counts?\s+from\s+(?P<english>[^.;。;\n]+)" # noqa: RUF001 - Chinese stops end a clause
182 r"|按(?P<chinese>[^,.;,。;\n]+?)(?:计算|计|算)", # noqa: RUF001
183 re.IGNORECASE,
184)
187def names_basis(words: str) -> Basis | None:
188 """The basis these words name: one basis's words and not the other's."""
189 folded = words.casefold()
190 named = [basis for basis, terms in _BASIS_TERMS.items() if any(t in folded for t in terms)]
191 return named[0] if len(named) == 1 else None
194def playbook_basis(playbook: str) -> Basis:
195 """What this guru's sell shares count from, as the owner's playbook says it ("Sell fractions
196 count from the original buy"); what is left when no line says (ADR-0010). A worked line
197 quotes a post, so it never sets the habit."""
198 for line in playbook.splitlines():
199 if "->" in line:
200 continue
201 for match in _PLAYBOOK_BASIS.finditer(line): 201 ↛ 198line 201 didn't jump to line 198 because the loop on line 201 didn't complete
202 basis = names_basis(match.group("english") or match.group("chinese"))
203 if basis is not None: 203 ↛ 201line 203 didn't jump to line 201 because the condition on line 203 was always true
204 return basis
205 return "remaining"
208def exit_basis(sell: Sell, playbook: str) -> Basis:
209 """What a sell's share counts from, decided by code: the basis the post's own words name,
210 when the reader cites them, else the playbook's. A post with no words for a basis
211 ("102.55出一半SOL/USD") always counts from the playbook's, however the model reads it."""
212 named = None if sell.counts_from_words is None else names_basis(sell.counts_from_words)
213 if named is not None and named == sell.counts_from:
214 return named
215 return playbook_basis(playbook)
218MASS_MENTIONS = ("@everyone", "@here")
221def without_mentions(text: str) -> str:
222 for mention in MASS_MENTIONS:
223 text = text.replace(mention, "")
224 return text.strip()
227# A Chinese keyboard types the full stop as a decimal point: "381。3" or "16 。1" is 381.3 or
228# 16.1. Only a stop between two digits is a decimal point; one ending a sentence stays.
229CHINESE_DECIMAL_POINT = re.compile(r"(?<=\d)\s*[。。]\s*(?=\d)")
232def normalize(text: str) -> str:
233 """The post as the reader and its checks see it: compatibility forms folded, Chinese
234 decimal points written as ".", and mass mentions removed."""
235 text = unicodedata.normalize("NFKC", text)
236 return without_mentions(CHINESE_DECIMAL_POINT.sub(".", text))
239def number_is_grounded(value: Decimal, evidence: str | None, text: str) -> bool:
240 if not evidence or evidence not in text or not re.fullmatch(r"\d+(?:\.\d+)?", evidence):
241 return False
242 # Require a complete numeric token, not 25 extracted from 125 or 25.8.
243 return Decimal(evidence) == value and bool(
244 re.search(r"(?<![\d.])" + re.escape(evidence) + r"(?![\d.])", text)
245 )
248def allocation_is_grounded(value: Decimal, evidence: str | None, text: str) -> bool:
249 """The cited evidence is in the post and covers exactly one complete allocation token (read
250 as a whole token of the post, so "half" inside "halfway" never counts) of that value."""
251 if not evidence: 251 ↛ 252line 251 didn't jump to line 252 because the condition on line 251 was never true
252 return False
253 tokens = list(EXPLICIT_ALLOCATION.finditer(text))
254 start = text.find(evidence)
255 while start != -1:
256 end = start + len(evidence)
257 inside = [token for token in tokens if start <= token.start() and token.end() <= end]
258 if len(inside) == 1 and same_fraction(_allocation_value(inside[0]), value):
259 return True
260 start = text.find(evidence, start + 1)
261 return False
264def _allocation_value(match: re.Match[str]) -> Decimal | None:
265 """Read the value of a complete source allocation token, if valid."""
266 token = match.group().lower()
267 chinese = {
268 "一": 1,
269 "二": 2,
270 "两": 2,
271 "三": 3,
272 "四": 4,
273 "五": 5,
274 "六": 6,
275 "七": 7,
276 "八": 8,
277 "九": 9,
278 "十": 10,
279 }
281 def integer(part: str) -> int | None:
282 if part.isascii() and part.isdigit():
283 return int(part)
284 if part in chinese: 284 ↛ 286line 284 didn't jump to line 286 because the condition on line 284 was always true
285 return chinese[part]
286 return None
288 if match.lastgroup == "chinese":
289 denominator_text, numerator_text = token.split("分之", 1)
290 denominator, numerator = integer(denominator_text), integer(numerator_text)
291 if denominator and numerator: 291 ↛ 310line 291 didn't jump to line 310 because the condition on line 291 was always true
292 return Decimal(numerator) / Decimal(denominator)
293 elif match.lastgroup == "ratio":
294 numerator_text, denominator_text = token.split("/", 1)
295 denominator = int(denominator_text.strip())
296 if denominator: 296 ↛ 310line 296 didn't jump to line 310 because the condition on line 296 was always true
297 return Decimal(numerator_text.strip()) / Decimal(denominator)
298 elif match.lastgroup == "percent": 298 ↛ 299line 298 didn't jump to line 299 because the condition on line 298 was never true
299 return Decimal(token[:-1]) / 100
300 elif match.lastgroup == "half":
301 return Decimal("0.5")
302 elif match.lastgroup == "full":
303 return Decimal(1)
304 elif match.lastgroup == "english": 304 ↛ 310line 304 didn't jump to line 310 because the condition on line 304 was always true
305 *count, part = re.split(r"[\s-]+", token)
306 written = count[0] if count else "one"
307 numerator = int(written) if written.isdigit() else _ENGLISH_COUNTS[written]
308 value = Decimal(numerator) / Decimal(_ENGLISH_PARTS[part.removesuffix("s")])
309 return value if value <= 1 else None
310 return None
313class GroundingError(ValueError):
314 def __init__(self, code: str, path: str, explanation: str) -> None:
315 self.issue = ValidationIssue(path=path, code=code)
316 super().__init__(explanation)
319# Words that make a trade conditional or historical. A reading that calls such a post a trade
320# made or an instruction goes back to the model. 附近 ("near") is a plan only when its clause
321# reports nothing done: "61.6附近加" waits, "qqq 660附近也加了" is a buy already made.
322NONCURRENT = re.compile(
323 r"如果|假如|计划|附近(?![^\uff0c。,\uff1b;\s]*了)|突破.*再|昨天.*加了"
324 r"|\b(if|would|might|yesterday)\b",
325 re.I,
326)
328# An amount as written: 1,500, 200, 2.5, 两百, 一千五.
329_AMOUNT = (
330 r"(?P<{name}>\d{{1,3}}(?:,\d{{3}})+(?:\.\d+)?|\d+(?:\.\d+)?"
331 r"|[一二两三四五六七八九十百千万]+)"
332)
333# A dollar amount to put in, as a size: "$200 of", "200$ of", "$200 worth", "200 dollars",
334# "200 bucks", 200刀, 两百刀, 200美元, 200美金, 200块. A bare "$71" is a price, never a size.
335DOLLAR_SIZE = re.compile(
336 r"\$\s*" + _AMOUNT.format(name="before") + r"\s+(?:of|worth|in)\b"
337 r"|(?<![\d.,])" + _AMOUNT.format(name="after") + r"\s*\$\s*(?:of|worth|in)\b"
338 r"|(?<![\d.,])" + _AMOUNT.format(name="word") + r"\s*(?:dollars?|bucks|usd|刀|美元|美金|块)",
339 re.I,
340)
341_CHINESE_UNITS = {"十": 10, "百": 100, "千": 1000, "万": 10000}
344def _chinese_amount(words: str) -> Decimal | None:
345 """两百 is 200, 一千五 is 1500, 五百 is 500; None when it is not a plain amount."""
346 total, current = 0, 0
347 for char in words:
348 if char in _CHINESE_DIGITS and _CHINESE_DIGITS[char] < 10:
349 current = _CHINESE_DIGITS[char]
350 elif char in _CHINESE_UNITS: 350 ↛ 354line 350 didn't jump to line 354 because the condition on line 350 was always true
351 total += (current or 1) * _CHINESE_UNITS[char]
352 current = 0
353 else:
354 return None
355 if current:
356 # A trailing digit after a unit is one step down: 一千五 is 1500.
357 last_unit = next((_CHINESE_UNITS[c] for c in reversed(words) if c in _CHINESE_UNITS), 10)
358 total += current * (last_unit // 10 if total else 1)
359 return Decimal(total) if total else None
362def _dollar_value(match: re.Match[str]) -> Decimal | None:
363 raw = next(group for group in match.groups() if group)
364 if re.fullmatch(r"[\d,.]+", raw):
365 return Decimal(raw.replace(",", ""))
366 return _chinese_amount(raw)
369def dollars_are_grounded(value: Decimal, evidence: str | None, text: str) -> bool:
370 """The cited words are in the post and hold exactly one dollar amount, of that value: the
371 post's size ("$200 of", "200 dollars"), or only its amount ("$200") when the post states that
372 amount as a size. A price with a dollar sign ("at $71") is never a size."""
373 if not evidence or evidence not in text: 373 ↛ 374line 373 didn't jump to line 374 because the condition on line 373 was never true
374 return False
375 found = list(DOLLAR_SIZE.finditer(evidence))
376 if found:
377 return len(found) == 1 and _dollar_value(found[0]) == value
378 amount = _CITED_AMOUNT.fullmatch(evidence.strip())
379 return (
380 amount is not None
381 and Decimal(next(group for group in amount.groups() if group).replace(",", "")) == value
382 and any(
383 _dollar_value(size) == value and size.group(0).startswith(evidence.strip())
384 for size in DOLLAR_SIZE.finditer(text)
385 )
386 )
389# Only the amount of a dollar size, as a reader may cite it: "$200" of "$200 of", "200$" of
390# "200$ of".
391_CITED_AMOUNT = re.compile(r"\$\s*([\d,]+(?:\.\d+)?)|([\d,]+(?:\.\d+)?)\s*\$")
394# The batch number as written: 第二批, 第2批, batch 2.
395BATCH_NUMBER = re.compile(r"第\s*(\d+|[一二两三四五六七八九十])\s*批|batch\s*(\d+)", re.I)
396_CHINESE_DIGITS = dict(zip("一二三四五六七八九十", range(1, 11), strict=True)) | {"两": 2}
399def check_reading(reading: PostReading, text: str, route: Route) -> None:
400 """Every stated value must be the post's own words, a name a ticker only through the
401 playbook, and a trade must not be conditional or historical. Raises GroundingError."""
402 if not isinstance(reading, TradeMade | Instruction | Conditional | Suggestion):
403 return
404 if isinstance(reading, TradeMade | Instruction) and NONCURRENT.search(text):
405 raise GroundingError(
406 "noncurrent_trade", "kind", "Conditional or historical words make this not a trade"
407 )
408 if isinstance(reading, Conditional):
409 _words(reading.condition, text, "condition")
410 for index, call in enumerate(reading.calls):
411 _check_call(call, text, route, f"calls.{index}")
412 if isinstance(call, Stop):
413 _check_stop(call, reading.calls, text, f"calls.{index}")
416def _check_stop(stop: Stop, calls: tuple[Call, ...], text: str, path: str) -> None:
417 """A stop protects a buy the post names by its price, the buy the post itself makes, or no
418 buy at all; a buy price is a number of the post, and the buy this post makes is one of its
419 calls, of the same stock."""
420 protects = stop.protects
421 if isinstance(protects, Lot):
422 _number(protects.buy_price, protects.words, text, f"{path}.protects")
423 elif isinstance(protects, Alongside):
424 named = calls[protects.call] if protects.call < len(calls) else None
425 if not isinstance(named, Buy) or named.stock.ticker != stop.stock.ticker:
426 raise GroundingError(
427 "stop_buy_not_in_post",
428 f"{path}.protects",
429 "alongside must be the place of a buy of the same stock among the post's calls",
430 )
433def _check_call(call: Call, text: str, route: Route, path: str) -> None:
434 _words(call.action_words, text, f"{path}.action_words")
435 _check_stock(call.stock, text, route, f"{path}.stock")
436 _check_price(call.price, text, f"{path}.price")
437 if isinstance(call, Stop):
438 return
439 if isinstance(call, Buy):
440 _check_size(call, text, route.playbook, f"{path}.size")
441 return
442 _check_share(call, text, route.playbook, f"{path}.share")
443 _check_basis(call, text, route.playbook, path)
444 if isinstance(call.sell_from, Lot):
445 _number(call.sell_from.buy_price, call.sell_from.words, text, f"{path}.sell_from")
446 if isinstance(call.price, Exact) and call.price.value == call.sell_from.buy_price:
447 occurrences = re.findall(r"(?<![\d.])\d+(?:\.\d+)?(?![\d.])", text)
448 if sum(Decimal(value) == call.price.value for value in occurrences) < 2:
449 raise GroundingError(
450 "price_occurrence_reused",
451 f"{path}.sell_from",
452 "The current price and the buy price need two numbers in the post",
453 )
456def _check_stock(stock: Stock, text: str, route: Route, path: str) -> None:
457 _words(stock.words, text, path)
458 # A coin is its pair however the post writes it: its ticker, its pair, or its name
459 # (BTC, BTC/USD, bitcoin, 比特币 are all BTC/USD).
460 named = (
461 crypto_pair(stock.words) != stock.ticker
462 if is_crypto(stock.ticker)
463 else stock.words.lstrip("$").upper() != stock.ticker
464 )
465 if named and not playbook_maps(route.playbook, stock.words, stock.ticker):
466 raise GroundingError(
467 "symbol_not_in_playbook",
468 path,
469 "A company name becomes a ticker only when the playbook says so",
470 )
471 # Posts often glue a ticker to its price ("14.1nfxl"). A ticker of three or more letters may
472 # touch a number; a shorter one may not, so "10pm" never reads as PM or "50k" as K.
473 edge = "A-Za-z" if len(stock.words.lstrip("$")) >= 3 else "A-Za-z0-9"
474 if not named and not re.search(
475 rf"(?<![{edge}])" + re.escape(stock.words) + rf"(?![{edge}])", text
476 ):
477 raise GroundingError("partial_symbol", path, "The ticker must be a whole word in the post")
480def _check_price(price: object, text: str, path: str) -> None:
481 if isinstance(price, Exact):
482 _number(price.value, price.words, text, path)
483 elif isinstance(price, Range):
484 _number(price.low, price.low_words, text, f"{path}.low")
485 _number(price.high, price.high_words, text, f"{path}.high")
486 elif isinstance(price, AtMarket):
487 _words(price.words, text, path)
490def _check_size(buy: Buy, text: str, playbook: str, path: str) -> None:
491 size = buy.size
492 if isinstance(size, Fraction):
493 if not allocation_is_grounded(size.value, size.words, text) and not _playbook_sized(
494 size.value, size.words, text, playbook
495 ):
496 raise GroundingError("fraction_not_grounded", path, "The size is not in the post")
497 elif isinstance(size, Batch):
498 _words(size.words, text, path)
499 match = BATCH_NUMBER.search(size.words)
500 written = match and (match.group(1) or match.group(2))
501 number = None
502 if written: 502 ↛ 504line 502 didn't jump to line 504 because the condition on line 502 was always true
503 number = int(written) if written.isdigit() else _CHINESE_DIGITS.get(written)
504 if number != size.number:
505 raise GroundingError("batch_not_grounded", path, "The batch number is not in the post")
506 elif isinstance(size, Dollars):
507 if not dollars_are_grounded(size.value, size.words, text):
508 raise GroundingError(
509 "dollars_not_grounded",
510 path,
511 "words must be the post's dollar amount, such as $200 of or 200 dollars",
512 )
513 elif isinstance(size, NotGiven) and EXPLICIT_ALLOCATION.search(text):
514 raise GroundingError("source_fraction_omitted", path, "The post states a size")
515 elif isinstance(size, NotGiven) and DOLLAR_SIZE.search(text):
516 raise GroundingError("source_dollars_omitted", path, "The post states a dollar amount")
519def _check_share(sell: Sell, text: str, playbook: str, path: str) -> None:
520 share = sell.share
521 if isinstance(share, All):
522 _words(share.words, text, path)
523 elif isinstance(share, NotGiven):
524 if EXPLICIT_ALLOCATION.search(text): 524 ↛ 525line 524 didn't jump to line 525 because the condition on line 524 was never true
525 raise GroundingError("source_fraction_omitted", path, "The post states a share")
526 elif not allocation_is_grounded(share.value, share.words, text) and not _playbook_sized(
527 share.value, share.words, text, playbook
528 ):
529 raise GroundingError("fraction_not_grounded", path, "The share is not in the post")
532def _check_basis(sell: Sell, text: str, playbook: str, path: str) -> None:
533 """A plain half is half of what is left unless the playbook says the original buy (ADR-0010). A
534 sell departs from the playbook's basis only on the post's own words for the other one: the
535 model reads, and never assumes. A full exit sells everything whatever it counts from."""
536 if (
537 isinstance(sell.share, All)
538 or sell.counts_from is None
539 or sell.counts_from == playbook_basis(playbook)
540 ):
541 return
542 words = sell.counts_from_words
543 if words is None or names_basis(words) != sell.counts_from:
544 of = "the original buy" if sell.counts_from == "original" else "what is left"
545 raise GroundingError(
546 "counts_from_not_grounded",
547 f"{path}.counts_from",
548 f"counts_from {sell.counts_from} needs counts_from_words, the words of the post that "
549 f"say the share is of {of}; leave counts_from out when the post does not",
550 )
551 _words(words, text, f"{path}.counts_from_words")
554def _playbook_sized(value: Decimal, words: str, text: str, playbook: str) -> bool:
555 """The words are in the post and the owner's playbook gives them exactly this size."""
556 sized = playbook_size(playbook, words) if words and words in text else None
557 return sized is not None and same_fraction(sized, value)
560def _words(words: str, text: str, path: str) -> None:
561 if not words.strip() or words not in text:
562 raise GroundingError(
563 "words_not_in_post", path, "words must be copied exactly from the post"
564 )
567def _number(value: Decimal, words: str, text: str, path: str) -> None:
568 if not number_is_grounded(value, words, text):
569 raise GroundingError(
570 "number_not_grounded",
571 path,
572 f"words must be only this number exactly as the post writes it, such as {value}",
573 )
576def _has_chinese(text: str) -> bool:
577 return any("\u3400" <= char <= "\u9fff" or "\uf900" <= char <= "\ufaff" for char in text)
580def check_summary_language(reading: PostReading, text: str, *, retried: bool) -> str | None:
581 """The summary is written in the post's own language. A post with no Chinese in it gets a
582 summary with none either: the reader's examples are Chinese and can pull it there. Asked
583 about once; a second answer stands, since a summary is read, never traded on."""
584 if isinstance(reading, Chatter) or retried or _has_chinese(text):
585 return None
586 if not _has_chinese(reading.summary):
587 return None
588 return "summary: write it in the post's own language, which is English here, not Chinese"
591def _side(action: str) -> str:
592 return "buy" if action == "buy" else "sell"
595def same_side(earlier: RecentCall, call: Buy | Sell) -> bool:
596 """Whether a call can restate `earlier`: a buy restates a buy, a sell restates a sell or a
597 close. A sell is never a repeat of the buy it sells."""
598 return _side(earlier.action) == call.action
601def without_cross_side_repeats(reading: PostReading, recent: tuple[RecentCall, ...]) -> PostReading:
602 """A sell is never a re-post of a buy, nor a buy of a sell, whatever the reader says: the
603 post's own words say which side it is, so such a repeat is dropped and the call stands as a
604 new call, without spending the reader's one retry on it. A live paper run read "Sold all F at
605 11.65" as a repeat of "Bought F at 11.75" on both tries."""
606 if not isinstance(reading, TradeMade | Instruction | Conditional | Suggestion):
607 return reading
608 by_ref = {call.ref: call for call in recent}
609 calls = tuple(
610 call.model_copy(update={"repeats": None})
611 if not isinstance(call, Stop)
612 and call.repeats in by_ref
613 and not same_side(by_ref[call.repeats], call)
614 else call
615 for call in reading.calls
616 )
617 return reading if calls == reading.calls else reading.model_copy(update={"calls": calls})
620def check_references(reading: PostReading, recent: tuple[RecentCall, ...]) -> str | None:
621 """What is wrong with how a reading names the guru's recent calls, if anything: a repeat
622 must name a listed call of the same stock. A sell naming a buy price none of the guru's open
623 buys has is never asked about again: asked once, DeepSeek dropped the post's own buy price
624 on 7 of 12 tries, and a sell naming no buy sells every share. The price stands, and the
625 engine holds the sell for the owner (ADR-0010)."""
626 if not isinstance(reading, TradeMade | Instruction | Conditional | Suggestion):
627 return None
628 by_ref = {call.ref: call for call in recent}
629 for index, call in enumerate(reading.calls):
630 if isinstance(call, Stop) or call.repeats is None:
631 continue
632 earlier = by_ref.get(call.repeats)
633 if earlier is None:
634 return (
635 f"calls.{index}.repeats: {call.repeats} is not one of the listed calls; "
636 "name a listed reference or leave repeats empty."
637 )
638 if earlier.symbol != call.stock.ticker: 638 ↛ 639line 638 didn't jump to line 639 because the condition on line 638 was never true
639 return (
640 f"calls.{index}.repeats: {call.repeats} is {earlier.symbol}, not "
641 f"{call.stock.ticker}; a repeat restates a call of the same stock."
642 )
643 return None