{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "147927eb",
   "metadata": {},
   "source": "# Spitzer API: quant quickstart\n\nUpdated November 4, 2026. From a bearer token to an exploratory factor sheet in one sitting, using only requests and pandas, with the additional evidence needed for calibration explained below. Every runnable step is also a cell of the companion notebook, spitzer_quant_quickstart.ipynb (download it from https://spitzerdata.com/api). Field definitions, units, formulas and the study statistics are in the data dictionary (docs/api/data-dictionary.md, GET /api/spitzer/schema); budgets, caches and latency are in workloads-and-latency.md.\n\nBudget note: the live book is one call, a history pull is five calls, and this walk-through pulls fifty histories. On Research (50 calls per 10 minutes) the helper below sleeps on HTTP 429 for Retry-After, so the history loop takes about an hour. On Research+ (10,000 calls per 30 minutes) it runs straight through. Credentials are read from the SPITZER_API_USERNAME and SPITZER_API_PASSWORD environment variables or prompted for; never paste them into a notebook cell.\n\nThis notebook is generated from docs/api/quant-quickstart.md; the guide carries the same cells with their explanations. Only requests and pandas are needed. Credentials come from the environment or a prompt; never store them in a cell."
  },
  {
   "cell_type": "markdown",
   "id": "d7cbe03a",
   "metadata": {},
   "source": "## 1. Sign in\n\nPOST /login with your account email and password. The response carries an opaque bearer, your plan level and expires_in_hours (24). Send the bearer as Authorization: Bearer <token> on every call and log in again on HTTP 401; there is no refresh endpoint."
  },
  {
   "cell_type": "code",
   "id": "1740a552",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "import datetime as dt\nimport getpass\nimport os\nimport time\n\nimport pandas as pd\nimport requests\n\nBASE = os.environ.get(\"SPITZER_API_BASE\", \"https://spitzerdata.com\")\nUSERNAME = os.environ.get(\"SPITZER_API_USERNAME\") or input(\"Spitzer API username (email): \")\nPASSWORD = os.environ.get(\"SPITZER_API_PASSWORD\") or getpass.getpass(\"Password: \")\n\nsession = requests.Session()\nsession.headers[\"User-Agent\"] = \"spitzer-quant-quickstart/1.0\"\n\n\ndef login():\n    r = session.post(f\"{BASE}/login\", json={\"username\": USERNAME, \"password\": PASSWORD},\n                     timeout=30)\n    if r.status_code in (401, 403):\n        raise SystemExit(r.json().get(\"detail\"))     # bad credentials / plan without API access\n    r.raise_for_status()\n    body = r.json()\n    session.headers[\"Authorization\"] = f\"Bearer {body['token']}\"\n    print(f\"level={body['level']} expires_in_hours={body['expires_in_hours']}\")\n    return body\n\n\nlogin_info = login()"
  },
  {
   "cell_type": "markdown",
   "id": "7ab70bf0",
   "metadata": {},
   "source": "## 2. One helper for every pull\n\nSuccessful responses wrap the payload as {\"status\":\"ok\",\"value\":...}. Unknown situations return HTTP 404 with an #ERR value; a budget overrun returns HTTP 429 with Retry-After; a cold-cache build that outlasts Cloudflare's 100-second origin limit surfaces as HTTP 524 while the build finishes in the worker, so a retry a minute later is served from cache. The helper handles all three and records the elapsed time of every call, which is the only latency figure that matters: the one from your location."
  },
  {
   "cell_type": "code",
   "id": "1600c7d3",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "CALLS = []   # (path, elapsed_s, status): your own latency log\n\n\ndef api(path, retries=6, **params):\n    \"\"\"GET one endpoint and return the `value` of the {\"status\",\"value\"} envelope.\n    Sleeps on 429 for Retry-After, logs in again once on 401, and waits 60 s on a\n    Cloudflare 524 / 5xx (a cold-cache build that completes in the worker).\"\"\"\n    relogged = False\n    for attempt in range(retries):\n        t0 = time.monotonic()\n        r = session.get(f\"{BASE}{path}\", params=params, timeout=120)\n        CALLS.append((path, round(time.monotonic() - t0, 3), r.status_code))\n        if r.status_code == 429:\n            wait = int(r.headers.get(\"Retry-After\", \"60\"))\n            print(f\"429 on {path}: budget exhausted, sleeping {wait} s\")\n            time.sleep(wait)\n            continue\n        if r.status_code == 401 and not relogged:\n            login()\n            relogged = True\n            continue\n        if r.status_code in (502, 503, 504, 524):\n            print(f\"{r.status_code} on {path}: cold build or restart, retrying in 60 s\")\n            time.sleep(60)\n            continue\n        if r.status_code == 404:\n            return None          # unknown situation / company (value is an #ERR string)\n        r.raise_for_status()     # 400 = bad parameter, 403 = plan restriction\n        body = r.json()\n        if body.get(\"status\") != \"ok\":\n            raise RuntimeError(body.get(\"value\"))\n        return body[\"value\"]\n    raise RuntimeError(f\"gave up on {path} after {retries} attempts\")"
  },
  {
   "cell_type": "markdown",
   "id": "4e203b02",
   "metadata": {},
   "source": "## 3. The field dictionary (one call)\n\nGET /api/spitzer/schema is the same dictionary as docs/api/data-dictionary.md: one entry per field with aliases, unit, formula, point-in-time tag, first date, cadence, null rule and the study statistics. Keep it next to the data."
  },
  {
   "cell_type": "code",
   "id": "498cb919",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "schema = api(\"/api/spitzer/schema\")\nfields = pd.DataFrame(schema[\"fields\"]).set_index(\"name\")\nfields[[\"surface\", \"unit\", \"point_in_time\", \"first_date\", \"cadence\"]].head(12)"
  },
  {
   "cell_type": "markdown",
   "id": "3d1c01f5",
   "metadata": {},
   "source": "## 4. Pull the live book (one call)\n\nGET /api/spitzer/live-metrics returns every Live Metrics row as the website shows it after its live refresh. Each row carries sit_id, parties and tickers, a metrics map of raw values for every column (the document's fields list names them), a display map of the formatted cells, the 1D/3D/5D/1W change windows and the SSF URL. table=live limits it to announced deals; pre_event and asset_sales are the other books. refreshed_at and live_prices_at tell you which build you received: the document is cached for 30 seconds per worker and the live-priced columns move on the 60-second tick.\n\nFractions are decimals (0.05 = 5%). Blank cells are null; the dictionary's null rule says why (no offer on a pre-event row, a frozen quote, a below-market offer, no usable comps)."
  },
  {
   "cell_type": "code",
   "id": "f288dc0a",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "book = api(\"/api/spitzer/live-metrics\", table=\"live\")\nprint(book[\"refreshed_at\"], book[\"live_prices_at\"], book[\"count\"], \"rows\")\nprint(\"metric keys:\", book[\"fields\"])\n\nlive = pd.json_normalize(book[\"rows\"], sep=\".\")\nkeep = [\"sit_id\", \"target\", \"acquirer\", \"target_ticker\", \"situation_type\"] + [\n    f\"metrics.{f}\" for f in book[\"fields\"]]\nlive = live[[c for c in keep if c in live.columns]]\nlive.columns = [c.replace(\"metrics.\", \"\") for c in live.columns]\nlive = live.set_index(\"sit_id\")\nlive.sort_values(\"all_in_spread\", ascending=False).head(10)"
  },
  {
   "cell_type": "markdown",
   "id": "9702574b",
   "metadata": {},
   "source": "## 5. Choose up to fifty currently live situations\n\nGET /api/spitzer/deals is the directory: every situation with status, a live flag, announcement, undisturbed and close dates, EV and the Bloomberg action ID. Rival bidders share a target ticker, so always key by sit_id. The sample below takes up to fifty currently live situations with known announcement dates and the highest available liquidity. Selecting today's live book excludes situations that have already disappeared or resolved, and selecting by current liquidity introduces additional selection bias. This is an exploratory sample, not a historical inception universe or an outcome-labelled calibration sample."
  },
  {
   "cell_type": "code",
   "id": "c32bd214",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "directory = pd.DataFrame(api(\"/api/spitzer/deals\", status=\"all\", limit=5000)[\"items\"])\ndirectory = directory.set_index(\"sit_id\")\neligible = directory[directory[\"live\"].eq(True)].copy()\neligible[\"announced\"] = pd.to_datetime(eligible[\"announced\"], errors=\"coerce\").dt.strftime(\"%Y-%m-%d\")\neligible = eligible.dropna(subset=[\"announced\"])\nliquidity = pd.to_numeric(live[\"liquidity_usd_mn\"], errors=\"coerce\")\nsample_ids = liquidity.reindex(eligible.index.intersection(live.index)).dropna().nlargest(50).index\nsample = eligible.loc[sample_ids]\nif sample.empty:\n    raise RuntimeError(\"No currently live situations have both a known announcement and available liquidity.\")\nsample[[\"target\", \"acquirer\", \"status\", \"live\", \"announced\"]]"
  },
  {
   "cell_type": "markdown",
   "id": "e2ecaba4",
   "metadata": {},
   "source": "## 6. Pull the history (five calls per pull)\n\nGET /api/spitzer/live-metrics/history returns recorded daily observations for one situation. Specify sit_id or ticker (plus acquirer to identify a bidder), from and to as ISO dates, and fields to trim the metrics map. Each row has date, source, metrics and notes. source is \"published\" for observations captured as served, and \"reconstructed\" for historical estimates from the stored break series. Reconstruction is not point-in-time evidence: offer terms, comp weights and closing guidance can contain later information, and the row grid is not a verified exchange-session calendar. Close-unit normalization preserves the stored all-in spread numerator, including its carry; undated gross offer terms, gross spread, gross chance and premium remain unavailable rather than substituting an all-in offer. Read the notes and field_dictionary alongside every observation.\n\nBreak and close history begins September 12, 2022; all-in columns begin January 2, 2025. Reconstructed offer-based fields and their deltas are withheld before a known announcement and when the announcement date is unknown. Published observations with an unknown announcement retain their observed provenance with an explicit note. target_close, target_break and gross_downside remain available where their inputs exist. target_break is a nominal price in the listing's major unit, not a return. These safeguards do not repair retrospective inputs or create settlement payoffs.\n\nThe metrics are target_close, target_break, target_break_rt, offer, all_in_offer, premium, gross_downside, downside_rt, gross_spread, all_in_spread, implied_chance_gross, implied_chance_allin and ann_all_in, plus 1/5/30-row deltas (legacy field_1d, field_5d, field_30d keys) of implied_chance_allin, all_in_spread, gross_spread and target_break. Missing required inputs produce nulls. The response's field_dictionary describes each field.\n\nA window is served from its newest edge and capped at 400 recorded rows per call: when truncated is true, effective_from is the oldest date covered, and you walk further back with to = effective_from - 1 day. The helper does that and bounds the calls per situation."
  },
  {
   "cell_type": "code",
   "id": "4a2bf900",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "ALL_IN_FROM = \"2025-01-02\"     # all-in columns start here (break and closes from 2022-09-12)\n\n\ndef history(sit_id, date_from, date_to, max_calls=3):\n    \"\"\"Every row for one situation between two dates, walking back past the\n    400-row cap (truncated / effective_from). Five calls of budget per call.\"\"\"\n    frames, to = [], date_to\n    for _ in range(max_calls):\n        doc = api(\"/api/spitzer/live-metrics/history\", sit_id=sit_id,\n                  **{\"from\": date_from, \"to\": to})\n        if doc is None:\n            break\n        if doc[\"rows\"]:\n            frames.append(pd.DataFrame([{\"date\": r[\"date\"], \"source\": r[\"source\"], **r[\"metrics\"]}\n                                        for r in doc[\"rows\"]]))\n        if not doc[\"truncated\"] or doc[\"effective_from\"] <= date_from:\n            break\n        to = (dt.date.fromisoformat(doc[\"effective_from\"]) - dt.timedelta(days=1)).isoformat()\n    if not frames:\n        return pd.DataFrame()\n    out = pd.concat(frames).drop_duplicates(\"date\").sort_values(\"date\")\n    out.insert(0, \"sit_id\", sit_id)\n    return out\n\n\ntoday = dt.date.today().isoformat()\npanels = []\nfor sit_id, row in sample.iterrows():\n    start = max(row[\"announced\"], ALL_IN_FROM)\n    end = today\n    h = history(sit_id, start, end)\n    if len(h):\n        panels.append(h)\n    print(f\"{sit_id} {str(row['target'])[:28]:<28} {len(h):>4} rows  {start} -> {end}\")\n\nif not panels:\n    raise RuntimeError(\"No history rows were returned for the selected live situations.\")\npanel = pd.concat(panels, ignore_index=True)\npanel[\"date\"] = pd.to_datetime(panel[\"date\"])\npanel.groupby(\"source\").size()"
  },
  {
   "cell_type": "markdown",
   "id": "c0eb95d0",
   "metadata": {},
   "source": "## 7. The factor sheet: rank IC at 5 and 30 recorded rows\n\nForward returns here use target_close over each situation's recorded rows. Those rows are not a verified exchange-session calendar. This introductory calculation is a retrospective association diagnostic: it does not reconstruct settlement payoffs, an unbiased inception universe or historical data availability. Reconstructed fields may be unavailable where the required historical inputs do not exist. The sheet reports pooled Spearman rho and mean daily cross-sectional rank IC. It omits a naive independent-day t-statistic because overlapping forward outcomes make daily observations dependent. The study's t_cl instead tests an OLS slope with situation-clustered errors; it is not a test of Spearman rho.\n\nCompare pooled_rho with the study column only after comparing dates, eligibility, field provenance and missing outcomes. A different sample can change both the sign and magnitude. This example does not reproduce the complete corrected study or establish prospective skill."
  },
  {
   "cell_type": "code",
   "id": "644c5787",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "METRICS = [\"gross_spread\", \"all_in_spread\", \"gross_downside\", \"downside_rt\",\n           \"implied_chance_gross\", \"implied_chance_allin\", \"ann_all_in\", \"premium\",\n           \"implied_chance_allin_5d\", \"all_in_spread_5d\", \"gross_spread_5d\", \"target_break_5d\"]\nHORIZONS = (5, 30)\n\npanel = panel.sort_values([\"sit_id\", \"date\"]).reset_index(drop=True)\nclose_by_deal = panel.groupby(\"sit_id\")[\"target_close\"]\nfor h in HORIZONS:\n    panel[f\"fret_{h}d\"] = close_by_deal.shift(-h) / panel[\"target_close\"] - 1\n\n\ndef spearman(x, y):\n    \"\"\"Spearman rho with pandas only: the Pearson correlation of the ranks.\"\"\"\n    ok = x.notna() & y.notna()\n    if ok.sum() < 3:\n        return float(\"nan\")\n    return x[ok].rank().corr(y[ok].rank())\n\n\ndef factor_sheet(panel, metrics=METRICS, horizons=HORIZONS, min_names=8):\n    rows = []\n    for m in metrics:\n        if m not in panel:\n            continue\n        for h in horizons:\n            y = f\"fret_{h}d\"\n            sub = panel[[m, y, \"sit_id\", \"date\"]].dropna()\n            pooled = spearman(sub[m], sub[y])                 # the study's rho\n            daily = {}                                         # cross-sectional IC per date\n            for date, d in sub.groupby(\"date\"):\n                if len(d) >= min_names:\n                    daily[date] = spearman(d[m], d[y])\n            daily = pd.Series(daily, dtype=float).dropna()\n            rows.append({\"metric\": m, \"horizon_rows\": h, \"pooled_rho\": round(pooled, 4),\n                         \"daily_ic_mean\": round(daily.mean(), 4) if len(daily) else float(\"nan\"),\n                         \"days\": len(daily),\n                         \"deal_days\": len(sub), \"deals\": sub[\"sit_id\"].nunique()})\n    return pd.DataFrame(rows).set_index([\"metric\", \"horizon_rows\"])\n\n\nsheet = factor_sheet(panel)\nsheet"
  },
  {
   "cell_type": "markdown",
   "id": "943b43f9",
   "metadata": {},
   "source": "## 8. What calibration requires\n\nimplied_chance_allin is the ratio downside / (downside + spread), conditional on the modeled offer and break. It is not an independently estimated physical completion probability. The currently live sample above has no verified terminal outcomes, so this quickstart does not calculate calibration or invent completion labels.\n\nThe directory's live flag or close_date alone cannot verify a terminal outcome and its date. A calibration study needs an explicit outcome ledger keyed by sit_id, with a verified completion or termination event, its recorded date and the source establishing it. Do not treat every non-live status as a failed deal or use a completion date as a termination date. Unknown outcomes or dates remain unavailable.\n\nBefore calculating calibration, require every observation to be strictly before its verified resolution date and fix the observation rule in advance. For a first-observed deal-level diagnostic, use the first eligible observed score under that rule; do not average scores across the eventual lifecycle. Keep unresolved situations explicit and assess inception-universe coverage, retention and historical input availability. These controls do not by themselves make reconstructed inputs point-in-time.\n\nThe corrected study's selected resolved-sample diagnostics are in the data dictionary. AUC describes ranking, Brier measures squared probability error, and reliability bins compare scores with observed completion fractions. Its deal-level AUC uses the first eligible observed score before recorded resolution, which may still be later than announcement. Neither a whole-lifecycle score nor the 2026 subset is a validated prospective cohort, and resolved-only completion rates are not an upper bound on eventual completion."
  },
  {
   "cell_type": "markdown",
   "id": "943eeaee",
   "metadata": {},
   "source": "## 9. Read the WSS push log (Immediate plan)\n\nPushes arrive on the WebSocket, which requests cannot speak, so the recorder is a separate script that appends one JSON object per frame with the time it was received. It needs the websockets package (pip install websockets; on versions before 13 the keyword is extra_headers). Leave it running next to your session and send a ping every few minutes.\n\nBack in the notebook, read the log with pandas. News pushes carry the article summary (slug, headline, tickers, published_at); the difference between received_at and published_at is the publish-to-push latency as you observed it. Data pushes carry the full parameter map for a subscribed ticker and arrive only when a value changed on the 60-second tick, so a quiet ticker produces no frames. Result frames carry remaining, the authoritative pull-budget signal."
  },
  {
   "cell_type": "markdown",
   "id": "0d855789",
   "metadata": {},
   "source": "Recorder script (needs the websockets package; not run here):\n\n```python\n# wss_recorder.py: append every frame to wss_push_log.jsonl with a receive time.\nimport asyncio, datetime as dt, json, os, websockets\n\nTOKEN = os.environ[\"SPITZER_API_TOKEN\"]        # the bearer from POST /login\nTICKERS = [\"NSC\", \"WBD\"]\n\n\nasync def main(path=\"wss_push_log.jsonl\"):\n    async with websockets.connect(\"wss://spitzerdata.com/ws\",\n                                  additional_headers={\"Authorization\": f\"Bearer {TOKEN}\"}) as ws:\n        await ws.send(json.dumps({\"type\": \"subscribe\", \"tickers\": TICKERS}))\n        with open(path, \"a\", encoding=\"utf-8\") as f:\n            async for raw in ws:\n                f.write(json.dumps({\"received_at\": dt.datetime.now(dt.timezone.utc).isoformat(),\n                                    \"frame\": json.loads(raw)}) + \"\\n\")\n                f.flush()\n\nasyncio.run(main())\n```"
  },
  {
   "cell_type": "code",
   "id": "169fdbc7",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "PUSH_LOG = os.environ.get(\"SPITZER_PUSH_LOG\", \"wss_push_log.jsonl\")\n\nif not os.path.exists(PUSH_LOG):\n    print(f\"No push log at {PUSH_LOG}: run wss_recorder.py (Immediate plan) and re-run this cell.\")\nelse:\n    log = pd.read_json(PUSH_LOG, lines=True)\n    frames = pd.json_normalize(log[\"frame\"].tolist())\n    frames[\"received_at\"] = pd.to_datetime(log[\"received_at\"], utc=True)\n    pushes = frames[frames[\"type\"] == \"push\"]\n    news = pushes[pushes[\"channel\"] == \"news\"].copy()\n    if len(news):\n        news[\"published_at\"] = pd.to_datetime(news[\"content.published_at\"], utc=True)\n        news[\"latency_s\"] = (news[\"received_at\"] - news[\"published_at\"]).dt.total_seconds()\n        print(\"news pushes:\", len(news))\n        print(news[\"latency_s\"].describe(percentiles=[0.5, 0.9, 0.99]).round(1))\n    data = pushes[pushes[\"channel\"] == \"data\"]\n    if len(data):\n        print(data.groupby(\"ticker\").agg(frames=(\"received_at\", \"size\"),\n                                         first=(\"received_at\", \"min\"), last=(\"received_at\", \"max\")))\n    results = frames[frames[\"type\"] == \"result\"]\n    if len(results) and \"remaining\" in results:\n        print(\"pull budget remaining after the last result frame:\", results[\"remaining\"].iloc[-1])"
  },
  {
   "cell_type": "markdown",
   "id": "47dfc9ac",
   "metadata": {},
   "source": "## 10. Your own latency table\n\nEvery call went through the helper, so the latency distribution per endpoint from your location is already in CALLS. This is the table to keep when sizing a production job; the server-side clocks it runs against are in workloads-and-latency.md."
  },
  {
   "cell_type": "code",
   "id": "53e9e287",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "calls = pd.DataFrame(CALLS, columns=[\"path\", \"elapsed_s\", \"status\"])\ncalls.groupby(\"path\")[\"elapsed_s\"].describe(percentiles=[0.5, 0.9]).round(2)"
  },
  {
   "cell_type": "markdown",
   "id": "086f2e6b",
   "metadata": {},
   "source": "## Support\n\nPlans: https://spitzerdata.com/pricing. Downloads: https://spitzerdata.com/api. Technical support: Greg Falkowski, greg.falkowski@ctfn.news, +1 (609) 410-0556."
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
