A successful options data API request can still give you a poor shortlist.
The response contains prices. Your code has to decide which rows deserve further investigation. That means checking the bid and ask, handling missing values, and keeping the contracts that failed your rules so you can explain the result.
I ran the Python screener below against EODHD APIs' AAPL options data on November 24, 2026. It retrieved 312 call contracts in the selected expiration window. Fifty-two passed the numerical filters. The other 260 went into a separate CSV with rejection reasons.
Those 52 are research candidates. Their presence in a file says nothing about whether a broker could fill an order at the recorded prices.
What this options data API tutorial builds
The script retrieves a filtered option-chain snapshot, follows its pages, calculates bid-ask spread as a percentage of midpoint, and exports two files: candidates and rejected contracts. It also saves the source response and retrieval time so you can inspect the evidence behind a shortlist.
If you're building an options research dashboard, a data-quality check, or a screener that someone else needs to audit, that separation matters.
This is a specific workflow built on EODHD APIs. My complete Options Data API guide covers the broader endpoint surface. Here the focus is on turning one response into an explainable screening result.
Disclosure: I work with EODHD APIs on technical content. EODHD links in this article include referral tracking, and I may earn a commission if you subscribe through them.
A bid-ask spread needs a denominator
An option quoted at $2.00 bid and $2.10 ask has a $0.10 spread. The midpoint is $2.05, so the spread is approximately 4.88% of midpoint.
An option quoted at $0.05 bid and $0.15 ask has the same dollar spread. Its midpoint is $0.10, making the relative spread 100%.
midpoint = (bid + ask) / 2
spread_pct = 100 × (ask - bid) / midpoint
The denominator makes these two quotes look very different. It also creates a bias: expensive contracts can look attractive on percentage spread while carrying a large dollar spread. The export retains both measures.
Volume and open interest add context, but neither proves that a contract is liquid. The Options Industry Council's explanation of liquidity emphasizes the two-sided market and available size, and warns against treating volume or open interest as a guarantee.
Our screen uses those activity fields as explicit research preferences. It does not turn them into evidence of an executable market.
Choose the data source before writing the filters
The EODHD options product provides end-of-day and historical data, rather than an intraday execution feed. The options demo supports AAPL and AMZN. Access beyond the demo requires an appropriate paid options subscription; the general free plan does not include options data.
The code uses the contracts endpoint to retrieve a snapshot. An expiration filter selects when contracts expire. It does not select a historical observation date. Historical studies need the separate historical endpoint and observations aligned to the date of each decision.
See the options product and access details before choosing a plan. Use the options API documentation to check the current request parameters.
For this run, I selected AAPL calls expiring from December 15, 2026 through January 23, 2027. That is a manageable research slice, rather than a claim to have downloaded the entire AAPL chain across every expiration.
Set transparent screening rules
The example accepts a row only when it has a positive bid, an ask at least as large as that bid, a relative spread no greater than 10%, volume of at least 10, and open interest of at least 100.
Those thresholds are demonstration settings. They are not universal definitions of liquidity and were not optimized against returns.
| Check | Example rule | What it catches |
|---|---|---|
| Bid and ask | Finite values; bid > 0; ask >= bid | Missing, zero-bid and crossed quotes |
| Relative spread | At most 10% of midpoint | Wide spreads relative to option price |
| Volume | At least 10 | Rows below the chosen activity threshold |
| Open interest | At least 100 | Rows below the chosen outstanding-contract threshold |
An invalid quote and missing open interest can occur on the same row. The script records every failing rule, so rejection counts overlap.
The screen deliberately does not label passing quotes as fresh. It preserves bid_date, ask_date and tradetime for review. A production research pipeline should apply its own documented timestamp policy before promoting a candidate to an execution system.
Run the Python options screener
Install Python 3.10 or later and Requests:
python -m pip install "requests>=2.32,<3"
Save the following as options_liquidity.py. It uses the public demo token unless you set EODHD_API_TOKEN. Pagination requests go back to the fixed endpoint with your authentication parameters; the code does not assume that a returned next-page URL includes your token.
"""Screen an EODHD options snapshot; never place orders."""
import argparse
import csv
import json
import math
import os
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
ENDPOINT = "https://eodhd.com/api/mp/unicornbay/options/contracts"
def number(value):
try:
result = float(value)
except (TypeError, ValueError):
return None
return result if math.isfinite(result) else None
def screen(records, max_spread_pct=10, min_volume=10, min_oi=100):
accepted, rejected = [], []
for record in records:
row = dict(record)
bid, ask = number(row.get("bid")), number(row.get("ask"))
volume, oi = number(row.get("volume")), number(row.get("open_interest"))
reasons = []
spread_pct = None
if bid is None or ask is None or bid <= 0 or ask < bid:
reasons.append("invalid_quote")
else:
midpoint = (bid + ask) / 2
spread_pct = 100 * (ask - bid) / midpoint
row.update(midpoint_calculated=midpoint, spread_absolute=ask - bid,
spread_pct=spread_pct)
if spread_pct > max_spread_pct:
reasons.append("wide_spread")
if volume is None or volume < min_volume:
reasons.append("low_or_missing_volume")
if oi is None or oi < min_oi:
reasons.append("low_or_missing_open_interest")
row["rejection_reasons"] = ";".join(reasons)
(rejected if reasons else accepted).append(row)
accepted.sort(key=lambda row: (row["spread_pct"], -number(row["open_interest"])))
return accepted, rejected
def fetch_chain(session, token, symbol, start, end, page_size=1000, max_pages=11):
records, pages, seen = [], [], set()
for page in range(max_pages):
offset = page * page_size
if offset > 10000:
raise RuntimeError("Offset cap reached; narrow the expiry window.")
params = {
"api_token": token, "fmt": "json",
"filter[underlying_symbol]": symbol, "filter[type]": "call",
"filter[exp_date_from]": start, "filter[exp_date_to]": end,
"sort": "exp_date", "page[limit]": page_size, "page[offset]": offset,
}
response = session.get(ENDPOINT, params=params, timeout=30)
if not response.ok:
# Do not print response.url: it contains the API token.
raise RuntimeError(f"EODHD returned HTTP {response.status_code}")
payload = response.json()
if not isinstance(payload, dict) or not isinstance(payload.get("data"), list):
raise RuntimeError("Unexpected response shape")
pages.append(payload)
batch = payload["data"]
new_count = 0
for item in batch:
attrs = item.get("attributes")
if not isinstance(attrs, dict) or not attrs.get("contract"):
raise RuntimeError("Missing contract attributes")
key = attrs["contract"]
if key not in seen:
records.append(attrs)
seen.add(key)
new_count += 1
if not batch or not payload.get("links", {}).get("next"):
return records, pages
if not new_count:
raise RuntimeError("Pagination repeated a page; no complete export written.")
raise RuntimeError("Page budget reached; narrow the expiry window.")
def write_csv(path, rows):
fields = ["contract", "underlying_symbol", "exp_date", "type", "strike",
"bid", "ask", "midpoint_calculated", "spread_absolute", "spread_pct", "volume",
"open_interest", "bid_date", "ask_date", "tradetime", "rejection_reasons"]
with path.open("w", newline="", encoding="utf-8") as handle:
writer = csv.DictWriter(handle, fieldnames=fields, extrasaction="ignore")
writer.writeheader()
writer.writerows(rows)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--symbol", default="AAPL")
parser.add_argument("--start", default=str(date.today() + timedelta(days=21)))
parser.add_argument("--end", default=str(date.today() + timedelta(days=60)))
parser.add_argument("--page-size", type=int, default=1000)
parser.add_argument("--max-spread-pct", type=float, default=10)
parser.add_argument("--min-volume", type=float, default=10)
parser.add_argument("--min-oi", type=float, default=100)
parser.add_argument("--out", default="options-output")
args = parser.parse_args()
if not 1 <= args.page_size <= 1000:
parser.error("--page-size must be between 1 and 1000")
if date.fromisoformat(args.start) > date.fromisoformat(args.end):
parser.error("--start must be on or before --end")
if min(args.max_spread_pct, args.min_volume, args.min_oi) < 0:
parser.error("Screen thresholds must be non-negative")
token = os.environ.get("EODHD_API_TOKEN", "demo")
if token == "demo" and args.symbol not in {"AAPL", "AMZN"}:
parser.error("The options demo supports AAPL and AMZN; set EODHD_API_TOKEN.")
retry = Retry(total=3, backoff_factor=1, status_forcelist=[429, 500, 502, 503, 504],
allowed_methods=["GET"], respect_retry_after_header=True,
raise_on_status=False)
with requests.Session() as session:
session.mount("https://", HTTPAdapter(max_retries=retry))
records, pages = fetch_chain(session, token, args.symbol, args.start, args.end,
page_size=args.page_size)
accepted, rejected = screen(records, args.max_spread_pct, args.min_volume, args.min_oi)
out = Path(args.out)
out.mkdir(parents=True, exist_ok=True)
# Keep public data and timestamps; strip the transport's pagination URLs.
archive = [{key: value for key, value in page.items() if key != "links"} for page in pages]
(out / "response.json").write_text(json.dumps(archive, indent=2), encoding="utf-8")
write_csv(out / "candidates.csv", accepted)
write_csv(out / "rejected.csv", rejected)
summary = {
"retrieved_at_utc": datetime.now(timezone.utc).isoformat(),
"symbol": args.symbol, "expiry_from": args.start, "expiry_to": args.end,
"pages": len(pages), "contracts": len(records),
"accepted": len(accepted), "rejected": len(rejected),
"max_spread_pct": args.max_spread_pct, "min_volume": args.min_volume,
"min_open_interest": args.min_oi,
}
(out / "summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8")
print(json.dumps(summary, indent=2))
if __name__ == "__main__":
main()
Run the same expiration selection used for the recorded example:
python options_liquidity.py --start 2026-12-15 --end 2027-01-23 --out options-output
For a future run, omit the date arguments to select expirations 21 to 60 days ahead. The numerical output will change as the source snapshot changes.
The script retries selected temporary HTTP failures, keeps the API token out of normal HTTP error messages, and stops if pagination exceeds its budget. A failed fetch does not produce a partial export reported as complete.
The recorded AAPL result: 312 contracts, 52 candidates
The request completed at 20:05 UTC on November 24, 2026. It retrieved 312 unique call contracts in one page. With the stated thresholds, 52 passed and 260 failed at least one rule.
These are the first five candidates sorted by relative spread. Values below are rounded for display; the CSV retains the underlying numbers.
| Contract | Spread $ | Spread % |
|---|---|---|
| AAPL270115C00100000 | 3.30 | 1.32% |
| AAPL261218C00090000 | 4.05 | 1.56% |
| AAPL261218C00175000 | 2.85 | 1.63% |
| AAPL261218C00180000 | 2.95 | 1.74% |
| AAPL270115C00255000 | 2.05 | 2.13% |
The first row explains why percentage spread is only one view. Its relative spread is 1.32%, yet its dollar spread is $3.30 per quoted option unit. Sorting by percentage alone places expensive contracts near the top without considering capital requirements or your intended order size.
Screenshot of the archived-results viewer, built from the saved API response and CSV exports. The 52 passing contracts satisfy the numerical rules; quote freshness and execution still need review.
The rejected set contained 193 rows below the volume requirement or missing that value, 116 below the open-interest requirement or missing it, 70 with wide relative spreads, and 38 with invalid quotes. These counts total more than 260 because a row can fail several checks.
The first six rejected rows in the archived result. Keeping the reasons makes it possible to inspect a rejected contract without rerunning the request. These screenshots show a local archive viewer, not the EODHD platform interface.
Timestamp inspection deserves equal attention. In the first candidate, the bid timestamp was 2026-11-24T07:10:31.000000Z, the ask timestamp was 2026-11-23 21:10:31, and tradetime was 2026-11-23. The strings have different date and timezone representations. The script preserves them without assuming a timezone for the value that has no offset. Its calculated midpoint is therefore a screening calculation on the supplied fields, not a synchronized executable quote.
Test pagination before trusting an export
A one-page success doesn't establish that pagination works.
I ran a second request restricted to the December 18, 2026 expiration, with 50 records per page. That request returned 112 unique contracts across three pages, with 22 passing the same screen.
For that run:
python options_liquidity.py --start 2026-12-18 --end 2026-12-18 --page-size 50 --out pagination-check
The complete script checks that pagination makes progress, deduplicates contract identifiers, and stops rather than silently accepting a truncated result. A snapshot can still change between page requests; deduplication cannot turn a moving dataset into an atomic historical snapshot.
For repeatable analysis, keep the archived response together with the parameters and retrieval time. A CSV on its own loses too much context.
Use the shortlist as an input to further research
candidates.csv contains contracts that pass your numerical preferences. rejected.csv contains the others, including their rejection reasons. response.json preserves the returned data, while summary.json records the query window and counts.
That gives a dashboard or notebook something inspectable to consume. You can add a maximum dollar spread, contract-size checks, strike selection, quote-age requirements, or a consistent observation-date policy according to the research question.
Keep screening and execution separate. Bid and ask size, timing, fees and the broker's current market belong in any later fill analysis. The code here does not submit orders or measure strategy returns.
Frequently asked questions
Can I test this options data API for free?
Yes. The EODHD options demo supports AAPL and AMZN, and this script defaults to demo. That is different from the general free account, which does not include options data. Check the options product's current access terms for other symbols.
Does EODHD provide real-time options quotes for this screener?
The product used here supplies end-of-day and historical options data. The screener is for research on returned snapshots, not live order routing or intraday fill decisions.
Is high open interest enough to identify liquid options?
No. Open interest measures outstanding contracts. It does not guarantee the size or price available for a new order. Review the two-sided market and timestamps as well as activity fields.
Can I use the contracts endpoint for a historical backtest?
A current contract snapshot is not a historical dataset. Use observations from the historical endpoint, retain their dates, and make sure each input was available at the strategy's decision time. Today's snapshot cannot establish that.
Why did my rerun produce different counts?
The contracts endpoint returns a changing snapshot. Contract coverage, prices and activity fields can change. Reproduce calculations against an archived response when you need to compare code changes against the same inputs.
Start with a result you can explain
An options data API gives you the fields. An auditable screener keeps the rules, rejected rows and observation context together.
You can test EODHD's options product with its supported demo symbols. Start with the recorded workflow, then change one research assumption at a time.
Looking for technical content for your company? I can help — LinkedIn · kevinmenesesgonzalez@gmail.com



Top comments (0)