{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": "# Polymarket Resolution Archive — Sample Analysis\n\nThis notebook runs against the **free teaser slice** exactly as it runs against the full archive —\nsame schema, same code. Put the notebook in the same folder as the dataset files\n(`markets.csv`, `prices_daily.csv.gz`, `provenance.csv`) and run top to bottom.\n\nRequires: `pandas`, `matplotlib` (`pip install pandas matplotlib`)." }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from pathlib import Path\n", "\n", "import pandas as pd\n", "import matplotlib.pyplot as plt\n", "\n", "DATA_DIR = Path(\".\")\n", "\n", "markets = pd.read_csv(DATA_DIR / \"markets.csv\", parse_dates=[\"created_at\", \"resolved_at\"])\n", "prices = pd.read_csv(DATA_DIR / \"prices_daily.csv.gz\", parse_dates=[\"date_utc\"])\n", "provenance = pd.read_csv(\n", " DATA_DIR / \"provenance.csv\", parse_dates=[\"requested_at\", \"proposed_at\", \"settled_at\"]\n", ")\n", "\n", "print(f\"markets: {len(markets):>10,} rows\")\n", "print(f\"prices: {len(prices):>10,} rows ({prices['condition_id'].nunique():,} markets)\")\n", "print(f\"provenance: {len(provenance):>10,} rows\")\n", "print(f\"total volume represented: ${markets['volume_usd'].sum():,.0f}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## What's in here — coverage by tag\n", "\n", "Tags are `|`-separated event slugs. Volume concentrates in politics/elections, but the long\n", "tail (sports, crypto, science, pop culture) is where most *markets* live." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "tag_volume = (\n", " markets.assign(tag=markets[\"tags\"].fillna(\"\").str.split(\"|\"))\n", " .explode(\"tag\")\n", " .query(\"tag != '' and tag != 'all'\")\n", " .groupby(\"tag\")\n", " .agg(markets=(\"id\", \"count\"), volume_usd=(\"volume_usd\", \"sum\"))\n", " .sort_values(\"volume_usd\", ascending=False)\n", ")\n", "tag_volume.head(15).style.format({\"volume_usd\": \"${:,.0f}\"})" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Were the markets calibrated? Price 30 days out vs. what actually happened\n", "\n", "The core question for anyone backtesting an event-trading strategy: when a market said\n", "\"30%\", did the event happen 30% of the time? We take each binary market's **Yes** price\n", "~30 days before resolution and compare against the realized outcome, bucketed by price." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": "ACCENT = \"#4269d0\" # single-series hue; reference line stays neutral gray\nDAYS_OUT = 30\n\nbinary = markets[markets[\"outcomes\"] == \"Yes|No\"].copy()\nbinary[\"won\"] = (binary[\"winning_outcome\"] == \"Yes\").astype(int)\n\nyes_prices = prices[prices[\"outcome\"] == \"Yes\"].merge(\n binary[[\"condition_id\", \"resolved_at\", \"won\"]], on=\"condition_id\", how=\"inner\"\n)\n# resolved_at is tz-aware UTC, date_utc is naive — strip tz before subtracting\nyes_prices[\"days_before\"] = (\n yes_prices[\"resolved_at\"].dt.tz_localize(None).dt.normalize() - yes_prices[\"date_utc\"]\n).dt.days\n\nwindow = yes_prices[yes_prices[\"days_before\"].between(DAYS_OUT - 5, DAYS_OUT + 5)].copy()\nwindow[\"dist\"] = (window[\"days_before\"] - DAYS_OUT).abs()\nsnapshot = window.sort_values(\"dist\").groupby(\"condition_id\").first().reset_index()\n\nsnapshot[\"bucket\"] = pd.cut(snapshot[\"price\"], bins=[i / 10 for i in range(11)])\ncalib = snapshot.groupby(\"bucket\", observed=True).agg(\n mean_price=(\"price\", \"mean\"), realized=(\"won\", \"mean\"), n=(\"won\", \"size\")\n)\ncalib = calib[calib[\"n\"] >= 5] # drop unstable buckets\n\nfig, ax = plt.subplots(figsize=(7, 6))\nax.plot([0, 1], [0, 1], linestyle=\"--\", linewidth=1, color=\"#9aa0a6\", zorder=1)\nax.plot(calib[\"mean_price\"], calib[\"realized\"], linewidth=2, color=ACCENT, zorder=2)\nax.scatter(calib[\"mean_price\"], calib[\"realized\"], s=64, color=ACCENT, zorder=3)\nfor _, row in calib.iterrows():\n ax.annotate(f\"n={row['n']:,.0f}\", (row[\"mean_price\"], row[\"realized\"]),\n textcoords=\"offset points\", xytext=(8, -4), fontsize=8, color=\"#5f6368\")\nax.set_xlabel(f\"Yes price, ~{DAYS_OUT} days before resolution\")\nax.set_ylabel(\"Realized frequency of Yes\")\nax.set_title(f\"Calibration: market price {DAYS_OUT} days out vs. realized outcome\\n\"\n f\"({len(snapshot):,} binary markets; dashed line = perfect calibration)\")\nax.set_xlim(0, 1); ax.set_ylim(0, 1)\nax.spines[[\"top\", \"right\"]].set_visible(False)\nax.grid(alpha=0.2)\nplt.tight_layout(); plt.show()" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## How resolution actually works — UMA oracle mechanics\n", "\n", "`provenance.csv` is the part you can't scrape from Polymarket's market API: on-chain\n", "settlement records from the UMA Optimistic Oracle — who proposed the outcome, whether it\n", "was disputed, and how long settlement took. Useful for modeling *when* capital is released\n", "back after an event, and which market types attract disputes." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "liveness_h = (provenance[\"liveness_lag_sec\"] / 3600).clip(upper=(provenance[\"liveness_lag_sec\"] / 3600).quantile(0.99))\n", "dispute_rate = provenance[\"disputed\"].mean()\n", "\n", "fig, ax = plt.subplots(figsize=(7, 4.5))\n", "ax.hist(liveness_h, bins=40, color=ACCENT, edgecolor=\"white\", linewidth=0.5)\n", "med = liveness_h.median()\n", "ax.axvline(med, linestyle=\"--\", linewidth=1, color=\"#5f6368\")\n", "ax.annotate(f\"median {med:.1f}h\", (med, ax.get_ylim()[1] * 0.9),\n", " textcoords=\"offset points\", xytext=(8, 0), fontsize=9, color=\"#5f6368\")\n", "ax.set_xlabel(\"Hours from settlement proposal to on-chain settlement (99th-pct clipped)\")\n", "ax.set_ylabel(\"Markets\")\n", "ax.set_title(\"UMA settlement liveness — how long until an outcome is final\")\n", "ax.spines[[\"top\", \"right\"]].set_visible(False)\n", "ax.grid(alpha=0.2, axis=\"y\")\n", "plt.tight_layout(); plt.show()\n", "\n", "print(f\"dispute rate: {dispute_rate:.2%} of settled markets\")\n", "print(f\"median proposal lag: {provenance['proposal_lag_sec'].median() / 3600:.1f}h after oracle request\")\n", "disputed = provenance[provenance[\"disputed\"]]\n", "if len(disputed):\n", " print(f\"\\nmost recent disputed settlements:\")\n", " print(disputed.sort_values(\"settled_at\", ascending=False)[[\"slug\", \"resolved_outcome\", \"settled_at\"]].head(5).to_string(index=False))" ] }, { "cell_type": "markdown", "metadata": {}, "source": "## The full archive\n\nThe teaser is the top slice by volume. The full archive is the complete **resolution\nlayer**: every resolved Polymarket market with its winning outcome, the on-chain UMA\nsettlement provenance table, and daily price history — same schema, one purchase\n(next refresh included), yours for internal research use.\n\nColumn-level docs: `DATA-DICTIONARY.md` ships alongside the data." } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python", "version": "3.11" } }, "nbformat": 4, "nbformat_minor": 5 }