diff --git a/README.md b/README.md index 14a25ef..936eadd 100644 --- a/README.md +++ b/README.md @@ -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. @@ -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 diff --git a/gexlab/config.py b/gexlab/config.py index 6a4c8fc..ed89c11 100644 --- a/gexlab/config.py +++ b/gexlab/config.py @@ -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. diff --git a/gexlab/engine/dex.py b/gexlab/engine/dex.py index 98e5b59..e803cc4 100644 --- a/gexlab/engine/dex.py +++ b/gexlab/engine/dex.py @@ -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. diff --git a/gexlab/sources/alpaca.py b/gexlab/sources/alpaca.py index 902498a..a4dea5f 100644 --- a/gexlab/sources/alpaca.py +++ b/gexlab/sources/alpaca.py @@ -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) diff --git a/tests/test_same_day_indicative.py b/tests/test_same_day_indicative.py new file mode 100644 index 0000000..846080c --- /dev/null +++ b/tests/test_same_day_indicative.py @@ -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" diff --git a/tests/test_vol_drift_dex.py b/tests/test_vol_drift_dex.py index 6e15bee..93f9bc8 100644 --- a/tests/test_vol_drift_dex.py +++ b/tests/test_vol_drift_dex.py @@ -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]) diff --git a/web/src/screens/LiveMap.tsx b/web/src/screens/LiveMap.tsx index 4c1e855..bc76459 100644 --- a/web/src/screens/LiveMap.tsx +++ b/web/src/screens/LiveMap.tsx @@ -895,6 +895,7 @@ function LevelsPanel({ def: GEX_UNITS, }, ); + if (m.dex) tiles.push(dexTile(m.dex, onExplain)); } else { tiles.push({ key: "abs", @@ -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 }); @@ -963,7 +964,10 @@ function LevelsPanel({ return ( -
+
{tiles.map((k) => (
{k.label} @@ -976,7 +980,6 @@ function LevelsPanel({ ))}
{m.signed && m.magnitude && } - {m.signed && m.dex && } {!m.signed && (

{UNSIGNED_NOTE} {SIDES_NOTE} @@ -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 ( -

- - 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"} - )} -
+function dexTile(dx: Dex, onExplain?: () => void): Kpi { + const label = ( + <> + DEX + + ); + 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 {gex(dx.call_usd)} / puts {gex(dx.put_usd)} + + ), + 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 ---------- diff --git a/web/src/styles/app.css b/web/src/styles/app.css index 7376244..c537825 100644 --- a/web/src/styles/app.css +++ b/web/src/styles/app.css @@ -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 { @@ -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); }