Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(uk): enforce GBP quote-currency contract

warren61885e1c97664e6
diff --git a/agent/backtest/engines/_market_hooks.py b/agent/backtest/engines/_market_hooks.py
index 67145c080..55cbe43f6 100644
--- a/agent/backtest/engines/_market_hooks.py
+++ b/agent/backtest/engines/_market_hooks.py
@@ -67,9 +67,11 @@ _MARKET_PATTERNS = [
_CHINA_EXCHANGES = {"CFFEX", "SHFE", "DCE", "ZCE", "INE", "GFEX"}
-# Settlement currency per market. A composite backtest holds one shared capital
-# pool, so a code set spanning two of these would add CNY to USD to KRW as if
-# they were the same unit.
+# Supported settlement-currency contract per market. A composite backtest holds
+# one shared capital pool, so a code set spanning two of these would add CNY to
+# USD to KRW as if they were the same unit. The suffix alone cannot prove an
+# LSE line's currency; UK loaders admit only declared GBP/GBp and reject every
+# other/unknown quote before it reaches this table.
_MARKET_CURRENCY = {
"a_share": "CNY",
"us_equity": "USD",
@@ -95,7 +97,7 @@ _FUTURES_EXCHANGE_CURRENCY = {"EUREX": "EUR"}
def code_currency(code: str) -> str:
- """Return the currency a symbol settles in.
+ """Return the supported settlement-currency contract for a symbol.
Args:
code: Ticker / symbol string.
diff --git a/agent/backtest/loaders/base.py b/agent/backtest/loaders/base.py
index 3dc0b005f..45503c4d4 100644
--- a/agent/backtest/loaders/base.py
+++ b/agent/backtest/loaders/base.py
@@ -14,35 +14,32 @@ import hashlib
import json
import logging
import os
+import re
import time
import uuid
from pathlib import Path
from typing import Callable, Protocol, TypeVar, runtime_checkable
import pandas as pd
-import re
logger = logging.getLogger(__name__)
-# Yahoo quotes LSE (.L) equities in pence, not pounds: VOD.L is ~117p,
-# HSBA.L ~1500p. `code_currency`/`_MARKET_CURRENCY`
-# declare GBP, so prices must be normalized ÷100 when a source reports the
-# pence marker (HKUDS/Vibe-Trading#1206). Anything else is left untouched.
+# The supported LSE contract settles in GBP. Yahoo may declare an individual
+# ``.L`` line in pence (``GBp``), pounds (``GBP``), another currency, or no
+# currency at all. Loaders must normalize declared pence to pounds and reject
+# every non-GBP/unknown line before the static GBP market accounting sees it.
_GBP_PENCE_CURRENCY = "GBp"
_PRICE_COLUMNS = ("open", "high", "low", "close")
_UK_EQUITY_PATTERN = re.compile(r"^[A-Z0-9&.\-]+\.L$", re.I)
-def is_gbp_pence_symbol(code: str) -> bool:
- """Return whether a project symbol quotes in GBp (LSE names).
+def is_lse_symbol(code: str) -> bool:
+ """Return whether a project symbol uses the supported LSE ``.L`` form.
- Both Yahoo sources (direct chart + yfinance) serve ``.L`` names in pence.
- The engine-side
- ``code_currency`` resolves these to GBP, so any loader emitting them must
- normalize ÷100 — callers with chart meta (Yahoo) pass the ``"GBp"``
- currency directly; sources without per-symbol meta (yfinance) fall back to
- this suffix rule (#1206).
+ The suffix identifies the venue, not the quote currency. Every caller must
+ still inspect source metadata through :func:`normalize_lse_quote_currency`
+ before emitting bars.
"""
return bool(_UK_EQUITY_PATTERN.match(str(code).strip()))
@@ -70,6 +67,43 @@ def scale_pence_to_currency(
return scaled, "GBp→GBP (÷100)"
+def normalize_lse_quote_currency(
+ frame: pd.DataFrame, currency: str | None
+) -> pd.DataFrame:
+ """Normalize a declared LSE quote into the engine's GBP-only contract.
+
+ Args:
+ frame: Normalized OHLCV frame.
+ currency: Quote currency declared by the source.
+
+ Returns:
+ A frame quoted in GBP with per-symbol conversion provenance attached.
+
+ Raises:
+ ValueError: If the source declares USD/another currency or omits the
+ currency. Passing such bars into the static ``uk_equity=GBP``
+ accounting contract would silently mix currencies.
+ """
+ declared = currency.strip() if isinstance(currency, str) else ""
+ normalized = frame.copy()
+ if declared in {_GBP_PENCE_CURRENCY, "p"}:
+ normalized, conversion = scale_pence_to_currency(
+ normalized, _GBP_PENCE_CURRENCY
+ )
+ elif declared == "GBP":
+ conversion = "none"
+ else:
+ label = declared or "missing"
+ raise ValueError(
+ "LSE quote currency must be declared as GBP or GBp; "
+ f"got {label!r}"
+ )
+
+ normalized.attrs["quote_currency"] = "GBP"
+ normalized.attrs["currency_conversion"] = conversion
+ return normalized
+
+
class NoAvailableSourceError(Exception):
"""Raised when no data source is available for a given market."""
@@ -293,9 +327,11 @@ _LOADER_CACHE_TRUE_VALUES = {"1", "true", "yes", "on"}
# simply never matched (old files become unreachable garbage, safe to delete).
# v4: baostock volume normalized from shares to lots (#1062) — entries cached
# under the pre-normalization unit must never be served again.
-# v5: UK (.L) prices normalized from GBp to GBP (÷100) (#1206) — entries
-# cached under the pre-normalization pence values must never be served again.
-_LOADER_CACHE_VERSION = 5
+# v5: UK (.L) prices normalized from GBp to GBP (÷100) (#1206).
+# v6: LSE quote currency is fail-closed and per-symbol conversion provenance is
+# persisted. v5 USD/unknown .L entries must never be served as static GBP.
+_LOADER_CACHE_VERSION = 6
+_LOADER_FRAME_METADATA_ATTRS = ("quote_currency", "currency_conversion")
def loader_cache_enabled() -> bool:
@@ -558,6 +594,12 @@ def _read_loader_cache_frame(cache_path: Path) -> pd.DataFrame | None:
frame.index.names = metadata.get("index_names") or index_columns
frame = _restore_cache_index_dtypes(frame, metadata.get("index_dtypes"))
frame.columns.name = metadata.get("columns_name")
+ frame_attrs = metadata.get("frame_attrs")
+ if isinstance(frame_attrs, dict):
+ for name in _LOADER_FRAME_METADATA_ATTRS:
+ value = frame_attrs.get(name)
+ if isinstance(value, str):
+ frame.attrs[name] = value
return frame
@@ -641,6 +683,11 @@ def _frame_for_loader_cache(frame: pd.DataFrame) -> tuple[pd.DataFrame, dict[str
# resolution, e.g. [s] -> [us]).
"columns_name": None if columns_name is None else str(columns_name),
"index_dtypes": index_dtypes,
+ "frame_attrs": {
+ name: frame.attrs[name]
+ for name in _LOADER_FRAME_METADATA_ATTRS
+ if isinstance(frame.attrs.get(name), str)
+ },
}
return cache_frame.reset_index(), metadata
diff --git a/agent/backtest/loaders/yahoo_client.py b/agent/backtest/loaders/yahoo_client.py
index e9177b774..ce5c7f186 100644
--- a/agent/backtest/loaders/yahoo_client.py
+++ b/agent/backtest/loaders/yahoo_client.py
@@ -35,7 +35,6 @@ from typing import Any, Dict, List, Optional, Tuple
import requests
from backtest.loaders._http import (
- DEFAULT_USER_AGENT,
resolve_min_interval,
throttled_get,
throttled_get_json,
@@ -218,8 +217,8 @@ def _parse_chart(payload: Any, yahoo_symbol: str) -> Tuple[List[Dict[str, Any]],
Returns:
``(rows, currency)``: rows as in :func:`get_chart`, plus the quote
- currency declared in the chart meta (``"GBp"`` when the venue quotes
- UK names in pence — LSE always quotes, GBp when chart meta says so).
+ currency declared in the chart meta (for example ``"GBp"``, ``"GBP"``,
+ or ``"USD"`` for different LSE lines).
"""
chart = (payload or {}).get("chart") or {}
error = chart.get("error")
diff --git a/agent/backtest/loaders/yahoo_loader.py b/agent/backtest/loaders/yahoo_loader.py
index c725b14a3..ccfe1c82d 100644
--- a/agent/backtest/loaders/yahoo_loader.py
+++ b/agent/backtest/loaders/yahoo_loader.py
@@ -26,7 +26,8 @@ import pandas as pd
from backtest.loaders import yahoo_client
from backtest.loaders.base import (
cached_loader_fetch,
- scale_pence_to_currency,
+ is_lse_symbol,
+ normalize_lse_quote_currency,
validate_date_range,
)
from backtest.loaders.registry import register
@@ -54,8 +55,8 @@ def _is_supported(code: str) -> bool:
Covers US/HK/India/Korea/Canada/Vietnam/UK equities plus Yahoo's own
futures (``GC=F``) and forex (``EURUSD=X``) suffix conventions, which the
public chart endpoint serves verbatim (the code is used as-is in the
- request URL, no conversion) (#718). UK ``.L`` quotes in GBp and is
- normalized to GBP at fetch time (#1206).
+ request URL, no conversion) (#718). Supported UK ``.L`` lines must declare
+ GBP or GBp; GBp is normalized to GBP at fetch time (#1206).
"""
upper = code.strip().upper()
return upper.endswith(
@@ -194,9 +195,6 @@ class DataLoader:
# (HKUDS/Vibe-Trading#1062; HK verified 2026-08-11, 00700.HK ratio 1.00
# vs tencent/eastmoney). Other equity markets stay undeclared.
volume_units = {"us_equity": "shares", "hk_equity": "shares", "uk_equity": "shares"}
- # Post-fetch price unit per market. UK names arrive GBp-quoted (pence) and
- # are normalized to GBP (÷100) at fetch time (#1206); US/HK are native.
- price_units = {"uk_equity": "GBP"}
requires_auth = False
def is_available(self) -> bool:
@@ -268,8 +266,8 @@ class DataLoader:
interval: Backtest interval string.
Returns:
- The OHLCV DataFrame for *code*, ``None`` if it is not a US/HK/India
- symbol or Yahoo returns no usable bars.
+ The OHLCV DataFrame for *code*, ``None`` if it is unsupported or
+ Yahoo returns no usable bars.
"""
if not _is_supported(code):
return None
@@ -286,5 +284,6 @@ class DataLoader:
period2=period2,
)
frame = _rows_to_frame(rows, start_date, end_date, interval)
- frame, _ = scale_pence_to_currency(frame, currency)
+ if is_lse_symbol(code):
+ frame = normalize_lse_quote_currency(frame, currency)
return frame if not frame.empty else None
diff --git a/agent/backtest/loaders/yfinance_loader.py b/agent/backtest/loaders/yfinance_loader.py
index 76a26ecf8..6a41a61fb 100644
--- a/agent/backtest/loaders/yfinance_loader.py
+++ b/agent/backtest/loaders/yfinance_loader.py
@@ -1,4 +1,4 @@
-"""yfinance-backed loader for HK/US equity OHLCV data."""
+"""yfinance-backed loader for global equity and crypto OHLCV data."""
from __future__ import annotations
@@ -9,18 +9,18 @@ from typing import Dict, List, Optional, Union
import pandas as pd
import yfinance as yf
-logger = logging.getLogger(__name__)
-
from backtest.loaders.base import (
- is_gbp_pence_symbol,
+ is_lse_symbol,
loader_cache_get,
loader_cache_put,
- scale_pence_to_currency,
+ normalize_lse_quote_currency,
validate_date_range,
validate_ohlc,
)
from backtest.loaders.registry import register
+logger = logging.getLogger(__name__)
+
_OHLCV_COLUMNS = ["open", "high", "low", "close", "volume"]
_COLUMN_RENAMES = {
"Open": "open",
@@ -100,10 +100,9 @@ def _declared_currency(symbol: str) -> Optional[str]:
"""Return Yahoo's declared currency for ``symbol``, or ``None`` when absent.
``yf.Ticker(...).history_metadata`` carries the exchange's declared quote
- currency. Absence (or any probe failure) MUST NOT be treated as GBp: a
- missing currency means "do not scale", not "assume pence" — the suffix
- heuristic alone would wrongly ÷100 every LSE line priced in GBP or USD
- (e.g. VUSA.L=GBP, VUSD.L=USD).
+ currency. Absence (or any probe failure) MUST NOT be treated as GBp. The
+ LSE loader contract rejects a missing or non-GBP currency rather than
+ allowing a USD line into static GBP accounting.
"""
try:
meta = yf.Ticker(symbol).history_metadata
@@ -347,16 +346,13 @@ class DataLoader:
logger.warning("yfinance returned no usable data for %s", symbol)
continue
- # Yahoo-family data: LSE names may quote in GBp (pence) —
- # normalize ÷100 so code_currency's GBP matches the values.
- # Scale ONLY on Yahoo's declared currency (GBp/p). A GBP or
- # USD-priced .L line (VUSA.L=GBP, VUSD.L=USD) must pass
- # through unscaled; a missing currency means "do not scale"
- # (fail closed — never assume pence from the suffix).
- if is_gbp_pence_symbol(symbol):
+ # The engine currently has one static GBP pool for uk_equity.
+ # Normalize declared GBp/p to GBP, pass declared GBP unchanged,
+ # and reject USD/other/unknown .L lines before they can enter
+ # that pool. The suffix identifies LSE, never the currency.
+ if is_lse_symbol(symbol):
declared = _declared_currency(symbol)
- if declared in ("GBp", "p"):
- normalized, _ = scale_pence_to_currency(normalized, "GBp")
+ normalized = normalize_lse_quote_currency(normalized, declared)
loader_cache_put(
source=self.name,
diff --git a/agent/src/market_data.py b/agent/src/market_data.py
index 02ea01bc7..b5b4a6512 100644
--- a/agent/src/market_data.py
+++ b/agent/src/market_data.py
@@ -289,12 +289,10 @@ def fetch_market_data(
results[symbol] = cap_rows(records, max_rows)
if include_provenance:
volume_units = getattr(provider_cls, "volume_units", None) or {}
- price_units = getattr(provider_cls, "price_units", None) or {}
- if price_units.get(market):
- # Loader normalizes GBp-quoted UK prices to GBP at fetch
- # (#1206); declare the applied conversion explicitly.
- currency_conversion = f"GBp→{price_units[market]} (÷100)"
- else:
+ frame_attrs = getattr(df, "attrs", None)
+ frame_attrs = frame_attrs if isinstance(frame_attrs, dict) else {}
+ currency_conversion = frame_attrs.get("currency_conversion")
+ if not isinstance(currency_conversion, str) or not currency_conversion:
currency_conversion = "none"
entry: dict[str, Any] = {
"source": used_source or src,
@@ -304,6 +302,9 @@ def fetch_market_data(
"currency_conversion": currency_conversion,
"volume_unit": volume_units.get(market),
}
+ quote_currency = frame_attrs.get("quote_currency")
+ if isinstance(quote_currency, str) and quote_currency:
+ entry["quote_currency"] = quote_currency
if extra_provenance:
entry.update(extra_provenance)
provenance[symbol] = entry
diff --git a/agent/tests/test_loader_retry_helpers.py b/agent/tests/test_loader_retry_helpers.py
index 2c9fea5c3..b78ca9277 100644
--- a/agent/tests/test_loader_retry_helpers.py
+++ b/agent/tests/test_loader_retry_helpers.py
@@ -320,6 +320,10 @@ def test_loader_cache_happy_path_writes_then_reuses(
monkeypatch.setenv(LOADER_CACHE_ENV, "1")
calls = {"count": 0}
frame = _cache_frame()
+ frame.attrs.update(
+ quote_currency="GBP",
+ currency_conversion="GBp→GBP (÷100)",
+ )
def fetch():
calls["count"] += 1
@@ -339,6 +343,7 @@ def test_loader_cache_happy_path_writes_then_reuses(
assert calls["count"] == 1
pd.testing.assert_frame_equal(first, frame)
pd.testing.assert_frame_equal(second, frame)
+ assert second.attrs == frame.attrs
assert loader_cache_path(**kwargs).is_file()
assert str(loader_cache_path(**kwargs)).startswith(str(loader_cache_root))
@@ -469,6 +474,10 @@ def test_loader_cache_real_duckdb_round_trip(tmp_path, monkeypatch, loader_cache
pytest.importorskip("duckdb")
monkeypatch.setenv(LOADER_CACHE_ENV, "1")
frame = _cache_frame()
+ frame.attrs.update(
+ quote_currency="GBP",
+ currency_conversion="GBp→GBP (÷100)",
+ )
kwargs = {
"source": "yfinance",
"symbol": "AAPL.US",
@@ -488,6 +497,7 @@ def test_loader_cache_real_duckdb_round_trip(tmp_path, monkeypatch, loader_cache
# The cache preserves columns name and per-level index dtype, so a real
# duckdb round-trip is byte-identical to the source frame.
pd.testing.assert_frame_equal(restored, frame)
+ assert restored.attrs == frame.attrs
def test_yfinance_loader_serves_second_fetch_from_cache(tmp_path, monkeypatch, fake_duckdb, loader_cache_root):
diff --git a/agent/tests/test_market_data_tool.py b/agent/tests/test_market_data_tool.py
index 0bf2257a6..26a6e87a8 100644
--- a/agent/tests/test_market_data_tool.py
+++ b/agent/tests/test_market_data_tool.py
@@ -133,8 +133,8 @@ def test_market_data_provenance_exposes_declared_volume_unit():
assert payload["_provenance"]["0700.HK"]["volume_unit"] == "shares"
-def test_market_data_provenance_declares_gbp_conversion_for_uk():
- """UK-serving loaders declare the GBp->GBP price normalization (#1206)."""
+def test_market_data_provenance_uses_per_symbol_currency_conversion():
+ """Conversion provenance follows the frame, not the ``.L`` suffix."""
idx = pd.date_range("2026-01-01", periods=1, freq="D")
idx.name = "trade_date"
df = pd.DataFrame(
@@ -150,14 +150,27 @@ def test_market_data_provenance_declares_gbp_conversion_for_uk():
class _UKAwareLoader:
volume_units = {"uk_equity": "shares"}
- price_units = {"uk_equity": "GBP"}
def fetch(self, codes, start, end, interval="1D"):
- return {code: df for code in codes}
+ result = {}
+ for code in codes:
+ frame = df.copy()
+ if code == "VOD.L":
+ frame.attrs.update(
+ quote_currency="GBP",
+ currency_conversion="GBp→GBP (÷100)",
+ )
+ elif code == "VUSA.L":
+ frame.attrs.update(
+ quote_currency="GBP",
+ currency_conversion="none",
+ )
+ result[code] = frame
+ return result
payload = json.loads(
fetch_market_data_json(
- codes=["VOD.L", "AAPL.US"],
+ codes=["VOD.L", "VUSA.L", "AAPL.US"],
start_date="2026-01-01",
end_date="2026-01-02",
source="yahoo",
@@ -167,8 +180,11 @@ def test_market_data_provenance_declares_gbp_conversion_for_uk():
)
assert payload["_provenance"]["VOD.L"]["currency_conversion"] == "GBp→GBP (÷100)"
+ assert payload["_provenance"]["VOD.L"]["quote_currency"] == "GBP"
assert payload["_provenance"]["VOD.L"]["volume_unit"] == "shares"
- # Non-UK symbols served by the same loader keep "none".
+ assert payload["_provenance"]["VUSA.L"]["currency_conversion"] == "none"
+ assert payload["_provenance"]["VUSA.L"]["quote_currency"] == "GBP"
+ # Non-LSE symbols without frame metadata keep the neutral default.
assert payload["_provenance"]["AAPL.US"]["currency_conversion"] == "none"
diff --git a/agent/tests/test_market_detection.py b/agent/tests/test_market_detection.py
index aa9aa208b..95b514532 100644
--- a/agent/tests/test_market_detection.py
+++ b/agent/tests/test_market_detection.py
@@ -68,14 +68,14 @@ class TestDetectMarket:
# Korea equity (KRX)
("005930.KS", "kr_equity"), # KOSPI
("247540.KQ", "kr_equity"), # KOSDAQ
-# Canada equity (TSX / TSX Venture)
- ("TD.TO", "ca_equity"),
- ("BBD-B.TO", "ca_equity"),
- ("PNG.V", "ca_equity"),
- # UK equity (LSE)
- ("VOD.L", "uk_equity"),
- ("SHEL.L", "uk_equity"),
- ("BARC.L", "uk_equity"),
+ # Canada equity (TSX / TSX Venture)
+ ("TD.TO", "ca_equity"),
+ ("BBD-B.TO", "ca_equity"),
+ ("PNG.V", "ca_equity"),
+ # UK equity (LSE)
+ ("VOD.L", "uk_equity"),
+ ("SHEL.L", "uk_equity"),
+ ("BARC.L", "uk_equity"),
# Crypto
("BTC-USDT", "crypto"),
("ETH-USDT", "crypto"),
diff --git a/agent/tests/test_uk_equity_support.py b/agent/tests/test_uk_equity_support.py
index 124c7d64a..778d2f142 100644
--- a/agent/tests/test_uk_equity_support.py
+++ b/agent/tests/test_uk_equity_support.py
@@ -4,15 +4,22 @@ Regression suite for issue #1205: UK symbols used to fall through the
source/market detection tables to the tushare default and the China
fallback chain, surfacing as ``_unresolved`` after several seconds of
network attempts. They must now route as a first-class market with the
-same parity as Canada/US: yahoo source, ``uk_equity`` market, GBP
-settlement, and GlobalEquityEngine with ``market="uk"``.
+same parity as Canada/US: yahoo source, ``uk_equity`` market, a GBP-only
+loader/accounting contract, and GlobalEquityEngine with ``market="uk"``.
"""
from __future__ import annotations
+import pandas as pd
+import pytest
+
from backtest.engines.global_equity import GlobalEquityEngine
from backtest.engines._market_hooks import _detect_market, _detect_submarket, code_currency
-from backtest.loaders.base import is_gbp_pence_symbol, scale_pence_to_currency
+from backtest.loaders.base import (
+ is_lse_symbol,
+ normalize_lse_quote_currency,
+ scale_pence_to_currency,
+)
from backtest.loaders.registry import FALLBACK_CHAINS
from backtest.runner import _create_market_engine, _MARKET_TO_SOURCE
from src.market_data import detect_source
@@ -23,7 +30,7 @@ class TestUKSourceDetection:
assert detect_source("VOD.L") == "yahoo"
assert detect_source("SHEL.L") == "yahoo"
- def test_ise_routes_to_yahoo(self) -> None:
+ def test_other_lse_name_routes_to_yahoo(self) -> None:
assert detect_source("BARC.L") == "yahoo"
def test_lowercase_suffix_routes_to_yahoo(self) -> None:
@@ -35,7 +42,7 @@ class TestUKMarketClassification:
assert _detect_market("VOD.L") == "uk_equity"
assert _detect_market("HSBA.L") == "uk_equity"
- def test_ise_classifies_as_uk_equity(self) -> None:
+ def test_other_lse_name_classifies_as_uk_equity(self) -> None:
assert _detect_market("BARC.L") == "uk_equity"
def test_lowercase_classifies_as_uk_equity(self) -> None:
@@ -51,12 +58,14 @@ class TestUKMarketClassification:
assert _detect_submarket(["700.HK"]) == "hk"
-class TestUKSettlementCurrency:
+class TestUKSettlementContract:
def test_lse_settles_in_gbp(self) -> None:
+ # This is the supported post-loader contract. Source metadata gates out
+ # USD/other/unknown .L lines before the engine sees them.
assert code_currency("VOD.L") == "GBP"
assert code_currency("SHEL.L") == "GBP"
- def test_ise_settles_in_gbp(self) -> None:
+ def test_other_lse_name_uses_gbp_contract(self) -> None:
assert code_currency("BARC.L") == "GBP"
def test_uk_market_cost_is_separate_from_cad(self) -> None:
@@ -94,7 +103,7 @@ class TestUKBacktestRouting:
assert isinstance(engine, GlobalEquityEngine)
assert engine.market == "uk"
- def test_ise_engine_is_global_equity(self) -> None:
+ def test_other_lse_name_engine_is_global_equity(self) -> None:
engine = _create_market_engine("auto", {"initial_cash": 100_000}, ["BARC.L"])
assert isinstance(engine, GlobalEquityEngine)
assert engine.market == "uk"
@@ -103,9 +112,7 @@ class TestUKBacktestRouting:
class TestGbpPenceNormalization:
"""GBp-quoted UK prices must normalize to GBP (÷100) at the loader."""
- def test_scale_scales_pence_when_currency_is_gbp(self) -> None:
- import pandas as pd
-
+ def test_scale_scales_pence_when_currency_is_gbp_pence(self) -> None:
frame = pd.DataFrame(
{
"open": [117.0],
@@ -122,8 +129,6 @@ class TestGbpPenceNormalization:
assert scaled["volume"].iloc[0] == 1000
def test_scale_leaves_other_currencies_untouched(self) -> None:
- import pandas as pd
-
frame = pd.DataFrame(
{"open": [10.0], "high": [11.0], "low": [9.0], "close": [10.5], "volume": [1]}
)
@@ -133,17 +138,26 @@ class TestGbpPenceNormalization:
assert scaled["close"].iloc[0] == 10.5
def test_scale_empty_frame_is_noop(self) -> None:
- import pandas as pd
-
empty = pd.DataFrame()
scaled, applied = scale_pence_to_currency(empty, "GBp")
assert applied == "none"
assert scaled.empty
- def test_pence_symbol_detection(self) -> None:
- assert is_gbp_pence_symbol("VOD.L")
- assert is_gbp_pence_symbol("BARC.L")
- assert is_gbp_pence_symbol("vod.l")
- assert not is_gbp_pence_symbol("AAPL.US")
- assert not is_gbp_pence_symbol("0700.HK")
- assert not is_gbp_pence_symbol("GC=F")
+ def test_lse_symbol_detection_does_not_claim_currency(self) -> None:
+ assert is_lse_symbol("VOD.L")
+ assert is_lse_symbol("BARC.L")
+ assert is_lse_symbol("vod.l")
+ assert not is_lse_symbol("AAPL.US")
+ assert not is_lse_symbol("0700.HK")
+ assert not is_lse_symbol("GC=F")
+
+ @pytest.mark.parametrize("currency", ["USD", "EUR", "", None])
+ def test_lse_contract_rejects_non_gbp_or_missing_currency(
+ self, currency: str | None
+ ) -> None:
+ frame = pd.DataFrame(
+ {"open": [1.0], "high": [1.1], "low": [0.9], "close": [1.05]}
+ )
+
+ with pytest.raises(ValueError, match="must be declared as GBP or GBp"):
+ normalize_lse_quote_currency(frame, currency)
diff --git a/agent/tests/test_yahoo_loader.py b/agent/tests/test_yahoo_loader.py
index c3dafb162..b7215bdf5 100644
--- a/agent/tests/test_yahoo_loader.py
+++ b/agent/tests/test_yahoo_loader.py
@@ -276,7 +276,7 @@ class TestFetch:
# LSE prices arrive in pence ("GBp") from Yahoo's chart meta; the
# loader must normalize ÷100 so 117p becomes £1.17.
rows = [
- _row("2024-01-02", 11700, 11800, 11600, 11750, 1000),
+ _row("2024-01-02", 117, 118, 116, 117.5, 1000),
]
with patch(
"backtest.loaders.yahoo_loader.yahoo_client.get_chart",
@@ -285,14 +285,53 @@ class TestFetch:
out = DataLoader().fetch(["VOD.L"], "2024-01-01", "2024-01-31")
assert "VOD.L" in out
frame = out["VOD.L"]
- assert frame["open"].iloc[0] == 117.0
- assert frame["high"].iloc[0] == 118.0
- assert frame["low"].iloc[0] == 116.0
- assert frame["close"].iloc[0] == 117.5
+ assert frame["open"].iloc[0] == 1.17
+ assert frame["high"].iloc[0] == 1.18
+ assert frame["low"].iloc[0] == 1.16
+ assert frame["close"].iloc[0] == 1.175
# Volume is untouched.
assert frame["volume"].iloc[0] == 1000
+ assert frame.attrs == {
+ "quote_currency": "GBP",
+ "currency_conversion": "GBp→GBP (÷100)",
+ }
assert mock_chart.call_args.args[0] == "VOD.L"
+ def test_gbp_quoted_lse_line_passes_unscaled(self):
+ rows = [_row("2024-01-02", 107.0, 108.0, 106.0, 107.8, 1000)]
+ with patch(
+ "backtest.loaders.yahoo_loader.yahoo_client.get_chart",
+ return_value=(rows, "GBP"),
+ ):
+ out = DataLoader().fetch(["VUSA.L"], "2024-01-01", "2024-01-31")
+
+ frame = out["VUSA.L"]
+ assert frame["close"].iloc[0] == 107.8
+ assert frame.attrs == {
+ "quote_currency": "GBP",
+ "currency_conversion": "none",
+ }
+
+ def test_usd_quoted_lse_line_is_omitted(self):
+ rows = [_row("2024-01-02", 146.0, 147.0, 145.0, 146.4, 1000)]
+ with patch(
+ "backtest.loaders.yahoo_loader.yahoo_client.get_chart",
+ return_value=(rows, "USD"),
+ ):
+ out = DataLoader().fetch(["VUSD.L"], "2024-01-01", "2024-01-31")
+
+ assert out == {}
+
+ def test_lse_line_with_missing_currency_is_omitted(self):
+ rows = [_row("2024-01-02", 117.0, 118.0, 116.0, 117.5, 1000)]
+ with patch(
+ "backtest.loaders.yahoo_loader.yahoo_client.get_chart",
+ return_value=(rows, ""),
+ ):
+ out = DataLoader().fetch(["VOD.L"], "2024-01-01", "2024-01-31")
+
+ assert out == {}
+
def test_non_gbp_currency_meta_left_untouched(self):
rows = [
_row("2024-01-02", 10, 11, 9, 10.5, 1000),
diff --git a/agent/tests/test_yfinance_uk_scale.py b/agent/tests/test_yfinance_uk_scale.py
index 2a0f1d73b..a3b21cefe 100644
--- a/agent/tests/test_yfinance_uk_scale.py
+++ b/agent/tests/test_yfinance_uk_scale.py
@@ -1,7 +1,8 @@
-"""yfinance loader scales GBp-quoted UK (.L) prices to GBP.
+"""yfinance loader enforces the GBP-only LSE quote contract.
-Yahoo-family data serves LSE UK names in pence (VOD.L ~117p); the loader
-must normalize ÷100 so ``code_currency``'s GBP matches the values (#1206).
+Yahoo-family data serves some LSE names in pence (VOD.L ~117p), some in
+pounds, and some in other currencies. The loader normalizes GBp to GBP and
+rejects anything that cannot safely enter ``code_currency``'s GBP pool.
"""
from __future__ import annotations
@@ -43,6 +44,10 @@ def test_fetch_scales_lse_pence_to_gbp(monkeypatch: pytest.MonkeyPatch) -> None:
assert frame["high"].iloc[1] == pytest.approx(1.19)
assert frame["low"].iloc[0] == pytest.approx(1.16)
assert frame["volume"].iloc[0] == 100
+ assert frame.attrs == {
+ "quote_currency": "GBP",
+ "currency_conversion": "GBp→GBP (÷100)",
+ }
def test_fetch_scales_other_lse_names(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -90,10 +95,15 @@ def test_fetch_leaves_gbp_quoted_lse_unscaled(monkeypatch: pytest.MonkeyPatch) -
frame = result["VUSA.L"]
assert frame["close"].iloc[0] == pytest.approx(117.5) # untouched
+ assert frame.attrs == {
+ "quote_currency": "GBP",
+ "currency_conversion": "none",
+ }
-def test_fetch_leaves_usd_quoted_lse_unscaled(monkeypatch: pytest.MonkeyPatch) -> None:
- # VUSD.L is USD-priced .L: suffix alone would wrongly ÷100.
+def test_fetch_rejects_usd_quoted_lse_line(monkeypatch: pytest.MonkeyPatch) -> None:
+ # VUSD.L is USD-priced. Passing it unscaled would still label the values GBP
+ # in the composite and shadow-accounting layers.
monkeypatch.delenv("VIBE_TRADING_DATA_CACHE", raising=False)
def fake_download(tickers, start_date, end_date, interval):
@@ -105,13 +115,12 @@ def test_fetch_leaves_usd_quoted_lse_unscaled(monkeypatch: pytest.MonkeyPatch) -
result = yfl.DataLoader().fetch(["VUSD.L"], "2025-01-01", "2025-01-03")
- frame = result["VUSD.L"]
- assert frame["close"].iloc[0] == pytest.approx(117.5) # untouched
+ assert "VUSD.L" not in result
def test_fetch_fails_closed_when_currency_absent(monkeypatch: pytest.MonkeyPatch) -> None:
- # A missing declared currency means "do not scale", not "assume pence":
- # the suffix heuristic must never be the fallback.
+ # Without metadata, 117.5 could mean GBP 117.50 or GBp 117.5. Returning it
+ # under either assumption is unsafe, so the symbol must be omitted.
monkeypatch.delenv("VIBE_TRADING_DATA_CACHE", raising=False)
def fake_download(tickers, start_date, end_date, interval):
@@ -123,8 +132,7 @@ def test_fetch_fails_closed_when_currency_absent(monkeypatch: pytest.MonkeyPatch
result = yfl.DataLoader().fetch(["VOD.L"], "2025-01-01", "2025-01-03")
- frame = result["VOD.L"]
- assert frame["close"].iloc[0] == pytest.approx(117.5) # NOT ÷100'd
+ assert "VOD.L" not in result
def test_fetch_scales_only_on_gbp_pence(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -147,24 +155,9 @@ def test_fetch_scales_only_on_gbp_pence(monkeypatch: pytest.MonkeyPatch) -> None
def test_fetch_declared_currency_failure_is_fail_closed(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- # CI/reviewer regression: _declared_currency hits the network. When it
- # fails (offline, metadata 403), the suffix heuristic must NOT kick in —
- # fail-closed = never assume pence; prices stay unscaled.
- monkeypatch.delenv("VIBE_TRADING_DATA_CACHE", raising=False)
+ def raise_offline(_symbol: str):
+ raise RuntimeError("offline")
- def fake_download(tickers, start_date, end_date, interval):
- assert tickers == ["VOD.L"]
- return _download_frame()
+ monkeypatch.setattr(yfl.yf, "Ticker", raise_offline)
- monkeypatch.setattr(yfl, "_download_history", fake_download)
-
- # Real offline behavior: _declared_currency swallows probe failures and
- # returns None (fail-closed). Simulating the raise would turn it into a
- # dropped symbol — the production function never raises.
- monkeypatch.setattr(yfl, "_declared_currency", lambda symbol: None)
-
- result = yfl.DataLoader().fetch(["VOD.L"], "2025-01-01", "2025-01-03")
-
- frame = result["VOD.L"]
- # Fail-closed: no scale. No exception may escape.
- assert frame["close"].iloc[0] == pytest.approx(117.5)
+ assert yfl._declared_currency("VOD.L") is None