"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(qveris): one price family per response, no cross-family volume (#1527)
Haozhe Wuc59e0a068c64
diff --git a/agent/backtest/loaders/qveris_loader.py b/agent/backtest/loaders/qveris_loader.pyindex b83e51bf7..e32f45782 100644--- a/agent/backtest/loaders/qveris_loader.py+++ b/agent/backtest/loaders/qveris_loader.py@@ -590,8 +590,37 @@ def _interval_value(param: dict[str, Any], interval: str) -> str:return "daily" if interval.upper() == "1D" else interval+def _response_field_set(records: list[dict[str, Any]]) -> dict[str, tuple[str, ...]] | None:+ """Return the one alias table every usable record in a response supports.++ Choosing per record let one payload carry an unadjusted row and an+ adjusted-only row, and the series then mixed the two price levels (#1527).+ Records with no complete quartet are skipped as before; if the rest do not+ share a family the response yields no bars rather than a mixed series.+ """+ complete = [+ [table for table in (_FIELD_ALIASES, _ADJUSTED_FIELD_ALIASES) if _resolve_field_set_in(keys, table)]+ for keys in ({str(key).lower() for key in record} for record in records)+ ]+ complete = [tables for tables in complete if tables]+ for table in (_FIELD_ALIASES, _ADJUSTED_FIELD_ALIASES):+ if complete and all(table in tables for tables in complete):+ return table+ if complete:+ logger.warning("QVeris response mixes unadjusted and adjusted records; no bars built from it")+ return None+++def _resolve_field_set_in(keys: set[str], table: dict[str, tuple[str, ...]]) -> bool:+ return all(any(alias in keys for alias in table[field]) for field in _PRICE_QUARTET)++def _result_to_frame(result: Any, start_date: str, end_date: str) -> Optional[pd.DataFrame]:- rows = [_normalize_record(record) for record in _iter_ohlcv_records(result)]+ records = list(_iter_ohlcv_records(result))+ table = _response_field_set(records)+ if table is None:+ return None+ rows = [_normalize_record(record, table) for record in records]cleaned = [row for row in rows if row is not None]if not cleaned:return None@@ -693,7 +722,7 @@ def _resolve_field_set(keys: Iterable[str]) -> dict[str, tuple[str, ...]] | Noneadjusted fields."""for table in (_FIELD_ALIASES, _ADJUSTED_FIELD_ALIASES):- if all(any(alias in keys for alias in table[field]) for field in _PRICE_QUARTET):+ if _resolve_field_set_in(set(keys), table):return tablereturn None@@ -702,23 +731,19 @@ def _record_has_ohlc(record: dict[str, Any]) -> bool:return _resolve_field_set({str(key).lower() for key in record}) is not None-def _normalize_record(record: dict[str, Any]) -> dict[str, Any] | None:+def _normalize_record(record: dict[str, Any], table: dict[str, tuple[str, ...]]) -> dict[str, Any] | None:+ """Build one bar from ``record`` using the response's alias ``table``.++ An unadjusted bar never takes ``adj_volume``: split-adjusted volume is not+ on the scale of unadjusted prices, so a missing unadjusted volume stays NaN.+ """lowered = {str(key).lower(): value for key, value in record.items()}date = _first_value(lowered, _DATE_KEYS)if date is None:return None- table = _resolve_field_set(lowered)- if table is None:- return Nonerow = {"trade_date": date}for field in _OHLCV_COLUMNS:row[field] = _first_value(lowered, table[field])- if row["volume"] is None:- # Volume carries no adjustment claim, so it is the one column resolved- # across both families: the chosen table first (so which name wins is- # unchanged), the other only to fill the gap the choice would leave.- fallback = _ADJUSTED_FIELD_ALIASES if table is _FIELD_ALIASES else _FIELD_ALIASES- row["volume"] = _first_value(lowered, fallback["volume"])if any(row[field] is None for field in _PRICE_QUARTET):return Nonereturn rowdiff --git a/agent/tests/test_qveris_loader.py b/agent/tests/test_qveris_loader.pyindex 3e2c02443..cca61bbdd 100644--- a/agent/tests/test_qveris_loader.py+++ b/agent/tests/test_qveris_loader.py@@ -673,14 +673,12 @@ def test_adjusted_volume_wins_over_a_plain_volume_key():assert frame is not Noneassert float(frame["volume"].iloc[0]) == pytest.approx(200.0)-def test_plain_quartet_still_reports_an_adjusted_only_volume():- """Volume is not a price level, so neither family may strand the other's name.-- When a payload publishes both price families and names its volume only- ``adj_volume``, the unadjusted quartet wins (the documented preference)- and the volume lookup then followed the chosen table alone — so the bar- resolved with a real price and a NaN volume, which ``_result_to_frame`` keeps- because it only drops NaN price rows.+def test_an_unadjusted_bar_does_not_take_the_adjusted_volume():+ """Split-adjusted volume is not on the scale of unadjusted prices.++ With both price families present and only ``adj_volume`` named, the+ unadjusted quartet wins (the documented preference) and its volume stays+ NaN instead of borrowing the adjusted family's (#1527 follow-up)."""result = {"data": [@@ -703,4 +701,31 @@ def test_plain_quartet_still_reports_an_adjusted_only_volume():assert frame is not Noneassert float(frame["close"].iloc[0]) == pytest.approx(1.1)- assert float(frame["volume"].iloc[0]) == pytest.approx(200.0)+ assert frame["volume"].isna().all()+++def test_a_response_mixing_families_yields_no_bars():+ """Per-record choice built one series from an unadjusted row and an+ adjusted-only row: closes 11.0 then 1.1, two price levels in one series."""+ result = {+ "data": [+ {"date": "2024-01-02", "open": 10.0, "high": 11.5, "low": 9.5, "close": 11.0, "volume": 5},+ {"date": "2024-01-03", "adj_open": 1.0, "adj_high": 1.2, "adj_low": 0.9, "adj_close": 1.1},+ ]+ }++ assert qv._result_to_frame(result, "2024-01-01", "2024-01-05") is None+++def test_a_response_whose_rows_carry_both_families_uses_the_unadjusted_one():+ result = {+ "data": [+ {"date": d, "open": 10.0, "high": 11.0, "low": 9.0, "close": c,+ "adj_open": 1.0, "adj_high": 1.1, "adj_low": 0.9, "adj_close": c / 10}+ for d, c in (("2024-01-02", 10.5), ("2024-01-03", 10.7))+ ]+ }++ frame = qv._result_to_frame(result, "2024-01-01", "2024-01-05")++ assert list(frame["close"]) == pytest.approx([10.5, 10.7])