"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(quantlib): add implied volatility surface grids (#2172)
Yufeng He871f1e48e05c
diff --git a/agent/src/quantlib/__init__.py b/agent/src/quantlib/__init__.pyindex fab42b7de..376855877 100644--- a/agent/src/quantlib/__init__.py+++ b/agent/src/quantlib/__init__.py@@ -29,6 +29,7 @@ Submodules:impact Market-impact and slippage modelsfundmath Private-markets fund maths on the irregular cash-flow spineperformance Client money-weighted performance (XIRR, TWR) on that spine+ volatility Heston pricing and observed-IV surface grid constructionTwo modules expose a function named ``xirr`` and they are not interchangeable.``fundmath.xirr`` takes a ``CashFlowSeries`` under a valuation policy, scans adiff --git a/agent/src/quantlib/volatility.py b/agent/src/quantlib/volatility.pyindex c96d21fc5..74ee7c92f 100644--- a/agent/src/quantlib/volatility.py+++ b/agent/src/quantlib/volatility.py@@ -25,6 +25,8 @@ from __future__ import annotationsimport cmathimport math+from collections.abc import Mapping, Sequence+from numbers import Realfrom scipy.integrate import quadfrom src.quantlib.options import normalise_option_type@@ -33,6 +35,7 @@ __all__ = ["heston_characteristic_function","heston_price","heston_feller_condition",+ "implied_volatility_surface",]@@ -224,3 +227,162 @@ def heston_price(discounted_K = K * math.exp(-r * T)put = call - discounted_F + discounted_Kreturn float(max(0.0, put))+++_SURFACE_GRID_LIMIT = 400+_SURFACE_FIELDS = {"strike", "time_to_expiry", "implied_volatility"}+++def _surface_number(value: Real, name: str, *, allow_zero: bool = False) -> float:+ if isinstance(value, bool) or not isinstance(value, Real):+ raise ValueError(f"{name} must be a finite real number, got {value!r}")+ result = float(value)+ if not math.isfinite(result):+ raise ValueError(f"{name} must be finite, got {value!r}")+ if result < 0.0 or (result == 0.0 and not allow_zero):+ relation = "non-negative" if allow_zero else "strictly positive"+ raise ValueError(f"{name} must be {relation}, got {value!r}")+ return result+++def _surface_grid(values: Sequence[Real] | None, defaults: Sequence[float], name: str) -> list[float]:+ if values is None:+ return list(defaults)+ try:+ supplied = list(values)+ except TypeError as exc:+ raise ValueError(f"{name} grid must be a sequence of real numbers") from exc+ if not supplied:+ raise ValueError(f"{name} grid must not be empty")+ return sorted({_surface_number(value, f"{name} grid value") for value in supplied})+++def implied_volatility_surface(+ observations: Sequence[Mapping[str, Real]],+ *,+ spot: Real,+ strikes: Sequence[Real] | None = None,+ expiries: Sequence[Real] | None = None,+) -> dict[str, object]:+ """Build a bounded strike-by-expiry grid from observed implied volatilities.++ This is a display and exploratory-analysis grid, not an arbitrage-free+ pricing model. Within each observed expiry, IV is interpolated linearly in+ log-moneyness. Between two adjacent expiries, total variance is interpolated+ linearly before converting back to IV at the requested expiry. Requests+ outside the convex coverage of those slices are rejected instead of being+ silently extrapolated.++ Args:+ observations: Mappings with exactly ``strike``, ``time_to_expiry`` (in+ years) and ``implied_volatility`` (decimal, so 0.20 means 20%). Each+ expiry/strike pair must be unique. Values must be finite and+ positive, except that zero IV is accepted.+ spot: Positive underlying spot used for log-moneyness coordinates.+ strikes: Optional strike grid. Defaults to every observed strike.+ expiries: Optional expiry grid in years. Defaults to observed expiries.++ Returns:+ A deterministic dictionary with the normalized grids, interpolation+ contract, and one record per grid point. Each point contains ``strike``,+ ``time_to_expiry``, ``implied_volatility``, ``total_variance`` and+ ``source`` (``observed`` or ``interpolated``). The cross product is+ limited to 400 points so callers can render or serialize it directly.++ Raises:+ ValueError: If observations are empty, malformed, duplicated, or a grid+ point would require extrapolation beyond adjacent quote coverage.+ """+ spot_value = _surface_number(spot, "spot")+ if not observations:+ raise ValueError("at least one volatility observation is required")++ groups: dict[float, list[tuple[float, float]]] = {}+ seen: set[tuple[float, float]] = set()+ for index, observation in enumerate(observations):+ if not isinstance(observation, Mapping) or set(observation) != _SURFACE_FIELDS:+ raise ValueError(+ "each observation must contain exactly strike, time_to_expiry "+ f"and implied_volatility; invalid index {index}"+ )+ strike = _surface_number(observation["strike"], f"observation {index} strike")+ expiry = _surface_number(observation["time_to_expiry"], f"observation {index} time_to_expiry")+ iv = _surface_number(+ observation["implied_volatility"],+ f"observation {index} implied_volatility",+ allow_zero=True,+ )+ key = (expiry, strike)+ if key in seen:+ raise ValueError(f"duplicate expiry/strike observation: {key}")+ seen.add(key)+ groups.setdefault(expiry, []).append((strike, iv))++ for expiry in groups:+ groups[expiry].sort()+ observed_expiries = sorted(groups)+ observed_strikes = sorted({strike for values in groups.values() for strike, _ in values})+ strike_grid = _surface_grid(strikes, observed_strikes, "strikes")+ expiry_grid = _surface_grid(expiries, observed_expiries, "expiries")+ if len(strike_grid) * len(expiry_grid) > _SURFACE_GRID_LIMIT:+ raise ValueError(f"grid exceeds {_SURFACE_GRID_LIMIT} points; narrow strikes or expiries")++ def smile(expiry: float, strike: float) -> float:+ quotes = groups[expiry]+ 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}")+ 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+ 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]}]"+ )+ for strike in strike_grid:+ if expiry in groups:+ iv = smile(expiry, strike)+ total_variance = iv * 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+ weight = (expiry - previous_expiry) / (next_expiry - previous_expiry)+ total_variance = lower_variance + (upper_variance - lower_variance) * weight+ iv = math.sqrt(total_variance / expiry)+ points.append(+ {+ "strike": strike,+ "time_to_expiry": expiry,+ "implied_volatility": iv,+ "total_variance": total_variance,+ "source": "observed" if (expiry, strike) in seen else "interpolated",+ }+ )++ return {+ "strikes": strike_grid,+ "expiries": expiry_grid,+ "interpolation": {+ "strike": "linear_iv_log_moneyness",+ "expiry": "linear_total_variance",+ "extrapolation": "rejected",+ },+ "points": points,+ }diff --git a/agent/src/skills/options-advanced/SKILL.md b/agent/src/skills/options-advanced/SKILL.mdindex be790814e..12db99ddd 100644--- a/agent/src/skills/options-advanced/SKILL.md+++ b/agent/src/skills/options-advanced/SKILL.md@@ -29,6 +29,8 @@ Three-dimensional structure: strike × expiry × implied volatility.| Term Structure | IV across expiries for the same strike | Normal case: near-month IV < far-month IV || Surface dynamics | Parallel or nonlinear movement of the entire surface | In panic, the whole surface lifts, and near-month IV lifts faster |+**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.+**SABR model parameters**:```α (alpha): initial volatility level, around 0.2-0.5diff --git a/agent/tests/quantlib/test_volatility_surface.py b/agent/tests/quantlib/test_volatility_surface.pynew file mode 100644index 000000000..c1035864f--- /dev/null+++ b/agent/tests/quantlib/test_volatility_surface.py@@ -0,0 +1,163 @@+"""Implied-volatility surface grid construction and public tool exposure."""++from __future__ import annotations++import copy+import json+import math++import pytest++from src.quantlib.volatility import implied_volatility_surface+from src.tools.quantlib_tool import QuantlibCallTool+++def _point(strike, expiry, iv):+ return {+ "strike": strike,+ "time_to_expiry": expiry,+ "implied_volatility": iv,+ }+++def _rectangle():+ return [+ _point(90.0, 0.1, 0.25),+ _point(110.0, 0.1, 0.35),+ _point(90.0, 0.2, 0.30),+ _point(110.0, 0.2, 0.40),+ ]+++def test_observed_anchors_and_input_order_are_deterministic():+ observations = _rectangle()+ original = copy.deepcopy(observations)++ first = implied_volatility_surface(observations, spot=100.0)+ second = implied_volatility_surface(list(reversed(observations)), spot=100.0)++ assert first == second+ assert observations == original+ assert first["strikes"] == [90.0, 110.0]+ assert first["expiries"] == [0.1, 0.2]+ assert first["interpolation"] == {+ "strike": "linear_iv_log_moneyness",+ "expiry": "linear_total_variance",+ "extrapolation": "rejected",+ }+ assert [point["source"] for point in first["points"]] == ["observed"] * 4+ assert [point["implied_volatility"] for point in first["points"]] == [+ 0.25,+ 0.35,+ 0.30,+ 0.40,+ ]+++def test_strike_grid_uses_log_moneyness_not_arithmetic_strike():+ strike = math.sqrt(90.0 * 110.0)++ result = implied_volatility_surface(+ [_point(90.0, 0.1, 0.25), _point(110.0, 0.1, 0.35)],+ spot=100.0,+ strikes=[strike],+ )++ point = result["points"][0]+ assert point["source"] == "interpolated"+ assert point["implied_volatility"] == pytest.approx(0.30)+ assert point["total_variance"] == pytest.approx(0.30**2 * 0.1)+++def test_expiry_grid_interpolates_total_variance_not_raw_iv():+ observations = [_point(100.0, 0.1, 0.20), _point(100.0, 0.2, 0.40)]++ result = implied_volatility_surface(observations, spot=100.0, expiries=[0.15])++ point = result["points"][0]+ lower_variance = 0.20**2 * 0.1+ upper_variance = 0.40**2 * 0.2+ expected_variance = (lower_variance + upper_variance) / 2.0+ assert point["total_variance"] == pytest.approx(expected_variance)+ assert point["implied_volatility"] == pytest.approx(math.sqrt(expected_variance / 0.15))+ assert point["implied_volatility"] != pytest.approx(0.30)+++def test_interpolation_requires_coverage_on_each_adjacent_slice():+ observations = [+ _point(90.0, 0.1, 0.20),+ _point(100.0, 0.1, 0.25),+ _point(100.0, 0.2, 0.30),+ _point(110.0, 0.2, 0.35),+ ]++ with pytest.raises(ValueError, match="no extrapolation"):+ implied_volatility_surface(observations, spot=100.0, strikes=[95.0], expiries=[0.15])++[email protected]("grid", [{"strikes": [120.0]}, {"expiries": [0.3]}])+def test_grid_outside_observed_domain_is_rejected(grid):+ with pytest.raises(ValueError, match="no extrapolation"):+ implied_volatility_surface(_rectangle(), spot=100.0, **grid)+++def test_duplicate_expiry_strike_quotes_are_rejected_even_when_identical():+ observations = _rectangle()+ observations.append(_point(90.0, 0.1, 0.25))++ with pytest.raises(ValueError, match="duplicate"):+ implied_volatility_surface(observations, spot=100.0)+++ ("field", "value"),+ [+ ("strike", 0.0),+ ("strike", math.nan),+ ("strike", True),+ ("time_to_expiry", 0.0),+ ("time_to_expiry", math.inf),+ ("implied_volatility", -0.01),+ ("implied_volatility", math.nan),+ ("implied_volatility", False),+ ],+)+def test_invalid_observation_values_are_rejected(field, value):+ observations = _rectangle()+ observations[0][field] = value++ with pytest.raises(ValueError):+ implied_volatility_surface(observations, spot=100.0)+++def test_empty_inputs_and_invalid_spot_are_rejected():+ with pytest.raises(ValueError, match="at least one"):+ implied_volatility_surface([], spot=100.0)+ with pytest.raises(ValueError, match="spot"):+ implied_volatility_surface(_rectangle(), spot=0.0)+ with pytest.raises(ValueError, match="grid"):+ implied_volatility_surface(_rectangle(), spot=100.0, strikes=[])+++def test_quantlib_tool_lists_and_calls_surface_builder():+ tool = QuantlibCallTool()+ listed = json.loads(tool.execute(action="list", module="volatility"))++ assert "implied_volatility_surface" in {item["name"] for item in listed["functions"]}+ called = json.loads(+ tool.execute(+ action="call",+ module="volatility",+ function="implied_volatility_surface",+ kwargs={+ "observations": _rectangle(),+ "spot": 100.0,+ "expiries": [0.15],+ "strikes": [100.0],+ },+ )+ )++ assert called["ok"] is True+ assert called["result"]["points"][0]["source"] == "interpolated"+ assert called["result"]["interpolation"]["extrapolation"] == "rejected"diff --git a/guides/capabilities.md b/guides/capabilities.mdindex 56beacfa8..57fbdac9e 100644--- a/guides/capabilities.md+++ b/guides/capabilities.md@@ -318,7 +318,7 @@ The shared backtest market classifier recognizes `BTC/USD`, `ETH/USD`,</details><details>-<summary><b>Quant Library</b> <sub>309 tested functions across 25 modules, callable from every transport</sub></summary>+<summary><b>Quant Library</b> <sub>310 tested functions across 25 modules, callable from every transport</sub></summary>`src/quantlib` holds one tested implementation of each piece of finance math theagent needs. Skills **import** these rather than carrying formulas insidediff --git a/guides/project.md b/guides/project.mdindex 25cb55f0b..f1ae64622 100644--- a/guides/project.md+++ b/guides/project.md@@ -41,7 +41,7 @@ Vibe-Trading is part of the **[HKUDS](https://github.com/HKUDS)** agent ecosyste| **Hypothesis Registry** | Durable research hypotheses with lifecycle status, data sources, skills, run-card links, and invalidation notes | Backend MVP Shipped || **Research Autopilot** | Manual-first research loop: hypothesis → deterministic backtest → evidence report | Phase 1–3 Shipped || **Data Bridge** | Bring-your-own data: local CSV/Parquet/SQL connectors with schema mapping | Local loader Shipped |-| **Options Lab** | Multi-leg payoff chart, Greeks dashboard and spot × IV scenario explorer | Available at `/options`. Volatility surface planned. |+| **Options Lab** | Multi-leg payoff chart, Greeks dashboard and spot × IV scenario explorer | Available at `/options`. Deterministic IV surface grids are available through the quantlib tool; interactive visualization is still planned. || **Portfolio Studio** | Consolidated holdings, risk X-ray, constrained turnover-aware optimization and snapshot-based allocation proposals | Available. Portfolio proposals show value changes for user-supplied target weights. || **Paper trading** | Persistent daily simulated accounts and a stateless paper step | Daily accounts since 0.1.17. Five-minute A-share steps since 0.1.19. || **Research artifacts** | Search, save and revise dated conclusions with evidence | Available since 0.1.19 via Web, CLI, API and agent tools. |