"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
Merge main into fix/grounding-tail-risk-identity: keep the table index-cell exemption alongside the tail-risk frames
Yufeng He095bc222c799
diff --cc agent/src/agent/grounding/evidence.pyindex f003a3256,12cce633c..4ba128166--- a/agent/src/agent/grounding/evidence.py+++ b/agent/src/agent/grounding/evidence.py@@@ -122,12 -122,13 +122,17 @@@ _ANALYSIS_KIND_ALIASES ="var": "tail_risk","var_95": "tail_risk","var_99": "tail_risk",+ # quantlib_call records a scalar result under the function name, and "var"+ # alone matches only a whole leaf (_EXACT_ONLY_ALIASES), so these two need+ # their own entries or a real VaR result grounds nothing (#1464).+ "historical_var": "tail_risk",+ "parametric_var": "tail_risk","cvar": "tail_risk",+ "cvar_95": "tail_risk",+ "cvar_99": "tail_risk","es": "tail_risk",+ "es_95": "tail_risk",+ "es_99": "tail_risk","expected_shortfall": "tail_risk",# Chinese TOOL FIELD NAMES from A-share tools, not answer prose."最大回撤": "drawdown",diff --cc agent/src/agent/grounding/figures.pyindex 067aef36d,71e2c117f..4d19d5036--- a/agent/src/agent/grounding/figures.py+++ b/agent/src/agent/grounding/figures.py@@@ -864,95 -869,39 +874,128 @@@ def _short_date_is_structural(content:return any(segment <= full.start() and full.end() <= match.start() for full in full_dates)+# A tail-risk claim's prose frame: the measure word, then an optional+# confidence level. VaR and ES/CVaR are different measurements at any+# confidence, and a 95% and a 99% VaR are different ones.+_TAIL_RISK_WORD_RE = re.compile(+ r"(?<![A-Za-z])(?:C?VaR|ES)(?![A-Za-z])|(?i:expected shortfall)|在险价值|风险价值|预期损失|条件在险价值"+)++# The confidence sits right after the measure word ("VaR 95%", "VaR (95%)",+# "ES at 99%") or right before it ("95% VaR", "95% 置信水平下的 VaR").+_TAIL_RISK_CONFIDENCE_AFTER_RE = re.compile(+ r"\s*[((]?\s*(?:at|of)?\s*(\d{1,3}(?:\.\d+)?)\s*[%%]"+)+_TAIL_RISK_CONFIDENCE_BEFORE_RE = re.compile(+ r"(\d{1,3}(?:\.\d+)?)\s*[%%]\s*(?:置信水平|置信度|confidence(?:\s+level)?)?\s*(?:下|中|的)?\s*[,,]?\s*$"+)+++def _tail_risk_measure_of(word: str) -> str:+ """The measure a tail-risk keyword reports: ES and CVaR are one family."""+ return (+ "es"+ if word.casefold() == "expected shortfall" or word in ("ES", "CVaR", "预期损失", "条件在险价值")+ else "var"+ )+++def _tail_risk_frames(content: str, figures: list[Figure]) -> list[Figure]:+ """Mark the tail-risk frame each percent figure sits in, when there is one.++ The confidence level in "VaR 95%: 1.57%" is part of the frame, not a+ measurement: it is flagged so the gate never checks it, while the value is+ checked only against evidence of the same measure and confidence.+ """+ if not any(figure.percent for figure in figures):+ return figures+ lines = _lines_with_offsets(content)+ out = list(figures)+ for line_index, (line_text, line_start) in enumerate(lines):+ line_figures = [+ (index, figure)+ for index, figure in enumerate(figures)+ if figure.line == line_index and figure.percent+ ]+ if not line_figures:+ continue+ keywords = list(_TAIL_RISK_WORD_RE.finditer(line_text))+ if not keywords:+ continue+ # A frame runs from its keyword to the next keyword or the clause end:+ # "VaR 95%: 1,57%. Drawdown máximo −5,132%" keeps the drawdown out of+ # the VaR frame entirely.+ terminators = [+ match.end()+ for match in re.finditer(r"[。!!??;;.]", line_text)+ ]+ regions: list[tuple[int, int]] = []+ for pos, keyword in enumerate(keywords):+ end = keywords[pos + 1].start() if pos + 1 < len(keywords) else len(line_text)+ boundary = next((mark for mark in terminators if mark > keyword.end()), end)+ regions.append((keyword.start(), min(end, boundary)))+ # (measure, confidence, confidence digit start in source coords, region)+ frames: list[tuple[str, int | None, int | None, tuple[int, int]]] = []+ for keyword, region in zip(keywords, regions):+ measure = _tail_risk_measure_of(keyword.group(0))+ confidence: int | None = None+ confidence_start: int | None = None+ match = _TAIL_RISK_CONFIDENCE_AFTER_RE.match(line_text, keyword.end())+ if match is None:+ match = _TAIL_RISK_CONFIDENCE_BEFORE_RE.search(line_text, 0, keyword.start())+ if match:+ confidence = int(float(match.group(1)))+ confidence_start = line_start + match.start(1)+ frames.append((measure, confidence, confidence_start, region))+ for index, figure in line_figures:+ if figure.start in {frame[2] for frame in frames}:+ out[index] = replace(figure, tail_risk_confidence=True)+ continue+ line_pos = figure.start - line_start+ region = next(+ (frame[3] for frame in frames if frame[3][0] <= line_pos < frame[3][1]),+ None,+ )+ if region is None:+ continue+ measure, confidence, _, _ = next(+ frame for frame in frames if frame[3] == region+ )+ out[index] = replace(figure, tail_risk=(measure, confidence))+ return out+ def _index_cells(rows: Sequence[TableRow]) -> set[tuple[int, int]]:+ """Spans of the cells of a column that only numbers its table's rows (#1471).++ A column whose numbered cells read 1, 2, 3 … in row order is the table's+ index. No price or metric takes that shape, and cutting it turned a ranking+ into a column of omission marks. A cell without a digit ("—", "Total") is+ skipped; one numbered row proves no sequence, so it takes two. A column the+ header binds to an OHLC field is never an index.++ Args:+ rows: Every table row of the document.++ Returns:+ ``(start, end)`` of each index cell.+ """+ tables: dict[int, list[TableRow]] = {}+ for row in rows:+ tables.setdefault(row.table, []).append(row)+ spans: set[tuple[int, int]] = set()+ for body in tables.values():+ for position in range(max(len(row.cells) for row in body)):+ if position in body[0].columns:+ continue+ numbered = [+ row.cells[position]+ for row in body+ if position < len(row.cells) and any(char.isdigit() for char in row.cells[position][0])+ ]+ if len(numbered) < 2 or not all(_INDEX_CELL_RE.fullmatch(text) for text, _, _ in numbered):+ continue+ if [int(text.rstrip(".)")) for text, _, _ in numbered] == list(range(1, len(numbered) + 1)):+ spans.update((start, end) for _, start, end in numbered)+ return spansdef scan_figures(content: str, block: FiguresBlock) -> list[Figure]: