Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(backtest): keep backtest outputs finite and validation.json strict

Santh5c299c0ce45c
diff --git a/agent/backtest/engines/base.py b/agent/backtest/engines/base.py
index 87a61f7be..4945a33fd 100644
--- a/agent/backtest/engines/base.py
+++ b/agent/backtest/engines/base.py
@@ -469,17 +469,17 @@ class BaseEngine(ABC):
# 7. Validation (optional — triggered by config["validation"])
if config.get("validation"):
- from backtest.validation import run_validation
+ from backtest.validation import run_validation, write_validation_json
v_results = run_validation(
config, equity_series, self.trades, self.initial_capital, bars_per_year,
)
m["validation"] = v_results
- # Write validation.json artifact. The artifacts dir is normally
- # created by _write_artifacts() below (step 8), so ensure it exists
- # here to avoid a FileNotFoundError when run_dir/artifacts is absent.
- v_path = run_dir / "artifacts" / "validation.json"
- v_path.parent.mkdir(parents=True, exist_ok=True)
- v_path.write_text(json.dumps(v_results, indent=2, ensure_ascii=False), encoding="utf-8")
+ # Write validation.json through the shared strict writer so a
+ # non-finite validation metric is serialized as null rather than an
+ # invalid bare NaN/Infinity token (matching the standalone
+ # `python -m backtest.validation` path and run_card). The writer
+ # also creates the artifacts dir, which step 8 otherwise creates.
+ write_validation_json(run_dir / "artifacts" / "validation.json", v_results)
# 8. Artifacts
self._write_artifacts(
diff --git a/agent/backtest/runner.py b/agent/backtest/runner.py
index c4e708df2..a48217dda 100644
--- a/agent/backtest/runner.py
+++ b/agent/backtest/runner.py
@@ -17,7 +17,7 @@ from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional
import pandas as pd
-from pydantic import BaseModel, ConfigDict, model_validator, field_validator
+from pydantic import BaseModel, ConfigDict, Field, model_validator, field_validator
try:
from dotenv import load_dotenv
@@ -63,6 +63,10 @@ class BacktestConfigSchema(BaseModel):
source: str = "tushare"
interval: str = "1D"
engine: str = "daily"
+ # Returns divide by initial_cash, so a non-positive value yields inf/NaN
+ # metrics (total_return, annual_return, ...). Reject it at the config
+ # boundary instead of letting the run produce non-finite results.
+ initial_cash: float = Field(default=1_000_000, gt=0)
fundamental_fields: Optional[Dict[str, List[str]]] = None
event_feeds: Optional[List[Dict[str, Any]]] = None
diff --git a/agent/backtest/validation.py b/agent/backtest/validation.py
index 95fdb7fd1..cff2f3657 100644
--- a/agent/backtest/validation.py
+++ b/agent/backtest/validation.py
@@ -372,6 +372,26 @@ def _json_safe(value: Any) -> Any:
return value
+def write_validation_json(path: Path, results: Dict[str, Any]) -> Dict[str, Any]:
+ """Write validation results to ``path`` as strict, RFC-8259 JSON.
+
+ A validation metric can be non-finite (e.g. a Sharpe computed from a path
+ whose equity touches zero), and ``json.dumps`` emits bare ``NaN`` /
+ ``Infinity`` tokens for those by default (``allow_nan=True``) — tokens that
+ strict parsers reject. Sanitize with :func:`_json_safe` (non-finite → null)
+ and serialize with ``allow_nan=False`` so every writer of
+ ``artifacts/validation.json`` produces the same valid JSON. Returns the
+ sanitized payload that was written.
+ """
+ safe_results = _json_safe(results)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(
+ json.dumps(safe_results, indent=2, ensure_ascii=False, allow_nan=False) + "\n",
+ encoding="utf-8",
+ )
+ return safe_results
+
+
def main(run_dir: Path) -> Dict[str, Any]:
"""Run all three validations on existing backtest artifacts.
@@ -399,14 +419,9 @@ def main(run_dir: Path) -> Dict[str, Any]:
"bootstrap": bootstrap_sharpe_ci(equity),
"walk_forward": walk_forward_analysis(equity, trades),
}
- safe_results = _json_safe(results)
- # Write results
out = run_dir / "artifacts" / "validation.json"
- out.write_text(
- json.dumps(safe_results, indent=2, ensure_ascii=False, allow_nan=False) + "\n",
- encoding="utf-8",
- )
+ safe_results = write_validation_json(out, results)
print(json.dumps(safe_results, indent=2, allow_nan=False))
return safe_results
diff --git a/agent/tests/test_engine_robustness.py b/agent/tests/test_engine_robustness.py
index 8929e5812..bdfdc90cf 100644
--- a/agent/tests/test_engine_robustness.py
+++ b/agent/tests/test_engine_robustness.py
@@ -355,6 +355,31 @@ class TestBacktestConfigSchema:
source="bloomberg",
)
+ @pytest.mark.parametrize("initial_cash", [0, -1, -1_000_000])
+ def test_non_positive_initial_cash_rejected(self, initial_cash: float) -> None:
+ """A non-positive initial_cash makes returns divide by <= 0 and yields
+ inf/NaN metrics; reject it at the config boundary."""
+ with pytest.raises(Exception, match="initial_cash"):
+ BacktestConfigSchema(
+ codes=["AAPL.US"],
+ start_date="2025-01-01",
+ end_date="2025-06-01",
+ initial_cash=initial_cash,
+ )
+
+ def test_initial_cash_defaults_and_accepts_positive(self) -> None:
+ default = BacktestConfigSchema(
+ codes=["AAPL.US"], start_date="2025-01-01", end_date="2025-06-01"
+ )
+ assert default.initial_cash == 1_000_000
+ explicit = BacktestConfigSchema(
+ codes=["AAPL.US"],
+ start_date="2025-01-01",
+ end_date="2025-06-01",
+ initial_cash=50_000,
+ )
+ assert explicit.initial_cash == 50_000
+
def test_mootdx_and_futu_sources_accepted(self) -> None:
"""mootdx and futu are registered loaders, so config validation must
accept them. Regression: ``_VALID_SOURCES`` drifted and rejected both
diff --git a/agent/tests/test_validation.py b/agent/tests/test_validation.py
index 7fad148a0..3ab2041ba 100644
--- a/agent/tests/test_validation.py
+++ b/agent/tests/test_validation.py
@@ -9,6 +9,9 @@ Validates:
from __future__ import annotations
+import json
+from pathlib import Path
+
import numpy as np
import pandas as pd
import pytest
@@ -19,6 +22,7 @@ from backtest.validation import (
monte_carlo_test,
run_validation,
walk_forward_analysis,
+ write_validation_json,
)
@@ -238,3 +242,47 @@ class TestRunValidation:
result = run_validation(config, eq, trades, 1_000_000)
assert "bootstrap" in result
assert "monte_carlo" not in result
+
+
+# ---------------------------------------------------------------------------
+# Strict validation.json writer
+# ---------------------------------------------------------------------------
+
+
+def _strict_json_load(text: str):
+ """Parse ``text`` rejecting non-RFC-8259 NaN/Infinity tokens."""
+
+ def _reject(value: str):
+ raise ValueError(f"non-strict JSON constant: {value}")
+
+ return json.loads(text, parse_constant=_reject)
+
+
+class TestWriteValidationJson:
+ def test_non_finite_metric_written_as_null(self, tmp_path: Path) -> None:
+ """A non-finite metric must be serialized as null, not a bare
+ NaN/Infinity token that strict JSON parsers reject."""
+ out = tmp_path / "artifacts" / "validation.json"
+ results = {
+ "monte_carlo": {
+ "actual_sharpe": float("inf"),
+ "p_value_sharpe": float("nan"),
+ "n_trades": 3,
+ }
+ }
+ written = write_validation_json(out, results)
+
+ text = out.read_text(encoding="utf-8")
+ assert "NaN" not in text
+ assert "Infinity" not in text
+ parsed = _strict_json_load(text) # must not raise
+ assert parsed["monte_carlo"]["actual_sharpe"] is None
+ assert parsed["monte_carlo"]["p_value_sharpe"] is None
+ assert parsed["monte_carlo"]["n_trades"] == 3
+ assert written["monte_carlo"]["actual_sharpe"] is None
+
+ def test_creates_parent_dir(self, tmp_path: Path) -> None:
+ out = tmp_path / "does" / "not" / "exist" / "validation.json"
+ write_validation_json(out, {"ok": 1.0})
+ assert out.is_file()
+ assert _strict_json_load(out.read_text(encoding="utf-8")) == {"ok": 1.0}