Skip to content

"Vibe-Trading: Your Personal Trading Agent"

test(options-chain): keep the original envelope tests beside the new expiration validation

Haozhe Wu8aebb7e72352
diff --git a/agent/src/tools/options_chain_tool.py b/agent/src/tools/options_chain_tool.py
index f32da944c..db0e15d49 100644
--- a/agent/src/tools/options_chain_tool.py
+++ b/agent/src/tools/options_chain_tool.py
@@ -117,9 +117,12 @@ class OptionsChainTool(BaseTool):
)
options = result.get("options") or []
if not isinstance(options, list) or not options:
+ # The date IS listed (checked above), so this is Yahoo
+ # returning no chain block for it — not an unlisted ticker.
return _error(
- "no option chain found for the requested expiration — "
- "the ticker may have no listed options"
+ f"no option chain returned for expiration "
+ f"{normalized_expiration} although Yahoo lists that date; "
+ f"retry, or pick another expiration from: {dates[:8]}"
)
block = options[0]
if not isinstance(block, dict):
diff --git a/agent/tests/test_options_chain_tool.py b/agent/tests/test_options_chain_tool.py
index dd4f6314c..44fa6b69a 100644
--- a/agent/tests/test_options_chain_tool.py
+++ b/agent/tests/test_options_chain_tool.py
@@ -1,6 +1,7 @@
-"""Tests for get_options_chain: expiration validation, empty ticker, exceptions.
+"""Tests for the get_options_chain tool.
-Yahoo Finance ``get_options`` is mocked so no test reaches a live endpoint.
+All HTTP is mocked at ``yahoo_client.get_options`` (the client function the tool
+imports), so no test ever reaches a live Yahoo endpoint.
"""
from __future__ import annotations
@@ -8,213 +9,220 @@ from __future__ import annotations
import json
from unittest.mock import patch
-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},
- ],
- }],
+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,
+ }
+ ],
+ }
+ ],
}
- 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()
+
+
+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"]
+
+
+class TestExplicitExpirationValidation:
+ """An explicit ``expiration`` must match what Yahoo actually returned.
+
+ Yahoo answers a ``date`` it does not list with the default (nearest)
+ chain, so before this validation a wrong-cycle date came back as
+ ``ok: true`` with another expiration's contracts — or zero contracts —
+ and nothing in the envelope said so.
+ """
+
+ def test_explicit_valid_expiration_passes_validation(self):
+ with patch.object(oc.yahoo_client, "get_options", return_value=_sample_result()):
+ out = oc.OptionsChainTool().execute(ticker="AAPL.US", expiration=1750000000)
+ payload = json.loads(out)
+ assert payload["ok"] is True
+ assert payload["data"]["expiration"] == 1750000000
+ assert payload["data"]["calls_count"] == 1
+ assert payload["data"]["puts_count"] == 1
+
+ def test_invalid_expiration_returns_error_with_available_dates(self):
+ with patch.object(oc.yahoo_client, "get_options", return_value=_sample_result()):
+ out = oc.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 "1750000000" in payload["error"]
+
+ def test_explicit_expiration_without_expiration_dates_is_malformed(self):
+ result_no_dates = {"options": [{"expirationDate": 1750000000, "calls": [], "puts": []}]}
+ with patch.object(oc.yahoo_client, "get_options", return_value=result_no_dates):
+ out = oc.OptionsChainTool().execute(ticker="AAPL.US", expiration=1750000000)
+ payload = json.loads(out)
+ assert payload["ok"] is False
+ assert "malformed" in payload["error"].lower()
+
+ def test_expiration_dates_not_a_list_is_malformed(self):
+ malformed = {"expirationDates": "not-a-list", "options": []}
+ with patch.object(oc.yahoo_client, "get_options", return_value=malformed):
+ out = oc.OptionsChainTool().execute(ticker="AAPL.US", expiration=1750000000)
+ payload = json.loads(out)
+ assert payload["ok"] is False
+ assert "malformed" in payload["error"].lower()
+
+ def test_listed_expiration_with_empty_options_is_an_error(self):
+ """Listed date but no chain block: an error, not ok:true with 0 contracts."""
+ no_options = {"expirationDates": [1750000000], "options": []}
+ with patch.object(oc.yahoo_client, "get_options", return_value=no_options):
+ out = oc.OptionsChainTool().execute(ticker="AAPL.US", expiration=1750000000)
+ payload = json.loads(out)
+ assert payload["ok"] is False
+ assert "no option chain" in payload["error"].lower()
+ assert "1750000000" in payload["error"]
+
+ def test_block_expiration_mismatch_is_an_error(self):
+ mismatch = {
+ "expirationDates": [1750000000, 1750604800],
+ "options": [{"expirationDate": 1750604800, "calls": [], "puts": []}],
+ }
+ with patch.object(oc.yahoo_client, "get_options", return_value=mismatch):
+ out = oc.OptionsChainTool().execute(ticker="AAPL.US", expiration=1750000000)
+ payload = json.loads(out)
+ assert payload["ok"] is False
+ assert "did not match" in payload["error"]
+ assert "1750604800" in payload["error"]
+
+ def test_non_dict_options_block_is_malformed_not_a_crash(self):
+ malformed = {
+ "expirationDates": [1750000000],
+ "options": [None, {"expirationDate": 1750000000, "calls": [], "puts": []}],
+ }
+ with patch.object(oc.yahoo_client, "get_options", return_value=malformed):
+ out = oc.OptionsChainTool().execute(ticker="AAPL.US", expiration=1750000000)
+ payload = json.loads(out)
+ assert payload["ok"] is False
+ assert "malformed" in payload["error"].lower()
+
+ def test_omitted_expiration_is_not_validated(self):
+ """No expiration → nearest chain, passthrough; an empty result stays ok."""
+ with patch.object(oc.yahoo_client, "get_options", return_value={"expirationDates": [], "options": []}):
+ out = oc.OptionsChainTool().execute(ticker="AAPL.US")
+ payload = json.loads(out)
+ assert payload["ok"] is True
+ assert payload["data"]["calls_count"] == 0