"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(journal): reject unknown trade directions
xkam7ar2248737bff6b
diff --git a/agent/src/tools/trade_journal_parsers.py b/agent/src/tools/trade_journal_parsers.pyindex f586d0237..0e85553f1 100644--- a/agent/src/tools/trade_journal_parsers.py+++ b/agent/src/tools/trade_journal_parsers.py@@ -24,8 +24,31 @@ _A_SHARE_EXCHANGE_MAP = {("4", "8"): ".BJ",}-_BUY_TOKENS = {"buy", "b", "买入", "证券买入", "融资买入", "做多", "long"}-_SELL_TOKENS = {"sell", "s", "卖出", "证券卖出", "融券卖出", "做空", "short"}+_BUY_TOKENS = {+ "buy",+ "b",+ "purchase",+ "buy to cover",+ "buy-to-cover",+ "buy_to_cover",+ "买入",+ "证券买入",+ "融资买入",+ "做多",+ "long",+}+_SELL_TOKENS = {+ "sell",+ "s",+ "sell short",+ "sell-short",+ "sell_short",+ "卖出",+ "证券卖出",+ "融券卖出",+ "做空",+ "short",+}@dataclass(frozen=True)@@ -122,11 +145,21 @@ def detect_format(df: pd.DataFrame) -> FormatName:# ---------------- Parsers ----------------def _normalize_side(raw: Any) -> str:- """Return 'buy'/'sell', falling back to 'buy'."""+ """Return ``buy`` or ``sell`` for an exact supported direction alias.++ Raises:+ ValueError: Direction is missing or unsupported.+ """+ if raw is None or pd.isna(raw):+ raise ValueError("Trade side is required")s = str(raw).strip().lower()- if s in _SELL_TOKENS or any(tok in s for tok in _SELL_TOKENS):+ if not s:+ raise ValueError("Trade side is required")+ if s in _BUY_TOKENS:+ return "buy"+ if s in _SELL_TOKENS:return "sell"- return "buy"+ raise ValueError(f"Unsupported trade side: {raw!r}")def _qualify_a_share(code: str) -> str:@@ -281,6 +314,11 @@ def parse_generic(df: pd.DataFrame) -> list[TradeRecord]:amount_col = pick("amount", "value", "notional")fee_col = pick("fee", "commission", "fees")+ if side_col is None:+ raise ValueError(+ "Generic trade journal requires a side, direction, or action column"+ )+records: list[TradeRecord] = []for _, row in df.iterrows():if dt_col:@@ -299,7 +337,7 @@ def parse_generic(df: pd.DataFrame) -> list[TradeRecord]:datetime=dt,symbol=symbol.upper(),name=str(row.get(name_col, "")).strip() if name_col else "",- side=_normalize_side(row.get(side_col) if side_col else "buy"),+ side=_normalize_side(row.get(side_col)),quantity=qty,price=price,amount=amount or qty * price,diff --git a/agent/tests/test_trade_journal.py b/agent/tests/test_trade_journal.pyindex db4ba432d..bd17d8860 100644--- a/agent/tests/test_trade_journal.py+++ b/agent/tests/test_trade_journal.py@@ -87,18 +87,26 @@ def test_qualify_a_share(code: str, expected: str) -> None:("证券买入", "buy"),("B", "buy"),("long", "buy"),+ (" Purchase ", "buy"),+ ("buy-to-cover", "buy"),("卖出", "sell"),("证券卖出", "sell"),("融券卖出", "sell"),("S", "sell"),("short", "sell"),- ("hold", "buy"), # no buy/sell token substring -> documented fallback+ (" SELL-SHORT ", "sell"),],)def test_normalize_side(raw: str, expected: str) -> None:assert _normalize_side(raw) == expected[email protected]("raw", [None, "", "hold", "strong buy"])+def test_normalize_side_rejects_missing_or_unknown(raw: object) -> None:+ with pytest.raises(ValueError, match="side"):+ _normalize_side(raw)++@pytest.mark.parametrize("symbol,expected",[@@ -192,6 +200,23 @@ def test_parse_file_unknown_raises(tmp_path: Path) -> None:parse_file(csv)+ "header,value,error",+ [+ ("datetime,symbol,quantity,price", "2026-01-02,AAPL,10,180", "requires a side"),+ ("datetime,symbol,side,quantity,price", "2026-01-02,AAPL,hold,10,180", "Unsupported trade side"),+ ],+)+def test_parse_file_rejects_missing_or_unknown_side(+ tmp_path: Path, header: str, value: str, error: str+) -> None:+ csv = tmp_path / "invalid_side.csv"+ csv.write_text(f"{header}\n{value}\n", encoding="utf-8")++ with pytest.raises(ValueError, match=error):+ parse_file(csv)++# --------------------------------------------------------------------------# FIFO pairing# --------------------------------------------------------------------------