Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(options): add analytic payoff and scenario tool

Haozhe Wu73967e476cd3
diff --git a/README.md b/README.md
index 9bfea7c29..cd2b57209 100644
--- a/README.md
+++ b/README.md
@@ -1098,7 +1098,7 @@ with `--host` / `--port`.
</details>
-**MCP tools exposed (54):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `analyze_options`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_margin_trading`, `get_block_trades`, `get_shareholder_count`, `get_lockup_expiry`, `get_sector_info`, `get_research_reports`, `get_stock_news`, `get_sec_filings`, `get_financial_statements`, `get_options_chain`, `get_stock_profile`, `screen_market`, `search_symbol`, `get_macro_series`, `iwencai_search`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`.
+**MCP tools exposed (55):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_margin_trading`, `get_block_trades`, `get_shareholder_count`, `get_lockup_expiry`, `get_sector_info`, `get_research_reports`, `get_stock_news`, `get_sec_filings`, `get_financial_statements`, `get_options_chain`, `get_stock_profile`, `screen_market`, `search_symbol`, `get_macro_series`, `iwencai_search`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`.
### SWARM external MCP tools
@@ -1389,7 +1389,7 @@ Vibe-Trading/
├── agent/ # Backend (Python)
│ ├── cli/ # CLI package — interactive TUI + subcommands
│ ├── api_server.py # FastAPI server — runs, sessions, upload, swarm, SSE
-│ ├── mcp_server.py # MCP server — 54 tools for OpenClaw / Claude Desktop
+│ ├── mcp_server.py # MCP server — 55 tools for OpenClaw / Claude Desktop
│ │
│ ├── src/
│ │ ├── agent/ # ReAct agent core
@@ -1494,7 +1494,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** | Vol surface, Greeks dashboard, payoff/scenario explorer | Planned |
+| **Options Lab** | Vol surface, Greeks dashboard, payoff/scenario explorer | Analytic payoff/scenario tool **Shipped**; surface/dashboard Planned |
| **Portfolio Studio** | Risk x-ray, constraints, turnover-aware optimizer, rebalance notes | Turnover-aware optimizer **Shipped 0.1.11**; rest Planned |
| **Alpha Zoo** | 462 pre-built alphas (Qlib 158 + Kakushadze 101 + GTJA 191 + academic + fundamental) with one-line bench, agent integration, and Web UI | **Shipped 0.1.8**, extended through 0.1.12 |
| **Strategy Development Manager** | Register papers / broker research as factors & strategies with a persistent store + automated IC/Sharpe decay lifecycle | **Shipped 0.1.11** |
diff --git a/agent/SKILL.md b/agent/SKILL.md
index 8c1e363cc..3dc98ddf8 100644
--- a/agent/SKILL.md
+++ b/agent/SKILL.md
@@ -130,7 +130,7 @@ Comprehensive knowledge base covering:
Use `load_skill(name)` to access full methodology docs with code templates.
-## Available MCP Tools (54)
+## Available MCP Tools (55)
| Tool | Description | API Key |
|------|-------------|---------|
@@ -143,6 +143,7 @@ Use `load_skill(name)` to access full methodology docs with code templates.
| `backtest` | Run vectorized backtest engine | None* |
| `factor_analysis` | IC/IR analysis + layered backtest | None* |
| `analyze_options` | Black-Scholes price + Greeks | None |
+| `analyze_options_payoff` | Multi-leg expiry payoff + spot/IV scenarios | None |
| `pattern_recognition` | Detect chart patterns (H&S, double top, etc.) | None |
| `get_market_data` | Fetch OHLCV data (auto-detect + ordered fallback across 24 sources) | None* |
| `get_fund_flow` | Capital fund-flow (main/retail net inflow) | None* |
@@ -353,3 +354,6 @@ Without `ALLOW_SESSION_MCP_SERVERS=1`, any `mcpServers` key in `session.config`
**Options analysis:**
> Use analyze_options: spot=100, strike=105, 90 days, vol=25%, rate=3%
+
+**Multi-leg options payoff:**
+> Use analyze_options_payoff for a 95/105 bull call spread at spot 100 with 30 days remaining: long one 95 call at premium 8, short one 105 call at premium 3, multiplier 100, commission rate 0.001.
diff --git a/agent/backtest/options_payoff.py b/agent/backtest/options_payoff.py
new file mode 100644
index 000000000..4ed553047
--- /dev/null
+++ b/agent/backtest/options_payoff.py
@@ -0,0 +1,496 @@
+"""Deterministic payoff and scenario math for multi-leg option strategies.
+
+The expiry summary is solved from the strategy's piecewise-linear payoff,
+independently of the caller's display grid. This keeps breakevens and finite
+extrema correct even when a chart grid omits one or more strikes.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+import numpy as np
+
+from backtest.engines.options_portfolio import bs_price
+
+_BREAKEVEN_TOLERANCE = 1e-9
+_DEFAULT_GRID_POINTS = 2001
+
+
+@dataclass(frozen=True)
+class OptionLeg:
+ """One European option leg in a payoff calculation.
+
+ Attributes:
+ option_type: ``"call"`` or ``"put"``.
+ strike: Positive strike price.
+ qty: Signed contract quantity; positive is long and negative is short.
+ premium: Optional per-share entry premium. When omitted, Black-Scholes
+ pricing is used at the supplied entry conditions.
+ """
+
+ option_type: str
+ strike: float
+ qty: int
+ premium: float | None = None
+
+
+@dataclass(frozen=True)
+class PayoffReport:
+ """Expiry payoff curve and analytic strategy summary.
+
+ Attributes:
+ spot_grid: Caller-supplied display spots.
+ payoff: Expiry P&L at each display spot.
+ net_premium: Signed gross entry premium; positive is a debit.
+ entry_commission: Entry commission paid in account currency.
+ entry_cost: Gross premium plus entry commission.
+ breakevens: Isolated non-negative expiry spots where P&L is zero.
+ breakeven_intervals: Continuous zero-P&L spot intervals. A ``None``
+ upper bound represents a flat zero-payoff right tail.
+ max_profit: Analytic maximum, or positive infinity when unbounded.
+ max_loss: Analytic minimum P&L, or negative infinity when unbounded.
+ profit_unbounded: Whether right-tail profit is unbounded.
+ loss_unbounded: Whether right-tail loss is unbounded.
+ """
+
+ spot_grid: np.ndarray
+ payoff: np.ndarray
+ net_premium: float
+ entry_commission: float
+ entry_cost: float
+ breakevens: list[float]
+ breakeven_intervals: list[tuple[float, float | None]]
+ max_profit: float
+ max_loss: float
+ profit_unbounded: bool
+ loss_unbounded: bool
+
+
+def _intrinsic(option_type: str, spots: np.ndarray, strike: float) -> np.ndarray:
+ """Return vectorized intrinsic values for one option leg."""
+ if option_type == "call":
+ return np.maximum(spots - strike, 0.0)
+ return np.maximum(strike - spots, 0.0)
+
+
+def _validate_legs(legs: list[OptionLeg]) -> None:
+ """Validate option-leg fields at the calculation boundary."""
+ if not legs:
+ raise ValueError("at least one leg is required")
+ for index, leg in enumerate(legs):
+ if leg.option_type not in ("call", "put"):
+ raise ValueError(f"legs[{index}].option_type must be 'call' or 'put'")
+ if not np.isfinite(leg.strike) or leg.strike <= 0:
+ raise ValueError(f"legs[{index}].strike must be positive and finite")
+ if isinstance(leg.qty, bool) or not isinstance(leg.qty, (int, np.integer)):
+ raise ValueError(f"legs[{index}].qty must be a non-zero integer")
+ if leg.qty == 0:
+ raise ValueError(f"legs[{index}].qty must be non-zero")
+ if leg.premium is not None and (not np.isfinite(leg.premium) or leg.premium < 0):
+ raise ValueError(f"legs[{index}].premium must be non-negative and finite")
+
+
+def _validate_market_inputs(
+ *,
+ entry_spot: float,
+ time_to_expiry: float,
+ rate: float,
+ iv: float,
+ multiplier: float,
+ commission_rate: float,
+) -> None:
+ """Validate common market and cost inputs."""
+ values = {
+ "entry_spot": entry_spot,
+ "time_to_expiry": time_to_expiry,
+ "rate": rate,
+ "iv": iv,
+ "multiplier": multiplier,
+ "commission_rate": commission_rate,
+ }
+ for name, value in values.items():
+ if not np.isfinite(value):
+ raise ValueError(f"{name} must be finite")
+ if entry_spot <= 0:
+ raise ValueError("entry_spot must be positive")
+ if time_to_expiry < 0:
+ raise ValueError("time_to_expiry must be non-negative")
+ if iv <= 0:
+ raise ValueError("iv must be positive")
+ if multiplier <= 0:
+ raise ValueError("multiplier must be positive")
+ if not 0 <= commission_rate < 1:
+ raise ValueError("commission_rate must be in [0, 1)")
+
+
+def _validate_grid(values: np.ndarray, *, name: str, allow_zero: bool) -> np.ndarray:
+ """Return a validated one-dimensional numeric grid."""
+ grid = np.asarray(values, dtype=float)
+ if grid.ndim != 1 or grid.size == 0:
+ raise ValueError(f"{name} must be a non-empty one-dimensional array")
+ if not np.isfinite(grid).all():
+ raise ValueError(f"{name} must contain only finite values")
+ if allow_zero:
+ invalid = grid < 0
+ else:
+ invalid = grid <= 0
+ if invalid.any():
+ qualifier = "non-negative" if allow_zero else "positive"
+ raise ValueError(f"{name} values must be {qualifier}")
+ return grid
+
+
+def _leg_premiums(
+ legs: list[OptionLeg],
+ entry_spot: float,
+ time_to_expiry: float,
+ rate: float,
+ iv: float,
+) -> np.ndarray:
+ """Resolve explicit or Black-Scholes entry premiums for every leg."""
+ premiums = []
+ for leg in legs:
+ premium = (
+ leg.premium
+ if leg.premium is not None
+ else bs_price(
+ entry_spot,
+ leg.strike,
+ time_to_expiry,
+ rate,
+ iv,
+ leg.option_type,
+ )
+ )
+ premiums.append(float(premium))
+ return np.asarray(premiums, dtype=float)
+
+
+def _entry_costs(
+ legs: list[OptionLeg],
+ premiums: np.ndarray,
+ multiplier: float,
+ commission_rate: float,
+) -> tuple[float, float, float]:
+ """Return gross premium, commission, and total signed entry cost."""
+ net_premium = float(sum(leg.qty * premium * multiplier for leg, premium in zip(legs, premiums, strict=True)))
+ entry_commission = float(
+ sum(abs(leg.qty) * premium * multiplier * commission_rate for leg, premium in zip(legs, premiums, strict=True))
+ )
+ return net_premium, entry_commission, net_premium + entry_commission
+
+
+def _payoff_at_spots(
+ legs: list[OptionLeg],
+ spots: np.ndarray,
+ *,
+ multiplier: float,
+ entry_cost: float,
+) -> np.ndarray:
+ """Calculate expiry P&L at arbitrary non-negative spots."""
+ intrinsic = np.zeros(len(spots), dtype=float)
+ for leg in legs:
+ intrinsic += leg.qty * _intrinsic(leg.option_type, spots, leg.strike)
+ return intrinsic * multiplier - entry_cost
+
+
+def _critical_points(legs: list[OptionLeg]) -> np.ndarray:
+ """Return every finite point at which expiry-payoff slope may change."""
+ return np.asarray(sorted({0.0, *(float(leg.strike) for leg in legs)}))
+
+
+def _analytic_breakevens(
+ critical_spots: np.ndarray,
+ critical_payoff: np.ndarray,
+ right_slope: float,
+) -> tuple[list[float], list[tuple[float, float | None]]]:
+ """Solve isolated roots and continuous zero intervals analytically."""
+ roots: list[float] = []
+ intervals: list[tuple[float, float | None]] = []
+
+ for index, (spot, value) in enumerate(zip(critical_spots, critical_payoff, strict=True)):
+ if index == len(critical_spots) - 1:
+ continue
+ next_spot = float(critical_spots[index + 1])
+ next_value = float(critical_payoff[index + 1])
+ value = float(value)
+ if abs(value) <= _BREAKEVEN_TOLERANCE and abs(next_value) <= _BREAKEVEN_TOLERANCE:
+ intervals.append((float(spot), next_spot))
+ elif value * next_value < 0:
+ fraction = value / (value - next_value)
+ roots.append(float(spot + fraction * (next_spot - spot)))
+
+ right_spot = float(critical_spots[-1])
+ right_value = float(critical_payoff[-1])
+ if abs(right_slope) <= _BREAKEVEN_TOLERANCE and abs(right_value) <= _BREAKEVEN_TOLERANCE:
+ intervals.append((right_spot, None))
+ elif abs(right_slope) > _BREAKEVEN_TOLERANCE:
+ right_root = right_spot - right_value / right_slope
+ if right_root > right_spot + _BREAKEVEN_TOLERANCE:
+ roots.append(float(right_root))
+
+ intervals = _merge_zero_intervals(intervals)
+ for spot, value in zip(critical_spots, critical_payoff, strict=True):
+ spot = float(spot)
+ if abs(float(value)) <= _BREAKEVEN_TOLERANCE and not _in_zero_interval(spot, intervals):
+ roots.append(spot)
+
+ roots.sort()
+ deduped: list[float] = []
+ for root in roots:
+ if not deduped or abs(root - deduped[-1]) > _BREAKEVEN_TOLERANCE:
+ deduped.append(root)
+ return deduped, intervals
+
+
+def _merge_zero_intervals(
+ intervals: list[tuple[float, float | None]],
+) -> list[tuple[float, float | None]]:
+ """Merge adjacent continuous zero-payoff intervals."""
+ merged: list[tuple[float, float | None]] = []
+ for start, end in intervals:
+ if not merged:
+ merged.append((start, end))
+ continue
+ previous_start, previous_end = merged[-1]
+ if previous_end is not None and abs(previous_end - start) <= _BREAKEVEN_TOLERANCE:
+ merged[-1] = (previous_start, end)
+ else:
+ merged.append((start, end))
+ return merged
+
+
+def _in_zero_interval(spot: float, intervals: list[tuple[float, float | None]]) -> bool:
+ """Return whether a spot belongs to a continuous zero-payoff interval."""
+ for start, end in intervals:
+ if spot < start - _BREAKEVEN_TOLERANCE:
+ continue
+ if end is None or spot <= end + _BREAKEVEN_TOLERANCE:
+ return True
+ return False
+
+
+def expiry_payoff(
+ legs: list[OptionLeg],
+ spot_grid: np.ndarray,
+ *,
+ entry_spot: float,
+ time_to_expiry: float,
+ rate: float = 0.05,
+ iv: float = 0.3,
+ multiplier: float = 1.0,
+ commission_rate: float = 0.001,
+) -> PayoffReport:
+ """Calculate an expiry payoff curve and analytic risk summary.
+
+ Premiums are pinned at entry. An explicit per-share premium wins over the
+ Black-Scholes price. Entry commission follows the existing options engine:
+ long legs pay ``premium * (1 + commission_rate)`` and short legs receive
+ ``premium * (1 - commission_rate)``. Expiry settlement has no exit fee.
+
+ Args:
+ legs: Signed option legs in the strategy.
+ spot_grid: Non-negative display spots. Summary values do not depend on
+ this grid containing strikes or breakevens.
+ entry_spot: Underlying spot at entry.
+ time_to_expiry: Years until expiry at entry.
+ rate: Annual continuously compounded risk-free rate.
+ iv: Annualized volatility used for legs without explicit premiums.
+ multiplier: Currency multiplier per option price unit.
+ commission_rate: Entry commission as a fraction of gross premium.
+
+ Returns:
+ Payoff report with the display curve and analytic extrema/breakevens.
+
+ Raises:
+ ValueError: If a leg, grid, market input, or cost input is invalid.
+ """
+ _validate_legs(legs)
+ _validate_market_inputs(
+ entry_spot=entry_spot,
+ time_to_expiry=time_to_expiry,
+ rate=rate,
+ iv=iv,
+ multiplier=multiplier,
+ commission_rate=commission_rate,
+ )
+ display_spots = _validate_grid(spot_grid, name="spot_grid", allow_zero=True)
+ premiums = _leg_premiums(legs, entry_spot, time_to_expiry, rate, iv)
+ net_premium, entry_commission, entry_cost = _entry_costs(legs, premiums, multiplier, commission_rate)
+
+ payoff = _payoff_at_spots(
+ legs,
+ display_spots,
+ multiplier=multiplier,
+ entry_cost=entry_cost,
+ )
+
+ critical_spots = _critical_points(legs)
+ critical_payoff = _payoff_at_spots(
+ legs,
+ critical_spots,
+ multiplier=multiplier,
+ entry_cost=entry_cost,
+ )
+ right_slope = float(sum(leg.qty for leg in legs if leg.option_type == "call") * multiplier)
+ profit_unbounded = right_slope > _BREAKEVEN_TOLERANCE
+ loss_unbounded = right_slope < -_BREAKEVEN_TOLERANCE
+ max_profit = float("inf") if profit_unbounded else float(np.max(critical_payoff))
+ max_loss = float("-inf") if loss_unbounded else float(np.min(critical_payoff))
+ breakevens, breakeven_intervals = _analytic_breakevens(critical_spots, critical_payoff, right_slope)
+
+ return PayoffReport(
+ spot_grid=display_spots,
+ payoff=payoff,
+ net_premium=net_premium,
+ entry_commission=entry_commission,
+ entry_cost=entry_cost,
+ breakevens=breakevens,
+ breakeven_intervals=breakeven_intervals,
+ max_profit=max_profit,
+ max_loss=max_loss,
+ profit_unbounded=profit_unbounded,
+ loss_unbounded=loss_unbounded,
+ )
+
+
+def default_spot_grid(
+ center: float,
+ half_width_pct: float = 0.5,
+ points: int = _DEFAULT_GRID_POINTS,
+) -> np.ndarray:
+ """Build a symmetric non-negative display grid around an entry spot.
+
+ Args:
+ center: Positive central spot.
+ half_width_pct: Fraction of ``center`` added to and subtracted from the
+ bounds.
+ points: Number of points, at least two.
+
+ Returns:
+ Increasing NumPy spot grid.
+
+ Raises:
+ ValueError: If a parameter is non-finite or outside its valid range.
+ """
+ if not np.isfinite(center) or center <= 0:
+ raise ValueError("center must be positive and finite")
+ if not np.isfinite(half_width_pct) or half_width_pct <= 0:
+ raise ValueError("half_width_pct must be positive and finite")
+ if isinstance(points, bool) or not isinstance(points, (int, np.integer)):
+ raise ValueError("points must be an integer")
+ if points < 2:
+ raise ValueError("points must be at least 2")
+ lower = max(center * (1.0 - half_width_pct), 0.0)
+ upper = center * (1.0 + half_width_pct)
+ return np.linspace(lower, upper, int(points))
+
+
+def scenario_grid(
+ legs: list[OptionLeg],
+ spot_grid: np.ndarray,
+ iv_values: np.ndarray,
+ *,
+ entry_spot: float,
+ time_to_expiry: float,
+ rate: float = 0.05,
+ entry_iv: float = 0.3,
+ multiplier: float = 1.0,
+ commission_rate: float = 0.001,
+) -> np.ndarray:
+ """Calculate pre-expiry mark-to-market P&L over spot and volatility.
+
+ The entry cost is pinned once using the entry spot/IV and includes entry
+ commission. Scenario values are marks, so no hypothetical closing
+ commission is deducted.
+
+ Args:
+ legs: Signed option legs in the strategy.
+ spot_grid: Non-negative scenario spots.
+ iv_values: Positive annualized volatility scenarios.
+ entry_spot: Underlying spot at entry.
+ time_to_expiry: Years remaining in every scenario.
+ rate: Annual continuously compounded risk-free rate.
+ entry_iv: Annualized volatility used to price the entry.
+ multiplier: Currency multiplier per option price unit.
+ commission_rate: Entry commission as a fraction of gross premium.
+
+ Returns:
+ Matrix shaped ``(len(iv_values), len(spot_grid))``.
+
+ Raises:
+ ValueError: If a leg, grid, market input, or cost input is invalid.
+ """
+ _validate_legs(legs)
+ _validate_market_inputs(
+ entry_spot=entry_spot,
+ time_to_expiry=time_to_expiry,
+ rate=rate,
+ iv=entry_iv,
+ multiplier=multiplier,
+ commission_rate=commission_rate,
+ )
+ spots = _validate_grid(spot_grid, name="spot_grid", allow_zero=True)
+ ivs = _validate_grid(iv_values, name="iv_values", allow_zero=False)
+ entry_premiums = _leg_premiums(legs, entry_spot, time_to_expiry, rate, entry_iv)
+ _, _, entry_cost = _entry_costs(legs, entry_premiums, multiplier, commission_rate)
+
+ grid = np.zeros((len(ivs), len(spots)), dtype=float)
+ for iv_row, iv_now in enumerate(ivs):
+ for spot_col, spot_now in enumerate(spots):
+ marked_value = 0.0
+ for leg in legs:
+ marked_value += (
+ leg.qty
+ * bs_price(
+ float(spot_now),
+ leg.strike,
+ time_to_expiry,
+ rate,
+ float(iv_now),
+ leg.option_type,
+ )
+ * multiplier
+ )
+ grid[iv_row, spot_col] = marked_value - entry_cost
+ return grid
+
+
+def bull_call_spread(lower_strike: float, upper_strike: float, qty: int = 1) -> list[OptionLeg]:
+ """Build a long lower-strike/short upper-strike call spread."""
+ if upper_strike <= lower_strike:
+ raise ValueError("upper strike must sit above lower strike")
+ if isinstance(qty, bool) or not isinstance(qty, (int, np.integer)) or qty <= 0:
+ raise ValueError("qty must be positive")
+ return [
+ OptionLeg("call", lower_strike, qty),
+ OptionLeg("call", upper_strike, -qty),
+ ]
+
+
+def long_straddle(strike: float, qty: int = 1) -> list[OptionLeg]:
+ """Build a long call plus long put at the same strike."""
+ if isinstance(qty, bool) or not isinstance(qty, (int, np.integer)) or qty <= 0:
+ raise ValueError("qty must be positive")
+ return [OptionLeg("call", strike, qty), OptionLeg("put", strike, qty)]
+
+
+def iron_condor(
+ put_wing: float,
+ put_body: float,
+ call_body: float,
+ call_wing: float,
+ qty: int = 1,
+) -> list[OptionLeg]:
+ """Build a defined-risk short iron condor."""
+ if not (put_wing < put_body < call_body < call_wing):
+ raise ValueError("strikes must nest as put_wing < put_body < call_body < call_wing")
+ if isinstance(qty, bool) or not isinstance(qty, (int, np.integer)) or qty <= 0:
+ raise ValueError("qty must be positive")
+ return [
+ OptionLeg("put", put_wing, qty),
+ OptionLeg("put", put_body, -qty),
+ OptionLeg("call", call_body, -qty),
+ OptionLeg("call", call_wing, qty),
+ ]
diff --git a/agent/mcp_server.py b/agent/mcp_server.py
index 990f3d69d..17005e922 100644
--- a/agent/mcp_server.py
+++ b/agent/mcp_server.py
@@ -6,7 +6,7 @@ Zero API key required for HK/US/crypto research markets (yfinance, OKX,
AKShare are free). Trading connector tools are profile-scoped and require the
selected connector's own local app or OAuth setup.
-Surfaces 54 tools: skills, research goals, backtest/factor/options/pattern
+Surfaces 55 tools: skills, research goals, backtest/factor/options/pattern
analysis, market data, fundamentals & capital-flow & news & discovery
(get_fund_flow / get_dragon_tiger / get_northbound_flow / get_margin_trading /
get_block_trades / get_shareholder_count / get_lockup_expiry / get_sector_info /
@@ -782,6 +782,64 @@ def analyze_options(
)
+def analyze_options_payoff(
+ legs: list[dict[str, Any]],
+ entry_spot: float,
+ expiry_days: float,
+ risk_free_rate: float = 0.05,
+ volatility: float = 0.3,
+ multiplier: float = 1.0,
+ commission_rate: float = 0.001,
+ spot_min: float | None = None,
+ spot_max: float | None = None,
+ spot_points: int = 121,
+ scenario_iv_values: list[float] | None = None,
+) -> str:
+ """Analyze a multi-leg option strategy's payoff and spot/IV scenarios.
+
+ The expiry summary is analytic rather than chart-grid dependent. Returns
+ entry debit/credit and commission, breakevens, bounded or unbounded maximum
+ profit/loss, an expiry curve, and a Black-Scholes spot/IV P&L matrix.
+ Research only; this tool cannot place orders.
+
+ Args:
+ legs: Option leg objects with ``option_type`` (call/put), positive
+ ``strike``, signed integer ``qty``, and optional per-share
+ ``premium``. Positive quantity is long; negative is short.
+ entry_spot: Positive underlying spot at entry.
+ expiry_days: Non-negative calendar days to expiry.
+ risk_free_rate: Annual continuously compounded risk-free rate.
+ volatility: Annualized entry volatility, e.g. 0.3 for 30%.
+ multiplier: Currency multiplier per option price unit.
+ commission_rate: Entry commission fraction, aligned with the options
+ backtest engine.
+ spot_min: Optional non-negative chart/scenario lower bound.
+ spot_max: Optional chart/scenario upper bound above ``spot_min``.
+ spot_points: Display-grid size from 21 through 501.
+ scenario_iv_values: Optional positive annualized IV scenarios. Omit for
+ 50%, 75%, 100%, 125%, and 150% of entry volatility.
+ """
+ params: dict[str, Any] = {
+ "legs": legs,
+ "entry_spot": entry_spot,
+ "expiry_days": expiry_days,
+ "risk_free_rate": risk_free_rate,
+ "volatility": volatility,
+ "multiplier": multiplier,
+ "commission_rate": commission_rate,
+ "spot_points": spot_points,
+ }
+ if spot_min is not None:
+ params["spot_min"] = spot_min
+ if spot_max is not None:
+ params["spot_max"] = spot_max
+ if scenario_iv_values is not None:
+ params["scenario_iv_values"] = scenario_iv_values
+ registry = _get_registry()
+ return registry.execute("options_payoff", params)
+
+
# ---------------------------------------------------------------------------
# Pattern recognition tool
# ---------------------------------------------------------------------------
diff --git a/agent/src/skills/options-payoff/SKILL.md b/agent/src/skills/options-payoff/SKILL.md
index ad2f9146f..d43a934e9 100644
--- a/agent/src/skills/options-payoff/SKILL.md
+++ b/agent/src/skills/options-payoff/SKILL.md
@@ -16,6 +16,15 @@ This skill is designed for option strategy analysis scenarios within the Vibe-Tr
**Constraint**: For research and backtesting only. Do not output live trading instructions, in line with the project's guardrails.
+### Built-in execution tool
+
+Load this skill for methodology, then call `options_payoff` for production
+calculations. Pass signed `legs` (`qty > 0` long, `qty < 0` short),
+`entry_spot`, and `expiry_days`; optionally pass actual per-share premiums,
+multiplier, commission, chart bounds, and IV scenarios. The tool returns an
+expiry curve, a spot × IV scenario matrix, and analytic breakeven/max-risk
+results that do not depend on the display grid containing every strike.
+
---
## 1. Supported Strategy Types
@@ -224,24 +233,25 @@ The gap between the theoretical value curve and the expiry curve equals the rema
### 3.3 Break-Even Points
-Numerically solve for the roots of `Payoff(S_T) = 0`:
-- Use `scipy.optimize.brentq` to solve within adjacent intervals where the sign changes
+Expiry payoff is piecewise linear. Solve `Payoff(S_T) = 0` on intervals formed
+by `S=0`, every unique strike, and the right tail. Do not search only the chart
+grid: a narrow grid can miss a valid root beyond its bounds.
+
- Single-leg strategies:
- Long Call BEP = K + premium
- Long Put BEP = K - premium
- Short Call BEP = K + premium received
- Short Put BEP = K - premium received
-- Multi-leg strategies: solve numerically, possibly resulting in 0 to 2 BEPs
+- Multi-leg strategies can have more than two breakevens; inspect every strike
+ interval and the unbounded right interval.
### 3.4 Max Profit / Max Loss
-```python
-max_profit = max(payoff_curve) # If inf, label as "Unlimited"
-max_loss = min(payoff_curve) # If -inf, label as "Unlimited"
-
-# Corresponding underlying price region
-profit_range = S_range[payoff_curve > 0]
-```
+Evaluate payoff at `S=0` and every unique strike. Those are all finite points
+where slope can change, so finite extrema occur in that set. Then inspect the
+right-tail slope: positive means unlimited profit, negative means unlimited
+loss, and zero means the payoff remains flat. Never derive max profit/loss only
+from sampled chart points.
### 3.5 P&L Under Different Volatility Scenarios
diff --git a/agent/src/tools/options_payoff_tool.py b/agent/src/tools/options_payoff_tool.py
new file mode 100644
index 000000000..b4b117e6e
--- /dev/null
+++ b/agent/src/tools/options_payoff_tool.py
@@ -0,0 +1,357 @@
+"""Agent tool for deterministic multi-leg option payoff analysis."""
+
+from __future__ import annotations
+
+import json
+import math
+from typing import Any
+
+import numpy as np
+
+from backtest.options_payoff import OptionLeg, expiry_payoff, scenario_grid
+from src.agent.tools import BaseTool
+
+_MAX_LEGS = 20
+_MIN_SPOT_POINTS = 21
+_MAX_SPOT_POINTS = 501
+_DEFAULT_SPOT_POINTS = 121
+_MAX_IV_SCENARIOS = 9
+
+
+class OptionsPayoffTool(BaseTool):
+ """Analyze expiry payoff and spot/IV scenarios for an option strategy."""
+
+ name = "options_payoff"
+ description = (
+ "Analyze a European multi-leg option strategy using deterministic "
+ "piecewise-linear expiry math and Black-Scholes spot/IV scenarios. "
+ "Returns entry debit/credit and commission, analytic breakevens, "
+ "bounded or unbounded max profit/loss, an expiry payoff curve, and a "
+ "scenario P&L matrix. Research only; does not place orders."
+ )
+ repeatable = True
+ parameters = {
+ "type": "object",
+ "properties": {
+ "legs": {
+ "type": "array",
+ "minItems": 1,
+ "maxItems": _MAX_LEGS,
+ "description": (
+ "Signed option legs. Positive qty is long; negative qty is "
+ "short. Omit premium to price that leg with Black-Scholes."
+ ),
+ "items": {
+ "type": "object",
+ "properties": {
+ "option_type": {"type": "string", "enum": ["call", "put"]},
+ "strike": {"type": "number", "exclusiveMinimum": 0},
+ "qty": {"type": "integer"},
+ "premium": {
+ "type": "number",
+ "minimum": 0,
+ "description": "Optional per-share entry premium.",
+ },
+ },
+ "required": ["option_type", "strike", "qty"],
+ },
+ },
+ "entry_spot": {
+ "type": "number",
+ "exclusiveMinimum": 0,
+ "description": "Underlying spot at entry.",
+ },
+ "expiry_days": {
+ "type": "number",
+ "minimum": 0,
+ "description": "Calendar days remaining to expiry.",
+ },
+ "risk_free_rate": {
+ "type": "number",
+ "default": 0.05,
+ "description": "Annual continuously compounded risk-free rate.",
+ },
+ "volatility": {
+ "type": "number",
+ "exclusiveMinimum": 0,
+ "default": 0.3,
+ "description": "Annualized entry volatility, e.g. 0.3 for 30%.",
+ },
+ "multiplier": {
+ "type": "number",
+ "exclusiveMinimum": 0,
+ "default": 1.0,
+ "description": "Currency multiplier per option price unit.",
+ },
+ "commission_rate": {
+ "type": "number",
+ "minimum": 0,
+ "exclusiveMaximum": 1,
+ "default": 0.001,
+ "description": "Entry commission fraction, aligned with the backtest engine.",
+ },
+ "spot_min": {
+ "type": "number",
+ "minimum": 0,
+ "description": "Optional lower chart/scenario spot bound.",
+ },
+ "spot_max": {
+ "type": "number",
+ "exclusiveMinimum": 0,
+ "description": "Optional upper chart/scenario spot bound.",
+ },
+ "spot_points": {
+ "type": "integer",
+ "minimum": _MIN_SPOT_POINTS,
+ "maximum": _MAX_SPOT_POINTS,
+ "default": _DEFAULT_SPOT_POINTS,
+ },
+ "scenario_iv_values": {
+ "type": "array",
+ "minItems": 1,
+ "maxItems": _MAX_IV_SCENARIOS,
+ "items": {"type": "number", "exclusiveMinimum": 0},
+ "description": (
+ "Optional annualized IV scenarios. Defaults to 50%, 75%, 100%, 125%, and 150% of entry volatility."
+ ),
+ },
+ },
+ "required": ["legs", "entry_spot", "expiry_days"],
+ }
+
+ def execute(self, **kwargs: Any) -> str:
+ """Run payoff and scenario analysis.
+
+ Args:
+ **kwargs: Inputs described by :attr:`parameters`.
+
+ Returns:
+ JSON envelope with summary, expiry curve, scenario grid, and model
+ limitations. Invalid inputs return a JSON error envelope.
+ """
+ try:
+ legs = _coerce_legs(kwargs.get("legs"))
+ entry_spot = _required_float(kwargs, "entry_spot")
+ expiry_days = _required_float(kwargs, "expiry_days")
+ rate = _optional_float(kwargs, "risk_free_rate", 0.05)
+ volatility = _optional_float(kwargs, "volatility", 0.3)
+ multiplier = _optional_float(kwargs, "multiplier", 1.0)
+ commission_rate = _optional_float(kwargs, "commission_rate", 0.001)
+ spot_points = _spot_points(kwargs.get("spot_points"))
+ spot_min, spot_max = _spot_bounds(kwargs, legs, entry_spot)
+ iv_values = _scenario_ivs(kwargs.get("scenario_iv_values"), volatility)
+
+ spots = np.linspace(spot_min, spot_max, spot_points)
+ time_to_expiry = expiry_days / 365.0
+ report = expiry_payoff(
+ legs,
+ spots,
+ entry_spot=entry_spot,
+ time_to_expiry=time_to_expiry,
+ rate=rate,
+ iv=volatility,
+ multiplier=multiplier,
+ commission_rate=commission_rate,
+ )
+ scenarios = scenario_grid(
+ legs,
+ spots,
+ iv_values,
+ entry_spot=entry_spot,
+ time_to_expiry=time_to_expiry,
+ rate=rate,
+ entry_iv=volatility,
+ multiplier=multiplier,
+ commission_rate=commission_rate,
+ )
+ except (KeyError, TypeError, ValueError, OverflowError) as exc:
+ return _error(str(exc))
+
+ payload = {
+ "status": "ok",
+ "tool": self.name,
+ "inputs": {
+ "legs": [
+ {
+ "option_type": leg.option_type,
+ "strike": leg.strike,
+ "qty": leg.qty,
+ "premium": leg.premium,
+ }
+ for leg in legs
+ ],
+ "entry_spot": entry_spot,
+ "expiry_days": expiry_days,
+ "risk_free_rate": rate,
+ "volatility": volatility,
+ "multiplier": multiplier,
+ "commission_rate": commission_rate,
+ },
+ "summary": {
+ "net_premium": _rounded(report.net_premium),
+ "entry_commission": _rounded(report.entry_commission),
+ "entry_cost": _rounded(report.entry_cost),
+ "entry_side": (
+ "flat" if abs(report.entry_cost) <= 1e-12 else "debit" if report.entry_cost > 0 else "credit"
+ ),
+ "breakevens": [_rounded(value) for value in report.breakevens],
+ "breakeven_intervals": [
+ {
+ "start": _rounded(start),
+ "end": None if end is None else _rounded(end),
+ }
+ for start, end in report.breakeven_intervals
+ ],
+ "max_profit": (None if report.profit_unbounded else _rounded(report.max_profit)),
+ "max_loss": (None if report.loss_unbounded else _rounded(report.max_loss)),
+ "profit_unbounded": report.profit_unbounded,
+ "loss_unbounded": report.loss_unbounded,
+ },
+ "expiry_curve": {
+ "spot": _rounded_array(report.spot_grid),
+ "pnl": _rounded_array(report.payoff),
+ },
+ "scenario_grid": {
+ "iv_values": _rounded_array(iv_values),
+ "spot": _rounded_array(report.spot_grid),
+ "pnl": [_rounded_array(row) for row in np.asarray(scenarios, dtype=float)],
+ },
+ "limitations": [
+ "European Black-Scholes marks with constant rate and volatility per scenario.",
+ "No dividends, early exercise, assignment, slippage, or margin model.",
+ "Scenario P&L is mark-to-market and does not deduct a hypothetical exit commission.",
+ ],
+ }
+ return json.dumps(payload, ensure_ascii=False, allow_nan=False)
+
+
+def _coerce_legs(raw: Any) -> list[OptionLeg]:
+ """Parse and validate raw JSON-style leg objects."""
+ if not isinstance(raw, list) or not raw:
+ raise ValueError("legs must be a non-empty array")
+ if len(raw) > _MAX_LEGS:
+ raise ValueError(f"legs may contain at most {_MAX_LEGS} entries")
+
+ legs: list[OptionLeg] = []
+ for index, item in enumerate(raw):
+ if not isinstance(item, dict):
+ raise ValueError(f"legs[{index}] must be an object")
+ option_type = str(item.get("option_type") or "").strip().lower()
+ try:
+ strike = float(item["strike"])
+ raw_qty = item["qty"]
+ qty_number = float(raw_qty)
+ except (KeyError, TypeError, ValueError, OverflowError) as exc:
+ raise ValueError(f"legs[{index}] has invalid strike or qty: {exc}") from exc
+ if isinstance(raw_qty, bool) or not qty_number.is_integer():
+ raise ValueError(f"legs[{index}].qty must be a non-zero integer")
+ qty = int(qty_number)
+ raw_premium = item.get("premium")
+ try:
+ premium = None if raw_premium is None else float(raw_premium)
+ except (TypeError, ValueError, OverflowError) as exc:
+ raise ValueError(f"legs[{index}].premium must be numeric or null") from exc
+ legs.append(OptionLeg(option_type, strike, qty, premium))
+ return legs
+
+
+def _required_float(kwargs: dict[str, Any], name: str) -> float:
+ """Read a required finite float."""
+ if name not in kwargs or kwargs[name] is None or kwargs[name] == "":
+ raise ValueError(f"{name} is required")
+ try:
+ value = float(kwargs[name])
+ except (TypeError, ValueError, OverflowError) as exc:
+ raise ValueError(f"{name} must be numeric") from exc
+ if not math.isfinite(value):
+ raise ValueError(f"{name} must be finite")
+ return value
+
+
+def _optional_float(kwargs: dict[str, Any], name: str, default: float) -> float:
+ """Read an optional finite float, treating null and empty text as omitted."""
+ raw = kwargs.get(name)
+ if raw is None or raw == "":
+ return default
+ try:
+ value = float(raw)
+ except (TypeError, ValueError, OverflowError) as exc:
+ raise ValueError(f"{name} must be numeric") from exc
+ if not math.isfinite(value):
+ raise ValueError(f"{name} must be finite")
+ return value
+
+
+def _spot_points(raw: Any) -> int:
+ """Validate the bounded display-grid size."""
+ if raw is None or raw == "":
+ return _DEFAULT_SPOT_POINTS
+ if isinstance(raw, bool):
+ raise ValueError("spot_points must be an integer")
+ try:
+ numeric = float(raw)
+ except (TypeError, ValueError, OverflowError) as exc:
+ raise ValueError("spot_points must be an integer") from exc
+ if not math.isfinite(numeric) or not numeric.is_integer():
+ raise ValueError("spot_points must be an integer")
+ points = int(numeric)
+ if not _MIN_SPOT_POINTS <= points <= _MAX_SPOT_POINTS:
+ raise ValueError(f"spot_points must be between {_MIN_SPOT_POINTS} and {_MAX_SPOT_POINTS}")
+ return points
+
+
+def _spot_bounds(kwargs: dict[str, Any], legs: list[OptionLeg], entry_spot: float) -> tuple[float, float]:
+ """Resolve explicit chart bounds or safe defaults covering every strike."""
+ reference = [entry_spot, *(leg.strike for leg in legs)]
+ default_min = max(min(reference) * 0.5, 0.0)
+ default_max = max(reference) * 1.5
+ spot_min = _optional_float(kwargs, "spot_min", default_min)
+ spot_max = _optional_float(kwargs, "spot_max", default_max)
+ if spot_min < 0:
+ raise ValueError("spot_min must be non-negative")
+ if spot_max <= spot_min:
+ raise ValueError("spot_max must be greater than spot_min")
+ return spot_min, spot_max
+
+
+def _scenario_ivs(raw: Any, entry_iv: float) -> np.ndarray:
+ """Resolve bounded explicit IV scenarios or the skill's five defaults."""
+ if raw is None:
+ values = [
+ entry_iv * 0.5,
+ entry_iv * 0.75,
+ entry_iv,
+ entry_iv * 1.25,
+ entry_iv * 1.5,
+ ]
+ else:
+ if not isinstance(raw, list) or not raw:
+ raise ValueError("scenario_iv_values must be a non-empty array")
+ if len(raw) > _MAX_IV_SCENARIOS:
+ raise ValueError(f"scenario_iv_values may contain at most {_MAX_IV_SCENARIOS} entries")
+ try:
+ values = [float(value) for value in raw]
+ except (TypeError, ValueError, OverflowError) as exc:
+ raise ValueError("scenario_iv_values must contain numbers") from exc
+ array = np.asarray(values, dtype=float)
+ if not np.isfinite(array).all() or (array <= 0).any():
+ raise ValueError("scenario_iv_values must contain positive finite values")
+ return array
+
+
+def _rounded(value: float) -> float:
+ """Round a finite scalar for stable, compact JSON."""
+ return round(float(value), 6)
+
+
+def _rounded_array(values: np.ndarray) -> list[float]:
+ """Round a numeric array for stable, compact JSON."""
+ return [round(float(value), 6) for value in np.asarray(values).tolist()]
+
+
+def _error(message: str) -> str:
+ """Build a stable error envelope."""
+ return json.dumps(
+ {"status": "error", "tool": "options_payoff", "error": message},
+ ensure_ascii=False,
+ )
diff --git a/agent/tests/test_options_payoff.py b/agent/tests/test_options_payoff.py
new file mode 100644
index 000000000..319a14d19
--- /dev/null
+++ b/agent/tests/test_options_payoff.py
@@ -0,0 +1,256 @@
+"""Regression tests for analytic option payoff and scenario calculations."""
+
+from __future__ import annotations
+
+import numpy as np
+import pytest
+
+from backtest.engines.options_portfolio import bs_price
+from backtest.options_payoff import (
+ OptionLeg,
+ bull_call_spread,
+ default_spot_grid,
+ expiry_payoff,
+ iron_condor,
+ long_straddle,
+ scenario_grid,
+)
+
+RATE = 0.05
+IV = 0.3
+TIME_TO_EXPIRY = 0.5
+
+
+def _grid(center: float = 100.0) -> np.ndarray:
+ """Return a compact display grid for tests."""
+ return default_spot_grid(center, 0.6, points=401)
+
+
+def test_long_call_breakeven_and_payoff() -> None:
+ """A long call has premium-limited loss and unbounded upside."""
+ leg = OptionLeg("call", 100.0, 1)
+ report = expiry_payoff(
+ [leg],
+ _grid(),
+ entry_spot=100.0,
+ time_to_expiry=TIME_TO_EXPIRY,
+ rate=RATE,
+ iv=IV,
+ commission_rate=0.0,
+ )
+
+ premium = bs_price(100.0, 100.0, TIME_TO_EXPIRY, RATE, IV, "call")
+ assert report.net_premium == pytest.approx(premium, rel=1e-9)
+ assert report.entry_commission == 0.0
+ assert report.breakevens == pytest.approx([100.0 + premium], abs=1e-6)
+ assert report.payoff[-1] == pytest.approx(report.spot_grid[-1] - 100.0 - premium, rel=1e-9)
+ assert report.profit_unbounded is True
+ assert report.loss_unbounded is False
+ assert report.max_loss == pytest.approx(-premium, rel=1e-9)
+
+
+def test_short_put_breakeven_and_zero_spot_floor() -> None:
+ """A naked short put's finite floor is solved at physically valid spot zero."""
+ leg = OptionLeg("put", 100.0, -1)
+ report = expiry_payoff(
+ [leg],
+ np.array([80.0, 120.0]),
+ entry_spot=100.0,
+ time_to_expiry=TIME_TO_EXPIRY,
+ rate=RATE,
+ iv=IV,
+ commission_rate=0.0,
+ )
+
+ premium = bs_price(100.0, 100.0, TIME_TO_EXPIRY, RATE, IV, "put")
+ assert report.breakevens == pytest.approx([100.0 - premium], abs=1e-6)
+ assert report.max_loss == pytest.approx(premium - 100.0, rel=1e-9)
+ assert report.max_profit == pytest.approx(premium, rel=1e-9)
+
+
+def test_bull_call_spread_shape() -> None:
+ """A bull call spread has analytic capped loss, profit, and one root."""
+ legs = bull_call_spread(95.0, 105.0)
+ report = expiry_payoff(
+ legs,
+ _grid(),
+ entry_spot=100.0,
+ time_to_expiry=TIME_TO_EXPIRY,
+ rate=RATE,
+ iv=IV,
+ commission_rate=0.0,
+ )
+
+ debit = bs_price(100.0, 95.0, TIME_TO_EXPIRY, RATE, IV, "call") - bs_price(
+ 100.0, 105.0, TIME_TO_EXPIRY, RATE, IV, "call"
+ )
+ assert report.max_profit == pytest.approx(10.0 - debit, abs=1e-6)
+ assert report.max_loss == pytest.approx(-debit, abs=1e-6)
+ assert report.breakevens == pytest.approx([95.0 + debit], abs=1e-6)
+
+
+def test_extrema_do_not_depend_on_display_grid_containing_strikes() -> None:
+ """A butterfly peak at an omitted strike is still included analytically."""
+ legs = [
+ OptionLeg("call", 90.0, 1, premium=0.0),
+ OptionLeg("call", 100.0, -2, premium=0.0),
+ OptionLeg("call", 110.0, 1, premium=0.0),
+ ]
+ report = expiry_payoff(
+ legs,
+ np.array([80.0, 120.0]),
+ entry_spot=100.0,
+ time_to_expiry=TIME_TO_EXPIRY,
+ commission_rate=0.0,
+ )
+
+ assert report.payoff.tolist() == pytest.approx([0.0, 0.0])
+ assert report.max_profit == pytest.approx(10.0)
+ assert report.max_loss == pytest.approx(0.0)
+ assert report.breakevens == []
+ assert report.breakeven_intervals == [(0.0, 90.0), (110.0, None)]
+
+
+def test_breakeven_can_sit_outside_display_grid() -> None:
+ """Right-tail roots are solved analytically beyond a narrow chart grid."""
+ report = expiry_payoff(
+ [OptionLeg("call", 100.0, 1, premium=10.0)],
+ np.array([80.0, 90.0]),
+ entry_spot=100.0,
+ time_to_expiry=TIME_TO_EXPIRY,
+ commission_rate=0.0,
+ )
+
+ assert report.breakevens == pytest.approx([110.0])
+
+
+def test_entry_commission_matches_options_engine_cash_semantics() -> None:
+ """Long and short entry fees both increase signed strategy entry cost."""
+ legs = [
+ OptionLeg("call", 95.0, 1, premium=8.0),
+ OptionLeg("call", 105.0, -1, premium=3.0),
+ ]
+ report = expiry_payoff(
+ legs,
+ _grid(),
+ entry_spot=100.0,
+ time_to_expiry=TIME_TO_EXPIRY,
+ multiplier=100.0,
+ commission_rate=0.001,
+ )
+
+ assert report.net_premium == pytest.approx(500.0)
+ assert report.entry_commission == pytest.approx(1.1)
+ assert report.entry_cost == pytest.approx(501.1)
+ assert report.breakevens == pytest.approx([100.011])
+ assert report.max_loss == pytest.approx(-501.1)
+ assert report.max_profit == pytest.approx(498.9)
+
+
+def test_long_straddle_two_breakevens() -> None:
+ """A long straddle has one root on either side of its strike."""
+ legs = long_straddle(100.0)
+ report = expiry_payoff(
+ legs,
+ _grid(),
+ entry_spot=100.0,
+ time_to_expiry=TIME_TO_EXPIRY,
+ rate=RATE,
+ iv=IV,
+ commission_rate=0.0,
+ )
+
+ cost = bs_price(100.0, 100.0, TIME_TO_EXPIRY, RATE, IV, "call") + bs_price(
+ 100.0, 100.0, TIME_TO_EXPIRY, RATE, IV, "put"
+ )
+ assert report.breakevens == pytest.approx([100.0 - cost, 100.0 + cost], abs=1e-6)
+
+
+def test_iron_condor_max_profit_inside_body() -> None:
+ """A short iron condor keeps its entry credit between the body strikes."""
+ legs = iron_condor(90.0, 95.0, 105.0, 110.0)
+ report = expiry_payoff(
+ legs,
+ _grid(),
+ entry_spot=100.0,
+ time_to_expiry=TIME_TO_EXPIRY,
+ rate=RATE,
+ iv=IV,
+ commission_rate=0.0,
+ )
+
+ body = (report.spot_grid >= 95.0) & (report.spot_grid <= 105.0)
+ assert np.allclose(report.payoff[body], -report.net_premium)
+ assert report.net_premium < 0
+ assert report.max_profit == pytest.approx(-report.net_premium, abs=1e-6)
+
+
+def test_naked_short_call_marks_unbounded_loss() -> None:
+ """A naked short call uses an explicit unbounded-loss marker."""
+ report = expiry_payoff(
+ [OptionLeg("call", 100.0, -1)],
+ _grid(),
+ entry_spot=100.0,
+ time_to_expiry=TIME_TO_EXPIRY,
+ commission_rate=0.0,
+ )
+
+ assert report.loss_unbounded is True
+ assert report.max_loss == float("-inf")
+ assert report.profit_unbounded is False
+
+
+def test_scenario_entry_cell_equals_negative_entry_commission() -> None:
+ """The entry scenario includes the same opening fee as the engine."""
+ legs = long_straddle(100.0)
+ spots = np.array([95.0, 100.0, 105.0])
+ ivs = np.array([0.2, IV, 0.4])
+ commission_rate = 0.001
+ grid = scenario_grid(
+ legs,
+ spots,
+ ivs,
+ entry_spot=100.0,
+ time_to_expiry=TIME_TO_EXPIRY,
+ rate=RATE,
+ entry_iv=IV,
+ commission_rate=commission_rate,
+ )
+
+ gross = bs_price(100.0, 100.0, TIME_TO_EXPIRY, RATE, IV, "call") + bs_price(
+ 100.0, 100.0, TIME_TO_EXPIRY, RATE, IV, "put"
+ )
+ assert grid[1, 1] == pytest.approx(-gross * commission_rate, abs=1e-9)
+ assert grid[2, 1] > grid[1, 1]
+ assert grid[0, 1] < grid[1, 1]
+
+
+ "legs, grid, error",
+ [
+ ([], np.array([100.0]), "at least one leg"),
+ ([OptionLeg("strangle", 100.0, 1)], np.array([100.0]), "option_type"),
+ ([OptionLeg("call", -1.0, 1)], np.array([100.0]), "strike"),
+ ([OptionLeg("call", 100.0, 0)], np.array([100.0]), "qty"),
+ ([OptionLeg("call", 100.0, 1)], np.array([-1.0]), "non-negative"),
+ ],
+)
+def test_rejects_invalid_legs_and_grids(legs: list[OptionLeg], grid: np.ndarray, error: str) -> None:
+ """Invalid strategy and chart inputs fail before numeric calculation."""
+ with pytest.raises(ValueError, match=error):
+ expiry_payoff(
+ legs,
+ grid,
+ entry_spot=100.0,
+ time_to_expiry=TIME_TO_EXPIRY,
+ )
+
+
+def test_preset_validations() -> None:
+ """Strategy helpers reject reversed strikes and non-positive quantities."""
+ with pytest.raises(ValueError):
+ bull_call_spread(105.0, 95.0)
+ with pytest.raises(ValueError):
+ iron_condor(95.0, 90.0, 105.0, 110.0)
+ with pytest.raises(ValueError):
+ long_straddle(100.0, qty=0)
diff --git a/agent/tests/test_options_payoff_tool.py b/agent/tests/test_options_payoff_tool.py
new file mode 100644
index 000000000..6c2790d76
--- /dev/null
+++ b/agent/tests/test_options_payoff_tool.py
@@ -0,0 +1,136 @@
+"""Tests for the Agent-facing options_payoff tool envelope."""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from src.tools.options_payoff_tool import OptionsPayoffTool
+
+
+def _spread_legs() -> list[dict[str, object]]:
+ """Return a deterministic debit-spread fixture."""
+ return [
+ {"option_type": "call", "strike": 95.0, "qty": 1, "premium": 8.0},
+ {"option_type": "call", "strike": 105.0, "qty": -1, "premium": 3.0},
+ ]
+
+
+def test_tool_returns_analytic_summary_curve_and_scenarios() -> None:
+ """The success envelope is bounded, serializable, and engine-cost aware."""
+ raw = OptionsPayoffTool().execute(
+ legs=_spread_legs(),
+ entry_spot=100.0,
+ expiry_days=30,
+ multiplier=100,
+ commission_rate=0.001,
+ spot_min=80,
+ spot_max=120,
+ spot_points=21,
+ )
+ payload = json.loads(raw)
+
+ assert payload["status"] == "ok"
+ assert payload["tool"] == "options_payoff"
+ assert payload["summary"]["net_premium"] == pytest.approx(500.0)
+ assert payload["summary"]["entry_commission"] == pytest.approx(1.1)
+ assert payload["summary"]["entry_cost"] == pytest.approx(501.1)
+ assert payload["summary"]["breakevens"] == pytest.approx([100.011])
+ assert payload["summary"]["max_profit"] == pytest.approx(498.9)
+ assert payload["summary"]["max_loss"] == pytest.approx(-501.1)
+ assert len(payload["expiry_curve"]["spot"]) == 21
+ assert len(payload["expiry_curve"]["pnl"]) == 21
+ assert len(payload["scenario_grid"]["iv_values"]) == 5
+ assert len(payload["scenario_grid"]["pnl"]) == 5
+ assert all(len(row) == 21 for row in payload["scenario_grid"]["pnl"])
+
+
+def test_unbounded_values_are_json_null_with_explicit_flags() -> None:
+ """Tool output never serializes non-standard Infinity values."""
+ payload = json.loads(
+ OptionsPayoffTool().execute(
+ legs=[
+ {
+ "option_type": "call",
+ "strike": 100,
+ "qty": -1,
+ "premium": 5,
+ }
+ ],
+ entry_spot=100,
+ expiry_days=30,
+ spot_points=21,
+ )
+ )
+
+ assert payload["status"] == "ok"
+ assert payload["summary"]["loss_unbounded"] is True
+ assert payload["summary"]["max_loss"] is None
+
+
+def test_tool_is_auto_discovered_by_the_agent_registry() -> None:
+ """Creating the module is sufficient to expose the read-only Agent tool."""
+ from src.tools import build_registry
+
+ registry = build_registry()
+ tool = registry.get("options_payoff")
+ assert tool is not None
+ assert tool.is_readonly is True
+
+
+def test_mcp_wrapper_exposes_the_same_research_calculation() -> None:
+ """The public MCP wrapper delegates to the Agent tool without mutation."""
+ import mcp_server
+
+ payload = json.loads(
+ mcp_server.analyze_options_payoff(
+ legs=_spread_legs(),
+ entry_spot=100.0,
+ expiry_days=30,
+ multiplier=100.0,
+ commission_rate=0.001,
+ spot_points=21,
+ )
+ )
+ assert payload["status"] == "ok"
+ assert payload["summary"]["breakevens"] == pytest.approx([100.011])
+
+
+ "kwargs, expected",
+ [
+ ({"legs": [], "entry_spot": 100, "expiry_days": 30}, "non-empty"),
+ (
+ {
+ "legs": [{"option_type": "call", "strike": 100, "qty": 1.5}],
+ "entry_spot": 100,
+ "expiry_days": 30,
+ },
+ "integer",
+ ),
+ (
+ {
+ "legs": _spread_legs(),
+ "entry_spot": 100,
+ "expiry_days": 30,
+ "spot_points": 10,
+ },
+ "between",
+ ),
+ (
+ {
+ "legs": _spread_legs(),
+ "entry_spot": 100,
+ "expiry_days": 30,
+ "scenario_iv_values": [0.2, 0.0],
+ },
+ "positive",
+ ),
+ ],
+)
+def test_tool_returns_error_envelopes(kwargs: dict[str, object], expected: str) -> None:
+ """Malformed tool arguments are contained in JSON error envelopes."""
+ payload = json.loads(OptionsPayoffTool().execute(**kwargs))
+ assert payload["status"] == "error"
+ assert expected in payload["error"]
diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.json
index ee3d6b7f8..89f739c8b 100644
--- a/frontend/src/i18n/locales/ar.json
+++ b/frontend/src/i18n/locales/ar.json
@@ -1012,6 +1012,7 @@
"link_autopilot_backtest": "ربط الاختبار العكسي بالبحث التلقائي",
"link_backtest": "ربط الاختبار العكسي بالفرضية",
"load_skill": "تحميل معرفة الاستراتيجية",
+ "options_payoff": "تحليل عائد الخيارات",
"options_pricing": "تسعير الخيارات",
"patch_skill": "تحديث مهارة مخصصة",
"pattern": "اكتشاف أنماط المخطط",
diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json
index 4b2a8e475..6d203f109 100644
--- a/frontend/src/i18n/locales/en.json
+++ b/frontend/src/i18n/locales/en.json
@@ -1012,6 +1012,7 @@
"link_autopilot_backtest": "Link autopilot backtest",
"link_backtest": "Link hypothesis backtest",
"load_skill": "Load strategy knowledge",
+ "options_payoff": "Analyze options payoff",
"options_pricing": "Price options",
"patch_skill": "Update custom skill",
"pattern": "Detect chart patterns",
diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.json
index 85838bb19..0d1557243 100644
--- a/frontend/src/i18n/locales/ja.json
+++ b/frontend/src/i18n/locales/ja.json
@@ -1012,6 +1012,7 @@
"link_autopilot_backtest": "自動リサーチにバックテストを関連付け",
"link_backtest": "仮説にバックテストを関連付け",
"load_skill": "戦略知識を読み込む",
+ "options_payoff": "オプション損益を分析",
"options_pricing": "オプションを評価",
"patch_skill": "カスタムスキルを更新",
"pattern": "チャートパターンを検出",
diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.json
index ee3ca85b3..98b78b13c 100644
--- a/frontend/src/i18n/locales/ko.json
+++ b/frontend/src/i18n/locales/ko.json
@@ -1012,6 +1012,7 @@
"link_autopilot_backtest": "자동 리서치에 백테스트 연결",
"link_backtest": "가설에 백테스트 연결",
"load_skill": "전략 지식 불러오기",
+ "options_payoff": "옵션 손익 분석",
"options_pricing": "옵션 가격 계산",
"patch_skill": "사용자 스킬 업데이트",
"pattern": "차트 패턴 감지",
diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.json
index 4b406f616..dbcabac4e 100644
--- a/frontend/src/i18n/locales/zh-CN.json
+++ b/frontend/src/i18n/locales/zh-CN.json
@@ -1012,6 +1012,7 @@
"link_autopilot_backtest": "关联自动回测",
"link_backtest": "关联假设回测",
"load_skill": "加载策略知识",
+ "options_payoff": "分析期权盈亏",
"options_pricing": "计算期权价格",
"patch_skill": "更新自定义技能",
"pattern": "识别图表形态",
diff --git a/frontend/src/lib/tools.ts b/frontend/src/lib/tools.ts
index 741dbea91..3b9661e13 100644
--- a/frontend/src/lib/tools.ts
+++ b/frontend/src/lib/tools.ts
@@ -12,6 +12,7 @@ export const TOOL_LABELS: Record<string, string> = {
bash: "Run command",
read_url: "Read webpage",
read_document: "Read document",
+ options_payoff: "Analyze options payoff",
get_market_data: "Get market data",
screen_market: "Screen market",
factor_analysis: "Analyze factors",