Skip to content

docs: add examples/polymarket_anomalies.py — prediction-market shocks#66

Merged
copyleftdev merged 1 commit into
mainfrom
docs/example-polymarket
Jun 2, 2026
Merged

docs: add examples/polymarket_anomalies.py — prediction-market shocks#66
copyleftdev merged 1 commit into
mainfrom
docs/example-polymarket

Conversation

@copyleftdev

@copyleftdev copyleftdev commented Jun 2, 2026

Copy link
Copy Markdown
Owner

What

A third worked example: anomalyx on Polymarket prediction-market data. Pulls a market's price history from Polymarket's public APIs (Gamma for discovery, CLOB for the series — read-only, no key), enriches it with the per-step probability change, runs anomalyx scan, and maps each finding back to its UTC timestamp.

python3 examples/polymarket_anomalies.py                 # top market by volume
python3 examples/polymarket_anomalies.py "bitcoin"       # match by question/slug
python3 examples/polymarket_anomalies.py "fed" --top 15  # search first, then scan flags

Why it's a good fit

A prediction market's implied probability is usually smooth, so a sudden jump is an information shock (news, a debate, a resolution). anomalyx catches:

  • point / mv.mahalanobis → the sharp probability-jump hours;
  • coll.cusum → sustained regime shifts in the odds;
  • the timestamp column is auto-classified a sequence (the 1.1.1 fix) and skipped, so findings are about the odds, not the clock advancing.

Verified live on the MicroStrategy-sells-BTC market (648 hourly points, prob 0.110 → 0.004): coll.cusum caught the 2026‑05‑20 regime shift (mean 0.345 → 0.133), mv.mahalanobis flagged the information-shock hours (05‑11, 05‑15, 06‑01).

Also

Fills in examples/README.md, which had only the stock example — the journal example (shipped in 1.1.1) was missing there.

Scope

Docs/example only — lives outside the Cargo workspace (shells out to the installed binary), so no build / gate / release impact.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Documentation

    • Extended examples documentation with guides for system event and market data anomaly detection, including command examples and timestamp mapping instructions.
  • New Features

    • Added example script demonstrating anomaly detection on market price history data with probability change analysis and temporal event mapping.

Third worked example: pulls a Polymarket market's price history from the public
Gamma + CLOB APIs (read-only, no key), enriches with per-step probability change,
runs `anomalyx scan`, and maps findings back to UTC timestamps. Surfaces the
information shocks — sharp probability jumps (point/mv) and sustained regime
shifts in the odds (coll.cusum). The `timestamp` column is auto-classified a
sequence (1.1.1) and skipped, so findings are about the odds, not the clock.

Verified on a live market (MicroStrategy-sells-BTC, 648 hourly points): coll.cusum
caught the 2026-05-20 regime shift (prob 0.345→0.133), mv.mahalanobis flagged the
information-shock hours. Also fills in examples/README.md, which had only the
stock example (the journal one from 1.1.1 was missing there).

Docs/example only — outside the Cargo workspace, no build/gate/release impact.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Jun 2, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds a new worked example script that demonstrates anomaly detection on Polymarket price data. It includes the Python script implementation, accompanying documentation with usage examples, and a changelog entry documenting the feature.

Changes

Polymarket Anomaly Detection Example

Layer / File(s) Summary
Polymarket example script
examples/polymarket_anomalies.py
New example script fetches market metadata and price history from Polymarket public endpoints, generates a CSV with computed probability deltas, executes anomalyx scan, and formats results by mapping anomaly handles to UTC-based date descriptions. Includes argparse for search term, candidates, and fidelity options.
README documentation and changelog
examples/README.md, CHANGELOG.md
Documents both polymarket_anomalies.py and journal_anomalies.py in README with command examples and timestamp mapping notes. Adds changelog entry describing the script's detection methods and timestamp translation behavior.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

  • copyleftdev/anomalyx#64: Adds the stock_anomalies.py worked example using the same pattern of fetching time-series data, invoking anomalyx scan, and decoding anomaly handles back to timestamps—providing the pattern that polymarket_anomalies.py follows.

Poem

🐰 A market watched, probabilities dance,
Through Polymarket's open expanse,
anomalyx finds the shocks that appear,
When prices shift strange, the anomalies cheer!
UTC timestamps tell the whole tale,
Of "information" events that don't fail. 📊✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title accurately describes the main change: adding a new example script for detecting prediction-market anomalies using Polymarket data.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch docs/example-polymarket

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
examples/polymarket_anomalies.py (1)

145-154: ⚡ Quick win

Clean up the temporary directory.

The script creates a temporary directory with tempfile.mkdtemp() at line 145 but never removes it. For a short-lived example script this may be acceptable, but it does leak resources. Consider using tempfile.TemporaryDirectory() as a context manager or explicitly calling shutil.rmtree(tmp) before exiting.

♻️ Proposed fix using context manager
-    tmp = tempfile.mkdtemp(prefix="anomalyx-polymarket-")
-    csv_path = os.path.join(tmp, "market.csv")
-    dates = write_csv(points, csv_path)
+    with tempfile.TemporaryDirectory(prefix="anomalyx-polymarket-") as tmp:
+        csv_path = os.path.join(tmp, "market.csv")
+        dates = write_csv(points, csv_path)

-    span = f"{points[0][0]} .. {points[-1][0]}"
-    print(f"# {question}")
-    print(f"# {len(points)} points, prob {points[0][1]:.3f} -> {points[-1][1]:.3f}\n")
-    env = anomalyx_scan(csv_path, scan_args)
-    report(env, dates)
-    sys.exit(0 if env["exit"] == 0 else 1)
+        span = f"{points[0][0]} .. {points[-1][0]}"
+        print(f"# {question}")
+        print(f"# {len(points)} points, prob {points[0][1]:.3f} -> {points[-1][1]:.3f}\n")
+        env = anomalyx_scan(csv_path, scan_args)
+        report(env, dates)
+        sys.exit(0 if env["exit"] == 0 else 1)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@examples/polymarket_anomalies.py` around lines 145 - 154, The temporary
directory created with tempfile.mkdtemp() (assigned to tmp) is never removed;
wrap the block that writes csv_path, calls anomalyx_scan(env) and report(env,
dates) and then exits in a tempfile.TemporaryDirectory() context manager (or
ensure shutil.rmtree(tmp) is called before sys.exit) so the temp dir is cleaned
up; update the code around tempfile.mkdtemp, csv_path, anomalyx_scan, report and
sys.exit to use the context manager or explicit rmtree.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@examples/polymarket_anomalies.py`:
- Around line 145-154: The temporary directory created with tempfile.mkdtemp()
(assigned to tmp) is never removed; wrap the block that writes csv_path, calls
anomalyx_scan(env) and report(env, dates) and then exits in a
tempfile.TemporaryDirectory() context manager (or ensure shutil.rmtree(tmp) is
called before sys.exit) so the temp dir is cleaned up; update the code around
tempfile.mkdtemp, csv_path, anomalyx_scan, report and sys.exit to use the
context manager or explicit rmtree.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: f3bca295-264b-4924-a91b-97f54cd3f674

📥 Commits

Reviewing files that changed from the base of the PR and between ff93a4f and 5f2ce72.

📒 Files selected for processing (3)
  • CHANGELOG.md
  • examples/README.md
  • examples/polymarket_anomalies.py

@copyleftdev copyleftdev merged commit e2db91d into main Jun 2, 2026
2 checks passed
@copyleftdev copyleftdev deleted the docs/example-polymarket branch June 2, 2026 01:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant