Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(backtest): validate options_config.default_iv and document it (review #1305)

cgycorey12ed0e995e79
diff --git a/agent/backtest/engines/options_portfolio.py b/agent/backtest/engines/options_portfolio.py
index 3964682db..47642f5f7 100644
--- a/agent/backtest/engines/options_portfolio.py
+++ b/agent/backtest/engines/options_portfolio.py
@@ -19,6 +19,7 @@ the per-leg vol every pricing site must agree on.
"""
import json
+import math
import sys
from pathlib import Path
from typing import Any, Dict, List, Optional
@@ -42,9 +43,10 @@ def historical_volatility(
Args:
close: Close price Series.
window: Rolling window in days.
- default_iv: Volatility used for bars without a full window. Backfilling
- the first computed window here would price bars before it with
- information from the window's own end (#1293).
+ default_iv: Volatility used for any bar without a full rolling window
+ (the leading warm-up and NaN gaps). Backfilling the first computed
+ window here would price bars before it with information from the
+ window's own end (#1293).
Returns:
Annualised historical volatility Series.
@@ -219,6 +221,8 @@ def run_options_backtest(
iv_skew = options_cfg.get("iv_skew", 0.0) # v2: smile skew param (0 = flat)
iv_curvature = options_cfg.get("iv_curvature", 0.0) # v2: smile curvature
default_iv = options_cfg.get("default_iv", 0.3)
+ if not math.isfinite(default_iv) or default_iv <= 0.0:
+ raise ValueError("options_config.default_iv must be a finite, positive float")
# Load underlying data
data_map = loader.fetch(codes, start_date, end_date)
diff --git a/agent/src/skills/options-strategy/SKILL.md b/agent/src/skills/options-strategy/SKILL.md
index 51456e917..6d6ebf09e 100644
--- a/agent/src/skills/options-strategy/SKILL.md
+++ b/agent/src/skills/options-strategy/SKILL.md
@@ -90,7 +90,8 @@ Iron Condor opening signal:
"options_config": {
"risk_free_rate": 0.05,
"iv_source": "historical",
- "contract_multiplier": 1.0
+ "contract_multiplier": 1.0,
+ "default_iv": 0.3
}
}
```
@@ -100,6 +101,7 @@ Key fields:
- `options_config.risk_free_rate`: risk-free rate, default `0.05`
- `options_config.iv_source`: volatility source, currently supports `"historical"` (30-day rolling historical volatility computed from underlying closes)
- `options_config.contract_multiplier`: contract multiplier, default `1.0`
+- `options_config.default_iv`: volatility used for bars without a full rolling window (warm-up and NaN gaps), default `0.3`; must be finite and positive
## BS Model Principles
diff --git a/agent/tests/test_options_hv_warmup.py b/agent/tests/test_options_hv_warmup.py
index 338aed167..b8977691a 100644
--- a/agent/tests/test_options_hv_warmup.py
+++ b/agent/tests/test_options_hv_warmup.py
@@ -9,10 +9,13 @@ volatility. (#1293, part 2.)
from __future__ import annotations
+from pathlib import Path
+
import numpy as np
import pandas as pd
+import pytest
-from backtest.engines.options_portfolio import historical_volatility
+from backtest.engines.options_portfolio import historical_volatility, run_options_backtest
def test_warmup_bars_use_default_iv_not_the_first_computed_window() -> None:
@@ -42,3 +45,39 @@ def test_full_window_bars_are_unchanged_by_the_warmup_fix() -> None:
log_ret = np.log(close / close.shift(1))
expected = log_ret.rolling(30).std() * np.sqrt(252)
pd.testing.assert_series_equal(hv.iloc[30:], expected.iloc[30:].fillna(0.0))
+
+
[email protected]("bad_iv", [0.0, -0.5, float("nan"), float("inf")])
+def test_default_iv_must_be_positive_and_finite(bad_iv: float) -> None:
+ """NaN/zero/negative config would silently break pricing or crash on dump."""
+
+ class _FlatLoader:
+ name = "yfinance"
+
+ def fetch(self, codes, start_date, end_date): # noqa: ANN001
+ return {
+ "SPY": pd.DataFrame(
+ {"close": [100.0, 101.0], "open": [100.0, 100.5]},
+ index=pd.to_datetime(["2025-01-01", "2025-01-02"]),
+ )
+ }
+
+ class _NoSignals:
+ def generate(self, data_map): # noqa: ANN001
+ return []
+
+ with pytest.raises(ValueError, match="default_iv"):
+ run_options_backtest(
+ {
+ "codes": ["SPY"],
+ "start_date": "2025-01-01",
+ "end_date": "2025-01-02",
+ "source": "yfinance",
+ "engine": "options",
+ "initial_cash": 100_000.0,
+ "options_config": {"default_iv": bad_iv},
+ },
+ _FlatLoader(),
+ _NoSignals(),
+ Path("/tmp/opts_guard"),
+ )