"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(portfolio): close five more holes a parser fuzz found in the extraETF reader
cgycoreyfc3496463781
diff --git a/agent/src/portfolio/extraetf.py b/agent/src/portfolio/extraetf.pyindex cad2e3492..bfa06022a 100644--- a/agent/src/portfolio/extraetf.py+++ b/agent/src/portfolio/extraetf.py@@ -134,11 +134,16 @@ _TRANSACTIONS_COLUMNS: tuple[str, ...] = (ExportKind = Literal["holdings", "transactions"]-_ISIN_PATTERN = re.compile(r"^[A-Z]{2}[A-Z0-9]{9}[0-9]$")+#: Case-insensitive so an otherwise valid lower-cased ISIN is still read, and+#: ASCII-anchored with an exact twelve-character length so ``.upper()`` is only+#: ever applied to a value that already has ISIN shape. ``.upper()`` is neither+#: length- nor ASCII-preserving — it turns ``ß`` into ``SS`` — so using it as the+#: predicate invents twelve-character ISINs out of eleven-character inputs.+_ISIN_PATTERN = re.compile(r"^[A-Za-z]{2}[A-Za-z0-9]{9}[0-9]$")_WIRE_QUANTUM = Decimal("0.00000001")_CRYPTO_PAIR_PATTERN = re.compile(r"^[A-Z0-9]{2,12}_to_[A-Z0-9]{2,12}$", re.IGNORECASE)_CURRENCY_PATTERN = re.compile(r"^[A-Z]{3}$")-_DATE_PATTERN = re.compile(r"^(\d{2})\.(\d{2})\.(\d{4})$")+_DATE_PATTERN = re.compile(r"^([0-9]{2})\.([0-9]{2})\.([0-9]{4})$")_NUMERAL_PATTERN = re.compile(r"^[0-9.,]+$")#: ``Typ`` is an instrument class, not a row shape: a class this reader does not@@ -281,6 +286,8 @@ def parse_export(raise ValueError("as_of_source cannot claim where an observation time came from when there is no observation time")+ if as_of_source not in ("file_mtime", "unavailable"):+ raise ValueError(f"as_of_source must be 'file_mtime' or 'unavailable', not {as_of_source!r}")text = _decode(data)kind, header, rows = _read_rows(text)if kind == "holdings":@@ -344,9 +351,9 @@ def _read_rows(for cells in reader:number += 1_refuse_multiline_record(cells, number)- if not any(cell.strip() for cell in cells):+ if _skip_blank_row(cells, number):continue- header = tuple(cell.strip().lstrip("\ufeff") for cell in cells)+ header = tuple(cell.replace("\ufeff", "").strip() for cell in cells)breakif header is None:raise ExtraEtfFormatError("export is empty")@@ -356,7 +363,7 @@ def _read_rows(for cells in reader:number += 1_refuse_multiline_record(cells, number)- if not any(cell.strip() for cell in cells):+ if _skip_blank_row(cells, number):continueif len(cells) != len(header):raise ExtraEtfFormatError(@@ -366,13 +373,41 @@ def _read_rows()rows.append((number, [cell.strip() for cell in cells]))except csv.Error as exc:- # csv raises its own errors for an over-long field or a stray quote. A- # caller catches the documented error type, so it is translated rather- # than allowed to escape as a bare csv error.+ # csv raises its own errors for an over-long field, a bare carriage return+ # or a stray quote. A caller catches the documented error type, so it is+ # translated rather than allowed to escape as a bare csv error.raise ExtraEtfFormatError(f"export is not readable as CSV: {exc}") from excreturn kind, header, rows+def _skip_blank_row(cells: list[str], number: int) -> bool:+ """Return whether a row is blank enough to skip, refusing an odd blank one.++ A genuinely empty line is how every file ends. A line of nothing but+ separators is not: it is a record this reader cannot align, and dropping it+ while claiming to refuse anything unalignable would be the silent skip the+ rest of this module exists to avoid.++ Args:+ cells: The record's fields.+ number: The record's position in the file, for error messages.++ Returns:+ ``True`` when the row carries no data and should be skipped.++ Raises:+ ExtraEtfFormatError: If the row is blank but wider than one field.+ """+ if any(cell.strip() for cell in cells):+ return False+ if len(cells) <= 1:+ return True+ raise ExtraEtfFormatError(+ f"row {number}: a blank row of {len(cells)} fields is not a layout this export "+ f"declares, so it is refused rather than dropped silently"+ )++def _refuse_multiline_record(cells: list[str], number: int) -> None:"""Refuse a csv record whose fields span more than one physical line.@@ -707,8 +742,8 @@ def _describe_identifier(raw: str) -> tuple[str, str, bool | None]:identifier = raw.strip()if not identifier:return "", "unknown", None- canonical = identifier.upper()- if _ISIN_PATTERN.fullmatch(canonical):+ if _ISIN_PATTERN.fullmatch(identifier):+ canonical = identifier.upper()return canonical, "isin", _isin_checksum_ok(canonical)if _CRYPTO_PAIR_PATTERN.fullmatch(identifier):return identifier, "crypto_pair", Nonediff --git a/agent/tests/test_extraetf_reader.py b/agent/tests/test_extraetf_reader.pyindex 591db050e..0f10c0251 100644--- a/agent/tests/test_extraetf_reader.py+++ b/agent/tests/test_extraetf_reader.py@@ -510,6 +510,83 @@ def test_control_characters_in_text_fields_are_refused():parse_export(_holdings_export(_holding(portfolio="Mein\x1fDepot")))+ "identifier",+ [+ # .upper() is neither length- nor ASCII-preserving: each of these maps to a+ # twelve-character upper-cased string matching the ISIN shape, and one of+ # them passes the check digit too. None of them is an ISIN.+ "a\u00df000000001",+ "\u0131\u01310000000001",+ "\ufb01n000000001",+ ],+)+def test_case_mapping_cannot_fabricate_an_isin(identifier):+ """A shape predicate must not be run on a case-folded value.++ Each input is eleven characters that upper-case to a twelve-character string+ matching the ISIN shape, and ``aß000000001`` even matches the check digit. So+ the guard is to refuse them as unattributable holdings, not to read them as+ ISINs, and the movements path shows they stay raw symbols rather than being+ rewritten.+ """+ with pytest.raises(ExtraEtfFormatError, match="neither an ISIN nor"):+ parse_export(_holdings_export(_holding(isin=identifier)))++ export = parse_export(_transactions_export(_movement(isin=identifier, instrument_type="Fremdwährung")))+ (movement,) = export.require_movements()+ assert movement["instrument_id_kind"] == "raw_symbol"+ assert movement["instrument_id"] == identifier+++def test_a_lowercased_isin_is_still_read_as_an_isin():+ """An ISIN is case-insensitive, so a lower-cased one is canonicalised."""+ export = parse_export(_holdings_export(_holding(isin="us0378331005")))++ (position,) = export.require_positions()+ assert position["instrument_id"] == "US0378331005"+ assert position["instrument_id_kind"] == "isin"+ assert position["instrument_id_checksum_ok"] is True+++ "datum",+ [+ "\uff10\uff11.\uff10\uff19.\uff12\uff10\uff12\uff16",+ "\u0660\u0661.\u0660\u0669.\u0662\u0660\u0662\u0666",+ ],+)+def test_non_ascii_digits_are_refused_in_dates_as_they_are_in_numbers(datum):+ """Unicode digits are accepted by \\d; numbers here are ASCII only."""+ with pytest.raises(ExtraEtfFormatError, match="DD.MM.YYYY"):+ parse_export(_transactions_export(_movement(datum=datum)))+++def test_a_blank_row_of_separators_is_refused_not_dropped():+ """An unalignable blank record must not be skipped silently."""+ with pytest.raises(ExtraEtfFormatError, match="blank row of 3 fields"):+ parse_export(_holdings_export(_holding()) + ";;\n")++ # A genuinely empty line is still just the end of a file.+ export = parse_export(_holdings_export(_holding()) + "\n\n \n")+ assert len(export.require_positions()) == 1+++def test_as_of_source_must_be_one_of_the_two_documented_origins():+ with pytest.raises(ValueError, match="as_of_source must be"):+ parse_export(+ _holdings_export(_holding()),+ as_of="2026-01-01T00:00:00+00:00",+ as_of_source="nonsense",+ )+++def test_a_bom_followed_by_whitespace_still_reads_the_header():+ export = parse_export("\ufeff " + _holdings_export(_holding()))++ assert len(export.require_positions()) == 1++def test_require_movements_refuses_a_holdings_export():export = parse_export(_holdings_export(_holding()))