"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(portfolio): close five holes an adversarial review found in the extraETF reader
cgycorey465df73f0758
diff --git a/agent/src/portfolio/extraetf.py b/agent/src/portfolio/extraetf.pyindex 88ad56490..cad2e3492 100644--- a/agent/src/portfolio/extraetf.py+++ b/agent/src/portfolio/extraetf.py@@ -15,23 +15,39 @@ Three properties are deliberate and load-bearing.**A transactions export can never be read as a portfolio.** Its rows aremovements — ``Kauf``/``Verkauf``/``Dividende``/``Einbuchung``/``Ausbuchung`` —not holdings. An allocation computed from trades looks perfectly plausible and-is wrong, so the two formats are told apart by their header and-:meth:`ExtraEtfExport.require_positions` refuses anything that is not a-holdings export. Movements carry an explicit ``movement_kind`` so a dividend or+is wrong, so the two formats are told apart by their header and positions are+reachable only through :meth:`ExtraEtfExport.require_positions`, which refuses+any other export. Movements carry an explicit ``movement_kind`` so a dividend ora transfer is never mistaken for a trade.**A holdings export carries no date.** The format has no snapshot column, sofreshness can only come from the file's own modification time, and the export-says so through ``as_of_source``. This reader never claims an observation time-it did not read.+says so through ``as_of_source``. No position carries an observation time: a+row's ``source_mtime`` is the file's modification time, kept under a name no+connector ever fills with a real fetch time, and ``updated_at`` is ``None``+rather than a copy of it. Copying or syncing an export rewrites that mtime, so+``source_mtime`` reports when the *file* last changed and nothing more.**Validation fails closed.** A row this reader does not recognise raises:class:`ExtraEtfFormatError` instead of being skipped: an import computed from90% of a portfolio reads as entirely plausible, whereas a refused import is-merely annoying. Numbers are parsed as German — ``1.386,608`` is 1386.608 — and-a value that cannot be read unambiguously is refused rather than guessed.-``1,234.56`` is US-formatted; reading it as German would be wrong by three-orders of magnitude, so it is refused instead.+merely annoying. That covers ragged rows, records that span more than one+physical line, unknown or missing columns, unreadable or contradictory numbers,+empty required fields, and text fields carrying control characters.++The number rule is precise, because it is the one that can change a position's+size by orders of magnitude. A comma is the decimal separator and a period may+only be a thousands separator, so ``1.386,608`` is 1386.608 and ``12,3456`` is+12.3456. A value whose separators are US-ordered (``1,234.56``) is refused,+because reading it as German would be wrong by a thousandfold. A period grouping+that is not a plain thousands separator (``1.23``, ``1234.56``) is refused too,+because it is neither a valid German number nor safely a US one. What is *not*+refused is a period-grouped value that is valid German — ``1.900`` is 1900 — and+that reading is a convention of the format, not a deduction: ``1.900`` could be+1.9 in a US-locale file, and no amount of parsing can tell the two apart.+extraETF writes German, so German wins, and a file that had been round-tripped+through a US-locale spreadsheet is caught by the *other* values in it rather+than by this one.Rows are read by column name, so a reordered export cannot mis-align a valueinto the wrong column. Rows are **not** merged or de-duplicated: two rows for@@ -39,6 +55,30 @@ the same instrument in one portfolio are returned as two positions, becausesumming them silently and dropping one silently are both wrong, and which onethe user meant is not this module's call.+The emitted position uses the portfolio package's own field names so a container+can consume it, and carries the export's remaining columns alongside them. It+does **not** route the row through+:func:`src.portfolio.normalization.normalize_position`, which is the obvious way+to guarantee one wire shape, because that function stamps ``updated_at`` with+the current time — an observation time this reader never made — and defaults an+unknown instrument class to ``"stock"``. Both are fabrications a file import+must not make, so the mapping is done here and the divergences are the three+shown above: ``quote_symbol``'s None, ``asset_type``'s None, and ``updated_at``+against ``source_mtime``.++Values are carried as the export reports them rather than repaired: a zero or+negative quantity, a zero FX rate, and two different portfolio names under one+portfolio ID all pass through, because a reader that silently corrects its input+is a reader whose output no longer describes the file. What is refused is input+that cannot be read at all.++Two limits are inherent to the format and belong in the caller's hands. A file+truncated exactly at a record boundary is indistinguishable from a short export,+because neither format carries a row count or a footer; a caller that knows how+many positions to expect is the only thing that can catch that. An export with a+header and no rows is read as a valid empty portfolio, because an empty+portfolio and an unreadable file are different states.+The module writes nothing, holds no credentials, and touches no network. Itonly reads a local file the user exported themselves, and it has no path to anyorder surface.@@ -95,6 +135,7 @@ _TRANSACTIONS_COLUMNS: tuple[str, ...] = (ExportKind = Literal["holdings", "transactions"]_ISIN_PATTERN = re.compile(r"^[A-Z]{2}[A-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})$")@@ -126,10 +167,14 @@ class ExtraEtfFormatError(ValueError):class ExtraEtfExport:"""One parsed export, with its provenance attached.+ The payloads are deliberately private. An export cannot hold both positions+ and movements, and reaching for the wrong one used to yield an empty tuple+ rather than an error — which turns "this is a transactions export" into "this+ portfolio is empty", the exact plausible-and-wrong outcome this module exists+ to prevent. Both accessors refuse a mismatched export instead.+Attributes:kind: Which of the two extraETF formats this file is.- positions: Holdings rows. Always empty for a transactions export.- movements: Transactions rows. Always empty for a holdings export.as_of: ISO-8601 observation time, or ``None`` when it could not be read.as_of_source: Where ``as_of`` came from — ``"file_mtime"`` for a fileread from disk, ``"unavailable"`` for bare text with no timestamp.@@ -140,11 +185,11 @@ class ExtraEtfExport:"""kind: ExportKind- positions: tuple[dict[str, Any], ...]- movements: tuple[dict[str, Any], ...]as_of: str | Noneas_of_source: Literal["file_mtime", "unavailable"]source_path: Path | None+ _positions: tuple[dict[str, Any], ...] = ()+ _movements: tuple[dict[str, Any], ...] = ()def require_positions(self) -> tuple[dict[str, Any], ...]:"""Return holdings positions, refusing any other export outright.@@ -161,7 +206,21 @@ class ExtraEtfExport:"this is a transactions export and holds movements, not positions; ""importing it as a portfolio would build an allocation out of trades")- return self.positions+ return self._positions++ def require_movements(self) -> tuple[dict[str, Any], ...]:+ """Return movements, refusing a holdings export outright.++ Returns:+ The parsed movements, possibly empty for an account with no history.++ Raises:+ ExtraEtfFormatError: If this export is a holdings export, whose rows+ are positions rather than movements.+ """+ if self.kind != "transactions":+ raise ExtraEtfFormatError("this is a holdings export and holds positions, not movements")+ return self._movementsdef read_export(path: str | Path) -> ExtraEtfExport:@@ -191,9 +250,7 @@ def read_export(path: str | Path) -> ExtraEtfExport:except OSError as exc:raise ExtraEtfFormatError(f"cannot read export {resolved}: {exc}") from excas_of = datetime.fromtimestamp(modified, tz=timezone.utc).isoformat()- return parse_export(- data, source_path=resolved, as_of=as_of, as_of_source="file_mtime"- )+ return parse_export(data, source_path=resolved, as_of=as_of, as_of_source="file_mtime")def parse_export(@@ -222,28 +279,23 @@ def parse_export("""if as_of is None and as_of_source != "unavailable":raise ValueError(- "as_of_source cannot claim where an observation time came from when "- "there is no observation time"+ "as_of_source cannot claim where an observation time came from when there is no observation time")text = _decode(data)kind, header, rows = _read_rows(text)if kind == "holdings":- positions = tuple(- _parse_holding(header, cells, number, as_of=as_of) for number, cells in rows- )+ positions = tuple(_parse_holding(header, cells, number, as_of=as_of) for number, cells in rows)movements: tuple[dict[str, Any], ...] = ()else:positions = ()- movements = tuple(- _parse_movement(header, cells, number) for number, cells in rows- )+ movements = tuple(_parse_movement(header, cells, number) for number, cells in rows)return ExtraEtfExport(kind=kind,- positions=positions,- movements=movements,as_of=as_of,as_of_source=as_of_source,source_path=Path(source_path) if source_path is not None else None,+ _positions=positions,+ _movements=movements,)@@ -288,31 +340,64 @@ def _read_rows(reader = csv.reader(io.StringIO(text), delimiter=";")header: tuple[str, ...] | None = Nonenumber = 0- for cells in reader:- number += 1- if not any(cell.strip() for cell in cells):- continue- header = tuple(cell.strip().lstrip("\ufeff") for cell in cells)- break- if header is None:- raise ExtraEtfFormatError("export is empty")- kind = _detect_kind(header)-- rows: list[tuple[int, list[str]]] = []- for cells in reader:- number += 1- if not any(cell.strip() for cell in cells):- continue- if len(cells) != len(header):- raise ExtraEtfFormatError(- f"row {number}: expected {len(header)} fields to match the header, "- f"found {len(cells)}; a row that cannot be aligned is refused rather "- f"than skipped"- )- rows.append((number, [cell.strip() for cell in cells]))+ try:+ for cells in reader:+ number += 1+ _refuse_multiline_record(cells, number)+ if not any(cell.strip() for cell in cells):+ continue+ header = tuple(cell.strip().lstrip("\ufeff") for cell in cells)+ break+ if header is None:+ raise ExtraEtfFormatError("export is empty")+ kind = _detect_kind(header)++ rows: list[tuple[int, list[str]]] = []+ for cells in reader:+ number += 1+ _refuse_multiline_record(cells, number)+ if not any(cell.strip() for cell in cells):+ continue+ if len(cells) != len(header):+ raise ExtraEtfFormatError(+ f"row {number}: expected {len(header)} fields to match the header, "+ f"found {len(cells)}; a row that cannot be aligned is refused rather "+ f"than skipped"+ )+ 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.+ raise ExtraEtfFormatError(f"export is not readable as CSV: {exc}") from excreturn kind, header, rows+def _refuse_multiline_record(cells: list[str], number: int) -> None:+ """Refuse a csv record whose fields span more than one physical line.++ extraETF writes one record per line and never quotes an embedded newline. A+ stray quote in one field therefore makes csv fold the *following* lines into+ that record: the record still has the right field count, so the arity check+ passes, and two positions silently become one with another instrument's+ quantity and value grafted onto it. That is a plausible-looking wrong+ portfolio, so the fold is refused outright rather than aligned.++ Args:+ cells: The record's fields.+ number: The record's position in the file, for error messages.++ Raises:+ ExtraEtfFormatError: If any field contains a line break.+ """+ if any("\n" in cell or "\r" in cell for cell in cells):+ raise ExtraEtfFormatError(+ f"row {number}: a field spans more than one line, so this record and "+ f"the line after it were folded together; a stray quote is the usual "+ f"cause and the positions it swallowed cannot be recovered here"+ )++def _detect_kind(header: tuple[str, ...]) -> ExportKind:"""Identify which extraETF format a header belongs to.@@ -328,9 +413,7 @@ def _detect_kind(header: tuple[str, ...]) -> ExportKind:columns = set(header)if len(header) == len(_HOLDINGS_COLUMNS) and columns == set(_HOLDINGS_COLUMNS):return "holdings"- if len(header) == len(_TRANSACTIONS_COLUMNS) and columns == set(- _TRANSACTIONS_COLUMNS- ):+ if len(header) == len(_TRANSACTIONS_COLUMNS) and columns == set(_TRANSACTIONS_COLUMNS):return "transactions"transactions_like = "Transaktion" in columnsexpected = _TRANSACTIONS_COLUMNS if transactions_like else _HOLDINGS_COLUMNS@@ -343,9 +426,7 @@ def _detect_kind(header: tuple[str, ...]) -> ExportKind:)-def _parse_holding(- header: tuple[str, ...], cells: list[str], number: int, *, as_of: str | None-) -> dict[str, Any]:+def _parse_holding(header: tuple[str, ...], cells: list[str], number: int, *, as_of: str | None) -> dict[str, Any]:"""Convert one holdings row into a position.Args:@@ -372,10 +453,7 @@ def _parse_holding(instrument_type = _required(row, "Typ", number)currency = _required(row, "Währung", number).upper()if not _CURRENCY_PATTERN.fullmatch(currency):- raise ExtraEtfFormatError(- f"row {number}: Währung is not a three-letter currency code: "- f"{row['Währung']!r}"- )+ raise ExtraEtfFormatError(f"row {number}: Währung is not a three-letter currency code: {row['Währung']!r}")portfolio_id = _required(row, "Portfolio ID", number)quantity = _parse_decimal(row["Anzahl"], field="Anzahl", row_number=number)if quantity is None:@@ -384,41 +462,43 @@ def _parse_holding("broker": BROKER,"source": "extraetf_export","symbol": identifier,- "quote_symbol": identifier,+ # The export names an instrument, never a quoting instrument: an ISIN in+ # a quote-symbol field is a request for a quote on a security identifier,+ # so this stays None for the container to resolve. ``market`` is None for+ # the same reason — extraETF rows carry no venue.+ "quote_symbol": None,"instrument_id": identifier,"instrument_id_kind": identifier_kind,"instrument_id_checksum_ok": checksum_ok,"name": name,"instrument_type": instrument_type,+ # The export's instrument class mapped into the repo's vocabulary, and+ # None when it is a class this reader does not know. Deliberately not+ # defaulted to "stock": a guessed asset type is a fabricated fact about+ # the instrument, where an unknown class is honestly unknown."asset_type": _ASSET_TYPE_BY_EXPORT_TYPE.get(instrument_type.strip().lower()),"market": None,"currency": currency,"price_currency": currency,"quantity": _number(quantity),- "cost_price": _optional_number(- row["Kaufpreis"], field="Kaufpreis", row_number=number- ),- "market_price": _optional_number(- row["Aktueller Kurs"], field="Aktueller Kurs", row_number=number- ),- "source_market_value": _optional_number(- row["Aktueller Wert"], field="Aktueller Wert", row_number=number- ),- "fx_rate": _optional_number(- row["Wechselkurs"], field="Wechselkurs", row_number=number- ),- "region": row["Region"] or None,- "country": row["Land"] or None,- "sector": row["Sektor"] or None,+ "cost_price": _optional_number(row["Kaufpreis"], field="Kaufpreis", row_number=number),+ "market_price": _optional_number(row["Aktueller Kurs"], field="Aktueller Kurs", row_number=number),+ "source_market_value": _optional_number(row["Aktueller Wert"], field="Aktueller Wert", row_number=number),+ "fx_rate": _optional_number(row["Wechselkurs"], field="Wechselkurs", row_number=number),+ "region": _optional_text(row, "Region", number),+ "country": _optional_text(row, "Land", number),+ "sector": _optional_text(row, "Sektor", number),"portfolio_id": portfolio_id,- "portfolio_name": row["Portfolioname"] or None,- "updated_at": as_of,+ "portfolio_name": _optional_text(row, "Portfolioname", number),+ # No observation time exists in this format, so the repo's "when was this+ # observed" field stays empty rather than borrowing the file's mtime,+ # which any copy, sync or restore rewrites.+ "updated_at": None,+ "source_mtime": as_of,}-def _parse_movement(- header: tuple[str, ...], cells: list[str], number: int-) -> dict[str, Any]:+def _parse_movement(header: tuple[str, ...], cells: list[str], number: int) -> dict[str, Any]:"""Convert one transactions row into a movement.Args:@@ -438,22 +518,15 @@ def _parse_movement(transaction_date = _required(row, "Datum", number)match = _DATE_PATTERN.fullmatch(transaction_date)if match is None:- raise ExtraEtfFormatError(- f"row {number}: Datum is not a DD.MM.YYYY date: {transaction_date!r}"- )+ raise ExtraEtfFormatError(f"row {number}: Datum is not a DD.MM.YYYY date: {transaction_date!r}")day, month, year = (int(part) for part in match.groups())try:booked_on = datetime(year, month, day).date().isoformat()except ValueError as exc:- raise ExtraEtfFormatError(- f"row {number}: Datum is not a real date: {transaction_date!r}"- ) from exc+ raise ExtraEtfFormatError(f"row {number}: Datum is not a real date: {transaction_date!r}") from exccurrency = _required(row, "Währung", number).upper()if not _CURRENCY_PATTERN.fullmatch(currency):- raise ExtraEtfFormatError(- f"row {number}: Währung is not a three-letter currency code: "- f"{row['Währung']!r}"- )+ raise ExtraEtfFormatError(f"row {number}: Währung is not a three-letter currency code: {row['Währung']!r}")identifier, identifier_kind, checksum_ok = _describe_identifier(row["ISIN"])quantity = _parse_decimal(row["Anzahl"], field="Anzahl", row_number=number)if quantity is None:@@ -474,19 +547,37 @@ def _parse_movement("fees": _optional_number(row["Gebühren"], field="Gebühren", row_number=number),"taxes": _optional_number(row["Steuern"], field="Steuern", row_number=number),"currency": currency,- "fx_rate": _optional_number(- row["Wechselkurs"], field="Wechselkurs", row_number=number- ),- "accrued_interest": _optional_number(- row["Stückzinsen"], field="Stückzinsen", row_number=number- ),+ "fx_rate": _optional_number(row["Wechselkurs"], field="Wechselkurs", row_number=number),+ "accrued_interest": _optional_number(row["Stückzinsen"], field="Stückzinsen", row_number=number),"portfolio_id": _required(row, "Portfolio ID", number),- "portfolio_name": row["Portfolioname"] or None,+ "portfolio_name": _optional_text(row, "Portfolioname", number),}+def _optional_text(row: dict[str, str], column: str, number: int) -> str | None:+ """Return an optional text column, refusing corruption.++ Args:+ row: The aligned row.+ column: The column to read.+ number: The row's line number, for error messages.++ Returns:+ The value, or ``None`` when the field is blank.++ Raises:+ ExtraEtfFormatError: If the value carries control characters.+ """+ value = row[column]+ if not value:+ return None+ if any(ord(character) < 32 for character in value):+ raise ExtraEtfFormatError(f"row {number}: {column} carries control characters")+ return value++def _required(row: dict[str, str], column: str, number: int) -> str:- """Return a column's value, refusing an empty one.+ """Return a column's value, refusing an empty or corrupt one.Args:row: The aligned row.@@ -497,11 +588,17 @@ def _required(row: dict[str, str], column: str, number: int) -> str:The non-empty value.Raises:- ExtraEtfFormatError: If the value is empty.+ ExtraEtfFormatError: If the value is empty or carries control+ characters. Control characters are refused for the same reason+ :func:`src.portfolio.config.parse_settings` refuses them in a source+ label: they are corruption, and text carrying them does not+ round-trip."""value = row[column]if not value:raise ExtraEtfFormatError(f"row {number}: {column} is empty")+ if any(ord(character) < 32 for character in value):+ raise ExtraEtfFormatError(f"row {number}: {column} carries control characters")return value@@ -567,16 +664,23 @@ def _parse_decimal(raw: str, *, field: str, row_number: int) -> Decimal | None:or (comma and not fraction.isdigit())):raise ExtraEtfFormatError(- f"row {row_number}: {field} has ambiguous separators: {raw!r}; expected "- f"German formatting such as 1.386,608"+ f"row {row_number}: {field} has ambiguous separators: {raw!r}; expected German formatting such as 1.386,608")digits = "".join(groups) + (f".{fraction}" if comma else "")try:- return Decimal(f"{sign}{digits}")+ value = Decimal(f"{sign}{digits}")except InvalidOperation as exc: # pragma: no cover - guarded by the checks above+ raise ExtraEtfFormatError(f"row {row_number}: {field} is not a number: {raw!r}") from exc+ try:+ # Probe the wire format's precision here, while the row is still known.+ # Handing an unrepresentable magnitude to the formatter would surface as+ # a bare decimal.InvalidOperation, which is not the documented error.+ value.quantize(_WIRE_QUANTUM)+ except InvalidOperation as exc:raise ExtraEtfFormatError(- f"row {row_number}: {field} is not a number: {raw!r}"+ f"row {row_number}: {field} carries more precision than a position can represent: {raw!r}") from exc+ return valuedef _describe_identifier(raw: str) -> tuple[str, str, bool | None]:@@ -620,10 +724,7 @@ def _isin_checksum_ok(value: str) -> bool:Returns:``True`` when the Luhn-style check digit is valid."""- digits = "".join(- str(ord(character) - 55) if character.isalpha() else character- for character in value- )+ digits = "".join(str(ord(character) - 55) if character.isalpha() else character for character in value)total = 0for index, character in enumerate(reversed(digits)):digit = int(character)@@ -639,10 +740,11 @@ def _number(value: Decimal) -> float:"""Return a wire-ready float, quantized as the connector path does.Args:- value: The parsed value.+ value: A value already probed by :func:`_parse_decimal`, which applies+ this same quantization so it cannot raise here.Returns:The value as a float, quantized to eight decimal places to match:func:`src.portfolio.normalization.normalize_position`."""- return float(value.quantize(Decimal("0.00000001")))+ return float(value.quantize(_WIRE_QUANTUM))diff --git a/agent/tests/test_extraetf_reader.py b/agent/tests/test_extraetf_reader.pyindex 928962846..591db050e 100644--- a/agent/tests/test_extraetf_reader.py+++ b/agent/tests/test_extraetf_reader.py@@ -208,9 +208,7 @@ def test_unreadable_number_is_refused(unreadable):def test_blank_optional_fields_are_none_rather_than_zero():- export = parse_export(- _holdings_export(_holding(kaufpreis="", kurs="", wert="", wechselkurs=""))- )+ export = parse_export(_holdings_export(_holding(kaufpreis="", kurs="", wert="", wechselkurs="")))(position,) = export.require_positions()assert position["cost_price"] is None@@ -237,10 +235,12 @@ def test_transactions_export_yields_movements_and_never_positions():)assert export.kind == "transactions"- assert export.positions == ()- assert export.movements[0]["movement"] == "Kauf"- assert export.movements[0]["movement_kind"] == "buy"- assert [m["movement_kind"] for m in export.movements] == [+ with pytest.raises(ExtraEtfFormatError, match="movements, not positions"):+ export.require_positions()+ movements = export.require_movements()+ assert movements[0]["movement"] == "Kauf"+ assert movements[0]["movement_kind"] == "buy"+ assert [m["movement_kind"] for m in movements] == ["buy","sell","dividend",@@ -248,12 +248,12 @@ def test_transactions_export_yields_movements_and_never_positions():"transfer_out",]# A dividend row carries a quantity of its own; it must never become a holding.- assert export.movements[2]["quantity"] == pytest.approx(0.5)- assert export.movements[2]["taxes"] == pytest.approx(0.45)- assert all("asset_type" not in movement for movement in export.movements)- assert all("accrued_interest" in movement for movement in export.movements)- assert export.movements[0]["date"] == "2026-09-01"- assert export.movements[0]["accrued_interest"] == pytest.approx(0.0)+ assert movements[2]["quantity"] == pytest.approx(0.5)+ assert movements[2]["taxes"] == pytest.approx(0.45)+ assert all("asset_type" not in movement for movement in movements)+ assert all("accrued_interest" in movement for movement in movements)+ assert movements[0]["date"] == "2026-09-01"+ assert movements[0]["accrued_interest"] == pytest.approx(0.0)def test_a_transactions_export_refuses_to_pose_as_a_portfolio():@@ -266,9 +266,11 @@ def test_a_transactions_export_refuses_to_pose_as_a_portfolio():def test_unknown_transaction_type_is_carried_through_not_invented():export = parse_export(_transactions_export(_movement(transaktion="Steuer")))- assert export.positions == ()- assert export.movements[0]["movement"] == "Steuer"- assert export.movements[0]["movement_kind"] is None+ with pytest.raises(ExtraEtfFormatError, match="movements, not positions"):+ export.require_positions()+ (movement,) = export.require_movements()+ assert movement["movement"] == "Steuer"+ assert movement["movement_kind"] is Nonedef test_invalid_transaction_date_is_refused():@@ -310,9 +312,7 @@ def test_unattributable_holding_identifier_is_refused(identifier):def test_invalid_isin_check_digit_is_reported_not_enforced():- export = parse_export(- _holdings_export(_holding(isin=VALID_ISIN), _holding(isin=PLACEHOLDER_ISIN))- )+ export = parse_export(_holdings_export(_holding(isin=VALID_ISIN), _holding(isin=PLACEHOLDER_ISIN)))valid, placeholder = export.require_positions()assert valid["instrument_id_checksum_ok"] is True@@ -348,9 +348,7 @@ def test_unknown_column_makes_the_export_unrecognisable():header = ";".join([*HOLDINGS_COLUMNS, "Neue Spalte"])body = ";".join([*(row[column] for column in HOLDINGS_COLUMNS), "x"])- with pytest.raises(- ExtraEtfFormatError, match="unexpected columns: \\['Neue Spalte'\\]"- ):+ with pytest.raises(ExtraEtfFormatError, match="unexpected columns: \\['Neue Spalte'\\]"):parse_export(f"{header}\n{body}\n")@@ -387,9 +385,7 @@ def test_reordered_columns_do_not_mis_align_values():def test_duplicate_rows_are_preserved_rather_than_merged():- export = parse_export(- _holdings_export(_holding(anzahl="1,0000"), _holding(anzahl="2,0000"))- )+ export = parse_export(_holdings_export(_holding(anzahl="1,0000"), _holding(anzahl="2,0000")))assert [position["quantity"] for position in export.require_positions()] == [pytest.approx(1.0),@@ -423,7 +419,11 @@ def test_as_of_comes_from_the_file_mtime_and_is_labelled(tmp_path):assert export.as_of_source == "file_mtime"assert export.as_of == expectedassert export.source_path == path- assert export.require_positions()[0]["updated_at"] == expected+ (position,) = export.require_positions()+ # The file's mtime is reported as the file's mtime, and never laundered into+ # the field every connector fills with a real observation time.+ assert position["source_mtime"] == expected+ assert position["updated_at"] is Nonedef test_bare_text_reports_no_observation_time():@@ -431,7 +431,9 @@ def test_bare_text_reports_no_observation_time():assert export.as_of is Noneassert export.as_of_source == "unavailable"- assert export.require_positions()[0]["updated_at"] is None+ (position,) = export.require_positions()+ assert position["updated_at"] is None+ assert position["source_mtime"] is Nonedef test_an_absent_as_of_cannot_claim_an_origin():@@ -456,6 +458,132 @@ def test_missing_file_is_refused(tmp_path):read_export(tmp_path / "absent.csv")+def test_a_record_folded_across_lines_is_refused_rather_than_aligned():+ """A stray quote makes csv fold the next line in; the fold must not land.++ The folded record still has the right field count, so an arity check alone+ passes: one instrument's quantity and value get grafted onto another's+ identity while a whole position disappears. That is a plausible-looking+ portfolio, so the fold is refused. Verified against the unfixed reader,+ which returned 3 positions totalling 3000.0 for this 4-position file.+ """+ document = (+ ";".join(HOLDINGS_COLUMNS) + "\n"+ "US0378331005;Apple Inc.;Aktie;10,0000;150,00;190,00;1.900,00;EUR;1,00;Nordamerika;USA;Technologie;Mein Depot;1000001\n"+ 'DE0007100000;"Zwei;ETF;5,0000;100,00;110,00;550,00;EUR;1,00;Welt;;;Mein Depot;1000001\n'+ 'IE00B4L5Y983;Three";ETF;7,0000;100,00;110,00;770,00;EUR;1,00;Welt;;;Mein Depot;1000001\n'+ "FR0000131104;Four;ETF;3,0000;100,00;110,00;330,00;EUR;1,00;Welt;;;Mein Depot;1000001\n"+ )++ with pytest.raises(ExtraEtfFormatError, match="spans more than one line"):+ parse_export(document)+++def test_a_stray_quote_that_swallows_the_tail_is_refused():+ """An unbalanced quote in the last column absorbs every following line."""+ document = _holdings_export(_holding(), _holding(isin="DE0007100000"))+ document = document.replace("Example broker;1000001", 'Example broker;"1000001', 1)++ with pytest.raises(ExtraEtfFormatError, match="spans more than one line"):+ parse_export(document)+++def test_an_over_long_field_is_refused_with_the_documented_error():+ """csv raises its own error for an over-long field; callers must not see it."""+ row = ";".join(["US0378331005", "x" * 140_000, *list(_holding().values())[2:]])++ with pytest.raises(ExtraEtfFormatError, match="not readable as CSV"):+ parse_export(_export(HOLDINGS_COLUMNS, []) + row + "\n")+++def test_unrepresentable_precision_is_refused_not_raised_as_decimal_error():+ """A magnitude the wire format cannot carry is a format error, not a crash."""+ with pytest.raises(ExtraEtfFormatError, match="more precision than a position"):+ parse_export(_holdings_export(_holding(anzahl="1" + "0" * 30 + ",0")))+++def test_control_characters_in_text_fields_are_refused():+ with pytest.raises(ExtraEtfFormatError, match="control characters"):+ parse_export(_holdings_export(_holding(name="Apple\x00Inc")))++ with pytest.raises(ExtraEtfFormatError, match="control characters"):+ parse_export(_holdings_export(_holding(portfolio="Mein\x1fDepot")))+++def test_require_movements_refuses_a_holdings_export():+ export = parse_export(_holdings_export(_holding()))++ with pytest.raises(ExtraEtfFormatError, match="holds positions, not movements"):+ export.require_movements()+ assert len(export.require_positions()) == 1+++def test_the_crypto_transactions_shape_from_the_report_is_read():+ """The Bitpanda transactions export identifies crypto by bare symbol only.++ Ground truth from the anonymized samples: the same asset is ``BTC_to_EUR``+ in the holdings export and bare ``BTC`` with ``Typ=Fremdwährung`` in the+ transactions export. Resolving those onto one another is the container's+ job, so the reader reports the divergence rather than inventing a base+ asset: a movement keeps the export's own label and is flagged as an+ unresolved raw symbol.+ """+ document = _export(+ TRANSACTIONS_COLUMNS,+ [+ _movement(+ isin="BTC",+ name="Bitcoin",+ instrument_type="Fremdwährung",+ anzahl="0,001234",+ preis="60.000,00",+ portfolio="Example crypto wallet",+ portfolio_id="1000002",+ ),+ _movement(+ isin="ETH",+ name="Ethereum",+ instrument_type="Fremdwährung",+ transaktion="Einbuchung",+ anzahl="0,100000",+ preis="2.500,00",+ gebuehren="2,50",+ portfolio="Example crypto wallet",+ portfolio_id="1000002",+ ),+ ],+ )++ export = parse_export(document)++ first, second = export.require_movements()+ assert first["instrument_id"] == "BTC"+ assert first["instrument_id_kind"] == "raw_symbol"+ assert first["instrument_id_checksum_ok"] is None+ assert first["quantity"] == pytest.approx(0.001234)+ assert first["price"] == pytest.approx(60000.0)+ assert second["movement_kind"] == "transfer_in"+ assert second["fees"] == pytest.approx(2.5)+ with pytest.raises(ExtraEtfFormatError, match="movements, not positions"):+ export.require_positions()+++def test_a_period_grouped_value_is_read_as_german_by_convention():+ """``1.900`` is 1900, because the export is German and nothing says otherwise.++ This reading is a convention of the format rather than a deduction — the+ same bytes could be 1.9 in a US-locale file — so it is pinned here to keep+ the behaviour deliberate. A file round-tripped through a US locale is caught+ by its other values, which stop looking like German thousands.+ """+ export = parse_export(_holdings_export(_holding(kaufpreis="1.900", kurs="110.123", wert="1.900")))++ (position,) = export.require_positions()+ assert position["cost_price"] == pytest.approx(1900.0)+ assert position["market_price"] == pytest.approx(110123.0)+ assert position["source_market_value"] == pytest.approx(1900.0)++def test_reader_imports_only_the_standard_library():"""No network, no broker SDK, no order path can be reached from here."""import ast@@ -468,12 +596,7 @@ def test_reader_imports_only_the_standard_library():for node in ast.walk(ast.parse(source)):if isinstance(node, ast.Import):roots.update(alias.name.split(".")[0] for alias in node.names)- elif (- isinstance(node, ast.ImportFrom)- and node.level == 0- and node.module- and node.module != "__future__"- ):+ elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module and node.module != "__future__":roots.add(node.module.split(".")[0])assert roots == {