Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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
Expand Down
36 changes: 36 additions & 0 deletions fixtures/vol_ref.json
Original file line number Diff line number Diff line change
@@ -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
}
}
}
23 changes: 21 additions & 2 deletions gexlab/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
15 changes: 15 additions & 0 deletions gexlab/engine/calendar.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
48 changes: 48 additions & 0 deletions gexlab/engine/dex.py
Original file line number Diff line number Diff line change
@@ -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)
157 changes: 157 additions & 0 deletions gexlab/engine/voldrift.py
Original file line number Diff line number Diff line change
@@ -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))
Loading
Loading