An options chain is a lot of rows: every strike, for every expiration, for calls and puts. Most projects don't need one raw dump. They need a clean table with calls and puts side by side, the Greeks next to each strike, and a way to loop over expirations. This tutorial builds that in Python with the Mboum v3 options endpoint and saves the result to CSV.
What you will build
A script that:
- Reads the list of available expirations for a ticker
- Fetches the chain for each expiration you choose
- Merges the Call and Put lists into one row per strike
- Converts bid, ask, implied volatility and the Greeks to numbers
- Writes everything to a CSV file and prints calls in a delta range
Prerequisites
- Python 3 and the
requestslibrary - A Mboum API key (free key)
The endpoint
GET https://api.mboum.com/v3/markets/options has weight 2 per call. It takes a ticker (or symbol) and an optional expiration in YYYY-MM-DD format. Prefix an index with $ or ^. See the endpoint docs.
Each call returns one expiration. Without expiration, you get this week's Friday, or next Friday once this week's has passed. If no chain exists for that date, the nearest listed expiration is used. The response has three parts:
meta.expirations: the available dates, split intoweeklyandmonthlymeta.field: a description of every columnbody: two lists,CallandPut, sorted by strike
The other chain endpoints work differently. /v1/markets/options takes expiration as a Unix timestamp and has a display option of list or straddle. /v2/markets/options takes a required type and a from_date to to_date range. This tutorial uses v3 because it returns the Greeks.
Step 1: fetch a chain safely
Numbers arrive as strings such as "0.5518" and "20.08%", and some fields can be "N/A". Some failures return HTTP 200 with a message and no body, so check the body, not only the status code.
import csv
import time
import requests
URL = "https://api.mboum.com/v3/markets/options"
HEADERS = {"Authorization": "Bearer YOUR_MBOUM_API_KEY"}
def num(value):
try:
return float(str(value).replace(",", "").replace("%", "").replace("+", ""))
except ValueError:
return None # "N/A" and similar
def fetch(ticker, expiration=None):
params = {"ticker": ticker}
if expiration:
params["expiration"] = expiration
resp = requests.get(URL, headers=HEADERS, params=params, timeout=30)
data = resp.json()
if resp.status_code != 200 or not isinstance(data.get("body"), dict):
print(f"No chain for {ticker} {expiration or '(default)'}: {str(data)[:120]}")
return None
return data
Step 2: list the expirations
A call with no expiration still returns meta.expirations, so use it to learn which dates exist. Flatten the weekly and monthly groups, remove duplicates (a monthly date can also be weekly) and keep the nearest few.
def list_expirations(meta, limit):
groups = meta.get("expirations", {})
return sorted({d for group in groups.values() for d in group})[:limit]
Step 3: put calls and puts side by side
Calls and puts share the same strikePrice string, so use it as the key. Each strike becomes one row with a call_ and a put_ version of every field you keep.
FIELDS = ["bidPrice", "askPrice", "volatility", "delta", "theta", "vega", "openInterest"]
def side_by_side(chain, expiration):
rows = {}
for side, prefix in (("Call", "call_"), ("Put", "put_")):
for contract in chain.get(side, []):
row = rows.setdefault(contract["strikePrice"], {
"expiration": expiration,
"strike": num(contract["strikePrice"]),
})
for field in FIELDS:
row[prefix + field] = num(contract.get(field))
return sorted(rows.values(), key=lambda r: r["strike"])
Step 4: loop, save and filter
def build_table(ticker, max_expirations=3):
first = fetch(ticker)
if not first:
raise SystemExit("Could not read the expiration list")
table = []
for expiration in list_expirations(first["meta"], max_expirations):
data = fetch(ticker, expiration)
if data:
table += side_by_side(data["body"], expiration)
time.sleep(0.2) # stay well under 10 requests per second
return table
if __name__ == "__main__":
table = build_table("AAPL", max_expirations=3)
if not table:
raise SystemExit("No rows returned")
with open("aapl_chain.csv", "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=list(table[0].keys()))
writer.writeheader()
writer.writerows(table)
print(f"{len(table)} strikes saved")
for r in table:
if r["call_delta"] is not None and 0.30 <= r["call_delta"] <= 0.50:
print(r["expiration"], r["strike"], r["call_delta"], r["call_theta"])
The last loop keeps calls with a delta between 0.30 and 0.50, close to the money. Change the range to match the strikes you care about.
Sample response
A trimmed call from the docs example, with the fields the script reads:
{
"strikePrice": "590.00",
"expirationDate": "05/30/25",
"bidPrice": "4.96",
"askPrice": "4.98",
"volatility": "20.08%",
"delta": "0.5518",
"vega": "0.2120",
"theta": "-0.7369",
"openInterest": "30,435",
"daysToExpiration": "3"
}
The docs also list rho among the Greeks, but the example response does not show it. If your response includes it, read it with contract.get("rho") the same way.
Best practices
- Budget your calls. Every call has weight 2, and only HTTP 200 responses count. Three expirations cost 8 including the list call, so cap
max_expirations. - Check the body. A 200 response can carry an error message. The script skips an expiration when
bodyis not a dictionary. - Use the right date format. The request takes YYYY-MM-DD, but each contract's
expirationDatecomes back as MM/DD/YY. Keep the request value as your key. - Respect the rate limit. The limit is 10 requests per second, and over it returns HTTP 429. Keep the sleep, and back off on a 429.
- Check liquidity before you trust a row. A strike with a wide bid-ask spread or tiny open interest can show Greeks that no one would trade at.
Next steps
You now have a script that lists expirations, fetches each chain and exports one clean table. Schedule it, load the CSV into pandas, or feed it into your own pricing checks. This is a data tool, not investment advice.
Claim your free API key and see the Mboum docs for Python, PHP, JavaScript and Bash samples.