Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(options-chain): validate explicit expiration against available dates

cgycorey70116fe7500d
diff --git a/agent/src/tools/options_chain_tool.py b/agent/src/tools/options_chain_tool.py
index 5c3c273c9..f32da944c 100644
--- a/agent/src/tools/options_chain_tool.py
+++ b/agent/src/tools/options_chain_tool.py
@@ -97,6 +97,42 @@ class OptionsChainTool(BaseTool):
except Exception as exc: # noqa: BLE001 - surface as error envelope
return _error(f"yahoo options request failed: {exc}")
+ # When the caller explicitly requested an expiration, validate that
+ # Yahoo returned a chain for that exact expiration. A non-matching
+ # expiration returns an empty or stale chain silently, which is
+ # misleading. The tool owns the guarantee that its envelope
+ # corresponds to the caller's requested expiration; the Yahoo client
+ # only guarantees raw data.
+ if normalized_expiration is not None:
+ dates = result.get("expirationDates")
+ if not isinstance(dates, list):
+ return _error(
+ "malformed Yahoo response: expirationDates is not a list"
+ )
+ if normalized_expiration not in dates:
+ return _error(
+ f"expiration {normalized_expiration} is not among the "
+ f"available dates; available: {dates[:8]}"
+ f"{'...' if len(dates) > 8 else ''}"
+ )
+ options = result.get("options") or []
+ if not isinstance(options, list) or not options:
+ return _error(
+ "no option chain found for the requested expiration — "
+ "the ticker may have no listed options"
+ )
+ block = options[0]
+ if not isinstance(block, dict):
+ return _error(
+ "malformed Yahoo response: options block is not a dict"
+ )
+ block_date = block.get("expirationDate")
+ if block_date != normalized_expiration:
+ return _error(
+ f"expiration {normalized_expiration} did not match the "
+ f"returned chain (block expiration is {block_date})"
+ )
+
return _success(ticker, result)
@@ -104,6 +140,8 @@ def _coerce_expiration(value: Any) -> Optional[int]:
"""Coerce an epoch-second expiration to ``int``; ``None`` when absent/bad."""
if value is None:
return None
+ if isinstance(value, bool):
+ return None
try:
return int(value)
except (TypeError, ValueError, OverflowError):
@@ -116,7 +154,7 @@ def _success(ticker: str, result: Dict[str, Any]) -> str:
epoch for epoch in (result.get("expirationDates") or []) if epoch is not None
]
options = result.get("options") or []
- block = options[0] if options else {}
+ block = options[0] if options and isinstance(options[0], dict) else {}
calls = _contracts(block.get("calls"))
puts = _contracts(block.get("puts"))
diff --git a/agent/tests/test_options_chain_tool.py b/agent/tests/test_options_chain_tool.py
index f4ad8d520..dd4f6314c 100644
--- a/agent/tests/test_options_chain_tool.py
+++ b/agent/tests/test_options_chain_tool.py
@@ -1,7 +1,6 @@
-"""Tests for the get_options_chain tool.
+"""Tests for get_options_chain: expiration validation, empty ticker, exceptions.
-All HTTP is mocked at ``yahoo_client.get_options`` (the client function the tool
-imports), so no test ever reaches a live Yahoo endpoint.
+Yahoo Finance ``get_options`` is mocked so no test reaches a live endpoint.
"""
from __future__ import annotations
@@ -9,136 +8,213 @@ from __future__ import annotations
import json
from unittest.mock import patch
-from src.tools import options_chain_tool as oc
-
-
-def _sample_result() -> dict:
- return {
- "expirationDates": [1750000000, 1750604800],
- "strikes": [190.0, 195.0, 200.0],
- "options": [
- {
- "expirationDate": 1750000000,
- "calls": [
- {
- "contractSymbol": "AAPL250101C00190000",
- "strike": 190.0,
- "lastPrice": 12.5,
- "bid": 12.3,
- "ask": 12.7,
- "volume": 1500,
- "openInterest": 8000,
- "impliedVolatility": 0.2841,
- "inTheMoney": True,
- "expiration": 1750000000,
- }
- ],
- "puts": [
- {
- "contractSymbol": "AAPL250101P00190000",
- "strike": 190.0,
- "lastPrice": 3.1,
- "bid": 3.0,
- "ask": 3.2,
- "volume": 900,
- "openInterest": 4200,
- "impliedVolatility": 0.3012,
- "inTheMoney": False,
- "expiration": 1750000000,
- }
- ],
- }
- ],
+from src.tools import options_chain_tool as oct
+from src.tools.options_chain_tool import OptionsChainTool
+
+_SAMPLE_RESULT = {
+ "expirationDates": [1787270400, 1787529600, 1787702400],
+ "options": [{
+ "expirationDate": 1787270400,
+ "calls": [{
+ "contractSymbol": "AAPL260821C00110000",
+ "strike": 110.0,
+ "lastPrice": 200.96,
+ "bid": 199.0,
+ "ask": 201.0,
+ "volume": 10,
+ "openInterest": 500,
+ "impliedVolatility": 0.25,
+ "inTheMoney": True,
+ "expiration": 1787270400,
+ }],
+ "puts": [{
+ "contractSymbol": "AAPL260821P00110000",
+ "strike": 110.0,
+ "lastPrice": 0.05,
+ "bid": 0.0,
+ "ask": 0.10,
+ "volume": 100,
+ "openInterest": 5000,
+ "impliedVolatility": 0.30,
+ "inTheMoney": False,
+ "expiration": 1787270400,
+ }],
+ }],
+}
+
+
+def test_success_with_valid_expiration():
+ with patch.object(oct.yahoo_client, "get_options", return_value=_SAMPLE_RESULT):
+ out = OptionsChainTool().execute(ticker="AAPL.US", expiration=1787270400)
+ payload = json.loads(out)
+ assert payload["ok"] is True
+ assert payload["data"]["calls_count"] == 1
+ assert payload["data"]["puts_count"] == 1
+
+
+def test_success_without_expiration_returns_nearest():
+ with patch.object(oct.yahoo_client, "get_options", return_value=_SAMPLE_RESULT):
+ out = OptionsChainTool().execute(ticker="AAPL.US")
+ payload = json.loads(out)
+ assert payload["ok"] is True
+
+
+def test_invalid_expiration_returns_error_with_available_dates():
+ """When the requested expiration is not in the available dates list,
+ the error must surface that with the available dates."""
+ with patch.object(oct.yahoo_client, "get_options", return_value=_SAMPLE_RESULT):
+ out = OptionsChainTool().execute(ticker="AAPL.US", expiration=9999999999)
+ payload = json.loads(out)
+ assert payload["ok"] is False
+ assert "not among the available" in payload["error"]
+ assert "1787270400" in payload["error"]
+
+
+def test_empty_ticker_returns_error():
+ out = OptionsChainTool().execute(ticker="")
+ payload = json.loads(out)
+ assert payload["ok"] is False
+ assert "ticker" in payload["error"].lower()
+
+
+def test_bad_expiration_format_returns_error():
+ out = OptionsChainTool().execute(ticker="AAPL.US", expiration="not-an-int")
+ payload = json.loads(out)
+ assert payload["ok"] is False
+ assert "epoch" in payload["error"].lower()
+
+
+def test_yahoo_request_failure_is_caught():
+ with patch.object(
+ oct.yahoo_client, "get_options", side_effect=RuntimeError("HTTP 429")
+ ):
+ out = OptionsChainTool().execute(ticker="AAPL.US")
+ payload = json.loads(out)
+ assert payload["ok"] is False
+ assert "429" in payload["error"]
+
+
+def test_contract_normalization():
+ """Yahoo camelCase fields are mapped to snake_case and capped at 60 per side."""
+ result = {
+ "expirationDates": [1787270400],
+ "options": [{
+ "expirationDate": 1787270400,
+ "calls": [
+ {"contractSymbol": "AAPL260821C00110000", "strike": 110.0,
+ "lastPrice": 200.96, "bid": 199.0, "ask": 201.0,
+ "volume": 10, "openInterest": 500, "impliedVolatility": 0.25,
+ "inTheMoney": True, "expiration": 1787270400},
+ ] * 65, # 65 contracts — must be capped to 60
+ "puts": [
+ {"contractSymbol": "AAPL260821P00110000", "strike": 110.0,
+ "lastPrice": 0.05, "bid": 0.0, "ask": 0.10,
+ "volume": 100, "openInterest": 5000, "impliedVolatility": 0.30,
+ "inTheMoney": False, "expiration": 1787270400},
+ ],
+ }],
}
-
-
-class TestOptionsChainSuccess:
- """Happy-path envelope shape and field normalization."""
-
- def test_success_envelope_normalizes_contracts(self):
- with patch.object(
- oc.yahoo_client, "get_options", return_value=_sample_result()
- ) as mock_get:
- out = oc.OptionsChainTool().execute(ticker="AAPL.US")
-
- payload = json.loads(out)
- assert payload["ok"] is True
- assert payload["market"] == "us"
- assert payload["source"] == "yahoo"
-
- data = payload["data"]
- assert data["ticker"] == "AAPL.US"
- assert data["expiration"] == 1750000000
- assert data["expirations"] == [1750000000, 1750604800]
- assert data["calls_count"] == 1
- assert data["puts_count"] == 1
-
- call = data["calls"][0]
- assert call["contract_symbol"] == "AAPL250101C00190000"
- assert call["strike"] == 190.0
- assert call["implied_volatility"] == 0.2841
- assert call["open_interest"] == 8000
- assert call["in_the_money"] is True
-
- put = data["puts"][0]
- assert put["in_the_money"] is False
- assert put["bid"] == 3.0
-
- # Ticker flows through unchanged; no expiration -> nearest.
- _, kwargs = mock_get.call_args
- assert kwargs["expiration"] is None
-
- def test_explicit_expiration_passed_through(self):
- with patch.object(
- oc.yahoo_client, "get_options", return_value=_sample_result()
- ) as mock_get:
- oc.OptionsChainTool().execute(ticker="AAPL", expiration="1750000000")
- _, kwargs = mock_get.call_args
- assert kwargs["expiration"] == 1750000000
-
- def test_empty_chain_is_ok_with_zero_contracts(self):
- with patch.object(oc.yahoo_client, "get_options", return_value={}):
- out = oc.OptionsChainTool().execute(ticker="AAPL")
- payload = json.loads(out)
- assert payload["ok"] is True
- assert payload["data"]["calls"] == []
- assert payload["data"]["puts"] == []
- assert payload["data"]["expiration"] is None
-
- def test_contracts_capped(self):
- bloated = _sample_result()
- bloated["options"][0]["calls"] = [
- {"strike": float(i)} for i in range(500)
- ]
- with patch.object(oc.yahoo_client, "get_options", return_value=bloated):
- out = oc.OptionsChainTool().execute(ticker="AAPL")
- payload = json.loads(out)
- assert payload["data"]["calls_count"] == oc._MAX_CONTRACTS_PER_SIDE
-
-
-class TestOptionsChainErrors:
- """Error envelopes: missing ticker, bad expiration, upstream failure."""
-
- def test_missing_ticker_returns_error_envelope(self):
- out = oc.OptionsChainTool().execute(ticker=" ")
- payload = json.loads(out)
- assert payload["ok"] is False
- assert "required" in payload["error"]
-
- def test_bad_expiration_returns_error_envelope(self):
- out = oc.OptionsChainTool().execute(ticker="AAPL", expiration="not-an-int")
- payload = json.loads(out)
- assert payload["ok"] is False
- assert "epoch" in payload["error"]
-
- def test_upstream_failure_becomes_error_envelope(self):
- with patch.object(
- oc.yahoo_client,
- "get_options",
- side_effect=RuntimeError("HTTP 429 banned"),
- ):
- out = oc.OptionsChainTool().execute(ticker="AAPL")
- payload = json.loads(out)
- assert payload["ok"] is False
- assert "yahoo options request failed" in payload["error"]
- assert "429" in payload["error"]
+ with patch.object(oct.yahoo_client, "get_options", return_value=result):
+ out = OptionsChainTool().execute(ticker="AAPL.US", expiration=1787270400)
+ payload = json.loads(out)
+ assert payload["ok"] is True
+ assert payload["data"]["calls_count"] == 60 # capped
+ assert payload["data"]["puts_count"] == 1
+ # Verify snake_case mapping
+ call = payload["data"]["calls"][0]
+ assert call["contract_symbol"] == "AAPL260821C00110000"
+ assert call["last_price"] == 200.96
+ assert call["implied_volatility"] == 0.25
+ assert call["in_the_money"] is True
+
+
+def test_omitted_expiration_passthrough():
+ """When no expiration is passed, the nearest is used — passthrough, no validation."""
+ result = {
+ "expirationDates": [1787270400],
+ "options": [{
+ "expirationDate": 1787270400,
+ "calls": [{"contractSymbol": "X", "strike": 100, "lastPrice": 1,
+ "bid": 1, "ask": 1, "volume": 1, "openInterest": 1,
+ "impliedVolatility": 0.2, "inTheMoney": False,
+ "expiration": 1787270400}],
+ "puts": [],
+ }],
+ }
+ with patch.object(oct.yahoo_client, "get_options", return_value=result):
+ out = OptionsChainTool().execute(ticker="AAPL.US")
+ payload = json.loads(out)
+ assert payload["ok"] is True
+ assert payload["data"]["calls_count"] == 1
+ assert payload["data"]["expirations"] == [1787270400]
+
+
+def test_omitted_expiration_not_validated():
+ """When no expiration is passed, the nearest is used — no validation."""
+ result_empty = {"expirationDates": [], "options": []}
+ with patch.object(oct.yahoo_client, "get_options", return_value=result_empty):
+ out = OptionsChainTool().execute(ticker="AAPL.US")
+ payload = json.loads(out)
+ assert payload["ok"] is True
+ assert payload["data"]["calls_count"] == 0
+
+
+def test_explicit_expiration_without_expiration_dates_returns_malformed_error():
+ """When Yahoo result lacks expirationDates entirely, surface a malformed error."""
+ result_no_dates = {"options": [
+ {"expirationDate": 1787270400, "calls": [], "puts": []}
+ ]}
+ with patch.object(oct.yahoo_client, "get_options", return_value=result_no_dates):
+ out = OptionsChainTool().execute(ticker="AAPL.US", expiration=1787270400)
+ payload = json.loads(out)
+ assert payload["ok"] is False
+ assert "malformed" in payload["error"].lower()
+
+
+def test_malformed_expiration_dates_not_list():
+ """expirationDates as a non-list must be rejected as malformed upstream."""
+ malformed = {"expirationDates": "not-a-list", "options": []}
+ with patch.object(oct.yahoo_client, "get_options", return_value=malformed):
+ out = OptionsChainTool().execute(ticker="AAPL.US", expiration=1787270400)
+ payload = json.loads(out)
+ assert payload["ok"] is False
+ assert "malformed" in payload["error"].lower()
+
+
+def test_empty_options_with_explicit_expiration():
+ """An empty options list with an explicit expiration must return an error,
+ not a silent ok:true with 0 contracts."""
+ no_options = {"expirationDates": [1787270400], "options": []}
+ with patch.object(oct.yahoo_client, "get_options", return_value=no_options):
+ out = OptionsChainTool().execute(ticker="AAPL.US", expiration=1787270400)
+ payload = json.loads(out)
+ assert payload["ok"] is False
+ assert "no option chain" in payload["error"].lower()
+
+
+def test_block_expiration_mismatch():
+ """When options[0].expirationDate differs from the requested expiration,
+ the error must surface the mismatch."""
+ mismatch = {
+ "expirationDates": [1787270400, 1787529600],
+ "options": [{"expirationDate": 1787529600, "calls": [], "puts": []}],
+ }
+ with patch.object(oct.yahoo_client, "get_options", return_value=mismatch):
+ out = OptionsChainTool().execute(ticker="AAPL.US", expiration=1787270400)
+ payload = json.loads(out)
+ assert payload["ok"] is False
+ assert "did not match" in payload["error"]
+ assert "1787529600" in payload["error"]
+
+
+def test_malformed_options_block_returns_error_not_500():
+ """A non-dict entry in options must not crash the tool — return an error envelope."""
+ malformed = {
+ "expirationDates": [1787270400],
+ "options": [None, {"expirationDate": 1787270400, "calls": [], "puts": []}],
+ }
+ with patch.object(oct.yahoo_client, "get_options", return_value=malformed):
+ out = OptionsChainTool().execute(ticker="AAPL.US", expiration=1787270400)
+ payload = json.loads(out)
+ assert payload["ok"] is False
+ assert "malformed" in payload["error"].lower()
diff --git a/agent/tests/test_tools_type_value_safety.py b/agent/tests/test_tools_type_value_safety.py
index 3faf9273e..57d5fd0f1 100644
--- a/agent/tests/test_tools_type_value_safety.py
+++ b/agent/tests/test_tools_type_value_safety.py
@@ -81,6 +81,8 @@ def test_clamp_helpers_survive_non_finite_and_preserve_finite_values() -> None:
assert symbol_clamp_limit(float("inf")) == 10
assert _coerce_expiration(float("inf")) is None
assert _coerce_expiration(float("-inf")) is None
+ assert _coerce_expiration(True) is None
+ assert _coerce_expiration(False) is None
# Finite requests must be untouched by the hardening.
assert _clamp_lookback(7) == 7