diff --git a/README.md b/README.md index 0c5ba6f..14a25ef 100644 --- a/README.md +++ b/README.md @@ -87,6 +87,9 @@ caches or screenshots with your account details. usable open interest and IV, and how many contracts were left out and why. - **Futures view**: the same levels as /ES or /MNQ equivalents for SPX, NDX, SPY and QQQ, with the basis estimated from the option chain. See [Futures view](#futures-view). +- **Vol drift and DEX**: whether at-the-money implied volatility is rising or falling since the session + began, and the size of call and put delta exposure from open interest. Context only, labeled + untested. See [Vol drift and DEX](#vol-drift-and-dex). - **Present mode** (key P): a larger layout for screen recording. ## Screenshots @@ -173,6 +176,11 @@ Privacy above), linking to its release notes. - **Feeds.** Alpaca OPRA (paid) gives live quotes and the IV is solved from the mid; Alpaca's free indicative feed gives a modified quote with its own IV. SPX and NDX come from Cboe, about 15 minutes delayed. The map labels which one you are looking at. +- **SPX and NDX before about 09:45 ET.** Cboe's delayed file still carries the prior session's index + close until its first live value arrives. The map labels spot "prior close" with Cboe's own time, the + gamma sign and distances say they are measured at that close, guidance shows no setups, and the + Futures view waits for live data before estimating a basis. The walls and the gamma flip come from + open interest by strike, so they still show. - **Valuation clock.** Time to expiry is measured from the quote time, and from the session close when the market is shut, so a weekend map is not distorted. @@ -203,6 +211,27 @@ estimate, not a futures quote. Works in demo mode on synthetic data, labeled as such. Not financial advice. +## Vol drift and DEX + +Two context readings on the Live Map. Neither changes the GEX math, the levels or the guidance, and +neither is tested: both carry an **Untested** chip. + +- **Vol drift** answers one question: is at-the-money implied volatility rising or falling today? It + reads the ATM IV of one expiry (the IVs of the two strikes around spot, interpolated to spot) and + compares it with the session's first reading after the open. The expiry is the nearest one with at + least 3 full trading days left, fixed for the whole session and never 0DTE, so the reference and the + current value measure the same contracts. The change counts as flat while it is smaller than + max(0.5 vol points, 5% of the reference IV); beyond that it reads rising or falling. The card pairs it + with the gamma regime as the conditions where moves tend to get bigger (rising IV in negative gamma) + or stay smaller (falling IV in positive gamma). A ticker that lists only Friday expiries can read + unavailable late in the week, when no expiry in the 7 day window has 3 full sessions left. +- **DEX** is delta exposure: delta x open interest x 100 x spot, summed per side. Net DEX is call delta + exposure minus put delta exposure, so it reads positive when calls are larger and negative when puts + are, with each side's size shown unsigned. Open interest is the previous session's, so DEX sizes + yesterday's positioning at today's price and IV. It is not a live flow scoreboard. + +Not financial advice. + ## Contributing Bug reports and pull requests are welcome. [CONTRIBUTING.md](CONTRIBUTING.md) covers setup, tests and diff --git a/fixtures/vol_ref.json b/fixtures/vol_ref.json new file mode 100644 index 0000000..99e4d5c --- /dev/null +++ b/fixtures/vol_ref.json @@ -0,0 +1,36 @@ +{ + "note": "Synthetic fixture", + "ts": "2026-10-16T13:45:00Z", + "tickers": { + "SPY": { + "ts": "2026-10-16T13:45:00Z", + "expiry": "2026-10-21", + "settlement": "PM", + "iv": 0.17845 + }, + "QQQ": { + "ts": "2026-10-16T13:45:00Z", + "expiry": "2026-10-21", + "settlement": "PM", + "iv": 0.1948 + }, + "SPX": { + "ts": "2026-10-16T13:45:00Z", + "expiry": "2026-10-21", + "settlement": "PM", + "iv": 0.16317 + }, + "NDX": { + "ts": "2026-10-16T13:45:00Z", + "expiry": "2026-10-21", + "settlement": "PM", + "iv": 0.21155 + }, + "NVDA": { + "ts": "2026-10-16T13:45:00Z", + "expiry": "2026-10-23", + "settlement": "PM", + "iv": 0.5228 + } + } +} diff --git a/gexlab/config.py b/gexlab/config.py index dd46b04..6a4c8fc 100644 --- a/gexlab/config.py +++ b/gexlab/config.py @@ -12,7 +12,7 @@ ROOT = Path(__file__).resolve().parent.parent # ---------------------------------------------------------------- identity -APP_VERSION = "1.1.2" # The public release this build is. Bump it before tagging a release: the update check +APP_VERSION = "1.2.0" # The public release this build is. Bump it before tagging a release: the update check # (gexlab/update_check.py) compares it with GitHub's latest release tag. UPDATE_REPO = "simonro/Edge-GEX-Lab" # Where the update check looks for releases (the public repo). UPDATE_EVERY_H = 24 # At most one update check a day; the answer is cached in CACHE_DIR. @@ -213,8 +213,27 @@ def is_demo() -> bool: ATR_FROM_ETF = {"SPX": "SPY", "NDX": "QQQ"} # Alpaca has no index bars. ATR% is a percentage, so the ETF's ATR% is a # fair stand in for the index's (no units problem, unlike dollar volume). Labeled. +# ---------------------------------------------------------------- context metrics (display only) +# Vol Drift and DEX sit beside the levels on the Live Map. Neither touches the GEX math, the levels, the gate, the +# recorder captures or the studies. +VOL_DRIFT_MIN_FULL_SESSIONS = 3 # The expiry measured is the nearest one that settles at or after the close of the + # third session after the current one: at least three full trading days left + # (decided 2026-10-28). 0DTE IV is distorted late in the day, and on a 1-day expiry the clock + # itself (calendar T, quiet overnight hours) moves IV through the session; three + # sessions dilute that. Friday-only stocks have no such expiry inside the 0 to 7 day + # window on Wednesdays and Thursdays: unavailable then. +VOL_DRIFT_BAND = 0.05 # Both strikes bracketing spot must lie within 5% of spot, and the quotes counted toward + # VOL_DRIFT_MIN_USABLE are those inside the same band. +VOL_DRIFT_MIN_USABLE = 4 # Fewer usable IVs (calls plus puts) inside the band on that expiry: unavailable, never + # a guess. Four is two strikes with both sides, the least that brackets spot. +VOL_DRIFT_FLAT_MIN_PTS = 0.5 # Flat band, relative to the IV level (decided 2026-10-28): flat while the change, as +VOL_DRIFT_FLAT_REL = 0.05 # displayed (0.1 vol point), is below max(0.5 vol point, 5% of the reference IV); + # rising or falling at or beyond it. SPY at 19% IV: 0.95 point; NVDA at 42%: 2.1 + # points. Round starting values, not tuned on any outcome. +VOL_DRIFT_DEMO_REF = FIXTURES_DIR / "vol_ref.json" # Synthetic 09:45 references for demo mode. + # ---------------------------------------------------------------- trade guidance -GUIDANCE_MAX_DATA_AGE_S = 300 # Market open: no setups when the vendor's data time (spot trade, or the Cboe payload) is +GUIDANCE_MAX_DATA_AGE_S = 300 # Market open: no setups when the vendor's data time (spot trade, or the Cboe payload) is # more than 5 min old, even if the last fetch "succeeded" (day-1 verification). GUIDANCE_MIN_RR = 1.0 # A scenario is shown only when the reward from the entry zone's worst edge to target 1 # is at least the risk from that edge to the stop. Below 1 to 1 the diff --git a/gexlab/engine/calendar.py b/gexlab/engine/calendar.py index 1d86cbf..66147ca 100644 --- a/gexlab/engine/calendar.py +++ b/gexlab/engine/calendar.py @@ -117,6 +117,11 @@ def market_open(self, now_utc: datetime) -> bool: return False return s.open <= ny.time().replace(microsecond=0) < s.close + def open_dt(self, d: date) -> datetime | None: + """Session open of day d (09:30 ET) as an aware UTC datetime; None when d is not a session.""" + s = self.sessions.get(d) + return datetime.combine(d, s.open, NY).astimezone(UTC) if s else None + def close_dt(self, d: date) -> datetime: """Session close of day d (16:00 ET or the early close) as an aware UTC datetime.""" return datetime.combine(d, self.close_time(d), NY).astimezone(UTC) @@ -148,6 +153,16 @@ def valuation_time(cal: "TradingCalendar | None", now: datetime, return min(quote_time, close) if quote_time is not None else close +def predates_session(cal: "TradingCalendar | None", value_ts: datetime | None, now: datetime) -> bool: + """True when the market is open at now and value_ts is earlier than today's session open: a prior session's + value served during today's session. Cboe's delayed payload carries the prior close as the index value until + its first live value, about 09:45 ET (seen 2026-10-29: last_trade_time Oct 28 16:14:59 at 09:39 ET).""" + if cal is None or value_ts is None or not cal.market_open(now): + return False + opened = cal.open_dt(now.astimezone(NY).date()) + return opened is not None and value_ts < opened + + def valuation_label(valuation: datetime, at_close: bool = True) -> str: """'Valued at Fri Oct 16 close' (or '... 15:45 ET' when the data predate the close), New York time.""" v = valuation.astimezone(NY) diff --git a/gexlab/engine/dex.py b/gexlab/engine/dex.py new file mode 100644 index 0000000..98e5b59 --- /dev/null +++ b/gexlab/engine/dex.py @@ -0,0 +1,48 @@ +"""DEX: delta exposure from open interest. A context line for positioning size only. Display only. + +DEX per contract = delta * OI * multiplier * S, in dollars of the underlying (decided 2026-10-28). + delta: Black-Scholes, r = q = 0, the same IV and the same valuation clock (T) as the GEX of that contract. + A call's delta is positive and a put's negative, with no extra sign flip, so net DEX = call delta exposure minus + put delta exposure and reads positive (call delta exposure larger) or negative (put delta exposure larger). The unsigned call and put totals show + each side's size. + +Open interest is the previous session's, so this sizes yesterday's positioning at today's price and IV. It is +not a live flow scoreboard. Only valid contracts (usable OI and IV) count, as in GEX. +""" +from __future__ import annotations + +from dataclasses import dataclass + +from gexlab.engine import bsm +from gexlab.models import Contract + + +@dataclass +class Dex: + net: float # sum of delta * OI * multiplier * S: call delta exposure minus put delta exposure + call_abs: float # sum of |delta| * OI * multiplier * S over calls + put_abs: float # same over puts + contracts: int # valid contracts counted + + +def contract_dex(delta: float, oi: float, multiplier: float, spot: float) -> float: + return delta * oi * multiplier * spot + + +def compute(contracts: list[Contract], spot: float) -> Dex: + net = call_abs = put_abs = 0.0 + n = 0 + for c in contracts: + if not c.valid: + continue + n += 1 + if not c.oi or c.T is None or c.T <= 0: + continue # confirmed zero OI carries no delta; finalize() already dropped expiries + d = bsm.delta(spot, c.strike, c.T, 0.0, c.iv, c.type) + size = abs(d) * c.oi * c.multiplier * spot + net += contract_dex(d, c.oi, c.multiplier, spot) + if c.type == "call": + call_abs += size + else: + put_abs += size + return Dex(net, call_abs, put_abs, n) diff --git a/gexlab/engine/voldrift.py b/gexlab/engine/voldrift.py new file mode 100644 index 0000000..cfcdc4f --- /dev/null +++ b/gexlab/engine/voldrift.py @@ -0,0 +1,157 @@ +"""Vol Drift: is at-the-money implied volatility rising or falling today. Display only. + +Measure: ATM IV of one expiry, interpolated linearly in strike between the two strikes that bracket spot. +A strike's IV is the average of its call and put when both are usable, else the one that is. Usable means +the contract's OWN IV (before the strike-pair sharing the GEX model does) passes iv_ok(); an IV the feed +dropped for its age never reaches here. No extrapolation: a side with no strike, a bracket wider than the band +or too few usable quotes is unavailable, never a guess. + +Expiry: the nearest one that settles at or after the close of the session after the current one (at least +VOL_DRIFT_MIN_FULL_SESSIONS full trading days left), never 0DTE. When that expiry is listed with both AM and PM +roots (SPX and NDX monthlies), the PM root is used so the two clocks never mix. If that expiry has too few +usable quotes the result is unavailable; the next expiry is NOT used instead, because the reference was taken +on this one and two expiries are not comparable. + +Change: current minus reference in vol points. The label reads the change as displayed (0.1 point) against a +band relative to the IV level: flat while below max(VOL_DRIFT_FLAT_MIN_PTS, VOL_DRIFT_FLAT_REL x reference IV), +rising or falling at or beyond it. + +Nothing here touches the GEX math, the levels, the gate, the recorder captures or the studies. +""" +from __future__ import annotations + +from dataclasses import dataclass +from datetime import date, datetime, timedelta + +from gexlab import config +from gexlab.engine.calendar import TradingCalendar, settlement_dt +from gexlab.engine.gex import iv_ok +from gexlab.models import Contract + + +@dataclass +class AtmIv: + iv: float # decimal, e.g. 0.1432 + expiry: date + settlement: str # AM | PM + k_lo: float + k_hi: float + iv_lo: float + iv_hi: float + usable: int # usable IVs (calls plus puts) inside the band + inputs: list # the contracts whose own IV entered the two bracketing strikes + + +def own_iv(c: Contract, exclude_sources: tuple = ()) -> float | None: + """The contract's own IV: before strike-pair sharing, after the feed's age checks. None when unusable or when + its method is in exclude_sources (off hours: the vendor's indicative IV runs on its own clock).""" + v = c.iv_own if c.iv_shared else c.iv + src = c.iv_own_source if c.iv_shared else c.iv_source + if exclude_sources and src in exclude_sources: + return None + return float(v) if iv_ok(v) else None + + +def next_session(cal: TradingCalendar, d: date) -> date: + x = d + timedelta(days=1) + for _ in range(15): + if cal.is_session(x): + return x + x += timedelta(days=1) + return x + + +def session_day(cal: TradingCalendar, valuation: datetime) -> date: + """The session the measurement belongs to: the valuation's New York day, or the session before it.""" + from gexlab.engine.calendar import NY + return cal.latest_session_on_or_before(valuation.astimezone(NY).date()) + + +def target_expiry(contracts: list[Contract], day: date, cal: TradingCalendar, + min_sessions: int | None = None) -> tuple[date, str] | None: + """(expiry, settlement) of the nearest expiry settling at or after the close of the session `min_sessions` + sessions after `day`. PM wins over AM on the same date. None when the chain lists no such expiry.""" + n = config.VOL_DRIFT_MIN_FULL_SESSIONS if min_sessions is None else min_sessions + last = day + for _ in range(max(0, n)): + last = next_session(cal, last) + need = cal.close_dt(last) + by: dict[date, set[str]] = {} + for c in contracts: + by.setdefault(c.expiry, set()).add(c.settlement) + for d in sorted(by): + st = "PM" if "PM" in by[d] else "AM" + if settlement_dt(d, st, cal) >= need: + return d, st + return None + + +def atm_iv(contracts: list[Contract], spot: float, expiry: date, settlement: str, + band: float | None = None, min_usable: int | None = None, + exclude_sources: tuple = ()) -> tuple[AtmIv | None, str | None]: + """(result, None) or (None, reason). reason: no_contracts | too_few_quotes | no_bracket.""" + band = config.VOL_DRIFT_BAND if band is None else band + min_usable = config.VOL_DRIFT_MIN_USABLE if min_usable is None else min_usable + cs = [c for c in contracts if c.expiry == expiry and c.settlement == settlement] + if not cs: + return None, "no_contracts" + by: dict[float, dict[str, float]] = {} + used: dict[float, list[Contract]] = {} + usable = 0 + for c in cs: + v = own_iv(c, exclude_sources) + if v is None: + continue + by.setdefault(c.strike, {})[c.type] = v + used.setdefault(c.strike, []).append(c) + if abs(c.strike / spot - 1.0) <= band + 1e-12: + usable += 1 + if usable < min_usable: + return None, "too_few_quotes" + k_iv = {k: sum(v.values()) / len(v) for k, v in by.items()} + lo = [k for k in k_iv if k <= spot and spot - k <= band * spot + 1e-9] + hi = [k for k in k_iv if k >= spot and k - spot <= band * spot + 1e-9] + if not lo or not hi: + return None, "no_bracket" + k_lo, k_hi = max(lo), min(hi) + iv_lo, iv_hi = k_iv[k_lo], k_iv[k_hi] + w = 0.0 if k_hi == k_lo else (spot - k_lo) / (k_hi - k_lo) + inputs = used[k_lo] + (used[k_hi] if k_hi != k_lo else []) + return AtmIv(iv_lo + w * (iv_hi - iv_lo), expiry, settlement, k_lo, k_hi, iv_lo, iv_hi, usable, inputs), None + + +def flat_band(ref_iv_pct: float) -> float: + """Half width of the flat band in vol points: max(VOL_DRIFT_FLAT_MIN_PTS, VOL_DRIFT_FLAT_REL x reference IV).""" + return max(config.VOL_DRIFT_FLAT_MIN_PTS, config.VOL_DRIFT_FLAT_REL * ref_iv_pct) + + +def change_label(change_pts: float, threshold: float) -> str: + """rising | falling | flat, read on the change as displayed (rounded to 0.1 vol point).""" + t = threshold + shown = round(change_pts, 1) + if shown >= t: + return "rising" + if shown <= -t: + return "falling" + return "flat" + + +PAIRINGS = { + ("negative", "rising"): "Negative gamma and rising IV: the conditions where moves tend to get bigger.", + ("negative", "falling"): "Negative gamma with falling IV: the options market is pricing smaller moves than at " + "the reference, even with dealers modeled short gamma.", + ("negative", "flat"): "Negative gamma with flat IV: the change in IV is inside the flat band.", + ("positive", "rising"): "Positive gamma with rising IV: the options market is pricing bigger moves than at the " + "reference, even with dealers modeled long gamma.", + ("positive", "falling"): "Positive gamma and falling IV: the conditions where moves tend to stay smaller.", + ("positive", "flat"): "Positive gamma with flat IV: the change in IV is inside the flat band.", + ("neutral", "rising"): "Gamma near neutral with rising IV: the options market is pricing bigger moves.", + ("neutral", "falling"): "Gamma near neutral with falling IV: the options market is pricing smaller moves.", + ("neutral", "flat"): "Gamma near neutral with flat IV: the change in IV is inside the flat band.", +} + + +def pairing(regime: str | None, label: str | None) -> str | None: + if regime is None or label is None: + return None + return PAIRINGS.get((regime, label)) diff --git a/gexlab/futures.py b/gexlab/futures.py index 6a302b9..d3476a9 100644 --- a/gexlab/futures.py +++ b/gexlab/futures.py @@ -37,9 +37,11 @@ from datetime import date, datetime, timedelta from gexlab import config -from gexlab.engine.calendar import NY, UTC, TradingCalendar, iso_z, ny_today, third_friday, time_to_expiry, valuation_time +from gexlab.engine.calendar import (NY, UTC, TradingCalendar, iso_z, ny_today, predates_session, third_friday, + time_to_expiry, valuation_time) from gexlab.models import parse_occ from gexlab.sources.base import SourceError +from gexlab.sources.cboe import parse_index_time ESTIMATE_LABEL = "Estimate: futures equivalents from the option chain, not a futures quote" @@ -148,15 +150,6 @@ def parity_forward(pairs: dict[float, dict], spot: float, T: float, r: float | N # ---------------------------------------------------------------- the Cboe payload -def parse_index_time(s: str | None) -> datetime | None: - """Cboe's `last_trade_time` ("2026-10-21T11:44:31") is New York wall time with no zone (checked 2026-10-21: - payload timestamp 15:59:33Z = 11:59:33 ET, last_trade_time 11:44:31, the 15 minute delay).""" - if not s: - return None - try: - return datetime.fromisoformat(s.strip()[:19]).replace(tzinfo=NY).astimezone(UTC) - except ValueError: - return None @dataclass @@ -228,7 +221,8 @@ def option_expiry(c: FuturesContract, p: IndexPayload) -> date | None: def parity_block(c: FuturesContract, p: IndexPayload, now: datetime, cal: TradingCalendar | None) -> dict: exp = option_expiry(c, p) - base = {"available": False, "reason": None, "forward": None, "index_spot": p.price, "basis": None, + base = {"available": False, "reason": None, "prior_close": False, "forward": None, "index_spot": p.price, + "basis": None, "basis_raw": None, "basis_window": None, "rate": config.FUTURES_RATE, "rate_source": config.FUTURES_RATE_SOURCE, "t_years": None, "strikes": [], "usable_pairs": 0, "spread": None, "option_root": config.FUTURES[c.index]["option_root"], @@ -238,6 +232,12 @@ def parity_block(c: FuturesContract, p: IndexPayload, now: datetime, cal: Tradin base["reason"] = (f"Cboe's payload lists no {base['option_root']} AM options for {c.expiry:%b %d}, " "the expiry that settles this contract") return base + if predates_session(cal, p.index_time, now): + # Never a basis from today's option quotes over yesterday's index, and never into the smoothing history. + base["prior_close"] = True + base["reason"] = (f"Cboe's {p.index} value is still the prior close (its first live value arrives about " + f"09:45 ET), so a basis would mix today's option quotes with yesterday's {p.index}") + return base t_ref = valuation_time(cal, now, p.payload_ts) T = time_to_expiry(t_ref, exp, "AM", cal) par = parity_forward(p.pairs_by_expiry[exp], p.price, T) @@ -290,18 +290,31 @@ def to_futures(level: float, basis: float, ratio: float = 1.0, tick: float | Non return round_tick(level * ratio + basis, tick) -def etf_ratio(etf: str, p: IndexPayload, trade_at) -> dict: +def pair_time(index_time: datetime, cal: TradingCalendar | None) -> datetime: + """The instant to price the ETF at. The index stops at the session close, so an index time stamped after that + day's close (Cboe stamps the closing value 16:14:59) pairs with the ETF's regular-session close, never an + after-hours print.""" + if cal is None: + return index_time + d = index_time.astimezone(NY).date() + if not cal.is_session(d): + return index_time + return min(index_time, cal.close_dt(d)) + + +def etf_ratio(etf: str, p: IndexPayload, trade_at, cal: TradingCalendar | None = None) -> dict: """ratio = index / ETF at the index value's market-data time. trade_at(symbol, at, lookback_s) -> Spot | None. Raises SourceError when no ETF price of that instant exists.""" if p.index_time is None: raise SourceError(f"Cboe's {p.index} payload carries no index time, so no same-instant {etf} price") - tr = trade_at(etf, p.index_time, config.FUTURES_RATIO_MAX_LAG_S) + at = pair_time(p.index_time, cal) + tr = trade_at(etf, at, config.FUTURES_RATIO_MAX_LAG_S) if tr is None or not tr.price: - raise SourceError(f"no {etf} trade within {config.FUTURES_RATIO_MAX_LAG_S} s before {iso_z(p.index_time)}") + raise SourceError(f"no {etf} trade within {config.FUTURES_RATIO_MAX_LAG_S} s before {iso_z(at)}") return {"value": p.price / tr.price, "index_price": p.price, "index_time": iso_z(p.index_time), "etf": etf, "etf_price": tr.price, "etf_time": iso_z(tr.ts), - "lag_s": round((p.index_time - tr.ts).total_seconds(), 1) if tr.ts else None, "source": tr.source, - "note": (f"{p.index} from Cboe (its {p.index_time.astimezone(NY):%H:%M:%S} ET value) over the last {etf} " + "lag_s": round((at - tr.ts).total_seconds(), 1) if tr.ts else None, "source": tr.source, + "note": (f"{p.index} from Cboe (its {at.astimezone(NY):%H:%M:%S} ET value) over the last {etf} " f"trade at or before that second (Alpaca). Same instant, so the 15 minute delay drops out.")} @@ -347,7 +360,7 @@ def build(ticker: str, *, now: datetime, cal: TradingCalendar | None, market_ope return out key = (etf, iso_z(p.index_time), p.price) try: - rb = _RATIO_CACHE.get(key) or etf_ratio(etf, p, trade_at) + rb = _RATIO_CACHE.get(key) or etf_ratio(etf, p, trade_at, cal) except SourceError as e: out["reason"] = f"{etf} to {index} ratio unavailable: {e}" return out @@ -359,7 +372,8 @@ def build(ticker: str, *, now: datetime, cal: TradingCalendar | None, market_ope if override_price is not None: out["override"] = _override(index, etf or _etf_for(index), p, ratio if etf else None, override_price, - market_open, trade_at, latest_trade, demo) + market_open, trade_at, latest_trade, demo, cal, + prior_close=bool(par.get("prior_close"))) if out["override"].get("basis") is not None: override_basis = out["override"]["basis"] if override_basis is not None: @@ -378,7 +392,8 @@ def build(ticker: str, *, now: datetime, cal: TradingCalendar | None, market_ope return out -def _override(index, etf, p: IndexPayload, ratio_known, price, market_open, trade_at, latest_trade, demo) -> dict: +def _override(index, etf, p: IndexPayload, ratio_known, price, market_open, trade_at, latest_trade, demo, + cal: TradingCalendar | None = None, prior_close: bool = False) -> dict: """basis = the typed price minus the latest index value; live when Alpaca keys and an open market allow it.""" o = {"price": price, "index_value": p.price, "index_source": "cboe_delayed", "index_time": iso_z(p.index_time), "delayed": True, "basis": None, "at": None, @@ -388,14 +403,18 @@ def _override(index, etf, p: IndexPayload, ratio_known, price, market_open, trad elif not market_open: o["label"] = f"Cboe {index} at the close: your basis also holds any move since the close" elif trade_at is not None and latest_trade is not None: + if prior_close: + o["label"] = f"Cboe {index} prior close: your basis also holds the move since that close" try: - ratio = ratio_known if ratio_known is not None else etf_ratio(etf, p, trade_at)["value"] + ratio = ratio_known if ratio_known is not None else etf_ratio(etf, p, trade_at, cal)["value"] last = latest_trade(etf) o.update(index_value=round(last.price * ratio, 4), index_source="live_etf_ratio", index_time=iso_z(last.ts), delayed=False, label=f"Live {index} estimate: last {etf} trade times the {index}/{etf} ratio") except SourceError as e: o["label"] += f" (live estimate unavailable: {e})" + elif prior_close: + o["label"] = f"Cboe {index} prior close: your basis also holds the move since that close" o["basis"] = round(price - o["index_value"], 4) o["at"] = o["index_time"] return o diff --git a/gexlab/guidance/build.py b/gexlab/guidance/build.py index 219afd5..1040caf 100644 --- a/gexlab/guidance/build.py +++ b/gexlab/guidance/build.py @@ -624,6 +624,8 @@ def build(m: dict, *, zero_dte: dict | None = None, scorecard: dict | None = Non blocked.append(f"the feed is stale (no successful refresh in {config.STALE_AFTER_S // 60} min)") elif feed.get("market_open") and (feed.get("data_age_s") or 0) > config.GUIDANCE_MAX_DATA_AGE_S: blocked.append(f"the vendor data is {int(feed['data_age_s'] // 60)} min old") + if (m.get("spot") or {}).get("basis") == "prior_close": + blocked.append("the index value is the prior close until Cboe's first live value, about 09:45 ET") cv = m.get("coverage") or {} if cv.get("gate_pct") is not None and cv.get("eligible"): if cv.get("gex_pct") is None: diff --git a/gexlab/models.py b/gexlab/models.py index b60e5bb..d522e7d 100644 --- a/gexlab/models.py +++ b/gexlab/models.py @@ -66,6 +66,8 @@ class Spot: source: str # alpaca_sip | alpaca_iex | cboe | demo basis: str = "last_trade" # last_trade (in session) | regular_close (market closed: the session's # official close, never an extended-hours print) | payload (Cboe current_price) + # | prior_close (Cboe, market open but the index value predates today's open; + # ts is then the index's own time, see cboe.parse_chain) @dataclass @@ -86,6 +88,8 @@ class Chain: oi_info: dict = field(default_factory=dict) # OI provenance: label, basis, matched counts, fallback reason valuation_ts: datetime | None = None # the one clock T is measured from (see calendar.valuation_time); # None = as_of (demo fixtures, older callers) + index_ts: datetime | None = None # Cboe index chains: the index value's own market-data time (Cboe's + # last_trade_time, about 15 min before source_ts); None for other feeds @property def valuation(self) -> datetime: diff --git a/gexlab/service.py b/gexlab/service.py index b176989..8b18d47 100644 --- a/gexlab/service.py +++ b/gexlab/service.py @@ -11,7 +11,9 @@ import logging from gexlab import config, magnitude, store +from gexlab.engine import dex as DX from gexlab.engine import gex as G +from gexlab.engine import voldrift as VD from gexlab.engine.calendar import (NY, UTC, TradingCalendar, expiry_kind, iso_z, ny_today, settlement_dt, utc_now, valuation_label) from gexlab.models import Chain, Contract, Spot @@ -202,11 +204,12 @@ def fmt_date_short(iso: str | None) -> str | None: return f"{d.strftime('%b')} {d.day}" -def lead_sentence(ticker: str, spot: float, lv: G.Levels, coverage_pct: float) -> str: +def lead_sentence(ticker: str, spot: float, lv: G.Levels, coverage_pct: float, prior_close: bool = False) -> str: """Plain-English, data-derived, descriptive only (no signal words). One line at 1920 px: the coverage rule detail lives in the coverage panel and the method drawer, not here. Vocabulary: always "gamma flip", never "flip" alone or "zero gamma".""" - s = f"{ticker} at {fmt_spot(spot, ticker)}" + s = (f"{ticker} at its prior close ({fmt_spot(spot, ticker)})" if prior_close + else f"{ticker} at {fmt_spot(spot, ticker)}") parts = [] if lv.nearest_zero_gamma is not None: rel = "above" if spot > lv.nearest_zero_gamma else "below" if spot < lv.nearest_zero_gamma else "at" @@ -222,6 +225,8 @@ def lead_sentence(ticker: str, spot: float, lv: G.Levels, coverage_pct: float) - band = int(round(config.SWEEP_BAND * 100)) body += (f" Net gamma stays {lv.regime if lv.regime != 'neutral' else 'near zero'} " f"with no gamma flip within {band}% of spot.") + if prior_close: + body += f" Cboe's first live {ticker} value arrives about 09:45 ET." band = int(round(config.COVERAGE_STRIKE_BAND * 100)) return f"{body} Built from {coverage_pct:.1f}% of the chain within {band}% of spot." @@ -401,6 +406,8 @@ def build_map(ticker: str, expiries: list[str] | None, signed: bool) -> dict: "totals": {"call_gex": call_tot, "put_gex": put_tot_out, "net_gex": call_tot + put_tot_out}, "magnitude": _magnitude(ticker, chain, call_tot, put_tot, spot, cal, now), + "dex": _dex(sel, spot, chain, quotes["usable"]), + "vol_drift": _vol_drift(ticker, chain, cal, now, market_open, lv.regime if quotes["usable"] else None), "quotes": quotes, "levels": {"call_wall": lv.call_wall, "put_wall": lv.put_wall, "zero_gamma": lv.zero_gamma, "nearest_zero_gamma": lv.nearest_zero_gamma, @@ -413,7 +420,7 @@ def build_map(ticker: str, expiries: list[str] | None, signed: bool) -> dict: "oi_source": chain.oi_source, "expiries": sorted({c.expiry.isoformat() for c in chain.contracts}), "excluded": None} if config.is_demo() else frozen_today(ticker, ny_today(now))), - "lead": (lead_sentence(ticker, spot, lv, pct) if quotes["usable"] else + "lead": (lead_sentence(ticker, spot, lv, pct, chain.spot.basis == "prior_close") if quotes["usable"] else no_quotes_lead(ticker, spot, quotes, cov, kind, None if config.is_demo() else cal, now, market_open)), "warnings": warnings, } @@ -444,6 +451,228 @@ def _magnitude(ticker: str, chain: Chain, call_gex: float, put_gex: float, spot: return None +# ---------------------------------------------------------------- context metrics (display only) + +DEX_CAVEAT = ("Built from the previous session's open interest, so it sizes yesterday's positioning at today's price " + "and IV. It is not a live flow scoreboard.") +DEX_METHOD = ("DEX per contract = delta x OI x 100 x spot, in dollars of the underlying. Delta is Black-Scholes with " + "r = q = 0, the same IV and valuation clock as GEX. A call's delta is positive and a put's negative, so net " + "DEX is call delta exposure minus put delta exposure: positive when call delta exposure exceeds put delta " + "exposure, negative when put delta exposure exceeds call delta exposure. Delta weighted, so it is not " + "a count of open interest. Each side is also shown without a sign. Valid contracts of the selected " + "expiries only, as in GEX.") + + +def _dex(sel: list[Contract], spot: float, chain: Chain, usable: bool) -> dict | None: + """Delta exposure of the selected expiries. Never takes the map down: a failure leaves `dex` null.""" + try: + d = DX.compute(sel, spot) + except Exception as ex: # noqa: BLE001 + log.warning("dex unavailable for %s: %s", chain.ticker, ex) + return None + ok = usable and d.contracts > 0 + return {"available": ok, "reason": None if ok else "No usable contracts in the selected expiries.", + "net_usd": d.net if ok else None, + "call_usd": d.call_abs if ok else None, "put_usd": d.put_abs if ok else None, + "contracts": d.contracts, "oi_date": chain.oi_date, "caveat": DEX_CAVEAT, "method": DEX_METHOD} + + +VOL_METHOD = ("At-the-money implied volatility of one expiry: the IVs of the two strikes that bracket spot, " + "interpolated linearly to spot. A strike's IV is the average of its call and put when both have a " + "usable IV of their own, else the one that does. The expiry is the nearest one with at least three full " + "trading days left, fixed for the session, never 0DTE: late in the day 0DTE IV is distorted, a few hours of " + "variance annualized over a sliver of time. Both strikes must lie within 5% of spot with at least 4 usable IVs " + "there, or the value is unavailable, never a guess.") +VOL_REF_METHOD = ("Reference: the first measurement of the session. When this install records 15-minute snapshots, " + "the first usable one of the session (about 09:45 ET); otherwise the first value this app computed " + "after the session opened, labeled with its time.") +VOL_CLOCK_NOTE = ("The expiry is fixed for the whole session, so the reference and the current value measure the same " + "contracts. Time to expiry is calendar time, so part of any change is the clock itself: as the session " + "runs, more of the time left is overnight, when prices usually move less. With at least three full " + "sessions to expiry one session's clock is a smaller share of the time left, so that effect is " + "smaller than on a next day expiry; it is not removed.") +VOL_CHIP = "Untested: no study tests this pairing" +_REASONS = { + "no_contracts": "the {exp} expiry is not in the chain", + "too_few_quotes": "the {exp} expiry has too few usable quotes within 5% of spot", + "no_bracket": "the {exp} expiry has no usable strike on one side of spot within 5%", +} + +_VOL_FIRST: dict[tuple, dict] = {} # (ticker, session, expiry, settlement) -> first app reading that session +_VOL_REC: dict[tuple, dict] = {} # same key -> recorder reference once found (captures never change) +_VOL_PIN: dict[tuple, tuple] = {} # (ticker, session) -> (expiry, settlement): fixed once chosen +_VOL_LOCK = threading.Lock() + + +def _day_text(d: date) -> str: + return f"{d.strftime('%a')} {d.strftime('%b')} {d.day}" + + +def recorder_vol_reference(ticker: str, day: date, expiry: date, settlement: str, + path: Path | str | None = None) -> dict | None: + """ATM IV of the first stored capture of the session (snapshot or 10:00 frozen, status not invalid) that + yields one on this expiry. Read only.""" + key = (ticker, day.isoformat(), expiry.isoformat(), settlement) + with _VOL_LOCK: + if key in _VOL_REC: + return _VOL_REC[key] + with store.session(path) as conn: + caps = conn.execute("SELECT id, kind, completed_at, spot, spot_ts, source_ts FROM captures WHERE ticker=? " + "AND session_date=? AND status!='invalid' AND spot IS NOT NULL AND completed_at IS NOT NULL " + "ORDER BY completed_at, id", (ticker, day.isoformat())).fetchall() + for cap in caps: + rows = conn.execute("SELECT strike, type, iv, iv_shared, iv_own FROM capture_contracts WHERE capture_id=? " + "AND expiry=? AND settlement=?", (cap["id"], expiry.isoformat(), settlement)).fetchall() + cs = [Contract(symbol="", root="", expiry=expiry, settlement=settlement, strike=float(r[0]), type=r[1], + iv=r[2], iv_shared=bool(r[3]), iv_own=r[4]) for r in rows] + res, _ = VD.atm_iv(cs, float(cap["spot"]), expiry, settlement) + if res is not None: + out = {"iv": res.iv, "ts": cap["completed_at"], "data_ts": cap["source_ts"] or cap["spot_ts"], + "source": "recorder", "kind": cap["kind"]} + with _VOL_LOCK: + for k in [k for k in _VOL_REC if k[1] != key[1]]: + del _VOL_REC[k] # keep one session in memory + _VOL_REC[key] = out + return out + return None + + +def demo_vol_reference(ticker: str, expiry: date, settlement: str) -> dict | None: + """The synthetic 09:45 reference for demo mode (fixtures), only for the expiry the demo chain targets.""" + try: + j = json.loads(config.VOL_DRIFT_DEMO_REF.read_text(encoding="utf-8")) + except (OSError, ValueError): + return None + r = (j.get("tickers") or {}).get(ticker) + if not r or r.get("expiry") != expiry.isoformat() or r.get("settlement") != settlement: + return None + return {"iv": float(r["iv"]), "ts": r["ts"], "data_ts": r["ts"], "source": "demo", "kind": "snapshot"} + + +def _remember_first(key: tuple, iv: float, at: datetime, data_ts: datetime) -> dict: + with _VOL_LOCK: + if key not in _VOL_FIRST: + for k in [k for k in _VOL_FIRST if k[1] != key[1]]: + del _VOL_FIRST[k] # keep one session in memory + _VOL_FIRST[key] = {"iv": iv, "ts": iso_z(at), "data_ts": iso_z(data_ts), "source": "app", "kind": None} + return _VOL_FIRST[key] + + +def _pinned_expiry(ticker: str, day: date, contracts: list[Contract], cal: TradingCalendar) -> tuple | None: + """The session's expiry, chosen once per ticker and session, so the reference and every later reading measure + the same contracts. A later chain that lacks it reads unavailable; another expiry is never substituted.""" + k = (ticker, day.isoformat()) + with _VOL_LOCK: + if k in _VOL_PIN: + return _VOL_PIN[k] + tgt = VD.target_expiry(contracts, day, cal) + if tgt is not None: + with _VOL_LOCK: + for x in [x for x in _VOL_PIN if x[1] != k[1]]: + del _VOL_PIN[x] + tgt = _VOL_PIN.setdefault(k, tgt) + return tgt + + +def _parse_z(s: str | None) -> datetime | None: + try: + return datetime.fromisoformat(s.replace("Z", "+00:00")) if s else None + except ValueError: + return None + + +def vol_drift(ticker: str, chain: Chain, cal: TradingCalendar, now: datetime, market_open: bool, + regime: str | None, *, db_path: Path | str | None = None) -> dict: + """GET /api/map `vol_drift`. Display only: reads the chain and, read only, the stored captures.""" + spot = chain.spot.price + day = VD.session_day(cal, chain.valuation) + out = {"available": False, "reason": None, "expiry": None, "settlement": None, "session": day.isoformat(), + "current": None, "reference": None, "reference_reason": None, "change_pts": None, "label": None, + "threshold_pts": None, "flat_min_pts": config.VOL_DRIFT_FLAT_MIN_PTS, + "flat_rel": config.VOL_DRIFT_FLAT_REL, "regime": regime, "pairing": None, "tested": False, + "chip": VOL_CHIP, "method": VOL_METHOD, "reference_method": VOL_REF_METHOD, "clock_note": VOL_CLOCK_NOTE} + if not config.is_demo() and not cal.exchange: + out["reason"] = ("Unavailable: the exchange calendar is unavailable, so the full trading days to expiry " + "cannot be confirmed.") + return out + if chain.spot.basis == "prior_close": + # Cboe's file before about 09:45 ET: yesterday's index over pre-open quotes. Never a reading, never a reference. + out["reason"] = (f"Unavailable until Cboe's first live {ticker} value, about 09:45 ET: the payload still " + "carries the prior close.") + return out + tgt = _pinned_expiry(ticker, day, chain.contracts, cal) + if tgt is None: + out["reason"] = (f"Unavailable: no listed expiry in the 0 to 7 day window has {config.VOL_DRIFT_MIN_FULL_SESSIONS} " + "full trading days left.") + return out + expiry, st = tgt + out.update(expiry=expiry.isoformat(), settlement=st) + # Off hours the vendor's indicative IV is computed on its own wall clock, not the close it is valued at. + excl = ("indicative",) if not market_open and not config.is_demo() else () + res, why = VD.atm_iv(chain.contracts, spot, expiry, st, exclude_sources=excl) + if res is None: + out["reason"] = "Unavailable: " + _REASONS.get(why, "the {exp} expiry has no usable ATM IV").format( + exp=_day_text(expiry)) + "." + return out + out["available"] = True + out["current"] = {"iv_pct": round(res.iv * 100, 2), "ts": iso_z(chain.valuation), "spot": spot, + "k_lo": res.k_lo, "k_hi": res.k_hi, "iv_lo_pct": round(res.iv_lo * 100, 2), + "iv_hi_pct": round(res.iv_hi * 100, 2), "usable": res.usable} + + key = (ticker, day.isoformat(), expiry.isoformat(), st) + ref = None + if config.is_demo(): + ref = demo_vol_reference(ticker, expiry, st) + else: + try: + ref = recorder_vol_reference(ticker, day, expiry, st, db_path) + except Exception as ex: # noqa: BLE001 + log.warning("stored vol reference unavailable for %s: %s", ticker, ex) + sess = cal.sessions.get(day) + opened = datetime.combine(day, sess.open, NY) if sess is not None else None + # Only a reading whose ATM inputs carry a known quote time at or after the open can anchor the session. + times = [c.iv_ts for c in res.inputs] + known = (opened is not None and times and all(t is not None for t in times) + and (chain.feed != "cboe_delayed" or chain.source_ts is not None)) + if market_open and day == ny_today(now) and known and min(times) >= opened and chain.valuation >= opened: + first = _remember_first(key, res.iv, chain.valuation, max(times)) + else: + with _VOL_LOCK: + first = _VOL_FIRST.get(key) + ref = ref or first + if ref is None: + out["reference_reason"] = (f"No reading from the {_day_text(day)} session yet: the reference is the first " + "value measured after the session opened.") + return out + out["reference"] = {"iv_pct": round(ref["iv"] * 100, 2), "ts": ref["ts"], "data_ts": ref["data_ts"], + "source": ref["source"], "kind": ref["kind"]} + # The reference's earliest clock (its market-data time or its valuation / completion time): a quote stamped a + # second after the fetch started must not make the very reading it came from look older than itself. + ref_ts = [t for t in (_parse_z(ref["data_ts"]), _parse_z(ref["ts"])) if t is not None] + ref_at = min(ref_ts) if ref_ts else None + if ref_at is not None and (ref_at - chain.valuation).total_seconds() > config.CLOCK_SKEW_S: + out["reference_reason"] = ("The current chain is older than the reference, so no change is shown until " + "the next refresh.") + return out + chg = (res.iv - ref["iv"]) * 100 + band = VD.flat_band(ref["iv"] * 100) # the label reads the unrounded band + out["threshold_pts"] = round(band, 2) # rounded for display only + out["change_pts"] = round(chg, 1) + out["label"] = VD.change_label(chg, band) + out["pairing"] = VD.pairing(regime, out["label"]) + return out + + +def _vol_drift(ticker: str, chain: Chain, cal: TradingCalendar, now: datetime, market_open: bool, + regime: str | None) -> dict | None: + """Never takes the map down: any failure here leaves `vol_drift` null.""" + try: + return vol_drift(ticker, chain, cal, now, market_open, regime) + except Exception as ex: # noqa: BLE001 + log.warning("vol drift unavailable for %s: %s", ticker, ex) + return None + + def expirations(ticker: str) -> dict: chain, _, _ = cached_chain(ticker) today = ny_today(chain.as_of) diff --git a/gexlab/sources/cboe.py b/gexlab/sources/cboe.py index 18b03ce..f74b2e7 100644 --- a/gexlab/sources/cboe.py +++ b/gexlab/sources/cboe.py @@ -47,7 +47,7 @@ import httpx from gexlab import config -from gexlab.engine.calendar import UTC, TradingCalendar, ny_today, time_to_expiry, valuation_time +from gexlab.engine.calendar import NY, UTC, TradingCalendar, ny_today, predates_session, time_to_expiry, valuation_time from gexlab.engine.gex import iv_ok from gexlab.engine.iv import implied_volatility from gexlab.models import Chain, Contract, Spot, parse_occ @@ -62,6 +62,21 @@ def parse_cboe_timestamp(s: str) -> datetime: return dt.replace(tzinfo=tz).astimezone(UTC) +def parse_index_time(s: str | None) -> datetime | None: + """Cboe's `last_trade_time` ("2026-10-21T11:44:31") is New York wall time with no zone (checked 2026-10-21: + payload timestamp 15:59:33Z = 11:59:33 ET, last_trade_time 11:44:31, the 15 minute delay).""" + if not s: + return None + try: + return datetime.fromisoformat(s.strip()[:19]).replace(tzinfo=NY).astimezone(UTC) + except (TypeError, ValueError): + return None + + +PRIOR_CLOSE_WARNING = ("{t} is the prior close: Cboe's first live {t} value arrives about 09:45 ET. Spot, the gamma " + "sign and the distances are measured at that close; the walls are strikes and still apply.") + + def settlement_for_root(ticker: str, root: str) -> str | None: return config.CBOE_ROOTS.get(ticker, {}).get(root) @@ -306,15 +321,25 @@ def parse_chain(ticker: str, body: bytes, as_of: datetime, cal: TradingCalendar # regular-session close (indexes have no extended hours). Label it so, stamped at the close; the # payload time stays in source_ts (feed.data_ts) for the method drawer. spot = Spot(float(price), src_ts, "cboe", basis="payload") + index_ts = parse_index_time(data.get("last_trade_time")) if cal is not None and src_ts is not None and not cal.market_open(as_of): try: close = cal.last_close(as_of) except ValueError: close = None - if close is not None and src_ts >= close: + # The closing value only once the index's own time reaches the close: the 16:00 to 16:15 payloads still + # carry the 15:45 to 16:00 value (seen 2026-10-29: 7706.14 in the 16:00 file, close 7720.39 at 16:14:59). + if close is not None and src_ts >= close and (index_ts is None or index_ts >= close): spot = Spot(float(price), close, "cboe", basis="regular_close") + elif close is not None and index_ts is not None and index_ts < close and src_ts >= close: + spot = Spot(float(price), index_ts, "cboe", basis="payload") + # Market open but the index value predates today's open: Cboe still carries the prior close (until about + # 09:45 ET). Stamp the spot with the index's own time and say so; the payload time stays in source_ts. + if predates_session(cal, index_ts, as_of): + spot = Spot(float(price), index_ts, "cboe", basis="prior_close") + warnings.insert(0, PRIOR_CLOSE_WARNING.format(t=ticker)) return Chain(ticker=ticker, as_of=as_of, spot=spot, - feed="cboe_delayed", contracts=contracts, oi_date=oi_date, source_ts=src_ts, + feed="cboe_delayed", contracts=contracts, oi_date=oi_date, source_ts=src_ts, index_ts=index_ts, complete=True, raw_hash=hashlib.sha256(len(body).to_bytes(8, "big") + body).hexdigest(), warnings=warnings, requests=1, valuation_ts=t_ref, oi_source="cboe", oi_info={"source": "cboe", "basis": "inferred", "label": CBOE_INFERRED_LABEL, "oi_date": oi_date, diff --git a/gexlab/store.py b/gexlab/store.py index 0bd0560..d25b9bd 100644 --- a/gexlab/store.py +++ b/gexlab/store.py @@ -251,6 +251,8 @@ def default_path() -> Path: ("captures", "gex_charged_pct", "REAL"), # % of the band |GEX| total that is that charge ("session_processing", "study_eligible", "INTEGER"), # 1 = counts toward the studies under the declared cohort ("session_processing", "study_reasons", "TEXT"), # why it does not count (comma separated), null when it does + ("captures", "index_ts", "TEXT"), # Cboe index captures: the index value's own market-data time + # (last_trade_time); NULL before 2026-10-29 and for Alpaca feeds ] # Indexes that depend on migrated columns: created after MIGRATIONS ran. diff --git a/tests/test_prior_close.py b/tests/test_prior_close.py new file mode 100644 index 0000000..825b61f --- /dev/null +++ b/tests/test_prior_close.py @@ -0,0 +1,178 @@ +"""Cboe before about 09:45 ET: the payload still carries the prior session's index value (seen 2026-10-29 at 09:39 ET: +last_trade_time Oct 28 16:14:59, SPX 7,744 while SPY put SPX near 7,701). The map labels it the prior close, the +Futures view computes no basis from it, Vol Drift never reads or anchors on it, and guidance shows no setups. +""" +from __future__ import annotations + +import json +from datetime import date, datetime, time, timezone + +import pytest + +import test_futures as TF +from gexlab import config, futures as F, service +from gexlab.engine import gex as G +from gexlab.engine.calendar import NY, predates_session +from gexlab.guidance import build as GB +from gexlab.models import Chain, Contract, Spot +from gexlab.sources import cboe +from conftest import exchange_cal + +UTC = timezone.utc +CAL = exchange_cal() +WED, THU = date(2026, 10, 28), date(2026, 10, 29) +EXP = date(2026, 10, 30) # Friday weekly, PM settled + + +def ny(d: date, h: int, m: int = 0, s: int = 0) -> datetime: + return datetime.combine(d, time(h, m, s), NY).astimezone(UTC) + + +PRIOR = ny(WED, 16, 14, 59) # Cboe's stamp on the prior session's closing value +PAYLOAD = ny(THU, 9, 38, 21) # the file the map downloaded at 09:38 +NOW = ny(THU, 9, 39) +LIVE_IDX = ny(THU, 9, 30, 23) # the first same-day index value (payload stamped 09:45:25) + + +def _cboe(ts: datetime, price: float, index_time: datetime | None) -> bytes: + opts = [] + for k in (7650.0, 7700.0, 7733.0, 7750.0, 7800.0): + for cp in ("C", "P"): + opts.append({"option": f"SPXW{EXP:%y%m%d}{cp}{int(k * 1000):08d}", "open_interest": 1000, "iv": 0.15, + "bid": 10.0, "ask": 10.4}) + data = {"current_price": price, "options": opts} + if index_time is not None: + data["last_trade_time"] = index_time.astimezone(NY).strftime("%Y-%m-%dT%H:%M:%S") + return json.dumps({"timestamp": ts.astimezone(UTC).strftime("%Y-%m-%d %H:%M:%S"), "data": data}).encode() + + +# ----------------------------------------------------------------------------- detection + +def test_predates_session_only_while_the_market_is_open(): + assert predates_session(CAL, PRIOR, NOW) # 09:39 with yesterday's value + assert not predates_session(CAL, LIVE_IDX, ny(THU, 9, 46)) # a same-day value after the open + assert not predates_session(CAL, ny(THU, 9, 30), NOW) # stamped at the open itself + assert not predates_session(CAL, PRIOR, ny(THU, 9, 20)) # pre-market: the close label already applies + assert not predates_session(CAL, PRIOR, ny(WED, 18, 0)) # after the close + assert not predates_session(None, PRIOR, NOW) + assert not predates_session(CAL, None, NOW) + + +def test_map_spot_is_labeled_the_prior_close_with_the_index_time(): + ch = cboe.parse_chain("SPX", _cboe(PAYLOAD, 7743.98, PRIOR), NOW, CAL) + assert ch.spot.basis == "prior_close" and ch.spot.source == "cboe" and ch.spot.price == 7743.98 + assert ch.spot.ts == PRIOR # the index's own time, not the download time + assert ch.source_ts == PAYLOAD and ch.valuation == PAYLOAD # the payload time stays for the feed and T + assert ch.warnings[0].startswith("SPX is the prior close") and "09:45 ET" in ch.warnings[0] + + +def test_same_day_index_and_closed_market_keep_their_labels(): + after = cboe.parse_chain("SPX", _cboe(ny(THU, 9, 45, 25), 7704.10, LIVE_IDX), ny(THU, 9, 46), CAL) + assert after.spot.basis == "payload" and not any("prior close" in w for w in after.warnings) + pre = cboe.parse_chain("SPX", _cboe(ny(THU, 9, 15), 7743.98, PRIOR), ny(THU, 9, 16), CAL) + assert pre.spot.basis == "regular_close" # pre-market reads as the close, as before + none = cboe.parse_chain("SPX", _cboe(PAYLOAD, 7743.98, None), NOW, CAL) + assert none.spot.basis == "payload" # no index time: nothing to judge by + + +def _levels(zg, nearest): + fields = {f: None for f in G.Levels.__dataclass_fields__} + fields.update(call_wall=7750.0, put_wall=7700.0, zero_gamma=zg, nearest_zero_gamma=nearest, regime="positive", + net_gex=1.0, gross_gex=2.0) + return G.Levels(**fields) + + +def test_lead_names_the_prior_close(): + lv = _levels([7733.0], 7733.0) + s = service.lead_sentence("SPX", 7743.98, lv, 94.2, prior_close=True) + assert s.startswith("SPX at its prior close (7,744) sits above the gamma flip") + assert "first live SPX value arrives about 09:45 ET" in s + assert service.lead_sentence("SPX", 7743.98, lv, 94.2).startswith("SPX at 7,744 sits") + + +def test_no_dashes_in_the_new_text(): + lv = _levels([], None) + texts = [cboe.PRIOR_CLOSE_WARNING.format(t="SPX"), service.lead_sentence("SPX", 7744.0, lv, 90.0, True)] + assert not any(chr(0x2013) in t or chr(0x2014) in t for t in texts) + + +# ----------------------------------------------------------------------------- Futures view + +@pytest.fixture +def futures_reset(monkeypatch): + F._PARSED.clear() + F._RATIO_CACHE.clear() + F._BASIS_HIST.clear() + monkeypatch.setattr(config, "FUTURES_RATE", TF.R) + yield + F._BASIS_HIST.clear() + + +def test_parity_is_unavailable_on_the_prior_close_and_stays_out_of_the_history(futures_reset): + body = TF._payload(spot=7744.0, ts=PAYLOAD, index_time=PRIOR) + out = F.build("SPX", now=NOW, cal=CAL, market_open=True, index_body=body) + par = out["parity"] + assert par["prior_close"] is True and par["available"] is False and par["basis"] is None + assert "prior close" in par["reason"] and "09:45 ET" in par["reason"] + assert not out["available"] and "Type your /ES price" in out["reason"] + assert F._BASIS_HIST == {} # never smoothed into a later basis + # The first same-day payload starts a clean window. + later = F.build("SPX", now=ny(THU, 9, 46), cal=CAL, market_open=True, + index_body=TF._payload(spot=7704.0, ts=ny(THU, 9, 45, 25), index_time=LIVE_IDX)) + assert later["available"] and later["parity"]["prior_close"] is False + assert later["parity"]["basis_window"]["payloads"] == 1 + + +def test_override_still_works_on_the_prior_close(futures_reset): + body = TF._payload(spot=7744.0, ts=PAYLOAD, index_time=PRIOR) + out = F.build("SPX", now=NOW, cal=CAL, market_open=True, index_body=body, override_price=7760.0) + assert out["available"] and out["basis"]["source"] == "override" + assert out["override"]["basis"] == pytest.approx(16.0) and "prior close" in out["override"]["label"] + assert out["check"]["diff"] is None + # With Alpaca keys the index value is live: last ETF trade times the ratio priced at the prior close (16:00). + calls = [] + live = F.build("SPX", now=NOW, cal=CAL, market_open=True, index_body=body, override_price=7735.0, + trade_at=TF._trade_at(772.31, calls), latest_trade=lambda s: Spot(768.04, NOW, "alpaca_sip")) + o = live["override"] + assert o["index_source"] == "live_etf_ratio" and o["delayed"] is False + assert calls[0][1] == ny(WED, 16, 0) + assert o["index_value"] == pytest.approx(768.04 * 7744.0 / 772.31) + + +def test_etf_ratio_pairs_a_closing_index_stamp_with_the_regular_close(futures_reset): + assert F.pair_time(PRIOR, CAL) == ny(WED, 16, 0) + assert F.pair_time(ny(THU, 11, 44, 31), CAL) == ny(THU, 11, 44, 31) + assert F.pair_time(PRIOR, None) == PRIOR + calls = [] + out = F.build("SPY", now=ny(WED, 18, 0), cal=CAL, market_open=False, + index_body=TF._payload(spot=7744.0, ts=ny(WED, 16, 15), index_time=PRIOR), + trade_at=TF._trade_at(772.31, calls)) + assert calls == [("SPY", ny(WED, 16, 0), config.FUTURES_RATIO_MAX_LAG_S)] + assert out["ratio"]["value"] == pytest.approx(7744.0 / 772.31) and out["ratio"]["lag_s"] == 2.0 + + +# ----------------------------------------------------------------------------- Vol Drift and guidance + +def test_vol_drift_never_reads_or_anchors_on_the_prior_close(monkeypatch, tmp_path): + monkeypatch.delenv("GEXLAB_DEMO", raising=False) + for d in (service._VOL_FIRST, service._VOL_REC, service._VOL_PIN): + d.clear() + cs = [Contract(symbol="", root="SPXW", expiry=date(2026, 11, 2), settlement="PM", strike=k, type=t, + iv=0.15, iv_source="cboe", iv_own=0.15, iv_own_source="cboe", iv_ts=PAYLOAD) + for k in (7700.0, 7740.0, 7750.0, 7800.0) for t in ("call", "put")] + ch = Chain(ticker="SPX", as_of=NOW, spot=Spot(7743.98, PRIOR, "cboe", basis="prior_close"), feed="cboe_delayed", + contracts=cs, source_ts=PAYLOAD, valuation_ts=PAYLOAD) + vd = service.vol_drift("SPX", ch, CAL, NOW, True, "positive", db_path=tmp_path / "empty.db") + assert not vd["available"] and vd["current"] is None and vd["reference"] is None + assert "09:45 ET" in vd["reason"] and "prior close" in vd["reason"] + assert service._VOL_FIRST == {} and service._VOL_PIN == {} + for d in (service._VOL_FIRST, service._VOL_REC, service._VOL_PIN): + d.clear() + + +def test_guidance_shows_no_setups_on_the_prior_close(): + m = json.loads((config.FIXTURES_DIR / "map_SPX.json").read_text(encoding="utf-8")) + m["spot"]["basis"] = "prior_close" + g = GB.build(m) + assert g["scenarios"] == [] + assert any(n.startswith(GB.NO_SETUPS) and "prior close" in n for n in g["setup_notes"]) diff --git a/tests/test_vol_drift_dex.py b/tests/test_vol_drift_dex.py new file mode 100644 index 0000000..6e15bee --- /dev/null +++ b/tests/test_vol_drift_dex.py @@ -0,0 +1,453 @@ +"""Vol Drift and DEX: context metrics on the Live Map (display only). + +Every chain here is synthetic with a known answer: IVs set by hand (or prices built from a known IV and solved +back), Black-Scholes deltas computed directly. No network. +""" +from __future__ import annotations + +import math +import re +from datetime import date, datetime, time, timedelta, timezone + +import pytest + +from gexlab import config, service, store +from gexlab.engine import bsm +from gexlab.engine import dex as DX +from gexlab.engine import voldrift as VD +from gexlab.engine.calendar import NY, TradingCalendar +from gexlab.engine.iv import implied_volatility +from gexlab.models import Chain, Contract, Spot + +UTC = timezone.utc +DEFAULT_SESSIONS = config.VOL_DRIFT_MIN_FULL_SESSIONS # read before any test patches it +BANNED = re.compile(r"\b(buy|sell|bullish|bearish|signal|entry|should)\b", re.I) +DASHES = re.compile("[" + chr(0x2013) + chr(0x2014) + "]") + + +def cal(holidays=(), start=date(2026, 10, 1), end=date(2026, 12, 31)) -> TradingCalendar: + rows, d = [], start + while d <= end: + if d.weekday() < 5 and d not in holidays: + rows.append({"date": d.isoformat(), "open": "09:30", "close": "16:00"}) + d += timedelta(days=1) + c = TradingCalendar.from_alpaca(rows) + c.covered = (start, end) + return c + + +CAL = cal() +WED = date(2026, 10, 28) +THU = date(2026, 10, 29) + + +def ny(d: date, h: int, m: int = 0) -> datetime: + return datetime.combine(d, time(h, m), NY).astimezone(UTC) + + +def k(strike, typ, expiry=THU, iv=None, settlement="PM", **kw) -> Contract: + return Contract(symbol=f"X{expiry:%y%m%d}{typ[0].upper()}{int(strike * 1000):08d}", root="X", expiry=expiry, + settlement=settlement, strike=float(strike), type=typ, iv=iv, **kw) + + +def smile(strikes, expiry=THU, base=0.20, slope=0.01, atm=100.0, **kw): + """Calls and puts sharing a linear IV in strike: IV(K) = base + slope * (K - atm).""" + return [k(s, t, expiry, base + slope * (s - atm), **kw) for s in strikes for t in ("call", "put")] + + +@pytest.fixture(autouse=True) +def _live_mode(monkeypatch): + """Live mode, and a one-session rule so the hand-built chains can stay on a Wed / Thu pair. The 3-session default + is tested on its own below and in the demo API tests.""" + monkeypatch.delenv("GEXLAB_DEMO", raising=False) + monkeypatch.setattr(config, "VOL_DRIFT_MIN_FULL_SESSIONS", 1) + for d in (service._VOL_FIRST, service._VOL_REC, service._VOL_PIN): + d.clear() + yield + for d in (service._VOL_FIRST, service._VOL_REC, service._VOL_PIN): + d.clear() + + +# ---------------------------------------------------------------- ATM interpolation + +def test_atm_iv_interpolates_linearly_between_bracketing_strikes(): + cs = smile([97, 98, 99, 100, 101, 102, 103]) + res, why = VD.atm_iv(cs, 100.4, THU, "PM") + assert why is None and (res.k_lo, res.k_hi) == (100.0, 101.0) + assert res.iv == pytest.approx(0.204, abs=1e-12) # 0.20 + 0.4 * (0.21 - 0.20) + res, _ = VD.atm_iv(cs, 100.0, THU, "PM") # spot on a strike: that strike's IV + assert (res.k_lo, res.k_hi) == (100.0, 100.0) and res.iv == pytest.approx(0.20) + + +def test_atm_iv_recovers_a_known_iv_from_prices(): + """Mids priced at a known 23% IV and solved back with the app's own solver give 23% at the money.""" + S, T, sigma = 701.3, 2.0 / 365.0, 0.23 + cs = [] + for s in range(690, 712): + for t in ("call", "put"): + price = bsm.option_price(S, s, T, 0.0, sigma, t) + cs.append(k(s, t, iv=implied_volatility(price, S, s, T, 0.0, t))) + res, _ = VD.atm_iv(cs, S, THU, "PM") + assert res.iv == pytest.approx(sigma, abs=1e-5) + + +def test_atm_iv_averages_call_and_put_and_uses_each_contracts_own_iv(): + cs = smile([98, 99, 101, 102]) + cs += [k(100, "call", iv=0.20), k(100, "put", iv=0.22)] + res, _ = VD.atm_iv(cs, 100.0, THU, "PM") + assert res.iv == pytest.approx(0.21) # both usable: their average + # The put's IV was copied from the call (strike-pair sharing): its own 0.22 is what counts. + cs[-1] = k(100, "put", iv=0.20, iv_shared=True, iv_own=0.22) + assert VD.atm_iv(cs, 100.0, THU, "PM")[0].iv == pytest.approx(0.21) + # A shared IV with no own IV behind it is not a quote of that contract: only the call counts. + cs[-1] = k(100, "put", iv=0.20, iv_shared=True, iv_own=None) + assert VD.atm_iv(cs, 100.0, THU, "PM")[0].iv == pytest.approx(0.20) + # An own IV outside the usable range (a bad print) is ignored the same way. + cs[-1] = k(100, "put", iv=0.001) + assert VD.atm_iv(cs, 100.0, THU, "PM")[0].iv == pytest.approx(0.20) + + +def test_atm_iv_uses_only_the_requested_expiry_and_root(): + cs = smile([99, 100, 101], base=0.20) + smile([99, 100, 101], base=0.40, settlement="AM") + cs += smile([99, 100, 101], expiry=WED, base=0.90) + assert VD.atm_iv(cs, 100.0, THU, "PM")[0].iv == pytest.approx(0.20) + assert VD.atm_iv(cs, 100.0, THU, "AM")[0].iv == pytest.approx(0.40) + + +# ---------------------------------------------------------------- unavailable cases + +def test_atm_iv_unavailable_never_guesses(): + assert VD.atm_iv(smile([99, 100, 101], expiry=WED), 100.0, THU, "PM") == (None, "no_contracts") + few = [k(100, "call", iv=0.2), k(101, "call", iv=0.2), k(99, "put", iv=0.2)] # 3 usable < 4 + assert VD.atm_iv(few, 100.0, THU, "PM") == (None, "too_few_quotes") + unusable = smile([99, 101]) + [k(100, "call", iv=None), k(100, "put", iv=None)] + assert VD.atm_iv(unusable, 100.0, THU, "PM")[0].iv == pytest.approx(0.20) # 99 and 101 bracket + above = smile([101, 102, 103]) # nothing below spot + assert VD.atm_iv(above, 100.0, THU, "PM") == (None, "no_bracket") + far = smile([90, 94, 106, 110]) # quotes, but not within 5% + assert VD.atm_iv(far, 100.0, THU, "PM") == (None, "too_few_quotes") + gap = smile([94, 96, 97, 106]) # no strike above within 5% + assert VD.atm_iv(gap, 100.0, THU, "PM") == (None, "no_bracket") + + +# ---------------------------------------------------------------- expiry selection + +def test_target_expiry_skips_0dte_and_picks_the_next_full_day(): + cs = smile([100], expiry=WED) + smile([100], expiry=THU) + smile([100], expiry=date(2026, 10, 30)) + assert VD.target_expiry(cs, WED, CAL) == (THU, "PM") + fri, mon = date(2026, 10, 30), date(2026, 11, 2) + cs = smile([100], expiry=fri) + smile([100], expiry=mon) + assert VD.target_expiry(cs, fri, CAL) == (mon, "PM") # over the weekend: Monday settles after its close + + +def test_target_expiry_falls_back_to_the_nearest_listed_qualifying_expiry(): + fri = date(2026, 10, 30) + cs = smile([100], expiry=WED) + smile([100], expiry=fri) # weeklies only: no Thursday listed + assert VD.target_expiry(cs, WED, CAL) == (fri, "PM") + assert VD.target_expiry(smile([100], expiry=WED), WED, CAL) is None # only 0DTE: nothing qualifies + + +def test_target_expiry_am_settlement_and_holidays(): + tf = date(2026, 11, 20) # third Friday + am_pm = smile([100], expiry=tf, settlement="AM") + smile([100], expiry=tf) + assert VD.target_expiry(am_pm, date(2026, 11, 19), CAL) == (tf, "PM") # PM root wins on the same date + am_only = smile([100], expiry=tf, settlement="AM") + smile([100], expiry=date(2026, 11, 23)) + # AM settles at 09:30 Friday, before Friday's close: not a full day left + assert VD.target_expiry(am_only, date(2026, 11, 19), CAL) == (date(2026, 11, 23), "PM") + hol = cal(holidays={THU}) # Thursday closed: the next session is Friday + cs = smile([100], expiry=THU) + smile([100], expiry=date(2026, 10, 30)) + assert VD.target_expiry(cs, WED, hol) == (date(2026, 10, 30), "PM") + + +def test_default_needs_three_full_sessions(): + assert DEFAULT_SESSIONS == 3 + mon, tue = date(2026, 11, 2), date(2026, 11, 3) + cs = (smile([100], expiry=WED) + smile([100], expiry=THU) + smile([100], expiry=date(2026, 10, 30)) + + smile([100], expiry=mon) + smile([100], expiry=tue)) + # Wednesday: Thursday, Friday and Monday must be full sessions, so the Monday expiry is the first that qualifies + assert VD.target_expiry(cs, WED, CAL, min_sessions=3) == (mon, "PM") + hol = cal(holidays={date(2026, 10, 30)}) # a Friday holiday pushes it to Tuesday + assert VD.target_expiry(cs, WED, hol, min_sessions=3) == (tue, "PM") + fri_only = smile([100], expiry=date(2026, 10, 30)) + smile([100], expiry=date(2026, 11, 6)) + # A Friday-only stock on a Wednesday: next Friday is beyond the 0 to 7 day chain, so nothing in it qualifies + assert VD.target_expiry(fri_only[:2], WED, CAL, min_sessions=3) is None + + +def test_session_day_off_hours_maps_to_the_last_session(): + assert VD.session_day(CAL, ny(date(2026, 10, 31), 12)) == date(2026, 10, 30) # Saturday -> Friday + assert VD.session_day(CAL, ny(WED, 10)) == WED + + +# ---------------------------------------------------------------- threshold labels + +def test_flat_band_is_relative_to_the_iv_level(): + assert (config.VOL_DRIFT_FLAT_MIN_PTS, config.VOL_DRIFT_FLAT_REL) == (0.5, 0.05) + assert VD.flat_band(8.0) == pytest.approx(0.5) # floor: 5% of 8 is 0.4 + assert VD.flat_band(10.0) == pytest.approx(0.5) + assert VD.flat_band(19.0) == pytest.approx(0.95) + assert VD.flat_band(42.0) == pytest.approx(2.1) + + +@pytest.mark.parametrize("chg,ref,label", [ + (0.5, 10.0, "rising"), (0.46, 10.0, "rising"), (0.44, 10.0, "flat"), (-0.5, 10.0, "falling"), + (0.9, 19.0, "flat"), (1.0, 19.0, "rising"), (-0.96, 19.0, "falling"), + (2.0, 42.0, "flat"), (2.1, 42.0, "rising"), (-2.04, 42.0, "flat"), (-2.06, 42.0, "falling"), (-2.2, 42.0, "falling"), (0.0, 30.0, "flat")]) +def test_change_label_reads_the_displayed_change(chg, ref, label): + assert VD.change_label(chg, VD.flat_band(ref)) == label + + +def test_pairing_text_is_plain_and_descriptive(): + assert VD.pairing("negative", "rising").startswith("Negative gamma and rising IV") + assert VD.pairing(None, "rising") is None and VD.pairing("positive", None) is None + for text in VD.PAIRINGS.values(): + assert not BANNED.search(text) and not DASHES.search(text) + + +# ---------------------------------------------------------------- reference selection (service) + +def chain_at(iv_base: float, at: datetime, spot: float = 100.0, iv_ts="at") -> Chain: + ts = at if iv_ts == "at" else iv_ts + cs = smile([96, 97, 98, 99, 100, 101, 102, 103, 104], base=iv_base, iv_ts=ts, iv_source="solved_mid") + cs += smile([96, 98, 100, 102, 104], expiry=WED, base=0.50, iv_ts=ts) # 0DTE, never measured + return Chain(ticker="SPY", as_of=at, spot=Spot(spot, at, "alpaca_sip"), feed="opra", contracts=cs, + valuation_ts=at) + + +def store_capture(path, at: datetime, iv_base: float, status="eligible", kind="snapshot", ticker="SPY", + day=WED, expiry=THU): + with store.session(path) as conn: + cid = conn.execute("INSERT INTO captures (ticker, kind, session_date, requested_at, completed_at, spot, spot_ts, " + "model_version, status) VALUES (?,?,?,?,?,?,?,?,?)", + (ticker, kind, day.isoformat(), at.isoformat(), at.strftime("%Y-%m-%dT%H:%M:%SZ"), 100.0, + at.strftime("%Y-%m-%dT%H:%M:%SZ"), "1.1", status)).lastrowid + for c in smile([98, 99, 100, 101, 102], expiry=expiry, base=iv_base): + conn.execute("INSERT INTO capture_contracts (capture_id, symbol, expiry, settlement, strike, type, iv, " + "iv_shared, iv_own, valid) VALUES (?,?,?,?,?,?,?,?,?,?)", + (cid, c.symbol, c.expiry.isoformat(), c.settlement, c.strike, c.type, c.iv, 0, c.iv, 1)) + + +def test_recorder_snapshot_is_the_reference(tmp_path): + db = tmp_path / "r.db" + store_capture(db, ny(WED, 9, 45), 0.30, status="invalid") # skipped: invalid + store_capture(db, ny(WED, 10, 0), 0.18, kind="frozen", status="late") # first usable capture + store_capture(db, ny(WED, 10, 15), 0.25) + now = ny(WED, 11, 30) + vd = service.vol_drift("SPY", chain_at(0.20, now), CAL, now, True, "negative", db_path=db) + assert vd["available"] and vd["expiry"] == THU.isoformat() and vd["settlement"] == "PM" + assert vd["current"]["iv_pct"] == pytest.approx(20.0) + ref = vd["reference"] + assert ref["source"] == "recorder" and ref["kind"] == "frozen" and ref["ts"] == "2026-10-28T14:00:00Z" + assert ref["iv_pct"] == pytest.approx(18.0) + assert vd["change_pts"] == pytest.approx(2.0) and vd["label"] == "rising" + assert vd["pairing"].startswith("Negative gamma and rising IV") and vd["tested"] is False + assert "Untested" in vd["chip"] + + +def test_recorder_reference_must_be_on_the_measured_expiry(tmp_path): + db = tmp_path / "r.db" + store_capture(db, ny(WED, 9, 45), 0.18, expiry=date(2026, 10, 30)) # another expiry: not comparable + now = ny(WED, 11, 30) + vd = service.vol_drift("SPY", chain_at(0.20, now), CAL, now, True, "positive", db_path=db) + assert vd["reference"]["source"] == "app" and vd["reference"]["iv_pct"] == pytest.approx(20.0) + + +def test_first_of_session_reference_when_nothing_is_recorded(tmp_path): + db = tmp_path / "empty.db" + t1, t2 = ny(WED, 10, 7), ny(WED, 13, 0) + vd = service.vol_drift("NVDA", chain_at(0.40, t1), CAL, t1, True, "positive", db_path=db) + assert vd["reference"]["source"] == "app" and vd["reference"]["ts"] == "2026-10-28T14:07:00Z" + assert vd["change_pts"] == 0.0 and vd["label"] == "flat" + vd = service.vol_drift("NVDA", chain_at(0.385, t2), CAL, t2, True, "positive", db_path=db) + assert vd["reference"]["ts"] == "2026-10-28T14:07:00Z" and vd["reference"]["iv_pct"] == pytest.approx(40.0) + assert vd["threshold_pts"] == pytest.approx(2.0) # 5% of a 40% reference + assert vd["change_pts"] == pytest.approx(-1.5) and vd["label"] == "flat" + vd = service.vol_drift("NVDA", chain_at(0.375, t2), CAL, t2, True, "positive", db_path=db) + assert vd["change_pts"] == pytest.approx(-2.5) and vd["label"] == "falling" + assert vd["pairing"].startswith("Positive gamma and falling IV") + + +def test_no_reference_before_the_open_or_with_the_market_closed(tmp_path): + db = tmp_path / "empty.db" + pre = ny(WED, 9, 20) # data valued before the open: never the reference + vd = service.vol_drift("NVDA", chain_at(0.40, pre), CAL, pre, True, "positive", db_path=db) + assert vd["available"] and vd["reference"] is None and "session" in vd["reference_reason"] + assert vd["change_pts"] is None and vd["label"] is None and vd["pairing"] is None + close = ny(WED, 16, 0) # app started after the close: no reading of the day + vd = service.vol_drift("NVDA", chain_at(0.40, close), CAL, ny(WED, 18, 0), False, "positive", db_path=db) + assert vd["reference"] is None and vd["label"] is None + + +def test_vol_drift_unavailable_when_the_target_expiry_lacks_quotes(tmp_path): + now = ny(WED, 11, 0) + ch = chain_at(0.20, now) + for c in ch.contracts: + if c.expiry == THU: + c.iv = None # Thursday unquoted; Friday is NOT used instead + ch.contracts += smile([98, 99, 100, 101, 102], expiry=date(2026, 10, 30), base=0.22) + vd = service.vol_drift("SPY", ch, CAL, now, True, "negative", db_path=tmp_path / "e.db") + assert vd["available"] is False and vd["expiry"] == THU.isoformat() and vd["current"] is None + assert "too few usable quotes" in vd["reason"] and vd["label"] is None + + +# ---------------------------------------------------------------- DEX + +def dex_contract(strike, typ, oi, iv=0.2, T=3 / 365, valid=True) -> Contract: + c = k(strike, typ, iv=iv, oi=oi) + c.T, c.valid = T, valid + return c + + +def test_dex_sign_and_totals_on_a_synthetic_chain(): + S, T, iv = 100.0, 3 / 365, 0.2 + cs = [dex_contract(100, "call", 10), dex_contract(100, "put", 20), dex_contract(95, "put", 5), + dex_contract(105, "call", 7, valid=False), dex_contract(110, "call", 0)] + d = DX.compute(cs, S) + dc = bsm.delta(S, 100, T, 0.0, iv, "call") + dp = bsm.delta(S, 100, T, 0.0, iv, "put") + dp95 = bsm.delta(S, 95, T, 0.0, iv, "put") + assert dc > 0 > dp and dp95 < 0 + call_abs = dc * 10 * 100 * S + put_abs = (-dp * 20 + -dp95 * 5) * 100 * S + assert d.call_abs == pytest.approx(call_abs) and d.put_abs == pytest.approx(put_abs) + # Net = call delta exposure minus put delta exposure: a put's negative delta counts negative, no extra flip. + assert d.net == pytest.approx(call_abs - put_abs) and d.net < 0 # this chain is put heavy + assert d.contracts == 4 # the invalid one is out; zero OI counts, adds nothing + assert DX.contract_dex(dp, 20, 100, S) == pytest.approx(dp * 20 * 100 * S) and dp * 20 * 100 * S < 0 + call_heavy = DX.compute([dex_contract(100, "call", 50), dex_contract(100, "put", 5)], S) + assert call_heavy.net == pytest.approx(call_heavy.call_abs - call_heavy.put_abs) and call_heavy.net > 0 + + +def test_dex_payload_unavailable_without_usable_quotes(): + ch = chain_at(0.2, ny(WED, 11, 0)) + out = service._dex([], 100.0, ch, False) + assert out["available"] is False and out["net_usd"] is None and out["call_usd"] is None + assert "open interest" in out["caveat"] and "not a live flow" in out["caveat"] + + +# ---------------------------------------------------------------- API (demo fixtures) + +@pytest.fixture +def client(monkeypatch): + monkeypatch.setenv("GEXLAB_DEMO", "1") + monkeypatch.setattr(config, "VOL_DRIFT_MIN_FULL_SESSIONS", DEFAULT_SESSIONS) + from fastapi.testclient import TestClient + from gexlab import api + service._CHAINS.clear() + service._LEVEL_CACHE.clear() + return TestClient(api.app, base_url="http://127.0.0.1") + + +@pytest.mark.parametrize("ticker,label", [("SPY", "falling"), ("QQQ", "rising"), ("SPX", "flat"), + ("NDX", "rising"), ("NVDA", "flat")]) +def test_demo_map_carries_vol_drift_and_dex(client, ticker, label): + m = client.get("/api/map", params={"ticker": ticker}).json() + vd, dx = m["vol_drift"], m["dex"] + assert vd["available"] and vd["reference"]["source"] == "demo" and vd["label"] == label + # Demo session Fri Oct 16: Mon, Tue and Wed must be full sessions, so Wed Oct 21 (NVDA lists Fridays: Oct 23) + assert vd["expiry"] == ("2026-10-23" if ticker == "NVDA" else "2026-10-21") + assert vd["reference"]["ts"] == "2026-10-16T13:45:00Z" + assert 5 < vd["current"]["iv_pct"] < 80 + assert vd["threshold_pts"] == pytest.approx(round(max(0.5, 0.05 * vd["reference"]["iv_pct"]), 2)) + assert dx["available"] and dx["call_usd"] > 0 and dx["put_usd"] > 0 and "hedge_usd" not in dx + assert dx["net_usd"] == pytest.approx(dx["call_usd"] - dx["put_usd"]) + for text in (vd["method"], vd["reference_method"], vd["clock_note"], vd["chip"], vd["pairing"] or "", + dx["method"], dx["caveat"]): + assert not BANNED.search(text) and not DASHES.search(text), text + + +def test_demo_dex_follows_the_selected_expiries(client): + one = client.get("/api/map", params={"ticker": "SPY", "expiries": "2026-10-16"}).json()["dex"] + all_ = client.get("/api/map", params={"ticker": "SPY"}).json()["dex"] + assert 0 < one["contracts"] < all_["contracts"] and one["call_usd"] < all_["call_usd"] + vd_one = client.get("/api/map", params={"ticker": "SPY", "expiries": "2026-10-16"}).json()["vol_drift"] + assert vd_one["expiry"] == "2026-10-21" # Vol Drift ignores the expiry selection + + +# ---------------------------------------------------------------- audit fixes (ChatGPT review, 2026-10-28) + +def test_expiry_is_pinned_for_the_session(tmp_path): + db = tmp_path / "e.db" + t1, t2 = ny(WED, 10, 30), ny(WED, 11, 30) + ch = chain_at(0.20, t1) + ch.contracts += smile([98, 99, 100, 101, 102], expiry=date(2026, 10, 30), base=0.30, iv_ts=t1) + assert service.vol_drift("SPY", ch, CAL, t1, True, "positive", db_path=db)["expiry"] == THU.isoformat() + later = chain_at(0.20, t2) + later.contracts = [c for c in later.contracts if c.expiry != THU] # Thursday drops out of a response + later.contracts += smile([98, 99, 100, 101, 102], expiry=date(2026, 10, 30), base=0.30, iv_ts=t2) + vd = service.vol_drift("SPY", later, CAL, t2, True, "positive", db_path=db) + assert vd["expiry"] == THU.isoformat() and vd["available"] is False and "not in the chain" in vd["reason"] + + +def test_label_reads_the_unrounded_band(tmp_path): + """Reference 18.04%: band 0.902 points. A displayed +0.9 is under it (flat); the shown band rounds to 0.90.""" + db = tmp_path / "r.db" + store_capture(db, ny(WED, 9, 45), 0.1804) + now = ny(WED, 11, 0) + vd = service.vol_drift("SPY", chain_at(0.1894, now), CAL, now, True, "negative", db_path=db) + assert vd["threshold_pts"] == pytest.approx(0.9) and vd["change_pts"] == pytest.approx(0.9) + assert vd["label"] == "flat" + vd = service.vol_drift("SPY", chain_at(0.1714, now), CAL, now, True, "negative", db_path=db) + assert vd["change_pts"] == pytest.approx(-0.9) and vd["label"] == "flat" + + +def test_unknown_age_reading_never_anchors_the_session(tmp_path): + db = tmp_path / "e.db" + t1, t2 = ny(WED, 10, 0), ny(WED, 10, 30) + vd = service.vol_drift("NVDA", chain_at(0.40, t1, iv_ts=None), CAL, t1, True, "positive", db_path=db) + assert vd["available"] and vd["reference"] is None # shown now, but no reference from it + vd = service.vol_drift("NVDA", chain_at(0.42, t2), CAL, t2, True, "positive", db_path=db) + assert vd["reference"]["iv_pct"] == pytest.approx(42.0) and vd["reference"]["data_ts"] == "2026-10-28T14:30:00Z" + early = chain_at(0.40, ny(WED, 10, 45), iv_ts=ny(WED, 9, 20)) # quotes stamped before the open + service._VOL_FIRST.clear() + vd = service.vol_drift("NVDA", early, CAL, ny(WED, 10, 45), True, "positive", db_path=db) + assert vd["reference"] is None + + +def test_change_withheld_when_the_current_chain_predates_the_reference(tmp_path): + db = tmp_path / "r.db" + store_capture(db, ny(WED, 9, 45), 0.22) + at = ny(WED, 9, 44) # an older cached chain + vd = service.vol_drift("SPY", chain_at(0.20, at), CAL, ny(WED, 9, 46), True, "negative", db_path=db) + assert vd["reference"]["source"] == "recorder" and vd["change_pts"] is None and vd["label"] is None + assert "older than the reference" in vd["reference_reason"] + + +def test_unavailable_on_the_weekday_fallback_calendar(tmp_path): + fb = TradingCalendar.weekdays(date(2026, 10, 1), date(2026, 12, 31)) + now = ny(WED, 11, 0) + vd = service.vol_drift("SPY", chain_at(0.20, now), fb, now, True, "negative", db_path=tmp_path / "e.db") + assert vd["available"] is False and "calendar" in vd["reason"] + + +def test_off_hours_indicative_iv_is_not_measured(tmp_path): + close = ny(WED, 16, 0) + ch = chain_at(0.20, close) + for c in ch.contracts: + c.iv_source = "indicative" + vd = service.vol_drift("SPY", ch, CAL, ny(WED, 20, 0), False, "negative", db_path=tmp_path / "e.db") + assert vd["available"] is False and "too few usable quotes" in vd["reason"] + vd = service.vol_drift("SPY", chain_at(0.20, close), CAL, ny(WED, 20, 0), False, "negative", + db_path=tmp_path / "e.db") + assert vd["available"] and vd["current"]["iv_pct"] == pytest.approx(20.0) # solved closing quotes still count + + +def test_flat_pairing_never_claims_zero_change(): + for (reg, lab), text in VD.PAIRINGS.items(): + if lab == "flat": + assert "flat band" in text and "no change" not in text + + +def test_rendered_ui_text_keeps_the_vocabulary_rule(): + from pathlib import Path + src = (Path(__file__).resolve().parent.parent / "web" / "src" / "screens" / "LiveMap.tsx").read_text(encoding="utf-8") + i, j = src.index("// ---------- DEX: one context line"), src.index("const WEEKDAY = new Intl.DateTimeFormat(") + assert not BANNED.search(src[i:j]) and not DASHES.search(src[i:j]) + + +def test_first_reading_with_quotes_stamped_after_the_fetch_start_still_shows_its_change(tmp_path): + """Live regression (NVDA, 2026-10-28): a quote stamped a second after the fetch began made the first reading + look newer than its own chain, so no change was shown at all.""" + at = ny(WED, 11, 31) + ch = chain_at(0.42, at, iv_ts=at + timedelta(seconds=1)) + vd = service.vol_drift("NVDA", ch, CAL, at, True, "positive", db_path=tmp_path / "e.db") + assert vd["reference"]["source"] == "app" and vd["change_pts"] == 0.0 and vd["label"] == "flat" diff --git a/web/src/api/types.ts b/web/src/api/types.ts index 2f0d11b..8408235 100644 --- a/web/src/api/types.ts +++ b/web/src/api/types.ts @@ -157,6 +157,47 @@ export interface Magnitude { index_note?: string; } +/** Vol Drift: ATM IV of the nearest expiry with three full trading days left, against the session's first reading. + * Contract section "Vol Drift and DEX". Display only. */ +export interface VolDrift { + available: boolean; + reason: string | null; + expiry: string | null; + settlement: "AM" | "PM" | null; + session: string; + current: { iv_pct: number; ts: string; spot: number; k_lo: number; k_hi: number; iv_lo_pct: number; iv_hi_pct: number; usable: number } | null; + /** source: recorder (first stored capture of the session), app (first value this app computed), demo (fixture). */ + reference: { iv_pct: number; ts: string; data_ts: string | null; source: "recorder" | "app" | "demo"; kind: "snapshot" | "frozen" | null } | null; + reference_reason: string | null; + /** current minus reference, vol points, rounded to 0.1: the number the label reads */ + change_pts: number | null; + label: "rising" | "falling" | "flat" | null; + /** half width of the flat band, vol points: max(flat_min_pts, flat_rel x reference IV); null without a reference */ + threshold_pts: number | null; + flat_min_pts: number; + flat_rel: number; + regime: "positive" | "negative" | "neutral" | null; + pairing: string | null; + tested: boolean; + chip: string; + method: string; + reference_method: string; + clock_note: string; +} + +/** DEX: delta * OI * 100 * spot over the selected expiries. net = calls minus puts (put delta is negative), plus unsigned sides. */ +export interface Dex { + available: boolean; + reason: string | null; + net_usd: number | null; + call_usd: number | null; + put_usd: number | null; + contracts: number; + oi_date: string | null; + caveat: string; + method: string; +} + export interface OiSource { kind: "cboe" | "alpaca" | null; label: string | null; @@ -176,8 +217,9 @@ export interface GexMap { ticker: string; as_of: string; model_version: string; - /** basis: last_trade (in session), regular_close (market closed: official session close), payload (Cboe). */ - spot: { price: number; ts: string; source: string; basis?: "last_trade" | "regular_close" | "payload" }; + /** basis: last_trade (in session), regular_close (market closed: official session close), payload (Cboe), + * prior_close (Cboe with the market open but the index value from before today's open; ts is the index's own time). */ + spot: { price: number; ts: string; source: string; basis?: "last_trade" | "regular_close" | "payload" | "prior_close" }; /** The one clock T is measured from. label is set only when the market is closed. */ valuation?: { ts: string; basis: "quote_time" | "session_close"; label: string | null }; feed: { kind: FeedKind; label: string; stale: boolean; market_open: boolean; last_success: string | null; data_ts?: string | null }; @@ -203,6 +245,9 @@ export interface GexMap { totals: { call_gex: number; put_gex: number; net_gex: number }; /** null when the reference could not be built; absent from older payloads. */ magnitude?: Magnitude | null; + /** null only when the block could not be built; absent from older payloads. */ + vol_drift?: VolDrift | null; + dex?: Dex | null; /** usable false: no valid contract within 10% of spot, so the levels are unavailable, not neutral or zero. * reason "no_live_quotes": no bid, ask or IV anywhere in the selection (Cboe's first minutes after the open). */ quotes?: { usable: boolean; reason: "no_live_quotes" | "no_usable_contracts" | null; live: number }; @@ -317,6 +362,7 @@ export interface ReplaySnapshot { status?: CaptureStatus; status_reason?: string | null; spot_ts?: string | null; + index_ts?: string | null; // SPX/NDX: the index value's own time (Cboe last_trade_time) used?: boolean; } @@ -500,6 +546,8 @@ export interface FuturesContract { export interface FuturesParity { available: boolean; reason: string | null; + /** True while Cboe's index value is the prior close (before about 09:45 ET): no basis is computed. */ + prior_close?: boolean; forward: number | null; index_spot: number; /** median of basis_raw over the payloads of the last few minutes (basis_window) */ diff --git a/web/src/components/GexProfile.tsx b/web/src/components/GexProfile.tsx index a0793ac..221b054 100644 --- a/web/src/components/GexProfile.tsx +++ b/web/src/components/GexProfile.tsx @@ -1,6 +1,6 @@ import { useEffect, useId, useMemo, useRef, useState } from "react"; import type { GexMap, StrikeRow } from "../api/types"; -import { distText, gex, int, px, price as fmtPrice, strike as fmtStrike } from "../lib/format"; +import { distText, gex, int, px, price as fmtPrice, spotRef, strike as fmtStrike } from "../lib/format"; import { futPx, toFut, type FutConv } from "../lib/futures"; import { useMeasure } from "../lib/hooks"; @@ -458,7 +458,7 @@ export default function GexProfile({ map, levels, rangePct, showCurve, frozen, h >
Strike {fmtStrike(hv.strike)} - {distText(hv.strike, spot, map.ticker)} + {distText(hv.strike, spot, map.ticker, spotRef(map.spot.basis))}
Call GEX @@ -491,7 +491,7 @@ export default function GexProfile({ map, levels, rangePct, showCurve, frozen, h >
If price were {fmtPrice(ch.spot)} - {distText(ch.spot, spot, map.ticker)} + {distText(ch.spot, spot, map.ticker, spotRef(map.spot.basis))}
Net GEX, recalculated diff --git a/web/src/lib/format.ts b/web/src/lib/format.ts index c8713e4..41b3ce5 100644 --- a/web/src/lib/format.ts +++ b/web/src/lib/format.ts @@ -184,15 +184,30 @@ export function px(v: number | null | undefined, ticker: string): string { return price(v, isIndex(ticker) ? 0 : 2); } -/** "$2.35 below spot" (SPY, QQQ, stocks) or "4 index points above spot" (SPX, NDX). */ -export function distText(level: number | null | undefined, spot: number, ticker: string): string { +/** "$2.35 below spot" (SPY, QQQ, stocks) or "4 index points above spot" (SPX, NDX). ref names what spot is + * ("the prior close" while Cboe still carries the prior session's index value). */ +export function distText(level: number | null | undefined, spot: number, ticker: string, ref = "spot"): string { if (level === null || level === undefined || !Number.isFinite(level)) return "none in range"; const d = level - spot; - if (Math.abs(d) < 0.005) return "at spot"; + if (Math.abs(d) < 0.005) return `at ${ref}`; const dp = isIndex(ticker) ? 0 : 2; const a = Math.abs(d).toLocaleString("en-US", { minimumFractionDigits: dp, maximumFractionDigits: dp }); const side = d > 0 ? "above" : "below"; - return isIndex(ticker) ? `${a} index points ${side} spot` : `$${a} ${side} spot`; + return isIndex(ticker) ? `${a} index points ${side} ${ref}` : `$${a} ${side} ${ref}`; +} + +/** What distances are measured from: "spot", or "the prior close" when the map's spot is the prior session's. */ +export function spotRef(basis: string | null | undefined): string { + return basis === "prior_close" ? "the prior close" : "spot"; +} + +const fmtNyDay = new Intl.DateTimeFormat("en-US", { timeZone: "America/New_York", month: "short", day: "numeric" }); + +/** "Oct 28" in New York time. */ +export function nyDay(iso: string | null | undefined): string { + if (!iso) return "n/a"; + const d = new Date(iso); + return Number.isNaN(d.getTime()) ? "n/a" : fmtNyDay.format(d); } /** diff --git a/web/src/mocks/index.ts b/web/src/mocks/index.ts index 69db105..a774b22 100644 --- a/web/src/mocks/index.ts +++ b/web/src/mocks/index.ts @@ -7,6 +7,7 @@ import type { CaptureRow, CaptureStatus, Comparator, + Dex, Expirations, GexMap, Health, @@ -17,6 +18,7 @@ import type { Scorecard, SearchHit, Touch, + VolDrift, } from "../api/types"; const SESSION = "2026-10-19"; // synthetic "today" (a Monday) @@ -307,6 +309,8 @@ function buildMap(ticker: string, expiries: string[], signed: boolean): GexMap { .map(([expiry, v], i) => ({ expiry, contracts: v.contracts, valid_pct: Math.round((99.2 - i * 0.3) * 10) / 10, net_gex: v.net })), totals, magnitude: mockMagnitude(ticker, totals.call_gex + totals.put_gex * (signed ? 1 : -1), S, totals.call_gex, totals.put_gex), + dex: mockDex(ticker, S, Math.abs(totals.call_gex), Math.abs(totals.put_gex), eligible), + vol_drift: mockVolDrift(ticker, S, c.step, regime), levels: { call_wall: callWall, put_wall: putWall, zero_gamma: zeros, nearest_zero_gamma: nearest, regime }, profile_curve: curve, frozen_today: frozen, @@ -315,6 +319,42 @@ function buildMap(ticker: string, expiries: string[], signed: boolean): GexMap { }; } +// ---------- Vol Drift and DEX (synthetic; contract section "Vol Drift and DEX") ---------- +const MOCK_IV: Record = { SPY: [17.4, 16.1], QQQ: [19.4, 21.0], SPX: [15.5, 15.9], NDX: [20.6, 21.7] }; +const PAIR: Record = { + "negative rising": "Negative gamma and rising IV: the conditions where moves tend to get bigger.", + "positive falling": "Positive gamma and falling IV: the conditions where moves tend to stay smaller.", + "positive flat": "Positive gamma with flat IV: no change in the size of moves the options market prices.", +}; +function mockVolDrift(ticker: string, S: number, step: number, regime: string): VolDrift { + const [ref, cur] = MOCK_IV[ticker] ?? [41.2, 41.8]; + const chg = Math.round((cur - ref) * 10) / 10; + const band = Math.round(Math.max(0.5, 0.05 * ref) * 100) / 100; + const label = chg >= band ? "rising" : chg <= -band ? "falling" : "flat"; + const kLo = Math.floor(S / step) * step; + return { + available: true, reason: null, expiry: ticker === "NVDA" ? "2026-10-23" : "2026-10-22", settlement: "PM", session: SESSION, + current: { iv_pct: cur, ts: nyIso(SESSION, 10, 0, 41), spot: S, k_lo: kLo, k_hi: kLo + step, iv_lo_pct: cur - 0.05, iv_hi_pct: cur + 0.05, usable: 120 }, + reference: { iv_pct: ref, ts: nyIso(SESSION, 9, 45, 0), data_ts: nyIso(SESSION, 9, 45, 0), source: "demo", kind: "snapshot" }, + reference_reason: null, change_pts: chg, label, threshold_pts: band, flat_min_pts: 0.5, flat_rel: 0.05, + regime: regime as VolDrift["regime"], pairing: PAIR[`${regime} ${label}`] ?? null, tested: false, + chip: "Untested: no study tests this pairing", + method: "At-the-money implied volatility of the nearest expiry with at least three full trading days left (synthetic fixture).", + reference_method: "Reference: the first measurement of the session (synthetic fixture).", + clock_note: "Time to expiry is calendar time, so part of any change is the clock itself.", + }; +} +function mockDex(_ticker: string, _spot: number, callGex: number, putGex: number, contracts: number): Dex { + // synthetic sizes in the same order as the GEX totals; not a model output + const call = callGex * 40; + const put = putGex * 32; + return { + available: true, reason: null, net_usd: call - put, call_usd: call, put_usd: put, contracts, oi_date: PRIOR, + caveat: "Built from the previous session's open interest, so it sizes yesterday's positioning at today's price and IV. It is not a live flow scoreboard.", + method: "DEX per contract = delta x OI x 100 x spot, net = calls minus puts (synthetic fixture).", + }; +} + // ---------- net GEX magnitude (synthetic ADV; no volume reference for the indexes) ---------- const MOCK_ADV: Record = { SPY: 3.0e10, QQQ: 1.8e10, NVDA: 3.5e10 }; const NO_REF = new Set(["SPX", "NDX"]); diff --git a/web/src/screens/LiveMap.tsx b/web/src/screens/LiveMap.tsx index cc52250..4c1e855 100644 --- a/web/src/screens/LiveMap.tsx +++ b/web/src/screens/LiveMap.tsx @@ -1,10 +1,10 @@ import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from "react"; import { api } from "../api/client"; -import type { Expiration, FuturesView, GexMap, Magnitude, SearchHit } from "../api/types"; +import type { Dex, Expiration, FuturesView, GexMap, Magnitude, SearchHit, VolDrift } from "../api/types"; import GexProfile, { type ProfileLevels } from "../components/GexProfile"; import GuidancePanel from "../components/GuidancePanel"; import { Drawer, ErrorState, Icon, Lead, Panel, Seg, Skeleton, usePresent, useTopMeta } from "../components/ui"; -import { GEX_UNITS, dayFull, dayShort, distText, gex, int, nyTime, nyToday, pct, price, px, strike } from "../lib/format"; +import { GEX_UNITS, dayFull, dayShort, distText, gex, int, nyDay, nyTime, nyToday, pct, price, px, signed as signedNum, spotRef, strike } from "../lib/format"; import { CURRENT_GATE, gateMin } from "../lib/gate"; import FuturesPanel from "../components/FuturesPanel"; import { FUTURES_TICKERS, convOf, futPx, toFut, type FutConv, type StoredOverride } from "../lib/futures"; @@ -562,6 +562,7 @@ export default function LiveMap({ initialTicker, onTicker }: { initialTicker: st
{futOn && } setDrawer(true)} fut={conv} /> + {m && m.vol_drift !== undefined && setDrawer(true)} />} {m && m.warnings.length > 0 && ( @@ -777,6 +778,8 @@ function LevelsPanel({ const reg = m.levels.regime; const ft = m.frozen_today; const shared = levels.call_wall !== null && levels.call_wall === levels.put_wall; + const prior = m.spot.basis === "prior_close"; + const ref = spotRef(m.spot.basis); const nowNote = (cur: number | null, fmt: (v: number | null) => string) => (frozen ? <>Now {fmt(cur)}. : null); const tiles: Kpi[] = [ @@ -784,8 +787,9 @@ function LevelsPanel({ key: "spot", label: "Spot", value: px(S, m.ticker), - sub: - m.spot.basis === "regular_close" + sub: prior + ? `${t} prior close (Cboe, ${nyDay(m.spot.ts)} ${nyTime(m.spot.ts, true)} ET). Cboe's first live value arrives about 09:45 ET.` + : m.spot.basis === "regular_close" ? m.spot.source === "cboe" ? "Regular close (Cboe)" : "Regular close" @@ -808,7 +812,7 @@ function LevelsPanel({ {strike(levels.call_wall)} ), - sub: distText(levels.call_wall, S, t), + sub: distText(levels.call_wall, S, t, ref), def: ( <> Both exposure peaks occur at this strike. {nowNote(m.levels.call_wall, strike)} @@ -828,7 +832,7 @@ function LevelsPanel({ ), value: strike(levels.call_wall), valueClass: "g", - sub: distText(levels.call_wall, S, t), + sub: distText(levels.call_wall, S, t, ref), def: frozen ? nowNote(m.levels.call_wall, strike) : m.signed ? undefined : "Largest call exposure.", }, { @@ -842,7 +846,7 @@ function LevelsPanel({ ), value: strike(levels.put_wall), valueStyle: { color: "var(--purple-1)" }, - sub: distText(levels.put_wall, S, t), + sub: distText(levels.put_wall, S, t, ref), def: frozen ? nowNote(m.levels.put_wall, strike) : m.signed ? undefined : "Largest put exposure.", }, ); @@ -863,7 +867,7 @@ function LevelsPanel({ ), value: levels.nearest_zero_gamma === null ? "None" : px(levels.nearest_zero_gamma, m.ticker), valueClass: "p", - sub: levels.nearest_zero_gamma === null ? "no crossing within 10%" : distText(levels.nearest_zero_gamma, S, t), + sub: levels.nearest_zero_gamma === null ? "no crossing within 10%" : distText(levels.nearest_zero_gamma, S, t, ref), def: ( <> Where modeled net GEX crosses zero. {nowNote(m.levels.nearest_zero_gamma, (v) => (v === null ? "none" : px(v, m.ticker)))} @@ -876,7 +880,7 @@ function LevelsPanel({ value: reg === "positive" ? "Positive" : reg === "negative" ? "Negative" : "Neutral", valueClass: "word", valueStyle: { color: reg === "positive" ? "var(--green)" : reg === "negative" ? "var(--purple-2)" : "var(--text)" }, - sub: "at current spot", + sub: prior ? "at the prior close" : "at current spot", def: "Positive does not mean bullish.", }, { @@ -929,7 +933,7 @@ function LevelsPanel({ {t} {idx} - {k.key === "spot" ? <> · {k.sub} : <> · {distText(v, S, t)}} + {k.key === "spot" ? <> · {k.sub} : <> · {distText(v, S, t, ref)}} ); } @@ -972,6 +976,7 @@ function LevelsPanel({ ))}
{m.signed && m.magnitude && } + {m.signed && m.dex && } {!m.signed && (

{UNSIGNED_NOTE} {SIDES_NOTE} @@ -1287,6 +1292,8 @@ function MethodBody({ m, ticker }: { m: GexMap | null; ticker: string }) { + +

Net GEX at hypothetical prices

@@ -1301,7 +1308,9 @@ function MethodBody({ m, ticker }: { m: GexMap | null; ticker: string }) {

{m.feed.label}
Spot
- {m.spot.basis === "regular_close" + {m.spot.basis === "prior_close" + ? `${price(m.spot.price)}, the prior session's close: Cboe's payload${m.feed.data_ts ? ` stamped ${nyTime(m.feed.data_ts, true)} ET` : ""} still carries the ${nyDay(m.spot.ts)} ${nyTime(m.spot.ts, true)} ET index value. Its first live value arrives about 09:45 ET; until then the gamma sign and distances are measured at that close.` + : m.spot.basis === "regular_close" ? m.spot.source === "cboe" ? `${price(m.spot.price)}, the regular-session close from the Cboe delayed payload${m.feed.data_ts ? ` stamped ${nyWeekday(m.feed.data_ts)} ${nyTime(m.feed.data_ts, true)} ET` : ""}` : `${price(m.spot.price)}, the regular-session close (${m.spot.source}); extended-hours prints are ignored` @@ -1366,6 +1375,181 @@ function MethodBody({ m, ticker }: { m: GexMap | null; ticker: string }) { ); } +// ---------- DEX: one context line under Net GEX size (positioning size only) ---------- +const DEX_TIP = + "DEX: delta exposure from open interest, delta x OI x 100 x spot. Net is call delta exposure minus put delta exposure: positive when call delta exposure is larger, negative when put delta exposure is larger. Delta weighted, not a count of open interest. Built from the previous session's open interest: not a live flow scoreboard."; +function dexSide(net: number): string { + return net > 0 ? "call delta exposure larger" : net < 0 ? "put delta exposure larger" : "balanced"; +} +function DexLine({ dx, onExplain }: { dx: Dex; onExplain?: () => void }) { + return ( +
+ + DEX + + + {dx.available && dx.net_usd !== null ? ( + + Net {gex(dx.net_usd, { sign: true })} of delta ({dexSide(dx.net_usd)}) {"\u00b7"} calls {gex(dx.call_usd)}, puts {gex(dx.put_usd)}, unsigned.{" "} + From {dayShort(dx.oi_date)} open interest: not a live flow scoreboard. + + ) : ( + Unavailable: {dx.reason ?? "no usable contracts"} + )} +
+ ); +} + +// ---------- Vol Drift: is ATM implied volatility rising or falling today ---------- +const VD_WORD: Record = { rising: "Rising", falling: "Falling", flat: "Flat" }; +function refSource(vd: VolDrift): string { + const r = vd.reference; + if (!r) return ""; + if (r.source === "recorder") return r.kind === "frozen" ? "10:00 capture" : "first recorded snapshot"; + if (r.source === "demo") return "synthetic fixture"; + return "first reading this session"; +} +function VolDriftCard({ m, onExplain }: { m: GexMap; onExplain?: () => void }) { + const vd = m.vol_drift ?? null; + const chip = ( + + Untested + + ); + const title = ( + <> + Vol drift + + + ); + if (!vd) { + return ( + +

Unavailable: the measurement could not be built.

+
+ ); + } + const cur = vd.current; + const ref = vd.reference; + const exp = vd.expiry ? `${dayShort(vd.expiry)}${vd.settlement === "AM" ? " AM" : ""} expiry` : null; + const word = vd.label ? VD_WORD[vd.label] : null; + return ( + + {!vd.available || !cur ? ( +

{vd.reason ?? "Unavailable."}

+ ) : ( +
+
+ {word ?? "No reference yet"} + {vd.change_pts !== null && ( + + {signedNum(vd.change_pts, 1)} vol pts + + )} +
+
+ ATM IV {cur.iv_pct.toFixed(1)}% now + {ref ? ( + <> + {" "}{"\u00b7"} {ref.iv_pct.toFixed(1)}% at {nyTime(ref.ts)} ET ({refSource(vd)}) + + ) : null} +
+ {!ref && vd.reference_reason &&
{vd.reference_reason}
} +
+ {exp}, strikes {strike(cur.k_lo)} + {cur.k_hi !== cur.k_lo ? ` / ${strike(cur.k_hi)}` : ""}. Never 0DTE: the nearest expiry with three full trading days left. +
+ {m.signed && vd.pairing &&

{vd.pairing}

} +
+ )} +
+ ); +} + +function DexSection({ m }: { m: GexMap | null }) { + const dx = m?.dex ?? null; + return ( +
+

DEX (delta exposure)

+
+ {"DEX = Delta · OI · 100 · S\n"} + {"units = dollars of the underlying\n"} + {"net = calls minus puts (put delta is negative)"} +
+

+ {dx?.method ?? + "Delta is Black-Scholes with r = q = 0, the same IV and valuation clock as GEX. Net is call delta exposure minus put delta exposure."} +

+

+ {dx?.caveat ?? "Built from the previous session's open interest, so it sizes yesterday's positioning at today's price and IV. It is not a live flow scoreboard."} It is a + size for positioning context only. +

+ {dx && dx.available && ( +
+
Net DEX
+
+ {gex(dx.net_usd, { sign: true })}: calls minus puts, {dexSide(dx.net_usd ?? 0)}. +
+
Calls, unsigned
+
{gex(dx.call_usd)}
+
Puts, unsigned
+
{gex(dx.put_usd)}
+
Contracts
+
+ {int(dx.contracts)} valid contracts of the selected expiries, open interest from {dayFull(dx.oi_date)}. +
+
+ )} +
+ ); +} + +function VolDriftSection({ m }: { m: GexMap | null }) { + const vd = m?.vol_drift ?? null; + return ( +
+

Vol drift

+

+ Is implied volatility rising or falling today? Rising means the options market is pricing bigger moves than at the session's first reading; falling means smaller. +

+

{vd?.method ?? "At-the-money implied volatility of the nearest expiry with at least three full trading days left, interpolated between the two strikes that bracket spot. Never 0DTE."}

+

{vd?.reference_method ?? "Reference: the first measurement of the session, labeled with its time."}

+

+ Flat while the change from the reference is under the larger of {vd?.flat_min_pts ?? 0.5} vol point and {Math.round((vd?.flat_rel ?? 0.05) * 100)}% of the reference IV + {vd?.threshold_pts != null ? ` (${vd.threshold_pts.toFixed(2)} points here)` : ""}; rising or falling at or beyond it. Both values are round starting values, not tuned on any + outcome. +

+

{vd?.clock_note ?? "Time to expiry is calendar time, so part of any change is the clock itself."}

+

+ The sentence that joins the drift to the modeled gamma sign is untested: no study here checks whether it says anything about the moves that follow. It describes conditions; + it makes no forecast. +

+ {vd && vd.available && vd.current && ( +
+
Expiry
+
+ {dayFull(vd.expiry)} ({vd.settlement} settled), fixed for the {dayShort(vd.session)} session. +
+
Now
+
+ {vd.current.iv_pct.toFixed(2)}% at {nyTime(vd.current.ts, true)} ET: strike {strike(vd.current.k_lo)} at {vd.current.iv_lo_pct.toFixed(2)}% + {vd.current.k_hi !== vd.current.k_lo ? `, strike ${strike(vd.current.k_hi)} at ${vd.current.iv_hi_pct.toFixed(2)}%` : ""}, spot {price(vd.current.spot)}, {vd.current.usable} usable IVs within 5%. +
+
Reference
+
+ {vd.reference ? `${vd.reference.iv_pct.toFixed(2)}% at ${nyTime(vd.reference.ts, true)} ET (${refSource(vd)}).` : vd.reference_reason ?? "None yet."} +
+
+ )} +
+ ); +} + const WEEKDAY = new Intl.DateTimeFormat("en-US", { timeZone: "America/New_York", weekday: "short" }); function nyWeekday(iso: string): string { const d = new Date(iso); diff --git a/web/src/styles/app.css b/web/src/styles/app.css index 01243b1..7376244 100644 --- a/web/src/styles/app.css +++ b/web/src/styles/app.css @@ -2273,3 +2273,87 @@ button.cell { .drawer .mag-table { margin-top: 4px; } + +/* ---------- DEX line (positioning context) and the Vol drift card: private edition only, the export strips this block ---------- */ +.dex-line { + display: grid; + gap: 4px; + margin-top: 8px; + padding: 9px 12px 10px; + background: var(--surface); + border: 1px solid var(--line); + border-radius: var(--r-s); + font: 400 11.5px/1.45 var(--body); + color: var(--text-2); +} +.dex-line small { + font: 600 10px/1 var(--mono); + letter-spacing: 0.12em; + text-transform: uppercase; + color: var(--muted); + display: flex; + align-items: center; + gap: 6px; +} +.dex-line b { + font: 600 12.5px/1 var(--mono); + color: var(--text); + font-variant-numeric: tabular-nums; +} +.dex-line .muted, +.vd-panel .muted { + color: var(--muted); +} +.vd-panel .panel-h > span:first-child { + display: inline-flex; + align-items: center; + gap: 6px; +} +.vd-body { + display: grid; + gap: 6px; +} +.vd-head { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 10px; +} +.vd-word { + font: 600 20px/1.1 var(--display); + color: var(--text); +} +.vd-word.rising { + color: var(--amber); +} +.vd-word.none { + font-size: 14px; + color: var(--muted); +} +.vd-chg { + font: 600 13px/1 var(--mono); + color: var(--text-2); + font-variant-numeric: tabular-nums; +} +.vd-row { + font: 400 12.5px/1.4 var(--body); + color: var(--text-2); +} +.vd-row b { + font: 600 13px/1 var(--mono); + color: var(--text); + font-variant-numeric: tabular-nums; +} +.vd-sub, +.vd-na { + font: 400 11.5px/1.4 var(--body); + color: var(--muted); + margin: 0; +} +.vd-pair { + margin: 2px 0 0; + padding: 7px 9px; + border-left: 2px solid var(--line-2); + font: 400 12px/1.45 var(--body); + color: var(--text-2); +}