"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(report-audit): validate accounting formats and finite magnitudes
Haozhe Wu250e9466009e
diff --git a/agent/src/tools/report_audit_tool.py b/agent/src/tools/report_audit_tool.pyindex c647f2b7d..448ffe409 100644--- a/agent/src/tools/report_audit_tool.py+++ b/agent/src/tools/report_audit_tool.py@@ -32,14 +32,15 @@ from src.agent.tools import BaseTool# Markdown data-point extraction (handles Chinese financial reports)# ----------------------------------------------------------------------------_KV_LABEL_RE = re.compile(- r"(?P<label>[一-龥A-Za-z][^|\n::*]{1,30})[::]\s*[~约]?\$?"- r"(?P<open>[((])?(?P<num>[\d,,.]+)(?(open)[))])\s*"- r"(?P<unit>亿[元美港]?元?|万亿|[xX倍]|%|[BMT])?"-)-+_KV_LABEL_RE = re.compile(r"(?P<label>[一-龥A-Za-z][^|\n::*]{1,30})[::]\s*")+_UNIT_PATTERN = r"亿[元美港]?元?|万亿|倍|%|[BMTxX](?![A-Za-z])"_NUMUNIT_RE = re.compile(- r"[~约]?\$?([((])?([\d,,.]+)(?(1)[))])\s*(亿[元美港]?元?|万亿|[xX倍]|%|[BMT])?"+ r"[~约]?\$?\s*(?:"+ r"(?P<open>[((])\s*\$?\s*(?P<account_num>[\d,,.]+)\s*"+ rf"(?P<inside_unit>{_UNIT_PATTERN})?\s*(?P<close>[))])\s*"+ rf"(?P<outside_unit>{_UNIT_PATTERN})?"+ r"|(?P<num>[\d,,.]+)\s*"+ rf"(?P<unit>{_UNIT_PATTERN})?)")_TABLE_SEP_RE = re.compile(r"^\|[\-\s|:]+\|$")@@ -60,6 +61,49 @@ def _clean_num(s: str) -> float | None:return None+def _report_value(text: str, *, prose: bool = False) -> tuple[float, str, int] | None:+ """Read a financial value without rescuing malformed accounting notation.++ Args:+ text: Table cell or text immediately following a prose label.+ prose: Require a unit or currency for a parenthesized prose value.++ Returns:+ Finite signed value, its unit and consumed end offset, or None.+ """+ match = _NUMUNIT_RE.match(text) if prose else _NUMUNIT_RE.search(text)+ if match is None:+ return None+ # A failed accounting match must not restart at the unsigned inner digits.+ prefix = text[: match.start()]+ if prefix.count("(") > prefix.count(")") or prefix.count("(") > prefix.count(")"):+ return None+ suffix = text[match.end() :].lstrip()+ if suffix.startswith((")", ")")):+ return None+ if match.group("open"):+ if (match.group("open"), match.group("close")) not in {+ ("(", ")"),+ ("(", ")"),+ }:+ return None+ inside, outside = match.group("inside_unit"), match.group("outside_unit")+ if inside and outside:+ return None+ unit = inside or outside or ""+ if prose and not unit and "$" not in match.group():+ return None+ value = _clean_num(match.group("account_num"))+ if value is not None:+ value = -value+ else:+ value = _clean_num(match.group("num"))+ unit = match.group("unit") or ""+ if value is None or not math.isfinite(value):+ return None+ return value, unit, match.end()++def _is_valid_label(label: str) -> bool:"""True if a label looks like a meaningful financial field name."""label = label.strip()@@ -99,7 +143,9 @@ def _parse_md_tables(lines: list[str]) -> list[tuple[str, str, float, str, int,while i < len(lines):line = lines[i].strip()if "|" in line and not _TABLE_SEP_RE.match(line):- headers_raw = [h.strip().strip("*_").strip() for h in _split_md_table_row(line)]+ headers_raw = [+ h.strip().strip("*_").strip() for h in _split_md_table_row(line)+ ]if i + 1 < len(lines) and _TABLE_SEP_RE.match(lines[i + 1].strip()):i += 2 # skip the separator rowwhile i < len(lines):@@ -119,16 +165,13 @@ def _parse_md_tables(lines: list[str]) -> list[tuple[str, str, float, str, int,if col_idx < len(headers_raw)else f"col{col_idx}")- m = _NUMUNIT_RE.search(cell)- if m:- val = _clean_num(m.group(2))- # Tables follow accounting convention: a- # parenthesized number is a negative.- if val is not None and m.group(1):- val = -val- unit = (m.group(3) or "").strip()- if val and val != 0 and val < 1e15:- results.append((row_label, col_header, val, unit, i + 1, dline))+ parsed = _report_value(cell)+ if parsed is not None:+ val, unit, _ = parsed+ if val != 0 and abs(val) < 1e15:+ results.append(+ (row_label, col_header, val, unit, i + 1, dline)+ )i += 1continuei += 1@@ -155,7 +198,7 @@ def extract_data_points(md_text: str) -> list[dict[str, Any]]:label = re.sub(r"[*_`]+", "", label).strip()if not _is_valid_label(label):return- if val is None or val == 0 or val > 1e15:+ if val is None or not math.isfinite(val) or val == 0 or abs(val) > 1e15:returnif _QUARTER_RE.fullmatch(label.strip()):return@@ -163,14 +206,16 @@ def extract_data_points(md_text: str) -> list[dict[str, Any]]:if key in seen:returnseen.add(key)- points.append({- "id": len(points) + 1,- "label": label,- "reported_value": val,- "unit": unit,- "raw_text": raw[:120],- "line_number": lineno,- })+ points.append(+ {+ "id": len(points) + 1,+ "label": label,+ "reported_value": val,+ "unit": unit,+ "raw_text": raw[:120],+ "line_number": lineno,+ }+ )lines = md_text.split("\n")in_code = False@@ -182,7 +227,11 @@ def extract_data_points(md_text: str) -> list[dict[str, Any]]:continueif col_header.upper() in _YOY_HEADERS:continue- label = f"{row_label} · {col_header}" if (col_header and col_header != row_label) else row_label+ label = (+ f"{row_label} · {col_header}"+ if (col_header and col_header != row_label)+ else row_label+ )_add(label, val, unit, lineno, raw)# 2. ``label: value unit`` lines.@@ -195,21 +244,14 @@ def extract_data_points(md_text: str) -> list[dict[str, Any]]:continueif "|" in stripped:continue # handled as a table above- for m in _KV_LABEL_RE.finditer(stripped):- if m.group("open") and not m.group("unit"):- # A parenthesized bare number in prose is a year ("(2024)"),- # not a negative. Only a trailing unit makes it accounting.- continue- val = _clean_num(m.group("num"))- if val is not None and m.group("open"):- val = -val- _add(- m.group("label"),- val,- (m.group("unit") or "").strip(),- lineno,- stripped,- )+ cursor = 0+ while (m := _KV_LABEL_RE.search(stripped, cursor)) is not None:+ cursor = m.end()+ parsed = _report_value(stripped[m.end() :], prose=True)+ if parsed is not None:+ val, unit, consumed = parsed+ cursor += consumed+ _add(m.group("label"), val, unit, lineno, stripped)return pointsdiff --git a/agent/tests/test_report_audit_accounting_parens.py b/agent/tests/test_report_audit_accounting_parens.pyindex 3247737bd..86b5914d5 100644--- a/agent/tests/test_report_audit_accounting_parens.py+++ b/agent/tests/test_report_audit_accounting_parens.py@@ -5,7 +5,11 @@ used to read the bare digits out of the parentheses, so a loss came outpositive and the closing paren swallowed the unit. Issue #1660."""-from src.tools.report_audit_tool import extract_data_points+import json++import pytest++from src.tools.report_audit_tool import ReportAuditTool, extract_data_pointsdef _by_label(points, label_part):@@ -80,3 +84,107 @@ def test_kv_line_positive_control_unchanged():assert len(hits) == 1assert hits[0]["reported_value"] == 100.5assert hits[0]["unit"] == "亿元"+++ "cell,unit",+ [+ ("(25.3亿)", "亿"),+ ("(25.3%)", "%"),+ ("$(25.3)M", "M"),+ ("($25.3)M", "M"),+ ("($25.3M)", "M"),+ ("( 25.3 )亿元", "亿元"),+ ("( 25.3 亿元 )", "亿元"),+ ("($25.3)", ""),+ ],+)[email protected]("table", [False, True])+def test_accounting_variants_keep_the_sign_and_unit(cell, unit, table):+ report = (+ f"| 净利润 | FY2025 |\n|---|---|\n| 归母净利润 | {cell} |"+ if table+ else f"净利润:{cell}"+ )+ points = extract_data_points(report)+ assert len(points) == 1+ assert points[0]["reported_value"] == -25.3+ assert points[0]["unit"] == unit+++ "cell",+ [+ "(25.3)亿",+ "(25.3)亿",+ "(25.3亿",+ "25.3)亿",+ "((25.3))亿",+ "(25.3亿)M",+ ],+)[email protected]("table", [False, True])+def test_malformed_accounting_is_not_rescued_as_a_positive(cell, table):+ report = (+ f"| 指标 | FY2025 |\n|---|---|\n| 净利润 | {cell} |"+ if table+ else f"净利润:{cell}"+ )+ assert extract_data_points(report) == []+++ "text",+ [+ "规划:(2024) May",+ "规划:(2024) Million",+ "规划:(2024) Times",+ "估值:(25.3)xylophone",+ ],+)+def test_latin_word_is_not_an_accounting_unit(text):+ assert extract_data_points(text) == []++[email protected]("number", ["1000000000000001", "9" * 310])[email protected]("table", [False, True])+def test_accounting_magnitude_guard_and_strict_json(number, table):+ report = (+ f"| 指标 | FY2025 |\n|---|---|\n| 净利润 | ({number})亿 |"+ if table+ else f"净利润:({number})亿"+ )+ assert extract_data_points(report) == []+ result = json.loads(+ ReportAuditTool().execute(command="extract", report_text=report)+ )+ assert result["status"] == "ok"+ assert result["total_extracted"] == 0++[email protected]("wrapped", [False, True])+def test_magnitude_boundary_keeps_the_existing_table_and_prose_conventions(wrapped):+ value = "1000000000000000"+ if wrapped:+ value = f"({value})"+ assert (+ extract_data_points(f"| 指标 | FY2025 |\n|---|---|\n| 净利润 | {value}亿 |")+ == []+ )+ points = extract_data_points(f"净利润:{value}亿")+ assert points[0]["reported_value"] == (-1e15 if wrapped else 1e15)+++ "report,labels,values",+ [+ ("收入:100亿元,净利润:20亿元", ["收入", "净利润"], [100, 20]),+ ("Revenue: 100M; Profit: 20M", ["Revenue", "Profit"], [100, 20]),+ ("收入:100亿元 收入:100亿元", ["收入"], [100]),+ ("Revenue: 100M; Profit: ($20M)", ["Revenue", "Profit"], [100, -20]),+ ],+)+def test_multiple_prose_values_do_not_become_the_next_label(report, labels, values):+ points = extract_data_points(report)+ assert [point["label"] for point in points] == labels+ assert [point["reported_value"] for point in points] == values