"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(journal): emit strict JSON when a ratio is unbounded
Rudy Celekli95ecd3323d89
diff --git a/agent/src/tools/trade_journal_tool.py b/agent/src/tools/trade_journal_tool.pyindex 2307e9535..d2cad713b 100644--- a/agent/src/tools/trade_journal_tool.py+++ b/agent/src/tools/trade_journal_tool.py@@ -13,8 +13,10 @@ from __future__ import annotationsimport jsonimport logging+import mathimport refrom collections import defaultdict, deque+from collections.abc import Mappingfrom typing import Anyimport pandas as pd@@ -629,6 +631,22 @@ def _apply_filter(df: pd.DataFrame, expr: str) -> pd.DataFrame:return df+def _json_safe(value: Any) -> Any:+ """Recursively replace non-finite floats with ``None``.++ A journal with no losing round-trip yields an infinite profit/loss ratio,+ and ``json.dumps`` would emit the non-standard ``Infinity`` literal that+ strict JSON parsers reject.+ """+ if isinstance(value, float):+ return value if math.isfinite(value) else None+ if isinstance(value, Mapping):+ return {key: _json_safe(item) for key, item in value.items()}+ if isinstance(value, (list, tuple)):+ return [_json_safe(item) for item in value]+ return value++def analyze_trade_journal(file_path: str, analysis_type: str = "full", filter_expr: str = "") -> str:"""Parse a trade journal and return a JSON analysis.@@ -696,7 +714,7 @@ def analyze_trade_journal(file_path: str, analysis_type: str = "full", filter_ex"note": "Strategy extraction → backtest bridging lands in Phase 4c.",}- return json.dumps(result, ensure_ascii=False, default=str)+ return json.dumps(_json_safe(result), ensure_ascii=False, default=str, allow_nan=False)def _format_range(df: pd.DataFrame) -> str:diff --git a/agent/tests/test_trade_journal_strict_json.py b/agent/tests/test_trade_journal_strict_json.pynew file mode 100644index 000000000..0f8f7b84b--- /dev/null+++ b/agent/tests/test_trade_journal_strict_json.py@@ -0,0 +1,49 @@+"""The journal analysis must be strict JSON even when a ratio is unbounded."""++from __future__ import annotations++import json+from pathlib import Path++import pytest++from src.tools.trade_journal_tool import analyze_trade_journal+++def _reject_constant(name: str) -> None:+ raise ValueError(f"non-standard JSON literal {name}")+++def _analyze(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, rows: str) -> dict:+ monkeypatch.setenv("VIBE_TRADING_ALLOWED_FILE_ROOTS", str(tmp_path))+ csv = tmp_path / "journal.csv"+ csv.write_text("datetime,symbol,side,quantity,price\n" + rows, encoding="utf-8")+ raw = analyze_trade_journal(str(csv), "full")+ return json.loads(raw, parse_constant=_reject_constant)+++def test_winners_only_journal_has_null_profit_loss_ratio(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ out = _analyze(+ tmp_path,+ monkeypatch,+ "2026-01-02 09:35:00,AAPL,buy,10,180\n"+ "2026-01-05 14:00:00,AAPL,sell,10,190\n",+ )+ assert out["status"] == "ok"+ assert out["profile"]["profit_loss_ratio"] is None+++def test_zero_day_winner_has_null_disposition_ratio(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ out = _analyze(+ tmp_path,+ monkeypatch,+ "2026-01-02 09:35:00,AAPL,buy,10,100\n"+ "2026-01-02 09:35:00,AAPL,sell,10,110\n"+ "2026-01-02 09:35:00,MSFT,buy,10,100\n"+ "2026-01-05 09:35:00,MSFT,sell,10,90\n",+ )+ assert out["behavior"]["disposition_effect"]["ratio_loss_to_win_hold"] is None