Data¶
The data package provides a clean, unified interface for fetching, loading,
and saving all market and historical data required by the optpricing library.
compact_snapshot ¶
Liquid-only, slimmed snapshot for compressed storage (e.g. the scheduled GitHub Action that grows the corpus): about 25 KB per ticker and day with zstd, versus ~130 KB for a full snapshot.
Keeps the rows selected by :func:liquid_option_mask and price_source,
drops columns that are constant, informational or reconstructible
(marketPrice is the bid-ask mid, contractSymbol the OCC code; both
are restored by :func:load_market_snapshot) and stores quotes in float32
(cent precision for strikes below ~80,000) and counts in int32.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
A full snapshot frame. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
The compacted frame. |
Source code in src/optpricing/data/market_data_manager.py
get_available_snapshot_dates ¶
Lists all available snapshot dates for a given ticker.
Scans the market data directory for saved parquet files corresponding to the ticker and extracts the date from the filenames.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
The stock ticker to search for, e.g., 'SPY'. |
required |
ascending
|
bool
|
Return oldest first (what a backtest needs); by default newest first. |
False
|
Returns:
| Type | Description |
|---|---|
list[str]
|
A sorted list of available dates in 'YYYY-MM-DD' format. |
Source code in src/optpricing/data/market_data_manager.py
get_live_dividend_yield ¶
Fetches the live trailing dividend yield for a ticker using yfinance.
Handles the unit change in yfinance (fraction before 0.2.5x, percent since).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
The stock ticker to search for, e.g., 'SPY'. |
required |
Returns:
| Type | Description |
|---|---|
float
|
The continuous dividend yield as a decimal, or zero. |
Source code in src/optpricing/data/market_data_manager.py
get_live_option_chain ¶
Fetches a live option chain from the configured data provider.
The data provider is determined by the live_data_provider key in the
config.yaml file. Supported providers are "yfinance".
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
The stock ticker for which to fetch the option chain, e.g., 'SPY'. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame | None
|
A DataFrame containing the formatted option chain data (schema v2), or None if the fetch fails or no data is returned. |
Source code in src/optpricing/data/market_data_manager.py
get_live_risk_free_rate ¶
Current risk-free rate from the live ^IRX quote.
Returns:
| Type | Description |
|---|---|
float | None
|
Continuously compounded rate, or None if the quote is unavailable. |
Source code in src/optpricing/data/historical_manager.py
historical_returns_if_available ¶
Historical log returns from the local file, or None if there is no file.
Unlike :func:load_historical_returns this never downloads anything, so
it is safe inside offline workflows.
Source code in src/optpricing/data/historical_manager.py
is_v2_snapshot ¶
True if the frame carries the schema-v2 market-parameter columns.
liquid_option_mask ¶
liquid_option_mask(df: DataFrame, *, max_relative_spread: float = 0.3, min_maturity_days: float = 3.0, max_maturity_years: float = 1.5, moneyness: tuple[float, float] = (0.7, 1.3), min_open_interest: int = 5, min_volume: int = 1) -> pd.Series
Boolean mask of options worth keeping in a compact snapshot.
A row passes when it has a positive bid, a bid-ask spread no wider than
max_relative_spread of the mid, open interest of at least
min_open_interest or volume of at least min_volume, a maturity
inside the window and a strike within the moneyness band.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
A snapshot frame. |
required |
max_relative_spread
|
float
|
Maximum |
0.3
|
min_maturity_days
|
float
|
Maturity window, by default 3 days to 1.5 years. |
3.0
|
max_maturity_years
|
float
|
Maturity window, by default 3 days to 1.5 years. |
3.0
|
moneyness
|
tuple[float, float]
|
Allowed |
(0.7, 1.3)
|
min_open_interest
|
int
|
Activity floor (either one suffices), by default 5 contracts / 1 trade. |
5
|
min_volume
|
int
|
Activity floor (either one suffices), by default 5 contracts / 1 trade. |
5
|
Returns:
| Type | Description |
|---|---|
Series
|
Boolean mask aligned with |
Source code in src/optpricing/data/market_data_manager.py
load_historical_prices ¶
Loads the historical frame for a ticker, downloading it if missing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
The stock ticker, e.g., 'SPY'. |
required |
period
|
str
|
The history period of the file, by default "10y". |
'10y'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Frame indexed by date with |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the data file cannot be found and also fails to be downloaded. |
Source code in src/optpricing/data/historical_manager.py
load_historical_returns ¶
Loads historical log returns, fetching and saving them if not found.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
The stock ticker for which to load returns, e.g., 'SPY'. |
required |
period
|
str
|
The time period for which to fetch data, e.g., "10y", "5y", "1mo". Defaults to "10y". |
'10y'
|
Returns:
| Type | Description |
|---|---|
Series
|
A pandas Series containing the historical log returns. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the data file cannot be found and also fails to be downloaded. |
Source code in src/optpricing/data/historical_manager.py
load_market_snapshot ¶
Loads a previously saved market data snapshot for a specific date.
Version-1 files are upgraded to schema v2 in memory (see
:func:upgrade_snapshot); the file on disk is not modified.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
The stock ticker of the desired snapshot, e.g., 'SPY'. |
required |
snapshot_date
|
str
|
The date of the snapshot in 'YYYY-MM-DD' format. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame | None
|
A DataFrame containing the snapshot data, or None if the file is not found. |
Source code in src/optpricing/data/market_data_manager.py
load_risk_free_rate ¶
Risk-free rate on (or shortly before) a date from the stored history.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
as_of
|
date | str | Timestamp
|
Valuation date. |
required |
max_staleness_days
|
int
|
Oldest acceptable observation, by default 10 days before |
10
|
Returns:
| Type | Description |
|---|---|
float | None
|
Continuously compounded rate, or None when no history is stored or the nearest observation is too old. |
Source code in src/optpricing/data/historical_manager.py
option_contract_symbols ¶
option_contract_symbols(ticker: str, n_contracts: int, *, chain: DataFrame | None = None, as_of: date | None = None) -> list[str]
Most active option contracts of a ticker, for streaming alongside the spot.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
Underlying ticker. |
required |
n_contracts
|
int
|
How many contracts to return (ranked by open interest, then volume). |
required |
chain
|
DataFrame | None
|
An option chain to rank; the live chain is fetched when omitted. |
None
|
as_of
|
date | None
|
Only contracts expiring after this date are considered (default today). |
None
|
Returns:
| Type | Description |
|---|---|
list[str]
|
Contract symbols such as |
Source code in src/optpricing/data/stream.py
record_live_quotes ¶
record_live_quotes(symbols: list[str], duration: float, output: Path | str | None = None, *, websocket_factory: Callable[[], Any] | None = None, heartbeat: float = 15.0, flush_every: int = 1000) -> tuple[Path | None, int]
Streams quotes for symbols for duration seconds and saves them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbols
|
list[str]
|
Yahoo symbols (tickers, indices such as |
required |
duration
|
float
|
Recording length in seconds (Ctrl-C stops early and still saves). |
required |
output
|
Path | str | None
|
Parquet destination; defaults to :func: |
None
|
websocket_factory
|
Callable[[], Any] | None
|
Returns an object with |
None
|
heartbeat
|
float
|
Seconds between re-subscriptions keeping the stream alive, by default 15. |
15.0
|
flush_every
|
int
|
Messages between intermediate writes, by default 1000. |
1000
|
Returns:
| Type | Description |
|---|---|
tuple[Path | None, int]
|
The written file (None when no message arrived) and the message count. |
Source code in src/optpricing/data/stream.py
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 | |
save_historical_returns ¶
Fetches and saves historical prices, dividends and log returns for tickers.
For each ticker the adjusted close history is downloaded from yfinance,
daily log returns are computed and the frame (close, dividends,
log_return) is written to the historical data directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tickers
|
list[str]
|
A list of stock tickers to process, e.g., ['SPY', 'AAPL']. |
required |
period
|
str
|
The time period for which to fetch data, e.g., "10y", "5y", "1mo". Defaults to "10y". |
'10y'
|
Source code in src/optpricing/data/historical_manager.py
save_market_snapshot ¶
save_market_snapshot(tickers: list[str], *, compact: bool = False, only_fresh: bool = False) -> list[Path]
Saves a snapshot of the current market option chain for given tickers.
For each ticker, it fetches the live option chain using
get_live_option_chain and saves it to a parquet file named with the
ticker and the New York session date (see :func:session_date).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tickers
|
list[str]
|
A list of stock tickers to process, e.g., ['SPY', 'AAPL']. |
required |
compact
|
bool
|
Store only liquid options with zstd compression (see
:func: |
False
|
only_fresh
|
bool
|
Skip tickers whose chain shows no trade today (holidays, stale feeds), by default False. |
False
|
Returns:
| Type | Description |
|---|---|
list[Path]
|
Paths of the files written. |
Source code in src/optpricing/data/market_data_manager.py
save_risk_free_history ¶
Downloads the ^IRX (13-week T-bill) history and stores it as a
continuously compounded rate series in the historical data directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
period
|
str
|
History period, by default "10y". |
'10y'
|
Source code in src/optpricing/data/historical_manager.py
snapshot_market_params ¶
Builds the Stock and Rate atoms described by a snapshot.
Uses the stored v2 columns; for v1 frames (or frames without them, e.g.
synthetic test data) the rate defaults to DEFAULT_RISK_FREE_RATE and the
dividend yield is implied from the chain, all offline.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
A market snapshot with at least |
required |
Returns:
| Type | Description |
|---|---|
tuple[Stock, Rate]
|
The underlying (spot and continuous dividend yield) and the flat rate. |
Source code in src/optpricing/data/market_data_manager.py
trailing_dividend_yield ¶
trailing_dividend_yield(ticker: str, as_of: date | str | Timestamp, *, period: str = '10y', spot: float | None = None) -> float | None
Trailing twelve-month cash dividend yield from the historical file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticker
|
str
|
The stock ticker. |
required |
as_of
|
date | str | Timestamp
|
Valuation date; dividends with ex-dates in the preceding 365 days count. |
required |
period
|
str
|
History period of the file, by default "10y". |
'10y'
|
spot
|
float | None
|
Price to divide by; defaults to the last close on or before |
None
|
Returns:
| Type | Description |
|---|---|
float | None
|
Continuously compounded yield |
Source code in src/optpricing/data/historical_manager.py
upgrade_snapshot ¶
upgrade_snapshot(df: DataFrame, ticker: str, snapshot_date: str, *, rate: float | None = None) -> pd.DataFrame
Upgrades a v1 snapshot to schema v2 without network access.
The risk-free rate is taken from the stored ^IRX history for the
snapshot date (rate overrides it); when neither is available a flat
DEFAULT_RISK_FREE_RATE is used. The dividend yield is implied from
put-call parity given that rate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
The v1 snapshot frame. |
required |
ticker
|
str
|
Ticker symbol of the snapshot. |
required |
snapshot_date
|
str
|
|
required |
rate
|
float | None
|
Risk-free rate to use instead of the stored history. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
The frame with the v2 columns added (already-v2 frames are returned unchanged). |