"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix: preserve financial precision and invalidate stale portfolio aggregates
Haozhe Wuce469ba1fea1
diff --git a/agent/backtest/engines/_market_hooks.py b/agent/backtest/engines/_market_hooks.pyindex e91c357df..aed18027d 100644--- a/agent/backtest/engines/_market_hooks.py+++ b/agent/backtest/engines/_market_hooks.py@@ -612,7 +612,7 @@ _SWAP_SHORT: dict[str, float] = {def _normalize_symbol(symbol: str) -> str:"""Normalize forex symbol to 'XXX/YYY' format."""- s = symbol.replace(".FX", "").replace(".", "").strip()+ s = symbol.strip().upper().removesuffix(".FX").replace(".", "")# Yahoo's forex notation (EURUSD=X) routes here too; without dropping the# suffix the pair misses the spread and swap tables and gets the defaults.if s.upper().endswith("=X"):diff --git a/agent/backtest/engines/china_a.py b/agent/backtest/engines/china_a.pyindex 8831c568a..d1963a247 100644--- a/agent/backtest/engines/china_a.py+++ b/agent/backtest/engines/china_a.py@@ -3,7 +3,8 @@Market rules:- T+1: cannot sell shares bought today- No short selling for retail investors- - Price limits: ±10% main board, ±20% ChiNext/STAR, ±5% ST+ - Ordinary price limits: ±10% main board, ±20% ChiNext/STAR, ±30% Beijing+ (ST status and listing-day exemptions cannot be inferred from code alone)- Minimum lot: 100 shares (odd lots can only be sold, not bought)- Commission: ¥5 minimum, 0.025% bilateral- Stamp tax: 0.05% sell-side only@@ -161,13 +162,12 @@ def _price_limit(symbol: str) -> float:symbol: Stock code (e.g. 300001.SZ, 688001.SH, 000001.SZ).Returns:- Limit as fraction (0.10, 0.20, or 0.05).+ Ordinary board limit as fraction (0.10, 0.20, or 0.30)."""code = symbol.split(".")[0] if "." in symbol else symbol# ChiNext (300xxx/301xxx) / STAR (688xxx, 689xxx CDRs): ±20%if code.startswith(("300", "301", "688", "689")):return 0.20- # ST stocks: ±5% (heuristic: can't fully detect from code alone)# Beijing exchange: ±30%. Current codes are 920xxx; legacy 4xxxxx/8xxxxx# codes remain in historical data.if len(code) == 6 and code.startswith(("4", "8", "920")):diff --git a/agent/src/portfolio/service.py b/agent/src/portfolio/service.pyindex 10711a376..fd7d79513 100644--- a/agent/src/portfolio/service.py+++ b/agent/src/portfolio/service.py@@ -45,7 +45,7 @@ _RISK_XRAY_MAX_SYMBOLS = 50# Version 3 makes all valuation use an explicit FX rates map. Existing v2# snapshots/history are intentionally hidden after upgrade, including# USD/HKD/CNY snapshots whose numeric values would otherwise remain valid.-PORTFOLIO_VALUATION_VERSION = 3+PORTFOLIO_VALUATION_VERSION = 4_LOADER_MARKET_SUFFIXES = frozenset({"US", "HK", "SZ", "SH", "BJ", "KS", "KQ", "NS", "BO", "TO", "V"})_NON_EQUITY_ASSET_TYPES = frozenset({"crypto", "stablecoin", "cash"})# Futu reports codes market-first (``HK.00700``, ``US.AAPL``); the rest of the@@ -839,7 +839,7 @@ class PortfolioService:"""grouped: dict[str, dict[str, Any]] = {}for row in positions:- symbol = _suffix_form(str(row.get("symbol") or "").upper())+ symbol = _suffix_form(str(row.get("symbol") or "").strip().upper())currency = str(row.get("currency") or "").upper()market = str(row.get("market") or "").upper()if symbol.endswith(".US"):diff --git a/agent/src/tools/financial_statements_tool.py b/agent/src/tools/financial_statements_tool.pyindex cf4e0e324..fbcaaa97b 100644--- a/agent/src/tools/financial_statements_tool.py+++ b/agent/src/tools/financial_statements_tool.py@@ -560,8 +560,16 @@ def _is_additive_unit(unit: Any) -> bool:average over its own period, and a per-share figure (``USD/shares``) is aratio; quarterly EPS need not sum to the annual EPS. Subtracting threequarters from the year is meaningless for both, so they are not derived.++ Args:+ unit: SEC XBRL unit bucket; currency flows use three-letter codes.++ Returns:+ Whether the unit has the currency-code shape, excluding dimensionless,+ share-count, per-share and unknown compound units."""- return isinstance(unit, str) and unit != "shares" and "/" not in unit+ return (isinstance(unit, str) and len(unit) == 3+ and unit.isascii() and unit.isalpha() and unit.isupper())def _synthesize_fiscal_q4(@@ -602,7 +610,10 @@ def _synthesize_fiscal_q4(values = {concept: annual[concept] - sum(quarter[concept] for quarter in inside)for concept, unit in annual["_units"].items()- if _is_additive_unit(unit) and all(concept in quarter for quarter in inside)+ if _is_additive_unit(unit) and all(+ concept in quarter and quarter["_units"].get(concept) == unit+ for quarter in inside+ )}if not values:continuediff --git a/agent/src/tools/technical_indicator_tool.py b/agent/src/tools/technical_indicator_tool.pyindex f3902cfd7..613527bcf 100644--- a/agent/src/tools/technical_indicator_tool.py+++ b/agent/src/tools/technical_indicator_tool.py@@ -198,13 +198,26 @@ def _round_keeping_precision(value: float, min_decimals: int, reference: float |A fixed 2- or 4-decimal round collapses the output of a sub-penny asset(e.g. a 1.2e-5 crypto price) to 0.0. Keep at least four significant digits- of ``reference`` (default ``value``); ordinary prices keep ``min_decimals``.+ of each nonzero value, using ``reference`` only if it requires more+ precision; ordinary prices keep ``min_decimals``. Python's decimal-place+ count can exceed 15 for tiny floats without claiming more significant+ digits than the input carries.++ Args:+ value: Indicator value to round.+ min_decimals: Minimum number of decimal places.+ reference: Optional scale of the related indicator.++ Returns:+ Rounded value with at least four significant digits when nonzero."""- ref = abs(value if reference is None else reference)- if not math.isfinite(ref) or ref == 0:+ if not math.isfinite(value) or value == 0:return round(value, min_decimals)+ ref = abs(value)+ if reference is not None and math.isfinite(reference) and reference != 0:+ ref = min(ref, abs(reference))decimals = max(min_decimals, 3 - math.floor(math.log10(ref)))- return round(value, min(decimals, 15))+ return round(value, decimals)def _compute_macd(diff --git a/agent/tests/quantlib/test_eventstudy_post_event_window.py b/agent/tests/quantlib/test_eventstudy_post_event_window.pyindex eff64802c..830dfdce2 100644--- a/agent/tests/quantlib/test_eventstudy_post_event_window.py+++ b/agent/tests/quantlib/test_eventstudy_post_event_window.py@@ -47,3 +47,16 @@ def test_pre_event_windows_keep_their_estimation_sample(shocked_frame) -> None:returns["A"].iloc[end - window:end], market.iloc[end - window:end])assert result.events[0].fit.residual_std == pytest.approx(expected.residual_std)++[email protected]("model", ["market", "market_adjusted", "mean_adjusted"])+def test_zero_gap_excludes_event_and_later_returns(shocked_frame, model) -> None:+ returns, market, index, position = shocked_frame+ before = event_study(returns, market, [("A", index[position])],+ event_window=(1, 5), estimation_gap=0, model=model)+ shocked = returns.copy()+ shocked.iloc[position:position + 6, 0] += 10+ after = event_study(shocked, market, [("A", index[position])],+ event_window=(1, 5), estimation_gap=0, model=model)+ assert before.events[0].fit == after.events[0].fit+ assert after.events[0].car - before.events[0].car == pytest.approx(50)diff --git a/agent/tests/test_china_a_engine.py b/agent/tests/test_china_a_engine.pyindex 356cb0778..d3fe961ce 100644--- a/agent/tests/test_china_a_engine.py+++ b/agent/tests/test_china_a_engine.py@@ -117,6 +117,24 @@ class TestTPlusOne:class TestPriceLimits:+ @pytest.mark.parametrize("symbol,limit", [+ ("301269.SZ", 0.20), ("689009.SH", 0.20),+ ("430047.BJ", 0.30), ("920002.BJ", 0.30),+ ])+ @pytest.mark.parametrize("direction", [0, 1])+ def test_new_board_codes_enforce_both_sides_of_band(self, symbol, limit, direction):+ engine = _make_engine(slippage=0)+ engine.positions[symbol] = Position(+ symbol, 1, 100.0, pd.Timestamp("2025-06-09"), 100.0,+ )+ sign = 1 if direction == 1 else -1+ inside = _make_bar(close=100 * (1 + sign * (limit - 0.01)),+ pre_close=100, trade_date="2025-06-10")+ boundary = _make_bar(close=100 * (1 + sign * limit),+ pre_close=100, trade_date="2025-06-10")+ assert engine.can_execute(symbol, direction, inside) is True+ assert engine.can_execute(symbol, direction, boundary) is False+def test_limit_up_buy_blocked(self) -> None:"""Mainboard +10% limit-up: can't buy."""engine = _make_engine()diff --git a/agent/tests/test_forex_engine.py b/agent/tests/test_forex_engine.pyindex 4f69175f4..10fc20928 100644--- a/agent/tests/test_forex_engine.py+++ b/agent/tests/test_forex_engine.py@@ -60,6 +60,7 @@ class TestNormalize:("EURUSD=X", "EUR/USD"),("usdjpy=x", "USD/JPY"),("XAUUSD=X", "XAU/USD"),+ (" eurusd.fx ", "EUR/USD"),],)def test_normalize(self, raw: str, expected: str) -> None:diff --git a/agent/tests/test_portfolio_futu_prefixed_codes.py b/agent/tests/test_portfolio_futu_prefixed_codes.pyindex ba4622b93..93ef37918 100644--- a/agent/tests/test_portfolio_futu_prefixed_codes.py+++ b/agent/tests/test_portfolio_futu_prefixed_codes.py@@ -2,6 +2,8 @@from __future__ import annotations+import pytest+from src.portfolio.normalization import normalize_positionfrom src.portfolio.service import PortfolioService@@ -43,3 +45,19 @@ def test_suffix_form_symbols_still_route_to_the_risk_xray() -> None:position = {"symbol": "700.HK", "currency": "HKD", "market": "HK", "priced": True,"market_value_usd": 1000, "asset_type": "stock"}assert PortfolioService._risk_xray_symbol(position) == "700.HK"++[email protected]("code,expected", [+ (" US.BRK.B ", "BRK.B.US"), ("sh.600519", "600519.SH"),+ ("SZ.000001", "000001.SZ"), ("BJ.920002", "920002.BJ"),+])+def test_prefix_conversion_preserves_share_classes_and_venues(code, expected):+ assert PortfolioService._risk_xray_symbol({"symbol": code}) == expected+++def test_futu_whitespace_does_not_split_the_same_holding():+ rows = PortfolioService._combine_holdings([+ _futu(" US.AAPL ", "US", "USD"), _futu("AAPL.US", "US", "USD"),+ ])+ assert len(rows) == 1+ assert rows[0]["market_value_usd"] == 2000.0diff --git a/agent/tests/test_portfolio_service.py b/agent/tests/test_portfolio_service.pyindex 013de315e..8cb91db36 100644--- a/agent/tests/test_portfolio_service.py+++ b/agent/tests/test_portfolio_service.py@@ -914,10 +914,11 @@ def test_a_pinned_read_hides_a_snapshot_that_includes_a_disabled_source(tmp_pathassert service.analysis_context(snapshot_id=snapshot["snapshot_id"]) is None-def test_a_pinned_read_refuses_a_snapshot_valued_under_another_contract(tmp_path):[email protected]("old_version", [1, 3])+def test_a_pinned_read_refuses_a_snapshot_valued_under_another_contract(tmp_path, old_version):service, _ = _pinned_service(tmp_path, "300")snapshot = service.refresh()- service.store.save_snapshot({**snapshot, "snapshot_id": "old-contract", "valuation_version": 1})+ service.store.save_snapshot({**snapshot, "snapshot_id": "old-contract", "valuation_version": old_version})assert service.analysis_context(snapshot_id="old-contract") is Nonediff --git a/agent/tests/test_sec_period_frames.py b/agent/tests/test_sec_period_frames.pyindex 900a3fd76..6a34117f1 100644--- a/agent/tests/test_sec_period_frames.py+++ b/agent/tests/test_sec_period_frames.py@@ -16,6 +16,8 @@ from __future__ import annotationsimport jsonfrom unittest.mock import patch+import pytest+from backtest.loaders import sec_framesfrom src.tools.financial_statements_tool import FinancialStatementsToolfrom src.tools.sec_filings_tool import _parse_metric@@ -271,6 +273,26 @@ class TestDerivedQ4NonAdditiveUnits:)return {"units": {unit: rows}}+ @pytest.mark.parametrize("unit", ["pure", "shares", "USD/shares", "", "percent"])+ def test_non_currency_units_are_not_synthesized(self, unit):+ facts = {"facts": {"us-gaap": {+ "NetIncomeLoss": self._concept("USD", [30, 24, 19], 97),+ "EarningsPerShareDiluted": self._concept(unit, [1, 2, 3], 7),+ }}}+ q4 = next(p for p in _fetch(facts, statement="indicators", period="quarter")+ if p["REPORT_DATE"] == "2023-09-30")+ assert q4["NetIncomeLoss"] == 24+ assert "EarningsPerShareDiluted" not in q4++ @pytest.mark.parametrize("unit", ["USD", "EUR", "JPY"])+ def test_currency_flows_are_still_synthesized(self, unit):+ facts = {"facts": {"us-gaap": {+ "NetIncomeLoss": self._concept(unit, [30, 24, 19], 97),+ }}}+ q4 = next(p for p in _fetch(facts, statement="income", period="quarter")+ if p["REPORT_DATE"] == "2023-09-30")+ assert q4["NetIncomeLoss"] == 24+def test_share_counts_and_eps_are_not_derived(self):facts = {"facts": {diff --git a/agent/tests/test_technical_indicator_small_price_rounding.py b/agent/tests/test_technical_indicator_small_price_rounding.pyindex 4d32de1ef..27f2692c2 100644--- a/agent/tests/test_technical_indicator_small_price_rounding.py+++ b/agent/tests/test_technical_indicator_small_price_rounding.py@@ -4,10 +4,34 @@ from __future__ import annotationsimport numpy as npimport pandas as pd+import pytestfrom src.tools.technical_indicator_tool import _compute_bollinger, _compute_macd[email protected]("scale", [1.2e-12, 1.2e-20, 1.2e-100])+def test_indicators_preserve_significant_digits_below_fifteen_decimals(scale) -> None:+ close = _series(scale)+ bands = _compute_bollinger(close)+ macd = _compute_macd(close)+ middle = close.rolling(20).mean().iloc[-1]+ line = close.ewm(span=12, adjust=False).mean() - close.ewm(span=26, adjust=False).mean()+ signal = line.ewm(span=9, adjust=False).mean()+ assert bands["middle"] == pytest.approx(middle, rel=5e-4, abs=0)+ for key, value in {"macd_line": line.iloc[-1], "signal_line": signal.iloc[-1],+ "histogram": (line - signal).iloc[-1]}.items():+ assert macd[key] == pytest.approx(value, rel=5e-4, abs=0)++[email protected]("reference", [0.0, 1.0, 1e-5])+def test_small_component_is_not_erased_by_larger_or_zero_reference(reference) -> None:+ from src.tools.technical_indicator_tool import _round_keeping_precision++ assert _round_keeping_precision(-1.23456e-12, 4, reference) == pytest.approx(+ -1.23456e-12, rel=5e-4, abs=0+ )++def _series(scale: float) -> pd.Series:rng = np.random.RandomState(0)return pd.Series(scale * np.cumprod(1 + rng.normal(0, 0.02, 80)))