-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetch_data.py
More file actions
59 lines (46 loc) · 1.94 KB
/
Copy pathfetch_data.py
File metadata and controls
59 lines (46 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
"""Fetch the SPY option chain from yfinance and save a raw snapshot to CSV"""
from datetime import datetime, timezone
from pathlib import Path
import pandas as pd
import yfinance as yf
def fetch_option_chain(ticker: str = "SPY") -> tuple[pd.DataFrame, float, str]:
"""Fetch the full option chain (all expirations, calls and puts).
Returns
-------
chain : pd.DataFrame
All quotes stacked, with added columns: expiration, option_type
spot : float
Last close of the underlying at snapshot time
snapshot_date : str
UTC timestamp of the snapshot
"""
underlying = yf.Ticker(ticker)
expirations = underlying.options
spot = underlying.history(period="1d")["Close"].iloc[-1]
snapshot_date = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
frames = []
for expiration in expirations:
chain = underlying.option_chain(expiration)
for option_type, quotes in (("call", chain.calls), ("put", chain.puts)):
df = quotes.copy()
df["expiration"] = expiration
df["option_type"] = option_type
frames.append(df)
chain = pd.concat(frames, ignore_index=True)
chain["snapshot_date"] = snapshot_date
chain["spot"] = spot
return chain, float(spot), snapshot_date
def save_snapshot(chain: pd.DataFrame, ticker: str = "SPY", out_dir: str = "data") -> Path:
"""Save the raw chain to data/{ticker}_options_{YYYYMMDD}.csv"""
Path(out_dir).mkdir(exist_ok=True)
stamp = datetime.now(timezone.utc).strftime("%Y%m%d")
path = Path(out_dir) / f"{ticker.lower()}_options_{stamp}.csv"
chain.to_csv(path, index=False)
return path
def main() -> None:
"""Fetch the SPY chain and persist a dated raw snapshot"""
chain, spot, snapshot_date = fetch_option_chain("SPY")
path = save_snapshot(chain)
print(f"Snapshot {snapshot_date} | spot={spot:.2f} | {len(chain)} rows -> {path}")
if __name__ == "__main__":
main()