Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(quantlib): stabilize volatility surface arithmetic

Haozhe Wu2c6081fd33ce
diff --git a/agent/src/quantlib/volatility.py b/agent/src/quantlib/volatility.py
index 74ee7c92f..38d19d22c 100644
--- a/agent/src/quantlib/volatility.py
+++ b/agent/src/quantlib/volatility.py
@@ -257,6 +257,25 @@ def _surface_grid(values: Sequence[Real] | None, defaults: Sequence[float], name
return sorted({_surface_number(value, f"{name} grid value") for value in supplied})
+def _surface_log_ratio(upper: float, lower: float) -> float:
+ """Compute log(upper / lower) for ordered positive strikes without overflow."""
+ relative_gap = (upper - lower) / lower
+ if math.isfinite(relative_gap):
+ # Unlike subtracting two logs, log1p preserves adjacent float strikes.
+ return math.log1p(relative_gap)
+ return math.log(upper) - math.log(lower)
+
+
+def _surface_variance(iv: float, expiry: float) -> float:
+ """Compute total variance, refusing overflow or loss of a positive value."""
+ # Squaring IV first can overflow/underflow even when IV**2 * T fits.
+ scaled = iv * math.sqrt(expiry)
+ variance = scaled * scaled
+ if not math.isfinite(variance) or (iv > 0.0 and variance == 0.0):
+ raise ValueError("total variance is outside the representable floating-point range")
+ return variance
+
+
def implied_volatility_surface(
observations: Sequence[Mapping[str, Real]],
*,
@@ -291,9 +310,11 @@ def implied_volatility_surface(
Raises:
ValueError: If observations are empty, malformed, duplicated, or a grid
- point would require extrapolation beyond adjacent quote coverage.
+ point would require extrapolation beyond adjacent quote coverage,
+ or its total variance cannot be represented as a finite float
+ without rounding a positive value to zero.
"""
- spot_value = _surface_number(spot, "spot")
+ _surface_number(spot, "spot")
if not observations:
raise ValueError("at least one volatility observation is required")
@@ -332,40 +353,44 @@ def implied_volatility_surface(
lower = quotes[0][0]
upper = quotes[-1][0]
if strike < lower or strike > upper:
- raise ValueError(f"no extrapolation: strike {strike} is outside [{lower}, {upper}] " f"for expiry {expiry}")
+ raise ValueError(f"no extrapolation: strike {strike} is outside [{lower}, {upper}] for expiry {expiry}")
for (left_strike, left_iv), (right_strike, right_iv) in zip(quotes, quotes[1:]):
if left_strike <= strike <= right_strike:
if strike == left_strike:
return left_iv
if strike == right_strike:
return right_iv
- left_coordinate = math.log(left_strike / spot_value)
- right_coordinate = math.log(right_strike / spot_value)
- coordinate = math.log(strike / spot_value)
- weight = (coordinate - left_coordinate) / (right_coordinate - left_coordinate)
- return left_iv + (right_iv - left_iv) * weight
+ # The spot cancels from log-moneyness differences. Avoid
+ # forming strike / spot, which may overflow or round to zero.
+ weight = _surface_log_ratio(strike, left_strike) / _surface_log_ratio(right_strike, left_strike)
+ return (1.0 - weight) * left_iv + weight * right_iv
return quotes[0][1]
points: list[dict[str, object]] = []
for expiry in expiry_grid:
if expiry < observed_expiries[0] or expiry > observed_expiries[-1]:
raise ValueError(
- f"no extrapolation: expiry {expiry} is outside " f"[{observed_expiries[0]}, {observed_expiries[-1]}]"
+ f"no extrapolation: expiry {expiry} is outside [{observed_expiries[0]}, {observed_expiries[-1]}]"
)
for strike in strike_grid:
if expiry in groups:
iv = smile(expiry, strike)
- total_variance = iv * iv * expiry
+ total_variance = _surface_variance(iv, expiry)
else:
next_expiry = next(value for value in observed_expiries if value > expiry)
previous_expiry = observed_expiries[observed_expiries.index(next_expiry) - 1]
lower_iv = smile(previous_expiry, strike)
upper_iv = smile(next_expiry, strike)
- lower_variance = lower_iv * lower_iv * previous_expiry
- upper_variance = upper_iv * upper_iv * next_expiry
+ lower_variance = _surface_variance(lower_iv, previous_expiry)
+ upper_variance = _surface_variance(upper_iv, next_expiry)
weight = (expiry - previous_expiry) / (next_expiry - previous_expiry)
- total_variance = lower_variance + (upper_variance - lower_variance) * weight
- iv = math.sqrt(total_variance / expiry)
+ total_variance = (1.0 - weight) * lower_variance + weight * upper_variance
+ if total_variance == 0.0 and (lower_variance > 0.0 or upper_variance > 0.0):
+ raise ValueError("interpolated total variance is below the representable floating-point range")
+ # The ratio can overflow even when its square root fits.
+ iv = math.sqrt(total_variance) / math.sqrt(expiry)
+ if not math.isfinite(iv) or not math.isfinite(total_variance):
+ raise ValueError("interpolated IV or total variance is outside the representable floating-point range")
points.append(
{
"strike": strike,
diff --git a/agent/src/skills/options-advanced/SKILL.md b/agent/src/skills/options-advanced/SKILL.md
index 12db99ddd..4c6aa9195 100644
--- a/agent/src/skills/options-advanced/SKILL.md
+++ b/agent/src/skills/options-advanced/SKILL.md
@@ -31,6 +31,8 @@ Three-dimensional structure: strike × expiry × implied volatility.
**Deterministic grid computation**: `quantlib_call(action="call", module="volatility", function="implied_volatility_surface", kwargs={"observations": observations, "spot": spot})` accepts explicit `strike`, `time_to_expiry` (years), and `implied_volatility` (decimal) observations. It interpolates IV across log-moneyness within each expiry and total variance between adjacent expiries, rejects extrapolation and duplicate quotes, and labels every point as `observed` or `interpolated`. This is a display and exploratory-analysis grid, not an arbitrage-free pricing model. The tool fetches no market data; obtain and validate the option chain first.
+Interpolation uses stable log-strike differences, so changing the positive spot scale alone does not change the grid. Results must have finite IV and total variance; a total variance outside the floating-point range (including a positive value rounding to zero) is rejected explicitly rather than returned as NaN, infinity, or a fabricated zero.
+
**SABR model parameters**:
```
α (alpha): initial volatility level, around 0.2-0.5
diff --git a/agent/tests/quantlib/test_volatility_surface.py b/agent/tests/quantlib/test_volatility_surface.py
index c1035864f..51712e7bd 100644
--- a/agent/tests/quantlib/test_volatility_surface.py
+++ b/agent/tests/quantlib/test_volatility_surface.py
@@ -161,3 +161,98 @@ def test_quantlib_tool_lists_and_calls_surface_builder():
assert called["ok"] is True
assert called["result"]["points"][0]["source"] == "interpolated"
assert called["result"]["interpolation"]["extrapolation"] == "rejected"
+
+
[email protected]("spot", [math.ulp(0.0), 1e-308, 1e308])
+def test_interpolated_surface_is_independent_of_spot_scale(spot):
+ kwargs = dict(observations=_rectangle(), strikes=[100.0], expiries=[0.15])
+ expected = implied_volatility_surface(**kwargs, spot=100.0)
+ actual = implied_volatility_surface(**kwargs, spot=spot)
+
+ assert actual == expected
+ json.dumps(actual, allow_nan=False)
+
+
[email protected]("scale", [1e-200, 1e200])
+def test_log_interpolation_handles_extreme_strike_scales(scale):
+ result = implied_volatility_surface(
+ [_point(scale, 0.1, 0.2), _point(4 * scale, 0.1, 0.4)],
+ spot=1e308,
+ strikes=[2 * scale],
+ )
+ assert result["points"][0]["implied_volatility"] == pytest.approx(0.3)
+
+
+def test_log_interpolation_preserves_distinct_nearby_strikes():
+ left = 100.0
+ middle = math.nextafter(left, math.inf)
+ right = math.nextafter(middle, math.inf)
+ result = implied_volatility_surface(
+ [_point(left, 0.1, 0.2), _point(right, 0.1, 0.4)],
+ spot=1.0,
+ strikes=[middle],
+ )
+ assert result["points"][0]["implied_volatility"] == pytest.approx(0.3)
+
+
+def test_log_interpolation_handles_a_ratio_larger_than_float_range():
+ result = implied_volatility_surface(
+ [_point(1e-300, 0.1, 0.2), _point(1e300, 0.1, 0.4)],
+ spot=1.0,
+ strikes=[1.0],
+ )
+ assert result["points"][0]["implied_volatility"] == pytest.approx(0.3)
+
+
+ ("iv", "expiry", "variance"),
+ [
+ (1e200, 1e-300, 1e100),
+ (1e-200, 1e300, 1e-100),
+ (0.0, 0.1, 0.0),
+ ],
+)
+def test_total_variance_avoids_intermediate_overflow_and_underflow(iv, expiry, variance):
+ result = implied_volatility_surface([_point(100.0, expiry, iv)], spot=100.0)
+ assert result["points"][0]["total_variance"] == pytest.approx(variance, rel=1e-12, abs=0.0)
+
+
[email protected]("iv", [1e200, 1e-200])
+def test_unrepresentable_total_variance_is_refused(iv):
+ with pytest.raises(ValueError, match="total variance"):
+ implied_volatility_surface([_point(100.0, 1.0, iv)], spot=100.0)
+
+
+def test_expiry_interpolation_avoids_overflow_before_square_root():
+ result = implied_volatility_surface(
+ [_point(100.0, 1e-300, 1e200), _point(100.0, 3e-300, 1e200)],
+ spot=100.0,
+ expiries=[2e-300],
+ )
+ assert result["points"][0]["implied_volatility"] == pytest.approx(1e200)
+
+
+def test_quantlib_surface_returns_finite_results_or_an_explicit_error():
+ tool = QuantlibCallTool()
+ kwargs = dict(observations=_rectangle(), spot=1e-308, strikes=[100.0], expiries=[0.15])
+ good = json.loads(
+ tool.execute(
+ action="call",
+ module="volatility",
+ function="implied_volatility_surface",
+ kwargs=kwargs,
+ )
+ )
+ assert good["ok"] is True
+ assert math.isfinite(good["result"]["points"][0]["implied_volatility"])
+ kwargs["observations"] = [_point(100.0, 1.0, 1e200)]
+ kwargs["expiries"] = [1.0]
+ bad = json.loads(
+ tool.execute(
+ action="call",
+ module="volatility",
+ function="implied_volatility_surface",
+ kwargs=kwargs,
+ )
+ )
+ assert bad["ok"] is False