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
18 changes: 16 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,17 @@ cd web && npm ci && npm run build && cd ..
.venv/bin/python -m uvicorn gexlab.api:app --host 127.0.0.1 --port 8240
```

**Install with an AI coding assistant:** if you use one (Claude Code, Codex, Cursor or similar), open it
in an empty folder and paste this prompt:

```text
Install Edge GEX Lab on this computer from github.com/simonro/Edge-GEX-Lab. Follow the README Quick start
exactly. First check that Python 3.11+ and Node.js LTS are installed, and if one is missing, tell me
instead of installing it. Then run the setup, start the app and confirm http://127.0.0.1:8240 opens.
Do not add any API keys. Show me where the .env file is so I can paste my own Alpaca keys.
SPX works without keys.
```

Every install starts empty: no saved maps and no history. Open the page, pick a ticker, and the map
loads from your own data feed.

Expand Down Expand Up @@ -174,8 +185,11 @@ Privacy above), linking to its release notes.
date is inferred from the payload time and labeled. If Cboe is unavailable the map falls back to
Alpaca open interest and says so.
- **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.
indicative feed gives a modified quote with its own IV. Alpaca computes no IV for contracts that expire
today, so on the free feed the app solves those from the indicative mid the same way it does on OPRA.
Checked side by side against OPRA on SPY and QQQ through a session, the walls matched and the flip
stayed within 0.25% of spot, but net GEX for today's expiry was off by as much as half. Trust the
levels on the free feed more than the bar sizes. 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
Expand Down
2 changes: 1 addition & 1 deletion 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.2.0" # The public release this build is. Bump it before tagging a release: the update check
APP_VERSION = "1.2.1" # 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
2 changes: 1 addition & 1 deletion gexlab/engine/dex.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""DEX: delta exposure from open interest. A context line for positioning size only. Display only.
"""DEX: delta exposure from open interest. A Levels now tile 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.
Expand Down
12 changes: 12 additions & 0 deletions gexlab/sources/alpaca.py
Original file line number Diff line number Diff line change
Expand Up @@ -496,9 +496,21 @@ def fetch_chain(self, ticker: str, as_of: datetime, cal: TradingCalendar | None,
for c in need:
self._apply_indicative(c, indicative.get(c.symbol), as_of=as_of, age_gate=age_gate)
else:
n_same_day = 0
for c in contracts:
self._apply_indicative(c, indicative.get(c.symbol), quote_too=True, as_of=as_of,
age_gate=age_gate)
# Alpaca computes no IV or greeks for a contract expiring today (its market data FAQ), so on
# this feed every same-day contract arrived invalid (issue 29). Solve it from the indicative
# mid like the OPRA path: same quote-to-spot alignment, same spread and IV checks.
if c.invalid_reason == "no_iv" and c.expiry == today and \
self._apply_opra(c, indicative.get(c.symbol), spot.price, t_cap, cal, spot.ts,
max_after_s=after):
n_same_day += 1
if n_same_day:
warnings.append(f"{n_same_day} contracts expiring today use an IV solved from the indicative quote "
"(Alpaca gives no IV for same-day expiries). Walls and the flip hold up against "
"OPRA, but bar sizes and net GEX can read noticeably smaller or larger.")

pair_iv_from_otm(contracts, spot.price) # after the age check: a dropped IV is never shared
n_unknown = sum(1 for c in contracts if iv_ok(c.iv) and c.iv_ts is None)
Expand Down
102 changes: 102 additions & 0 deletions tests/test_same_day_indicative.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
"""Issue 29: on the indicative feed Alpaca gives no IV for same-day expiries; the app solves it from the mid."""
from datetime import date, datetime, timezone

import httpx
import pytest

from gexlab.engine.bsm import call_price, put_price
from gexlab.engine.calendar import time_to_expiry
from gexlab.sources import alpaca as A
from gexlab.sources.base import RateLimiter

UTC = timezone.utc
AS_OF = datetime(2026, 10, 16, 14, 0, 30, tzinfo=UTC) # Friday 10:00:30 ET, market open
QUOTE_T = "2026-10-16T14:00:00Z"
TODAY, LATER = "2026-10-16", "2026-10-19"


@pytest.fixture(autouse=True)
def _reset_state():
A.FEED_STATE.update(options=None, options_checked=0.0, stocks=None)
A._CONTRACT_CACHE.clear()
yield
A.FEED_STATE.update(options=None, options_checked=0.0, stocks=None)
A._CONTRACT_CACHE.clear()


def _row(sym, exp, k, typ):
return {"symbol": sym, "expiration_date": exp, "strike_price": str(k), "type": typ, "root_symbol": "SPY",
"multiplier": "100", "open_interest": "1000", "open_interest_date": "2026-10-15"}


ROWS = [_row("SPY261016C00100500", TODAY, 100.5, "call"), _row("SPY261016P00099500", TODAY, 99.5, "put"),
_row("SPY261016C00115000", TODAY, 115, "call"), _row("SPY261019C00101000", LATER, 101, "call")]


def _fair(k, typ, exp, iv):
T = time_to_expiry(datetime(2026, 10, 16, 14, 0, 0, tzinfo=UTC), date.fromisoformat(exp), "PM")
return (call_price if typ == "call" else put_price)(100.0, k, T, 0.0, iv)


def _q(px, half=0.002):
return {"bp": round(px - half, 4), "ap": round(px + half, 4), "t": QUOTE_T}


def handler(req: httpx.Request) -> httpx.Response:
p, q = req.url.path, req.url.params
assert "/v2/orders" not in p
if p == "/v2/stocks/SPY/trades/latest":
return httpx.Response(200, json={"symbol": "SPY", "trade": {"p": 100.0, "t": "2026-10-16T14:00:05Z"}})
if p == "/v2/options/contracts":
return httpx.Response(200, json={"option_contracts": ROWS, "next_page_token": None})
if p == "/v1beta1/options/snapshots/SPY":
if q["feed"] == "opra":
return httpx.Response(403, json={"message": "subscription does not permit"})
snaps = { # same-day contracts carry a quote but no impliedVolatility, as Alpaca serves them
"SPY261016C00100500": {"latestQuote": _q(_fair(100.5, "call", TODAY, 0.18))},
"SPY261016P00099500": {"latestQuote": _q(_fair(99.5, "put", TODAY, 0.22))},
"SPY261016C00115000": {"latestQuote": {"bp": 0.0, "ap": 0.01, "t": QUOTE_T}}, # far OTM, no bid
"SPY261019C00101000": {"impliedVolatility": 0.19, "latestQuote": _q(_fair(101, "call", LATER, 0.19))},
}
return httpx.Response(200, json={"snapshots": snaps, "next_page_token": None})
return httpx.Response(404, json={"message": "not mocked"})


def _chain(tmp_path, h=handler):
client = httpx.Client(transport=httpx.MockTransport(h))
src = A.AlpacaSource(A.AlpacaCreds("k", "s", "paper"), client=client,
rate=RateLimiter(tmp_path / "rl.sqlite", cap=60, reserve=15))
return src.fetch_chain("SPY", AS_OF, None)


def test_same_day_iv_is_solved_from_the_indicative_mid(tmp_path):
ch = _chain(tmp_path)
assert ch.feed == "indicative"
c = {x.symbol: x for x in ch.contracts}
call, put = c["SPY261016C00100500"], c["SPY261016P00099500"]
assert call.invalid_reason is None and call.iv_source == "solved_mid" and abs(call.iv - 0.18) < 0.01
assert put.invalid_reason is None and put.iv_source == "solved_mid" and abs(put.iv - 0.22) < 0.01
assert any("expiring today use an IV solved from the indicative quote" in w for w in ch.warnings)


def test_unusable_same_day_quote_stays_invalid(tmp_path):
far = {x.symbol: x for x in _chain(tmp_path).contracts}["SPY261016C00115000"]
assert far.iv is None and far.invalid_reason == "mid_unusable"


def test_later_expiries_keep_alpacas_own_iv(tmp_path):
later = {x.symbol: x for x in _chain(tmp_path).contracts}["SPY261019C00101000"]
assert later.iv_source == "indicative" and later.iv == 0.19


def test_quote_far_from_the_spot_time_is_not_solved(tmp_path):
def stale(req):
r = handler(req)
if req.url.path == "/v1beta1/options/snapshots/SPY" and req.url.params["feed"] == "indicative":
j = r.json()
for s in j["snapshots"].values():
s["latestQuote"]["t"] = "2026-10-16T13:50:00Z" # 10 minutes before the spot trade
return httpx.Response(200, json=j)
return r
call = {x.symbol: x for x in _chain(tmp_path, stale).contracts}["SPY261016C00100500"]
assert call.iv is None and call.invalid_reason == "quote_spot_misaligned"
2 changes: 1 addition & 1 deletion tests/test_vol_drift_dex.py
Original file line number Diff line number Diff line change
Expand Up @@ -440,7 +440,7 @@ def test_flat_pairing_never_claims_zero_change():
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(")
i, j = src.index("// ---------- DEX: a Levels now tile"), src.index("const WEEKDAY = new Intl.DateTimeFormat(")
assert not BANNED.search(src[i:j]) and not DASHES.search(src[i:j])


Expand Down
55 changes: 33 additions & 22 deletions web/src/screens/LiveMap.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -895,6 +895,7 @@ function LevelsPanel({
def: GEX_UNITS,
},
);
if (m.dex) tiles.push(dexTile(m.dex, onExplain));
} else {
tiles.push({
key: "abs",
Expand Down Expand Up @@ -941,7 +942,7 @@ function LevelsPanel({
// No usable quotes: every current-chain value is unavailable, never a neutral sign or a $0 total. The 10:00
// reference levels (frozen) come from the capture, so they stay.
if (m.quotes?.usable === false) {
const current = frozen ? ["sign", "net", "abs"] : ["cpw", "cw", "pw", "zg", "sign", "net", "abs"];
const current = frozen ? ["sign", "net", "abs", "dex"] : ["cpw", "cw", "pw", "zg", "sign", "net", "abs", "dex"];
for (const k of tiles) {
if (!current.includes(k.key)) continue;
Object.assign(k, { value: "Unavailable", valueClass: "word", valueStyle: { color: "var(--muted)" }, sub: "no usable quotes", def: undefined });
Expand All @@ -963,7 +964,10 @@ function LevelsPanel({

return (
<Panel title={title} right={right} className="levels-panel">
<div className={`kpis ${layout}`} style={layout === "strip" ? { gridTemplateColumns: `repeat(${tiles.length}, minmax(0, 1fr))` } : undefined}>
<div
className={`kpis ${layout}`}
style={layout === "strip" ? ({ "--n": tiles.length, "--half": Math.ceil(tiles.length / 2) } as CSSProperties) : undefined}
>
{tiles.map((k) => (
<div className={`kpi ${k.wide ? "wide" : ""}`} key={k.key}>
<small>{k.label}</small>
Expand All @@ -976,7 +980,6 @@ function LevelsPanel({
))}
</div>
{m.signed && m.magnitude && <MagnitudeRef mg={m.magnitude} layout={layout} onExplain={onExplain} />}
{m.signed && m.dex && <DexLine dx={m.dex} onExplain={onExplain} />}
{!m.signed && (
<p className="kpi-note">
<b>{UNSIGNED_NOTE}</b> {SIDES_NOTE}
Expand Down Expand Up @@ -1375,31 +1378,39 @@ function MethodBody({ m, ticker }: { m: GexMap | null; ticker: string }) {
);
}

// ---------- DEX: one context line under Net GEX size (positioning size only) ----------
// ---------- DEX: a Levels now tile (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 (
<div className="dex-line">
<small>
DEX
<button type="button" className="mag-info" title={DEX_TIP} aria-label="What DEX means" onClick={onExplain}>
<Icon name="info" size={12} />
</button>
</small>
{dx.available && dx.net_usd !== null ? (
<span>
Net <b>{gex(dx.net_usd, { sign: true })}</b> of delta ({dexSide(dx.net_usd)}) {"\u00b7"} calls {gex(dx.call_usd)}, puts {gex(dx.put_usd)}, unsigned.{" "}
<span className="muted">From {dayShort(dx.oi_date)} open interest: not a live flow scoreboard.</span>
</span>
) : (
<span className="muted">Unavailable: {dx.reason ?? "no usable contracts"}</span>
)}
</div>
function dexTile(dx: Dex, onExplain?: () => void): Kpi {
const label = (
<>
DEX
<button type="button" className="mag-info" title={DEX_TIP} aria-label="What DEX means" onClick={onExplain}>
<Icon name="info" size={12} />
</button>
</>
);
if (!dx.available || dx.net_usd === null) {
return { key: "dex", label, value: "Unavailable", valueClass: "word", valueStyle: { color: "var(--muted)" }, sub: dx.reason ?? "no usable contracts" };
}
return {
key: "dex",
label,
value: gex(dx.net_usd, { sign: true }),
sub: (
<>
calls <span className="g">{gex(dx.call_usd)}</span> / puts <span className="p">{gex(dx.put_usd)}</span>
</>
),
def: (
<>
Net delta ({dexSide(dx.net_usd)}) from {dayShort(dx.oi_date)} open interest, not live flow.
</>
),
};
}

// ---------- Vol Drift: is ATM implied volatility rising or falling today ----------
Expand Down
45 changes: 18 additions & 27 deletions web/src/styles/app.css
Original file line number Diff line number Diff line change
Expand Up @@ -1650,9 +1650,26 @@ button.cell {
color: var(--text);
font-weight: 600;
}
/* Present strip: one row of --n tiles; two balanced rows below 1400px, two per row on phones. Flex so a short
last row fills the width (no empty cells). */
.kpis.strip {
display: flex;
flex-wrap: wrap;
}
.kpis.strip .kpi {
flex: 1 1 calc(100% / var(--n, 6) - 1px);
padding: 12px 16px 14px;
}
@media (max-width: 1400px) {
.kpis.strip .kpi {
flex-basis: calc(100% / var(--half, 3) - 1px);
}
}
@media (max-width: 760px) {
.kpis.strip .kpi {
flex-basis: calc(50% - 1px);
}
}

/* captions under charts */
.chart-notes {
Expand Down Expand Up @@ -2274,33 +2291,7 @@ button.cell {
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,
/* ---------- Vol drift card (DEX is a Levels now tile and uses the .kpi styles) ---------- */
.vd-panel .muted {
color: var(--muted);
}
Expand Down
Loading