Spaces:
Running
Running
Deploy SharpFlow (nav + example wallets + Polymarket copy)
Browse files- .gitignore +11 -0
- Dockerfile +26 -0
- GTM.md +95 -0
- Procfile +1 -0
- README.md +104 -4
- config.example.yaml +50 -0
- config.yaml +46 -0
- pmct/__init__.py +2 -0
- pmct/backtest.py +164 -0
- pmct/client.py +144 -0
- pmct/digest.py +188 -0
- pmct/discover.py +121 -0
- pmct/ledger.py +105 -0
- pmct/metrics.py +146 -0
- pmct/patterns.py +109 -0
- pmct/post.py +126 -0
- pmct/score.py +121 -0
- pmct/screen.py +66 -0
- pmct/sizing.py +97 -0
- pmct/util.py +46 -0
- render.yaml +10 -0
- requirements.txt +8 -0
- runtime.txt +1 -0
- scripts/01_discover_wallets.py +29 -0
- scripts/02_analyze_wallets.py +89 -0
- scripts/03_screen.py +43 -0
- scripts/04_backtest.py +74 -0
- scripts/05_digest.py +58 -0
- scripts/06_post.py +55 -0
- webapp/__init__.py +0 -0
- webapp/app.py +263 -0
.gitignore
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.venv/
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.pyc
|
| 4 |
+
*.pyo
|
| 5 |
+
.DS_Store
|
| 6 |
+
*.log
|
| 7 |
+
|
| 8 |
+
# Runtime + generated data. Keep one seed digest so /digest isn't empty on first
|
| 9 |
+
# deploy; ignore everything else (ledgers, cards, threads, subscriber emails).
|
| 10 |
+
data/*
|
| 11 |
+
!data/digest_20260707_1844.md
|
Dockerfile
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Hugging Face Spaces runs this as the container entrypoint (sdk: docker).
|
| 2 |
+
# HF exposes port 7860 and runs the container as a non-root user (uid 1000),
|
| 3 |
+
# so we install deps as root, then chown the app so runtime writes (e.g. the
|
| 4 |
+
# subscribers CSV) don't hit a permission error.
|
| 5 |
+
FROM python:3.11-slim
|
| 6 |
+
|
| 7 |
+
ENV PYTHONUNBUFFERED=1 \
|
| 8 |
+
PIP_NO_CACHE_DIR=1 \
|
| 9 |
+
MPLCONFIGDIR=/tmp/mpl \
|
| 10 |
+
PORT=7860
|
| 11 |
+
|
| 12 |
+
WORKDIR /app
|
| 13 |
+
|
| 14 |
+
COPY requirements.txt .
|
| 15 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 16 |
+
|
| 17 |
+
COPY . .
|
| 18 |
+
|
| 19 |
+
RUN useradd -m -u 1000 appuser \
|
| 20 |
+
&& mkdir -p /app/data \
|
| 21 |
+
&& chown -R appuser:appuser /app
|
| 22 |
+
USER appuser
|
| 23 |
+
|
| 24 |
+
EXPOSE 7860
|
| 25 |
+
|
| 26 |
+
CMD ["gunicorn", "webapp.app:app", "--bind", "0.0.0.0:7860", "--workers", "1", "--threads", "4", "--timeout", "120"]
|
GTM.md
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Go-to-Market β Consistent Smart-Money Digest
|
| 2 |
+
|
| 3 |
+
**Product in one line:** the Polymarket flow tracker that surfaces *consistent
|
| 4 |
+
mid-size* traders (not just $10k whales) and scores each move β the two things
|
| 5 |
+
users of Polywhaler / PolyTrack / Unusual Whales complain are missing.
|
| 6 |
+
|
| 7 |
+
**Honest framing:** we sell *flow intelligence*, like TradingView sells charts β
|
| 8 |
+
NOT guaranteed profit. The underlying copy edge is unproven. Never promise returns.
|
| 9 |
+
|
| 10 |
+
---
|
| 11 |
+
|
| 12 |
+
## 1. Why this can wedge into a crowded market
|
| 13 |
+
|
| 14 |
+
The space is a red ocean (10+ trackers), so we do NOT compete on "show whale
|
| 15 |
+
trades." We win on the two documented gaps:
|
| 16 |
+
|
| 17 |
+
- **Coverage:** incumbents rank by trade size β they miss steady mid-size
|
| 18 |
+
traders. Our engine ranks by *consistency + repeatability + copyability* and
|
| 19 |
+
deliberately excludes mega-whales and market-makers.
|
| 20 |
+
- **Judgement:** incumbents dump raw trades. We attach a signal-quality score so
|
| 21 |
+
a move arrives with context.
|
| 22 |
+
|
| 23 |
+
If we can't hold that differentiation, we don't have a business β so every piece
|
| 24 |
+
of content must show the score + the "traders others miss" angle.
|
| 25 |
+
|
| 26 |
+
## 2. Product ladder (freemium)
|
| 27 |
+
|
| 28 |
+
| Tier | Price | What they get |
|
| 29 |
+
|---|---|---|
|
| 30 |
+
| **Free** | $0 | Daily digest, 24h delayed, top 5 traders. Public. This is the marketing. |
|
| 31 |
+
| **Pro** | $19/mo | Real-time Telegram alerts, all ~15 tracked traders, custom wallet watchlist |
|
| 32 |
+
| **Trader** | $49/mo | Above + webhook/API access, faster poll, backtest a trader on demand |
|
| 33 |
+
|
| 34 |
+
Rule of thumb from the research: 100 customers at ~$29 avg > 1000 at $5. Target
|
| 35 |
+
= find 100 people who'll pay, not a million pageviews.
|
| 36 |
+
|
| 37 |
+
## 3. Distribution β channels that DON'T need a personal audience
|
| 38 |
+
|
| 39 |
+
The product's daily output *is* the top-of-funnel. Zero-audience-cold plan:
|
| 40 |
+
|
| 41 |
+
1. **The digest as content (daily).** Auto-render each run to:
|
| 42 |
+
- An **X/Twitter thread** ("5 consistent Polymarket traders whale trackers
|
| 43 |
+
miss β and what they bought today"). Screenshot the scored table.
|
| 44 |
+
- **r/Polymarket + r/PredictionMarkets** β post the digest as a weekly
|
| 45 |
+
value-add (follow sub rules; lead with data, not a sales pitch).
|
| 46 |
+
- **Polymarket Discord / Telegram trading groups** β drop the digest, soft CTA.
|
| 47 |
+
2. **SEO / programmatic pages.** Publish every digest as a web page +
|
| 48 |
+
per-trader profile pages. Long-tail targets: "best polymarket traders to
|
| 49 |
+
follow", "polymarket smart money", "<wallet> polymarket stats". This compounds
|
| 50 |
+
for free while the social posts drive the spike.
|
| 51 |
+
3. **Cold outbound.** DM active Polymarket traders visible on the public
|
| 52 |
+
leaderboard / in Discords: "built a tracker that flags consistent mid-size
|
| 53 |
+
traders, not just whales β want a free month?" 20 DMs/day.
|
| 54 |
+
4. **Free tool as a lead magnet.** A public "paste a wallet β get its
|
| 55 |
+
consistency + repeatability score" page (reuses the metrics engine). Ungated,
|
| 56 |
+
shareable, ranks, and captures emails for the digest.
|
| 57 |
+
|
| 58 |
+
Pick **X + r/Polymarket + the free wallet-scorer** as the beachhead. Don't spread
|
| 59 |
+
thin across 6 channels day one.
|
| 60 |
+
|
| 61 |
+
## 4. Two-week launch plan
|
| 62 |
+
|
| 63 |
+
- **Days 1β3:** wrap `05_digest.py` output into (a) an auto-posted X thread and
|
| 64 |
+
(b) a static site page. Stand up a landing page with an email capture + Stripe
|
| 65 |
+
($19/$49). Set up a Telegram channel (free = delayed feed, paid = real-time bot).
|
| 66 |
+
- **Days 4β7:** ship the free "wallet scorer" web page. Post the first 3 daily
|
| 67 |
+
digests to X + r/Polymarket. Start 20 cold DMs/day.
|
| 68 |
+
- **Days 8β14:** turn on real-time Telegram alerts behind the paywall. Ask the
|
| 69 |
+
first free users what they'd pay for; adjust the Pro tier. Publish 1 SEO
|
| 70 |
+
article ("How to find consistent Polymarket traders").
|
| 71 |
+
|
| 72 |
+
**Success signal by day 14:** not revenue β *engagement*. Are digests getting
|
| 73 |
+
saved/shared? Do DM'd traders reply? If the free digest gets zero traction, the
|
| 74 |
+
differentiation isn't landing β fix the product before scaling spend. If it does,
|
| 75 |
+
convert the warm free list to Pro.
|
| 76 |
+
|
| 77 |
+
## 5. Honest risks (so we go in eyes-open)
|
| 78 |
+
|
| 79 |
+
- **Distribution is the bottleneck, not code.** Most tools like this make $0
|
| 80 |
+
because nobody finds them. The daily-content engine is our hedge, but it needs
|
| 81 |
+
consistency for weeks before SEO/word-of-mouth compounds.
|
| 82 |
+
- **Incumbents can copy the "consistency" angle.** Our moat is speed + being
|
| 83 |
+
first to own that positioning, not proprietary tech.
|
| 84 |
+
- **Legal/claims:** never state or imply guaranteed profit. "Flow intelligence,
|
| 85 |
+
past performance not predictive" on every surface.
|
| 86 |
+
- **Data fragility:** Data API caps history at ~3500 events/wallet; if Polymarket
|
| 87 |
+
changes endpoints, the digest breaks β monitor `client.py`.
|
| 88 |
+
|
| 89 |
+
## 6. Next build steps to be launch-ready
|
| 90 |
+
|
| 91 |
+
1. `06_post.py` β render a digest run into an X-thread text + PNG table.
|
| 92 |
+
2. Static-site export of digests + per-trader pages (SEO surface).
|
| 93 |
+
3. Public wallet-scorer endpoint (lead magnet) reusing `metrics` + `patterns`.
|
| 94 |
+
4. Real-time poller + Telegram bot for the paid tier.
|
| 95 |
+
5. Landing page + Stripe.
|
Procfile
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
web: gunicorn webapp.app:app --bind 0.0.0.0:$PORT --workers 1 --threads 4 --timeout 120
|
README.md
CHANGED
|
@@ -1,10 +1,110 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
colorTo: gray
|
| 6 |
sdk: docker
|
|
|
|
| 7 |
pinned: false
|
| 8 |
---
|
| 9 |
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: SharpFlow
|
| 3 |
+
emoji: π·
|
| 4 |
+
colorFrom: green
|
| 5 |
colorTo: gray
|
| 6 |
sdk: docker
|
| 7 |
+
app_port: 7860
|
| 8 |
pinned: false
|
| 9 |
---
|
| 10 |
|
| 11 |
+
# pmct β Polymarket copy-trade research toolkit
|
| 12 |
+
|
| 13 |
+
Research + backtest only. **No live trading, no wallet, no funds.** This toolkit
|
| 14 |
+
scans Polymarket traders, finds the ones that are (a) long-term profitable and
|
| 15 |
+
(b) trading a repeatable pattern, then backtests copy-trading them with
|
| 16 |
+
**conviction-based position sizing** (εδ½θ·θζζ‘η¨εΊ¦θ΅°).
|
| 17 |
+
|
| 18 |
+
You run it on your own machine β it talks to Polymarket's public read APIs.
|
| 19 |
+
|
| 20 |
+
## Pipeline
|
| 21 |
+
|
| 22 |
+
```
|
| 23 |
+
01_discover_wallets.py leaderboard + market whales -> data/candidates.json
|
| 24 |
+
02_analyze_wallets.py fetch history, compute metrics -> data/wallets.csv
|
| 25 |
+
+ pattern/repeatability features data/ledgers/*.parquet
|
| 26 |
+
03_screen.py apply the two gates, rank -> data/shortlist.csv
|
| 27 |
+
04_backtest.py <wallet> conviction vs flat, equity curve -> data/backtest_*.png
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
## Quick start
|
| 31 |
+
|
| 32 |
+
```bash
|
| 33 |
+
cd polymarket-copytrade
|
| 34 |
+
python -m venv .venv && source .venv/bin/activate
|
| 35 |
+
pip install -r requirements.txt
|
| 36 |
+
cp config.example.yaml config.yaml # edit thresholds if you want
|
| 37 |
+
|
| 38 |
+
python scripts/01_discover_wallets.py
|
| 39 |
+
python scripts/02_analyze_wallets.py # slowest step (one API pass per wallet)
|
| 40 |
+
python scripts/03_screen.py
|
| 41 |
+
python scripts/04_backtest.py # backtests top of shortlist
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
## The two screens (your rules)
|
| 45 |
+
|
| 46 |
+
**Gate A β long-term consistent profit** (`screen:` in config):
|
| 47 |
+
`total_pnl`, `roi`, `win_rate`, `max_drawdown_pct`, `monthly_profit_ratio`
|
| 48 |
+
(share of active months that were green), plus `min_active_days` /
|
| 49 |
+
`min_resolved_markets` so a lucky week can't pass.
|
| 50 |
+
|
| 51 |
+
**Gate B β repeatable, replicable pattern** (`patterns.py`): each wallet is
|
| 52 |
+
reduced to entry-price-band tightness, sizing consistency, topic concentration,
|
| 53 |
+
and cadence regularity, scaled by trade count, into one `repeatability` β [0,1].
|
| 54 |
+
Copy a strategy, not a coin flip.
|
| 55 |
+
|
| 56 |
+
**Gate C β copyable, not market-making** (`max_rebate_share`): many top
|
| 57 |
+
leaderboard wallets profit from maker/taker rebates and liquidity rewards β an
|
| 58 |
+
edge you *cannot* copy. We measure `rebate_share` (incentive income Γ·
|
| 59 |
+
authoritative profit) and reject wallets above the threshold.
|
| 60 |
+
|
| 61 |
+
**Authoritative profit.** For wallets on the leaderboard we rank on Polymarket's
|
| 62 |
+
own reported profit (`lb-api/profit`), not our reconstruction β the reconstructed
|
| 63 |
+
PnL is only a cross-check / the fallback for unranked wallets.
|
| 64 |
+
|
| 65 |
+
## Conviction sizing (`sizing.py`)
|
| 66 |
+
|
| 67 |
+
We never copy the target's dollar amount. Per entry we infer conviction β [0,1]:
|
| 68 |
+
|
| 69 |
+
```
|
| 70 |
+
conviction = w_stake Β· stake_signal + w_edge Β· edge_signal
|
| 71 |
+
stake_signal = how big this bet was vs the target's own typical bet
|
| 72 |
+
edge_signal = |price β 0.5| Β· 2 (distance from a coin flip)
|
| 73 |
+
```
|
| 74 |
+
|
| 75 |
+
Our stake = `bankroll Β· frac`, where `frac` scales from `min_frac_per_trade`
|
| 76 |
+
(no conviction) up to `max_frac_per_trade` (full conviction), then is clamped by
|
| 77 |
+
a `kelly_cap Β· kelly_fraction` ceiling and a `max_frac_per_market` aggregate cap.
|
| 78 |
+
Defaults are tuned for a <$1k, conservative bankroll.
|
| 79 |
+
|
| 80 |
+
## Important caveats β read before trusting a number
|
| 81 |
+
|
| 82 |
+
- **Endpoints verified live (2026-07)** against the real API: Gamma `/markets`,
|
| 83 |
+
CLOB `/price` `/prices-history`, Data API `/activity` `/positions` `/holders`
|
| 84 |
+
`/value`, and the leaderboard at `lb-api.polymarket.com/profit` `/volume`
|
| 85 |
+
(windows: `all` `1d` `7d` `30d`). If Polymarket later moves a path, fix it in
|
| 86 |
+
`pmct/client.py` (one place).
|
| 87 |
+
- **History is capped at ~3500 most-recent activities per wallet.** The Data API
|
| 88 |
+
refuses offset paging past 3000 ("max historical activity offset of 3000
|
| 89 |
+
exceeded"). Enough for pattern/behavior analysis; for lifetime profit we use
|
| 90 |
+
the authoritative leaderboard number instead of reconstructing.
|
| 91 |
+
- **Reconstructed PnL validated** to ~11% of the authoritative leaderboard figure
|
| 92 |
+
on a full-history wallet ($3.61M vs $4.05M) β the gap is open-position marking +
|
| 93 |
+
rebates + methodology. Trust `profit_final` (leaderboard) over `total_pnl`.
|
| 94 |
+
- **Resolution is approximated** from the activity ledger (net share balance +
|
| 95 |
+
redemptions), not from on-chain payout events. Good enough for ranking; not an
|
| 96 |
+
accounting statement. Win-rate is the weakest metric β prefer profit + consistency.
|
| 97 |
+
- **Backtest fills are approximate**: entry/exit = target's price Β± slippage;
|
| 98 |
+
`copy_delay_sec` is folded into slippage rather than modeled tick-by-tick.
|
| 99 |
+
Real copy-trading is worse than backtest β you react after the target moves the
|
| 100 |
+
price. Treat backtest returns as an optimistic ceiling.
|
| 101 |
+
- **Past performance β future.** Prediction-market edges decay and crowd out.
|
| 102 |
+
This is a research scaffold, not investment advice.
|
| 103 |
+
|
| 104 |
+
## Next step toward live (only after backtests convince you)
|
| 105 |
+
|
| 106 |
+
The live agent would poll `data-api /activity` for your shortlisted wallets,
|
| 107 |
+
detect new fills, and place mirrored orders via `py-clob-client` with the same
|
| 108 |
+
`sizing.py` logic. That needs a funded Polygon wallet + CLOB API creds β not
|
| 109 |
+
included here on purpose, since you're at the research stage.
|
| 110 |
+
```
|
config.example.yaml
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copy this to config.yaml and edit. All values are safe defaults for the
|
| 2 |
+
# "research + backtest, <$1k, conservative" profile.
|
| 3 |
+
|
| 4 |
+
data_dir: data
|
| 5 |
+
|
| 6 |
+
discover:
|
| 7 |
+
# How to source candidate wallets. Any combination of the three.
|
| 8 |
+
use_leaderboard: true # pull top traders from the leaderboard
|
| 9 |
+
leaderboard_windows: [all, 30d] # time windows to pull
|
| 10 |
+
leaderboard_top_n: 200
|
| 11 |
+
use_market_holders: true # collect big holders of active high-volume markets
|
| 12 |
+
markets_to_scan: 60 # how many active markets to inspect for holders
|
| 13 |
+
holders_per_market: 40
|
| 14 |
+
seed_wallets: [] # optional: paste addresses you already trust
|
| 15 |
+
|
| 16 |
+
analyze:
|
| 17 |
+
max_wallets: 400 # cap to keep runs cheap
|
| 18 |
+
activity_page_limit: 500 # data-api page size
|
| 19 |
+
max_pages_per_wallet: 20 # hard cap on history depth per wallet
|
| 20 |
+
request_sleep_sec: 0.25 # politeness delay between calls
|
| 21 |
+
|
| 22 |
+
# --- Screening: "long-term consistent profit + repeatable pattern" ---
|
| 23 |
+
screen:
|
| 24 |
+
min_total_pnl_usd: 500 # must have made real money
|
| 25 |
+
min_roi: 0.10 # >= 10% return on deployed capital
|
| 26 |
+
min_win_rate: 0.52 # better than coin flip on resolved markets
|
| 27 |
+
min_resolved_markets: 40 # enough sample size
|
| 28 |
+
min_active_days: 90 # "long-term", not a lucky week
|
| 29 |
+
max_drawdown_pct: 0.5 # reject blow-up-prone wallets
|
| 30 |
+
min_monthly_profit_ratio: 0.55 # >=55% of active months green (consistency)
|
| 31 |
+
min_repeatability: 0.5 # pattern-repeatability score in [0,1]
|
| 32 |
+
max_rebate_share: 0.35 # reject wallets whose profit is >35% rebates (market makers = uncopyable)
|
| 33 |
+
top_n_shortlist: 25
|
| 34 |
+
|
| 35 |
+
# --- Copy-trade backtest ---
|
| 36 |
+
backtest:
|
| 37 |
+
our_bankroll_usd: 800
|
| 38 |
+
fee_bps: 0 # Polymarket has no maker/taker fee today; keep 0
|
| 39 |
+
slippage_bps: 150 # assumed adverse fill vs target's price (1.5%)
|
| 40 |
+
copy_delay_sec: 60 # we react N seconds after the target's fill
|
| 41 |
+
# Conviction-based position sizing (εδ½θ·θζζ‘η¨εΊ¦θ΅°)
|
| 42 |
+
sizing:
|
| 43 |
+
max_frac_per_trade: 0.05 # never risk >5% of bankroll on one entry
|
| 44 |
+
max_frac_per_market: 0.15 # aggregate cap per market
|
| 45 |
+
min_frac_per_trade: 0.005 # floor so tiny-conviction trades still register
|
| 46 |
+
# conviction blends how big the target bet (vs their bankroll) and their edge
|
| 47 |
+
w_stake: 0.6 # weight on target's stake-fraction signal
|
| 48 |
+
w_edge: 0.4 # weight on entry-price edge signal
|
| 49 |
+
kelly_cap: 0.5 # fraction of full-Kelly we allow (safety)
|
| 50 |
+
assumed_max_edge: 0.15 # true-vs-price gap we credit the target at full conviction
|
config.yaml
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
data_dir: data
|
| 2 |
+
|
| 3 |
+
discover:
|
| 4 |
+
use_leaderboard: true
|
| 5 |
+
leaderboard_windows: [all, 30d]
|
| 6 |
+
leaderboard_top_n: 150
|
| 7 |
+
use_market_holders: true
|
| 8 |
+
markets_to_scan: 25
|
| 9 |
+
holders_per_market: 25
|
| 10 |
+
seed_wallets: []
|
| 11 |
+
|
| 12 |
+
analyze:
|
| 13 |
+
max_wallets: 100
|
| 14 |
+
activity_page_limit: 500
|
| 15 |
+
max_pages_per_wallet: 15
|
| 16 |
+
request_sleep_sec: 0.15
|
| 17 |
+
|
| 18 |
+
# Exploration thresholds. RELAXED vs the shipped defaults because capped history
|
| 19 |
+
# (~3500 recent events) + the win-rate/resolution heuristic make these metrics
|
| 20 |
+
# unreliable β so ranking leans on authoritative leaderboard profit + copyability
|
| 21 |
+
# + repeatability, which ARE trustworthy. Tighten before trusting for real money.
|
| 22 |
+
screen:
|
| 23 |
+
min_total_pnl_usd: 10000 # authoritative profit; leaderboard whales exceed easily
|
| 24 |
+
min_roi: 0.03 # reconstructed ROI is noisy -> low bar
|
| 25 |
+
min_win_rate: 0.50 # heuristic-based -> modest bar
|
| 26 |
+
min_resolved_markets: 8 # heuristic under-counts resolved markets
|
| 27 |
+
min_active_days: 20 # truncated history shrinks the observed span
|
| 28 |
+
max_drawdown_pct: 1.5 # reconstructed drawdown is noisy -> loose
|
| 29 |
+
min_monthly_profit_ratio: 0.40
|
| 30 |
+
min_repeatability: 0.30 # observed max ~0.43 on the sample
|
| 31 |
+
max_rebate_share: 0.35 # reject market-maker / rebate-driven profit
|
| 32 |
+
top_n_shortlist: 25
|
| 33 |
+
|
| 34 |
+
backtest:
|
| 35 |
+
our_bankroll_usd: 800
|
| 36 |
+
fee_bps: 0
|
| 37 |
+
slippage_bps: 150
|
| 38 |
+
copy_delay_sec: 60
|
| 39 |
+
sizing:
|
| 40 |
+
max_frac_per_trade: 0.05
|
| 41 |
+
max_frac_per_market: 0.15
|
| 42 |
+
min_frac_per_trade: 0.005
|
| 43 |
+
w_stake: 0.6
|
| 44 |
+
w_edge: 0.4
|
| 45 |
+
kelly_cap: 0.5
|
| 46 |
+
assumed_max_edge: 0.15
|
pmct/__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""pmct β Polymarket copy-trade research toolkit (research + backtest only)."""
|
| 2 |
+
__version__ = "0.1.0"
|
pmct/backtest.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Event-driven copy-trade backtest against a single target wallet.
|
| 2 |
+
|
| 3 |
+
We replay the target's normalized ledger in time order and mirror it with OUR
|
| 4 |
+
bankroll, sizing each entry by conviction (sizing.py). Exits mirror the target:
|
| 5 |
+
when the target trims/redeems X% of their position, we trim the same % of ours.
|
| 6 |
+
|
| 7 |
+
Fill model (documented approximations β this is research, not a fill simulator):
|
| 8 |
+
* entry fill = target's price * (1 + slippage) # we pay up to get in
|
| 9 |
+
* exit fill = target's exit price * (1 - slippage) # we give up edge to exit
|
| 10 |
+
* redemptions use payout-per-share (usdc/size) as the exit price
|
| 11 |
+
* copy_delay_sec is folded into `slippage_bps` rather than modeled tick-by-tick
|
| 12 |
+
(modeling it exactly needs CLOB prices-history per token; left as a TODO).
|
| 13 |
+
|
| 14 |
+
Outputs an equity curve and summary stats, and can run a flat-sizing baseline
|
| 15 |
+
so you can see whether conviction sizing actually helped.
|
| 16 |
+
"""
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
from collections import defaultdict
|
| 20 |
+
from dataclasses import dataclass
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
import pandas as pd
|
| 24 |
+
|
| 25 |
+
from .sizing import SizingConfig, position_fraction
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@dataclass
|
| 29 |
+
class BacktestResult:
|
| 30 |
+
equity_curve: pd.DataFrame # ts, equity, cash, invested
|
| 31 |
+
final_equity: float
|
| 32 |
+
total_return: float
|
| 33 |
+
max_drawdown_pct: float
|
| 34 |
+
n_entries: int
|
| 35 |
+
n_exits: int
|
| 36 |
+
closed_win_rate: float
|
| 37 |
+
summary: dict
|
| 38 |
+
|
| 39 |
+
def to_summary(self) -> dict:
|
| 40 |
+
return {
|
| 41 |
+
"final_equity": round(self.final_equity, 2),
|
| 42 |
+
"total_return": round(self.total_return, 4),
|
| 43 |
+
"max_drawdown_pct": round(self.max_drawdown_pct, 4),
|
| 44 |
+
"n_entries": self.n_entries,
|
| 45 |
+
"n_exits": self.n_exits,
|
| 46 |
+
"closed_win_rate": round(self.closed_win_rate, 4),
|
| 47 |
+
**self.summary,
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _trailing_avg(values: list[float], window: int = 20) -> float:
|
| 52 |
+
if not values:
|
| 53 |
+
return 0.0
|
| 54 |
+
return float(np.mean(values[-window:]))
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def run(ledger: pd.DataFrame, bankroll: float, sizing: SizingConfig,
|
| 58 |
+
slippage_bps: float = 150, fee_bps: float = 0,
|
| 59 |
+
flat_sizing: bool = False) -> BacktestResult:
|
| 60 |
+
"""`flat_sizing=True` ignores conviction and stakes a constant
|
| 61 |
+
max_frac_per_trade on every entry (baseline for comparison)."""
|
| 62 |
+
slip = slippage_bps / 1e4
|
| 63 |
+
fee = fee_bps / 1e4
|
| 64 |
+
|
| 65 |
+
cash = bankroll
|
| 66 |
+
our_shares: dict = defaultdict(float) # asset -> shares WE hold
|
| 67 |
+
tgt_shares: dict = defaultdict(float) # asset -> shares TARGET holds
|
| 68 |
+
market_cost: dict = defaultdict(float) # market -> USD we've committed
|
| 69 |
+
last_price: dict = defaultdict(float) # asset -> last seen price
|
| 70 |
+
asset_market: dict = {} # asset -> market id
|
| 71 |
+
entry_cost: dict = defaultdict(float) # asset -> our cost basis (for win/loss)
|
| 72 |
+
realized: list = [] # per-closed-lot pnl
|
| 73 |
+
target_buy_usdc: list = []
|
| 74 |
+
|
| 75 |
+
curve = []
|
| 76 |
+
n_entries = n_exits = 0
|
| 77 |
+
|
| 78 |
+
def mark_equity(ts):
|
| 79 |
+
invested = sum(sh * last_price.get(a, 0.0) for a, sh in our_shares.items())
|
| 80 |
+
curve.append({"ts": ts, "equity": cash + invested,
|
| 81 |
+
"cash": cash, "invested": invested})
|
| 82 |
+
|
| 83 |
+
for row in ledger.itertuples(index=False):
|
| 84 |
+
side, typ = row.side, row.type
|
| 85 |
+
asset, market = row.asset, row.market
|
| 86 |
+
price = float(row.price) if row.price else last_price.get(asset, 0.0)
|
| 87 |
+
size = float(row.size)
|
| 88 |
+
last_price[asset] = price or last_price.get(asset, 0.0)
|
| 89 |
+
asset_market[asset] = market
|
| 90 |
+
|
| 91 |
+
if side == "BUY":
|
| 92 |
+
tgt_shares[asset] += size
|
| 93 |
+
target_buy_usdc.append(float(row.usdc))
|
| 94 |
+
rolling = _trailing_avg(target_buy_usdc)
|
| 95 |
+
|
| 96 |
+
exposure_frac = market_cost[market] / bankroll
|
| 97 |
+
if flat_sizing:
|
| 98 |
+
frac = max(0.0, min(sizing.max_frac_per_trade,
|
| 99 |
+
sizing.max_frac_per_market - exposure_frac))
|
| 100 |
+
conv = float("nan")
|
| 101 |
+
else:
|
| 102 |
+
frac, conv = position_fraction(
|
| 103 |
+
float(row.usdc), rolling, price, exposure_frac, sizing)
|
| 104 |
+
|
| 105 |
+
fill = price * (1 + slip)
|
| 106 |
+
stake = min(frac * bankroll, cash)
|
| 107 |
+
if stake <= 0 or fill <= 0:
|
| 108 |
+
mark_equity(row.ts)
|
| 109 |
+
continue
|
| 110 |
+
stake *= (1 - fee)
|
| 111 |
+
shares = stake / fill
|
| 112 |
+
cash -= stake
|
| 113 |
+
our_shares[asset] += shares
|
| 114 |
+
entry_cost[asset] += stake
|
| 115 |
+
market_cost[market] += stake
|
| 116 |
+
n_entries += 1
|
| 117 |
+
|
| 118 |
+
elif side == "SELL" or typ in ("REDEEM", "CLAIM"):
|
| 119 |
+
held = our_shares.get(asset, 0.0)
|
| 120 |
+
tgt_held = tgt_shares.get(asset, 0.0)
|
| 121 |
+
if held > 0 and size > 0 and tgt_held > 0:
|
| 122 |
+
frac_exit = min(1.0, size / tgt_held)
|
| 123 |
+
shares_out = held * frac_exit
|
| 124 |
+
exit_price = (float(row.usdc) / size) if typ in ("REDEEM", "CLAIM") else price
|
| 125 |
+
exec_price = exit_price * (1 - slip)
|
| 126 |
+
proceeds = shares_out * exec_price * (1 - fee)
|
| 127 |
+
cost_out = entry_cost.get(asset, 0.0) * (shares_out / held if held else 0)
|
| 128 |
+
cash += proceeds
|
| 129 |
+
our_shares[asset] -= shares_out
|
| 130 |
+
entry_cost[asset] -= cost_out
|
| 131 |
+
market_cost[asset_market.get(asset, market)] = max(
|
| 132 |
+
0.0, market_cost.get(market, 0.0) - cost_out)
|
| 133 |
+
realized.append(proceeds - cost_out)
|
| 134 |
+
n_exits += 1
|
| 135 |
+
tgt_shares[asset] = max(0.0, tgt_held - size)
|
| 136 |
+
|
| 137 |
+
mark_equity(row.ts)
|
| 138 |
+
|
| 139 |
+
if not curve:
|
| 140 |
+
empty = pd.DataFrame(columns=["ts", "equity", "cash", "invested"])
|
| 141 |
+
return BacktestResult(empty, bankroll, 0.0, 0.0, 0, 0, 0.0, {"note": "no trades"})
|
| 142 |
+
|
| 143 |
+
eq_df = pd.DataFrame(curve)
|
| 144 |
+
equity = eq_df["equity"].values
|
| 145 |
+
running_max = np.maximum.accumulate(equity)
|
| 146 |
+
max_dd = float(((running_max - equity) / running_max).max())
|
| 147 |
+
final_equity = float(equity[-1])
|
| 148 |
+
closed_wr = float(np.mean([r > 0 for r in realized])) if realized else 0.0
|
| 149 |
+
|
| 150 |
+
return BacktestResult(
|
| 151 |
+
equity_curve=eq_df,
|
| 152 |
+
final_equity=final_equity,
|
| 153 |
+
total_return=(final_equity - bankroll) / bankroll,
|
| 154 |
+
max_drawdown_pct=max_dd,
|
| 155 |
+
n_entries=n_entries,
|
| 156 |
+
n_exits=n_exits,
|
| 157 |
+
closed_win_rate=closed_wr,
|
| 158 |
+
summary={
|
| 159 |
+
"bankroll": bankroll,
|
| 160 |
+
"sizing": "flat" if flat_sizing else "conviction",
|
| 161 |
+
"realized_pnl": round(float(sum(realized)), 2),
|
| 162 |
+
"open_lots": int(sum(1 for v in our_shares.values() if v > 1e-9)),
|
| 163 |
+
},
|
| 164 |
+
)
|
pmct/client.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Thin HTTP clients for Polymarket's public read APIs.
|
| 2 |
+
|
| 3 |
+
Three services are used (all read-only, no auth needed for the endpoints here):
|
| 4 |
+
- Data API https://data-api.polymarket.com -> per-wallet activity/positions
|
| 5 |
+
- Gamma API https://gamma-api.polymarket.com -> market metadata / resolution
|
| 6 |
+
- CLOB API https://clob.polymarket.com -> prices / order book
|
| 7 |
+
|
| 8 |
+
Verified live 2026-07 against the real API: Gamma /markets, CLOB /price &
|
| 9 |
+
/prices-history, Data API /activity /positions /holders, and the leaderboard
|
| 10 |
+
at lb-api.polymarket.com/profit|/volume. If Polymarket later changes a path and
|
| 11 |
+
a call 404s, open https://docs.polymarket.com and fix it in ONE place here.
|
| 12 |
+
"""
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import time
|
| 16 |
+
from typing import Any, Iterable
|
| 17 |
+
|
| 18 |
+
import requests
|
| 19 |
+
from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class RetryableHTTP(Exception):
|
| 23 |
+
"""A 429/5xx worth backing off and retrying (unlike a 4xx, which is fatal)."""
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
# Data API refuses offset-based paging past this point:
|
| 27 |
+
# {"error":"max historical activity offset of 3000 exceeded"}
|
| 28 |
+
MAX_ACTIVITY_OFFSET = 3000
|
| 29 |
+
|
| 30 |
+
DATA_API = "https://data-api.polymarket.com"
|
| 31 |
+
GAMMA_API = "https://gamma-api.polymarket.com"
|
| 32 |
+
CLOB_API = "https://clob.polymarket.com"
|
| 33 |
+
# Leaderboard host has historically differed from the main data-api; verify.
|
| 34 |
+
LEADERBOARD_API = "https://lb-api.polymarket.com"
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class PolymarketClient:
|
| 38 |
+
def __init__(self, sleep_sec: float = 0.25, timeout: int = 20):
|
| 39 |
+
self.sleep_sec = sleep_sec
|
| 40 |
+
self.timeout = timeout
|
| 41 |
+
self.s = requests.Session()
|
| 42 |
+
self.s.headers.update({"User-Agent": "pmct-research/0.1"})
|
| 43 |
+
|
| 44 |
+
@retry(
|
| 45 |
+
reraise=True,
|
| 46 |
+
stop=stop_after_attempt(4),
|
| 47 |
+
wait=wait_exponential(multiplier=0.5, min=0.5, max=8),
|
| 48 |
+
retry=retry_if_exception_type(
|
| 49 |
+
(requests.ConnectionError, requests.Timeout, RetryableHTTP)),
|
| 50 |
+
)
|
| 51 |
+
def _get(self, url: str, params: dict | None = None) -> Any:
|
| 52 |
+
r = self.s.get(url, params=params, timeout=self.timeout)
|
| 53 |
+
if r.status_code == 429 or r.status_code >= 500:
|
| 54 |
+
raise RetryableHTTP(f"{r.status_code} on {url}")
|
| 55 |
+
r.raise_for_status() # 4xx -> HTTPError, NOT retried (e.g. offset cap)
|
| 56 |
+
if self.sleep_sec:
|
| 57 |
+
time.sleep(self.sleep_sec)
|
| 58 |
+
return r.json()
|
| 59 |
+
|
| 60 |
+
# ----- Data API: per-wallet history -------------------------------------
|
| 61 |
+
def activity(self, wallet: str, limit: int = 500, offset: int = 0) -> list[dict]:
|
| 62 |
+
"""Trade/redeem/reward ledger for a wallet, newest first.
|
| 63 |
+
|
| 64 |
+
Each item is expected to carry at least: type (TRADE/REDEEM/...),
|
| 65 |
+
side (BUY/SELL), size, price, usdcSize, timestamp, conditionId, asset,
|
| 66 |
+
outcome, title/slug. Field names vary β normalize in ledger.py.
|
| 67 |
+
"""
|
| 68 |
+
return self._get(
|
| 69 |
+
f"{DATA_API}/activity",
|
| 70 |
+
{"user": wallet.lower(), "limit": limit, "offset": offset},
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
def iter_activity(self, wallet: str, page_limit: int, max_pages: int) -> Iterable[dict]:
|
| 74 |
+
"""Yield a wallet's most-recent activity, newest first. Offset paging is
|
| 75 |
+
capped by the API at MAX_ACTIVITY_OFFSET, so very active wallets return
|
| 76 |
+
only their latest ~3500 events β enough for pattern/behavior analysis;
|
| 77 |
+
lifetime PnL for ranked wallets comes from the leaderboard instead."""
|
| 78 |
+
offset = 0
|
| 79 |
+
for _ in range(max_pages):
|
| 80 |
+
if offset > MAX_ACTIVITY_OFFSET:
|
| 81 |
+
return
|
| 82 |
+
try:
|
| 83 |
+
page = self.activity(wallet, limit=page_limit, offset=offset)
|
| 84 |
+
except requests.HTTPError:
|
| 85 |
+
return # offset cap or other 4xx -> stop with what we have
|
| 86 |
+
if not page:
|
| 87 |
+
return
|
| 88 |
+
yield from page
|
| 89 |
+
if len(page) < page_limit:
|
| 90 |
+
return
|
| 91 |
+
offset += page_limit
|
| 92 |
+
|
| 93 |
+
def positions(self, wallet: str) -> list[dict]:
|
| 94 |
+
"""Open positions with avgPrice, curPrice, size, cashPnl, percentPnl."""
|
| 95 |
+
return self._get(f"{DATA_API}/positions", {"user": wallet.lower()})
|
| 96 |
+
|
| 97 |
+
def value(self, wallet: str) -> Any:
|
| 98 |
+
"""Current portfolio USD value for a wallet."""
|
| 99 |
+
return self._get(f"{DATA_API}/value", {"user": wallet.lower()})
|
| 100 |
+
|
| 101 |
+
def holders(self, condition_id: str, limit: int = 40) -> list[dict]:
|
| 102 |
+
"""Largest holders of a market's outcome tokens -> source of whales."""
|
| 103 |
+
return self._get(
|
| 104 |
+
f"{DATA_API}/holders", {"market": condition_id, "limit": limit}
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
# ----- Leaderboard ------------------------------------------------------
|
| 108 |
+
# Verified live 2026-07: host lb-api.polymarket.com, paths /profit and
|
| 109 |
+
# /volume, window in {all, 1d, 7d, 30d}. Each row: {proxyWallet, amount,
|
| 110 |
+
# name, pseudonym, ...} where `amount` is profit-USD (/profit) or
|
| 111 |
+
# volume-USD (/volume).
|
| 112 |
+
def leaderboard(self, window: str = "all", top_n: int = 200,
|
| 113 |
+
metric: str = "profit") -> list[dict]:
|
| 114 |
+
"""Top traders by `metric` in {profit, volume} for a window in
|
| 115 |
+
{all, 1d, 7d, 30d}. For copy-trading you want profit."""
|
| 116 |
+
assert metric in ("profit", "volume")
|
| 117 |
+
return self._get(
|
| 118 |
+
f"{LEADERBOARD_API}/{metric}",
|
| 119 |
+
{"window": window, "limit": top_n},
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
# ----- Gamma: market metadata / resolution ------------------------------
|
| 123 |
+
def markets(self, **params) -> list[dict]:
|
| 124 |
+
"""Query markets. Useful params: active, closed, limit, offset,
|
| 125 |
+
order, ascending, condition_ids (comma-joined), volume_num_min."""
|
| 126 |
+
return self._get(f"{GAMMA_API}/markets", params)
|
| 127 |
+
|
| 128 |
+
def market_by_condition(self, condition_ids: list[str]) -> list[dict]:
|
| 129 |
+
return self._get(
|
| 130 |
+
f"{GAMMA_API}/markets",
|
| 131 |
+
{"condition_ids": ",".join(condition_ids), "limit": len(condition_ids)},
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
# ----- CLOB: prices -----------------------------------------------------
|
| 135 |
+
def price(self, token_id: str, side: str = "buy") -> Any:
|
| 136 |
+
return self._get(f"{CLOB_API}/price", {"token_id": token_id, "side": side})
|
| 137 |
+
|
| 138 |
+
def prices_history(self, token_id: str, interval: str = "max", fidelity: int = 60) -> Any:
|
| 139 |
+
"""Historical price series for a CLOB outcome token; used to mark
|
| 140 |
+
positions and to reconstruct fill context in the backtest."""
|
| 141 |
+
return self._get(
|
| 142 |
+
f"{CLOB_API}/prices-history",
|
| 143 |
+
{"market": token_id, "interval": interval, "fidelity": fidelity},
|
| 144 |
+
)
|
pmct/digest.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Daily 'consistent smart-money' digest engine.
|
| 2 |
+
|
| 3 |
+
Product wedge (from surveying the crowded Polymarket-tracker market): existing
|
| 4 |
+
whale trackers only flag $10k+ whales and just dump raw trades. Two documented
|
| 5 |
+
gaps we target instead:
|
| 6 |
+
|
| 7 |
+
1. COVERAGE β surface *consistent mid-size* traders the whale filters miss.
|
| 8 |
+
2. JUDGEMENT β attach a signal-quality score so a move comes with context,
|
| 9 |
+
not just "someone bought."
|
| 10 |
+
|
| 11 |
+
Inputs are the already-computed metrics table (data/wallets.csv, produced by
|
| 12 |
+
02_analyze_wallets.py) plus a live pull of each selected wallet's most recent
|
| 13 |
+
activity. We deliberately EXCLUDE mega-whales and market-makers β the opposite
|
| 14 |
+
of what the incumbents rank on.
|
| 15 |
+
|
| 16 |
+
This is market-intelligence tooling, NOT a profit promise. The underlying copy
|
| 17 |
+
edge is unproven (see README caveats); we sell flow context, like TradingView
|
| 18 |
+
sells charts, not guaranteed returns.
|
| 19 |
+
"""
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
from dataclasses import dataclass, field
|
| 23 |
+
|
| 24 |
+
import numpy as np
|
| 25 |
+
import pandas as pd
|
| 26 |
+
|
| 27 |
+
from .ledger import normalize_activity
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@dataclass
|
| 31 |
+
class SelectionConfig:
|
| 32 |
+
# the wedge: consistent, repeatable, copyable, NOT a mega-whale / market-maker
|
| 33 |
+
min_monthly_profit_ratio: float = 0.5 # green in >=half of active months
|
| 34 |
+
min_repeatability: float = 0.30
|
| 35 |
+
max_rebate_share: float = 0.35 # reject market-makers (uncopyable)
|
| 36 |
+
min_profit_usd: float = 5_000 # must be actually profitable...
|
| 37 |
+
max_profit_usd: float = 2_000_000 # ...but NOT a mega-whale (coverage gap)
|
| 38 |
+
max_avg_trade_usdc: float = 5_000 # mid-size, not size-you-can't-mirror
|
| 39 |
+
min_active_days: int = 20
|
| 40 |
+
min_resolved_markets: int = 5
|
| 41 |
+
top_n: int = 15
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _profit(row: pd.Series) -> float:
|
| 45 |
+
"""Authoritative profit if on leaderboard, else reconstructed total_pnl."""
|
| 46 |
+
p = row.get("profit_final")
|
| 47 |
+
if p is None or (isinstance(p, float) and np.isnan(p)):
|
| 48 |
+
p = row.get("total_pnl", 0.0)
|
| 49 |
+
return float(p or 0.0)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _trader_score(row: pd.Series) -> float:
|
| 53 |
+
"""Blend the trustworthy signals into one 0..1 quality score for a trader.
|
| 54 |
+
Leans on consistency + repeatability + copyability (NOT raw size or the noisy
|
| 55 |
+
win-rate / reconstructed-PnL fields)."""
|
| 56 |
+
consistency = float(row.get("monthly_profit_ratio", 0.0) or 0.0)
|
| 57 |
+
repeat = float(row.get("repeatability", 0.0) or 0.0)
|
| 58 |
+
copyable = 1.0 - min(1.0, float(row.get("rebate_share", 0.0) or 0.0))
|
| 59 |
+
roi = float(row.get("roi", 0.0) or 0.0)
|
| 60 |
+
roi_signal = float(np.clip(roi / 0.5, 0.0, 1.0)) # 50% ROI -> full
|
| 61 |
+
return round(float(np.mean([consistency, repeat, copyable, roi_signal])), 4)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def select_smart_money(df: pd.DataFrame, cfg: SelectionConfig) -> pd.DataFrame:
|
| 65 |
+
"""Apply the wedge filter and rank. Returns a copy with `trader_score`."""
|
| 66 |
+
if df.empty:
|
| 67 |
+
return df.assign(trader_score=[])
|
| 68 |
+
d = df.copy()
|
| 69 |
+
d["profit"] = d.apply(_profit, axis=1)
|
| 70 |
+
d["trader_score"] = d.apply(_trader_score, axis=1)
|
| 71 |
+
|
| 72 |
+
m = (
|
| 73 |
+
(d["monthly_profit_ratio"].fillna(0) >= cfg.min_monthly_profit_ratio)
|
| 74 |
+
& (d["repeatability"].fillna(0) >= cfg.min_repeatability)
|
| 75 |
+
& (d["rebate_share"].fillna(1) <= cfg.max_rebate_share)
|
| 76 |
+
& (d["profit"] >= cfg.min_profit_usd)
|
| 77 |
+
& (d["profit"] <= cfg.max_profit_usd) # <-- excludes mega-whales
|
| 78 |
+
& (d["avg_trade_usdc"].fillna(1e12) <= cfg.max_avg_trade_usdc)
|
| 79 |
+
& (d["active_days"].fillna(0) >= cfg.min_active_days)
|
| 80 |
+
& (d["n_resolved_markets"].fillna(0) >= cfg.min_resolved_markets)
|
| 81 |
+
)
|
| 82 |
+
out = d[m].sort_values("trader_score", ascending=False).head(cfg.top_n)
|
| 83 |
+
return out.reset_index(drop=True)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
@dataclass
|
| 87 |
+
class Move:
|
| 88 |
+
wallet: str
|
| 89 |
+
trader_score: float
|
| 90 |
+
title: str
|
| 91 |
+
outcome: str
|
| 92 |
+
price: float
|
| 93 |
+
usdc: float
|
| 94 |
+
ts: pd.Timestamp
|
| 95 |
+
conviction: float # this bet vs the trader's own typical size
|
| 96 |
+
signal_quality: float # trader_score blended with conviction+edge
|
| 97 |
+
dominant_topic: str = ""
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def _conviction(usdc: float, avg_usdc: float) -> float:
|
| 101 |
+
"""How big is this bet relative to the trader's own average? >1 means an
|
| 102 |
+
above-typical, higher-conviction entry. Squashed to 0..1."""
|
| 103 |
+
if avg_usdc <= 0:
|
| 104 |
+
return 0.5
|
| 105 |
+
ratio = usdc / avg_usdc
|
| 106 |
+
return float(np.clip(ratio / 3.0, 0.0, 1.0)) # 3x avg -> max conviction
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def fresh_moves(client, selected: pd.DataFrame, hours: int = 24,
|
| 110 |
+
page_limit: int = 200, per_wallet_cap: int = 3) -> list[Move]:
|
| 111 |
+
"""Pull each selected wallet's recent BUYs inside the window, scored."""
|
| 112 |
+
cutoff = pd.Timestamp.now("UTC") - pd.Timedelta(hours=hours)
|
| 113 |
+
moves: list[Move] = []
|
| 114 |
+
for _, row in selected.iterrows():
|
| 115 |
+
wallet = row["wallet"]
|
| 116 |
+
try:
|
| 117 |
+
raw = client.activity(wallet, limit=page_limit, offset=0)
|
| 118 |
+
except Exception:
|
| 119 |
+
continue
|
| 120 |
+
led = normalize_activity(raw)
|
| 121 |
+
if led.empty:
|
| 122 |
+
continue
|
| 123 |
+
led = led[(led["side"] == "BUY") & (led["ts"] >= cutoff)]
|
| 124 |
+
if led.empty:
|
| 125 |
+
continue
|
| 126 |
+
avg_usdc = float(row.get("avg_trade_usdc", 0.0) or 0.0)
|
| 127 |
+
tscore = float(row["trader_score"])
|
| 128 |
+
picked = 0
|
| 129 |
+
for t in led.sort_values("usdc", ascending=False).itertuples(index=False):
|
| 130 |
+
conv = _conviction(float(t.usdc), avg_usdc)
|
| 131 |
+
edge = abs(float(t.price) - 0.5) * 2.0
|
| 132 |
+
sig = round(float(np.mean([tscore, tscore, conv, edge])), 4) # trader weighted 2x
|
| 133 |
+
moves.append(Move(
|
| 134 |
+
wallet=wallet, trader_score=tscore, title=str(t.title),
|
| 135 |
+
outcome=str(t.outcome), price=float(t.price), usdc=float(t.usdc),
|
| 136 |
+
ts=t.ts, conviction=round(conv, 3), signal_quality=sig,
|
| 137 |
+
dominant_topic=str(row.get("dominant_topic", "") or ""),
|
| 138 |
+
))
|
| 139 |
+
picked += 1
|
| 140 |
+
if picked >= per_wallet_cap:
|
| 141 |
+
break
|
| 142 |
+
moves.sort(key=lambda m: m.signal_quality, reverse=True)
|
| 143 |
+
return moves
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def render_markdown(selected: pd.DataFrame, moves: list[Move],
|
| 147 |
+
hours: int, top_moves: int = 12) -> str:
|
| 148 |
+
date = pd.Timestamp.now("UTC").strftime("%Y-%m-%d %H:%M UTC")
|
| 149 |
+
lines = [
|
| 150 |
+
f"# Consistent Smart-Money Digest β {date}",
|
| 151 |
+
"",
|
| 152 |
+
f"_Mid-size, consistently-profitable Polymarket traders (the ones whale "
|
| 153 |
+
f"trackers skip) and their highest-conviction moves in the last {hours}h. "
|
| 154 |
+
f"Flow intelligence, not financial advice._",
|
| 155 |
+
"",
|
| 156 |
+
f"**Tracking {len(selected)} vetted traders Β· {len(moves)} fresh moves scored**",
|
| 157 |
+
"",
|
| 158 |
+
"## Top moves right now",
|
| 159 |
+
"",
|
| 160 |
+
]
|
| 161 |
+
if not moves:
|
| 162 |
+
lines.append("_No qualifying fresh moves in the window. Check back next run._")
|
| 163 |
+
else:
|
| 164 |
+
lines.append("| Signal | Trader | Move | Price | Size | Conviction |")
|
| 165 |
+
lines.append("|---|---|---|---|---|---|")
|
| 166 |
+
for m in moves[:top_moves]:
|
| 167 |
+
bar = "β" * int(round(m.signal_quality * 5)) or "β"
|
| 168 |
+
short = f"`{m.wallet[:6]}β¦{m.wallet[-4:]}`"
|
| 169 |
+
title = (m.title[:46] + "β¦") if len(m.title) > 47 else m.title
|
| 170 |
+
lines.append(
|
| 171 |
+
f"| {bar} {m.signal_quality:.2f} | {short} | {title} "
|
| 172 |
+
f"({m.outcome}) | {m.price:.2f} | ${m.usdc:,.0f} | {m.conviction:.0%} |"
|
| 173 |
+
)
|
| 174 |
+
lines += ["", "## The traders we're tracking", "",
|
| 175 |
+
"| Trader | Score | Profit | Consistency | Repeatability | Topic |",
|
| 176 |
+
"|---|---|---|---|---|---|"]
|
| 177 |
+
for _, r in selected.iterrows():
|
| 178 |
+
short = f"`{r['wallet'][:6]}β¦{r['wallet'][-4:]}`"
|
| 179 |
+
lines.append(
|
| 180 |
+
f"| {short} | {r['trader_score']:.2f} | ${_profit(r):,.0f} | "
|
| 181 |
+
f"{float(r.get('monthly_profit_ratio',0)):.0%} | "
|
| 182 |
+
f"{float(r.get('repeatability',0)):.2f} | "
|
| 183 |
+
f"{r.get('dominant_topic','')} |"
|
| 184 |
+
)
|
| 185 |
+
lines += ["", "---",
|
| 186 |
+
"_Built from Polymarket public data. Past performance is not "
|
| 187 |
+
"predictive; consistency scoring β guaranteed profit._"]
|
| 188 |
+
return "\n".join(lines)
|
pmct/discover.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Source a set of candidate wallet addresses to analyze.
|
| 2 |
+
|
| 3 |
+
Three independent sources, unioned and de-duped:
|
| 4 |
+
1. leaderboard - top traders by realized profit over several windows
|
| 5 |
+
2. market holders - the largest holders of currently active, high-volume
|
| 6 |
+
markets (catches whales who never top the leaderboard)
|
| 7 |
+
3. seed_wallets - addresses you already want to include
|
| 8 |
+
|
| 9 |
+
The goal is recall, not precision: cast a wide net here, then let metrics +
|
| 10 |
+
screening throw out the noise.
|
| 11 |
+
"""
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import re
|
| 15 |
+
|
| 16 |
+
from .client import PolymarketClient
|
| 17 |
+
|
| 18 |
+
_ADDR = re.compile(r"^0x[a-fA-F0-9]{40}$")
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _extract_wallet(item: dict) -> str | None:
|
| 22 |
+
for k in ("proxyWallet", "wallet", "user", "address", "account", "maker"):
|
| 23 |
+
v = item.get(k)
|
| 24 |
+
if isinstance(v, str) and _ADDR.match(v):
|
| 25 |
+
return v.lower()
|
| 26 |
+
return None
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def leaderboard_profit_map(client: PolymarketClient, windows, top_n: int) -> dict[str, dict]:
|
| 30 |
+
"""{wallet: {lb_profit_all, lb_volume_all, on_leaderboard}} β the AUTHORITATIVE
|
| 31 |
+
profit/volume Polymarket reports, used to cross-check (and override) our own
|
| 32 |
+
reconstructed PnL for wallets that are actually ranked. 'all' window is the
|
| 33 |
+
long-term figure; we keep the max seen across windows to be safe."""
|
| 34 |
+
out: dict[str, dict] = {}
|
| 35 |
+
for metric, key in (("profit", "lb_profit"), ("volume", "lb_volume")):
|
| 36 |
+
for w in windows:
|
| 37 |
+
try:
|
| 38 |
+
rows = client.leaderboard(window=w, top_n=top_n, metric=metric)
|
| 39 |
+
except Exception as e: # noqa: BLE001
|
| 40 |
+
print(f" [lb {metric} {w}] failed: {e}")
|
| 41 |
+
continue
|
| 42 |
+
for r in rows if isinstance(rows, list) else rows.get("data", []):
|
| 43 |
+
addr = _extract_wallet(r)
|
| 44 |
+
if not addr:
|
| 45 |
+
continue
|
| 46 |
+
amt = float(r.get("amount", 0) or 0)
|
| 47 |
+
rec = out.setdefault(addr, {"lb_profit": None, "lb_volume": None,
|
| 48 |
+
"on_leaderboard": True})
|
| 49 |
+
if w == "all": # prefer the all-time figure
|
| 50 |
+
rec[key] = amt
|
| 51 |
+
elif rec.get(key) is None:
|
| 52 |
+
rec[key] = amt
|
| 53 |
+
return out
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def from_leaderboard(client: PolymarketClient, windows, top_n: int) -> set[str]:
|
| 57 |
+
out: set[str] = set()
|
| 58 |
+
for w in windows:
|
| 59 |
+
try:
|
| 60 |
+
rows = client.leaderboard(window=w, top_n=top_n)
|
| 61 |
+
except Exception as e: # noqa: BLE001 - discovery is best-effort
|
| 62 |
+
print(f" [leaderboard {w}] failed: {e}")
|
| 63 |
+
continue
|
| 64 |
+
for r in rows if isinstance(rows, list) else rows.get("data", []):
|
| 65 |
+
addr = _extract_wallet(r)
|
| 66 |
+
if addr:
|
| 67 |
+
out.add(addr)
|
| 68 |
+
return out
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _volume(m: dict) -> float:
|
| 72 |
+
try:
|
| 73 |
+
return float(m.get("volume") or m.get("volumeNum") or 0)
|
| 74 |
+
except (TypeError, ValueError):
|
| 75 |
+
return 0.0
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def from_market_holders(client: PolymarketClient, n_markets: int, holders_per: int) -> set[str]:
|
| 79 |
+
out: set[str] = set()
|
| 80 |
+
# Gamma's server-side `order=volume` is unreliable, so over-fetch active
|
| 81 |
+
# markets and rank by volume client-side, then take the busiest N.
|
| 82 |
+
try:
|
| 83 |
+
markets = client.markets(active=True, closed=False, limit=max(n_markets * 6, 300))
|
| 84 |
+
except Exception as e: # noqa: BLE001
|
| 85 |
+
print(f" [markets] failed: {e}")
|
| 86 |
+
return out
|
| 87 |
+
|
| 88 |
+
rows = markets if isinstance(markets, list) else markets.get("data", [])
|
| 89 |
+
rows = sorted(rows, key=_volume, reverse=True)[:n_markets]
|
| 90 |
+
|
| 91 |
+
for m in rows:
|
| 92 |
+
cid = m.get("conditionId") or m.get("condition_id")
|
| 93 |
+
if not cid:
|
| 94 |
+
continue
|
| 95 |
+
try:
|
| 96 |
+
holders = client.holders(cid, limit=holders_per)
|
| 97 |
+
except Exception as e: # noqa: BLE001
|
| 98 |
+
print(f" [holders {cid[:10]}] failed: {e}")
|
| 99 |
+
continue
|
| 100 |
+
# shape: [{token, holders:[{proxyWallet,...}]}, ...] (one group per outcome)
|
| 101 |
+
groups = holders if isinstance(holders, list) else [holders]
|
| 102 |
+
for g in groups:
|
| 103 |
+
for h in (g.get("holders") if isinstance(g, dict) else g) or []:
|
| 104 |
+
addr = _extract_wallet(h)
|
| 105 |
+
if addr:
|
| 106 |
+
out.add(addr)
|
| 107 |
+
return out
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def discover(client: PolymarketClient, cfg: dict) -> list[str]:
|
| 111 |
+
wallets: set[str] = set(a.lower() for a in cfg.get("seed_wallets", []) if _ADDR.match(a))
|
| 112 |
+
if cfg.get("use_leaderboard"):
|
| 113 |
+
lb = from_leaderboard(client, cfg["leaderboard_windows"], cfg["leaderboard_top_n"])
|
| 114 |
+
print(f" leaderboard -> {len(lb)} wallets")
|
| 115 |
+
wallets |= lb
|
| 116 |
+
if cfg.get("use_market_holders"):
|
| 117 |
+
mh = from_market_holders(client, cfg["markets_to_scan"], cfg["holders_per_market"])
|
| 118 |
+
print(f" market holders -> {len(mh)} wallets")
|
| 119 |
+
wallets |= mh
|
| 120 |
+
print(f" total unique candidates: {len(wallets)}")
|
| 121 |
+
return sorted(wallets)
|
pmct/ledger.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Normalize a wallet's raw activity feed into a tidy trade ledger.
|
| 2 |
+
|
| 3 |
+
The Data API returns loosely-typed dicts whose exact keys drift over time, so
|
| 4 |
+
every field is read with fallbacks. The output is one DataFrame per wallet with
|
| 5 |
+
a stable schema the rest of the pipeline relies on.
|
| 6 |
+
|
| 7 |
+
Cashflow convention (from the trader's perspective):
|
| 8 |
+
BUY -> cash out (negative)
|
| 9 |
+
SELL -> cash in (positive)
|
| 10 |
+
REDEEM / REWARD -> cash in (positive) # market resolved in their favor
|
| 11 |
+
Open positions are marked to market separately in metrics.py.
|
| 12 |
+
"""
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import pandas as pd
|
| 16 |
+
|
| 17 |
+
LEDGER_COLS = [
|
| 18 |
+
"ts", "type", "side", "market", "asset", "outcome",
|
| 19 |
+
"size", "price", "usdc", "cashflow", "title",
|
| 20 |
+
]
|
| 21 |
+
|
| 22 |
+
# activity types that bring cash IN (winning redemptions + protocol incentives)
|
| 23 |
+
CASH_IN_TYPES = ("REDEEM", "CLAIM", "REWARD", "MAKER_REBATE", "TAKER_REBATE")
|
| 24 |
+
# the uncopyable subset: liquidity rewards + maker/taker rebates (market-making)
|
| 25 |
+
REBATE_TYPES = ("REWARD", "MAKER_REBATE", "TAKER_REBATE")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _first(d: dict, *keys, default=None):
|
| 29 |
+
for k in keys:
|
| 30 |
+
if k in d and d[k] not in (None, ""):
|
| 31 |
+
return d[k]
|
| 32 |
+
return default
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _to_float(x, default=0.0) -> float:
|
| 36 |
+
try:
|
| 37 |
+
return float(x)
|
| 38 |
+
except (TypeError, ValueError):
|
| 39 |
+
return default
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def normalize_activity(raw: list[dict]) -> pd.DataFrame:
|
| 43 |
+
rows = []
|
| 44 |
+
for a in raw:
|
| 45 |
+
typ = str(_first(a, "type", "activityType", default="TRADE")).upper()
|
| 46 |
+
side = str(_first(a, "side", default="")).upper()
|
| 47 |
+
size = _to_float(_first(a, "size", "shares", "amount"))
|
| 48 |
+
price = _to_float(_first(a, "price", "avgPrice"))
|
| 49 |
+
usdc = _first(a, "usdcSize", "usdc", "usdcValue", default=None)
|
| 50 |
+
usdc = _to_float(usdc) if usdc is not None else round(size * price, 6)
|
| 51 |
+
|
| 52 |
+
# ts may be unix seconds or ms
|
| 53 |
+
ts_raw = _to_float(_first(a, "timestamp", "ts", "time"))
|
| 54 |
+
if ts_raw > 1e12:
|
| 55 |
+
ts_raw /= 1000.0
|
| 56 |
+
ts = pd.to_datetime(ts_raw, unit="s", utc=True) if ts_raw else pd.NaT
|
| 57 |
+
|
| 58 |
+
# Protocol incentives (liquidity rewards + maker/taker rebates) are real
|
| 59 |
+
# income but NOT copyable directional skill β tag them so metrics can
|
| 60 |
+
# measure how rebate-driven a wallet is (market makers = uncopyable).
|
| 61 |
+
if typ in CASH_IN_TYPES or side == "SELL":
|
| 62 |
+
cashflow = +usdc
|
| 63 |
+
elif side == "BUY":
|
| 64 |
+
cashflow = -usdc
|
| 65 |
+
else: # unknown non-trade rows contribute no directional cashflow
|
| 66 |
+
cashflow = 0.0
|
| 67 |
+
|
| 68 |
+
rows.append({
|
| 69 |
+
"ts": ts,
|
| 70 |
+
"type": typ,
|
| 71 |
+
"side": side,
|
| 72 |
+
"market": _first(a, "conditionId", "condition_id", "market", default=""),
|
| 73 |
+
"asset": _first(a, "asset", "tokenId", "token_id", default=""),
|
| 74 |
+
"outcome": _first(a, "outcome", "outcomeIndex", default=""),
|
| 75 |
+
"size": size,
|
| 76 |
+
"price": price,
|
| 77 |
+
"usdc": usdc,
|
| 78 |
+
"cashflow": cashflow,
|
| 79 |
+
"title": _first(a, "title", "slug", "question", default=""),
|
| 80 |
+
})
|
| 81 |
+
|
| 82 |
+
df = pd.DataFrame(rows, columns=LEDGER_COLS)
|
| 83 |
+
if not df.empty:
|
| 84 |
+
df = df.dropna(subset=["ts"]).sort_values("ts").reset_index(drop=True)
|
| 85 |
+
return df
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def attach_open_positions(positions: list[dict]) -> pd.DataFrame:
|
| 89 |
+
"""Current open positions -> per-market marked-to-market value & PnL."""
|
| 90 |
+
rows = []
|
| 91 |
+
for p in positions:
|
| 92 |
+
size = _to_float(_first(p, "size", "shares"))
|
| 93 |
+
avg = _to_float(_first(p, "avgPrice", "averagePrice"))
|
| 94 |
+
cur = _to_float(_first(p, "curPrice", "currentPrice", "price"))
|
| 95 |
+
rows.append({
|
| 96 |
+
"market": _first(p, "conditionId", "condition_id", "market", default=""),
|
| 97 |
+
"asset": _first(p, "asset", "tokenId", default=""),
|
| 98 |
+
"size": size,
|
| 99 |
+
"avgPrice": avg,
|
| 100 |
+
"curPrice": cur,
|
| 101 |
+
"cost_basis": size * avg,
|
| 102 |
+
"mark_value": size * cur,
|
| 103 |
+
"cashPnl": _to_float(_first(p, "cashPnl", default=size * (cur - avg))),
|
| 104 |
+
})
|
| 105 |
+
return pd.DataFrame(rows)
|
pmct/metrics.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Per-wallet performance metrics computed from the normalized ledger.
|
| 2 |
+
|
| 3 |
+
Everything here is derived from two inputs:
|
| 4 |
+
- ledger : normalized activity (see ledger.normalize_activity)
|
| 5 |
+
- open_df : marked-to-market open positions (see ledger.attach_open_positions)
|
| 6 |
+
|
| 7 |
+
Key definitions:
|
| 8 |
+
total_pnl = realized cashflow over closed markets + MTM value of open ones
|
| 9 |
+
roi = total_pnl / capital_deployed (sum of buy cost basis)
|
| 10 |
+
win_rate = share of *resolved* markets that ended net-positive
|
| 11 |
+
equity_curve= cumulative realized cashflow over time (+ running deposits view)
|
| 12 |
+
max_dd = worst peak-to-trough drawdown of the equity curve
|
| 13 |
+
consistency = fraction of active months that were net green
|
| 14 |
+
"""
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
from dataclasses import dataclass, asdict
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import pandas as pd
|
| 21 |
+
|
| 22 |
+
from .ledger import REBATE_TYPES
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@dataclass
|
| 26 |
+
class WalletStats:
|
| 27 |
+
wallet: str
|
| 28 |
+
total_pnl: float
|
| 29 |
+
realized_pnl: float
|
| 30 |
+
open_pnl: float
|
| 31 |
+
capital_deployed: float
|
| 32 |
+
roi: float
|
| 33 |
+
win_rate: float
|
| 34 |
+
n_trades: int
|
| 35 |
+
n_markets: int
|
| 36 |
+
n_resolved_markets: int
|
| 37 |
+
active_days: int
|
| 38 |
+
first_ts: str
|
| 39 |
+
last_ts: str
|
| 40 |
+
max_drawdown_pct: float
|
| 41 |
+
monthly_profit_ratio: float
|
| 42 |
+
avg_trade_usdc: float
|
| 43 |
+
median_entry_price: float
|
| 44 |
+
rebate_pnl: float # income from liquidity rewards + maker/taker rebates
|
| 45 |
+
rebate_share: float # rebate_pnl / total_pnl -> high = market maker (uncopyable)
|
| 46 |
+
|
| 47 |
+
def to_dict(self) -> dict:
|
| 48 |
+
return asdict(self)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _resolved_market_pnl(ledger: pd.DataFrame) -> pd.Series:
|
| 52 |
+
"""Net cashflow per market. A market is 'resolved' for our purposes when the
|
| 53 |
+
trader has fully exited it (net share flow ~0) or redeemed it. We approximate
|
| 54 |
+
resolution by net share balance: BUY adds shares, SELL/REDEEM remove them."""
|
| 55 |
+
if ledger.empty:
|
| 56 |
+
return pd.Series(dtype=float)
|
| 57 |
+
signed_size = np.where(ledger["side"].eq("BUY"), ledger["size"], -ledger["size"])
|
| 58 |
+
tmp = ledger.assign(signed_size=signed_size)
|
| 59 |
+
pnl = tmp.groupby("market")["cashflow"].sum()
|
| 60 |
+
net_shares = tmp.groupby("market")["signed_size"].sum().abs()
|
| 61 |
+
# treat markets with a near-zero residual share balance as resolved/closed
|
| 62 |
+
resolved = net_shares < 1e-6
|
| 63 |
+
pnl.attrs["resolved_mask"] = resolved
|
| 64 |
+
return pnl
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _empty(wallet: str) -> WalletStats:
|
| 68 |
+
return WalletStats(
|
| 69 |
+
wallet=wallet, total_pnl=0.0, realized_pnl=0.0, open_pnl=0.0,
|
| 70 |
+
capital_deployed=0.0, roi=0.0, win_rate=0.0, n_trades=0, n_markets=0,
|
| 71 |
+
n_resolved_markets=0, active_days=0, first_ts="", last_ts="",
|
| 72 |
+
max_drawdown_pct=0.0, monthly_profit_ratio=0.0, avg_trade_usdc=0.0,
|
| 73 |
+
median_entry_price=0.0, rebate_pnl=0.0, rebate_share=0.0,
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def compute(wallet: str, ledger: pd.DataFrame, open_df: pd.DataFrame) -> WalletStats:
|
| 78 |
+
if ledger.empty:
|
| 79 |
+
return _empty(wallet)
|
| 80 |
+
|
| 81 |
+
market_pnl = _resolved_market_pnl(ledger)
|
| 82 |
+
resolved_mask = market_pnl.attrs.get("resolved_mask", pd.Series(dtype=bool))
|
| 83 |
+
|
| 84 |
+
realized_pnl = float(market_pnl.sum())
|
| 85 |
+
open_pnl = float(open_df["cashPnl"].sum()) if not open_df.empty else 0.0
|
| 86 |
+
total_pnl = realized_pnl + open_pnl
|
| 87 |
+
|
| 88 |
+
buys = ledger.loc[ledger["side"].eq("BUY"), "usdc"]
|
| 89 |
+
capital_deployed = float(buys.sum())
|
| 90 |
+
roi = total_pnl / capital_deployed if capital_deployed > 0 else 0.0
|
| 91 |
+
|
| 92 |
+
resolved_pnl = market_pnl[resolved_mask] if len(resolved_mask) else market_pnl
|
| 93 |
+
n_resolved = int(len(resolved_pnl))
|
| 94 |
+
win_rate = float((resolved_pnl > 0).mean()) if n_resolved else 0.0
|
| 95 |
+
|
| 96 |
+
first_ts, last_ts = ledger["ts"].iloc[0], ledger["ts"].iloc[-1]
|
| 97 |
+
active_days = int((last_ts - first_ts).days)
|
| 98 |
+
|
| 99 |
+
# equity curve = cumulative realized cashflow through time
|
| 100 |
+
eq = ledger.sort_values("ts")["cashflow"].cumsum()
|
| 101 |
+
max_dd = _max_drawdown_pct(eq.values, capital_deployed)
|
| 102 |
+
|
| 103 |
+
# monthly consistency
|
| 104 |
+
monthly = (ledger.set_index("ts")["cashflow"]
|
| 105 |
+
.resample("ME").sum())
|
| 106 |
+
monthly_profit_ratio = float((monthly > 0).mean()) if len(monthly) else 0.0
|
| 107 |
+
|
| 108 |
+
trade_rows = ledger[ledger["side"].isin(["BUY", "SELL"])]
|
| 109 |
+
avg_trade_usdc = float(trade_rows["usdc"].mean()) if not trade_rows.empty else 0.0
|
| 110 |
+
median_entry = float(ledger.loc[ledger["side"].eq("BUY"), "price"].median() or 0.0)
|
| 111 |
+
|
| 112 |
+
# copyability: how much of the profit is protocol incentives (market-making)
|
| 113 |
+
rebate_pnl = float(ledger.loc[ledger["type"].isin(REBATE_TYPES), "usdc"].sum())
|
| 114 |
+
rebate_share = rebate_pnl / total_pnl if total_pnl > 0 else (1.0 if rebate_pnl > 0 else 0.0)
|
| 115 |
+
|
| 116 |
+
return WalletStats(
|
| 117 |
+
wallet=wallet,
|
| 118 |
+
total_pnl=round(total_pnl, 2),
|
| 119 |
+
realized_pnl=round(realized_pnl, 2),
|
| 120 |
+
open_pnl=round(open_pnl, 2),
|
| 121 |
+
capital_deployed=round(capital_deployed, 2),
|
| 122 |
+
roi=round(roi, 4),
|
| 123 |
+
win_rate=round(win_rate, 4),
|
| 124 |
+
n_trades=int(len(trade_rows)),
|
| 125 |
+
n_markets=int(ledger["market"].nunique()),
|
| 126 |
+
n_resolved_markets=n_resolved,
|
| 127 |
+
active_days=active_days,
|
| 128 |
+
first_ts=str(first_ts),
|
| 129 |
+
last_ts=str(last_ts),
|
| 130 |
+
max_drawdown_pct=round(max_dd, 4),
|
| 131 |
+
monthly_profit_ratio=round(monthly_profit_ratio, 4),
|
| 132 |
+
avg_trade_usdc=round(avg_trade_usdc, 2),
|
| 133 |
+
median_entry_price=round(median_entry, 4),
|
| 134 |
+
rebate_pnl=round(rebate_pnl, 2),
|
| 135 |
+
rebate_share=round(min(max(rebate_share, 0.0), 1.0), 4),
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def _max_drawdown_pct(equity: np.ndarray, denom: float) -> float:
|
| 140 |
+
"""Max peak-to-trough drop, normalized by capital deployed so it reads as a
|
| 141 |
+
fraction. Returns 0..1 (higher = worse)."""
|
| 142 |
+
if len(equity) == 0 or denom <= 0:
|
| 143 |
+
return 0.0
|
| 144 |
+
running_max = np.maximum.accumulate(equity)
|
| 145 |
+
drawdown = running_max - equity
|
| 146 |
+
return float(drawdown.max() / denom)
|
pmct/patterns.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Detect *repeatable* trading patterns in a wallet's ledger.
|
| 2 |
+
|
| 3 |
+
The user's second screen is "εθ¦εΊηΎγε―θ€θ£½ηδΊ€ζ樑εΌ" β recurring, replicable
|
| 4 |
+
behavior. A wallet that made money once by luck is useless to copy; a wallet
|
| 5 |
+
that does the same identifiable thing over and over is copyable.
|
| 6 |
+
|
| 7 |
+
We reduce each wallet to a handful of style features, then collapse them into a
|
| 8 |
+
single `repeatability` score in [0, 1]. High score = tight entry-price band,
|
| 9 |
+
consistent bet sizing, topical concentration, and steady cadence over many
|
| 10 |
+
trades β i.e. a strategy, not noise.
|
| 11 |
+
"""
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
from dataclasses import dataclass, asdict
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
import pandas as pd
|
| 18 |
+
|
| 19 |
+
# crude topic buckets from title keywords; used when Gamma tags are absent
|
| 20 |
+
_TOPICS = {
|
| 21 |
+
"sports": ["nba", "nfl", "mlb", "soccer", "ufc", "game", "vs ", "win the", "match"],
|
| 22 |
+
"crypto": ["btc", "bitcoin", "eth", "ethereum", "crypto", "solana", "coin"],
|
| 23 |
+
"politics": ["election", "president", "senate", "trump", "biden", "poll", "governor"],
|
| 24 |
+
"econ": ["fed", "rate", "cpi", "inflation", "gdp", "recession", "jobs"],
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _topic(title: str) -> str:
|
| 29 |
+
t = (title or "").lower()
|
| 30 |
+
for name, kws in _TOPICS.items():
|
| 31 |
+
if any(k in t for k in kws):
|
| 32 |
+
return name
|
| 33 |
+
return "other"
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _cv(x: np.ndarray) -> float:
|
| 37 |
+
"""Coefficient of variation, guarded against zero mean."""
|
| 38 |
+
x = x[x > 0]
|
| 39 |
+
if len(x) < 2 or x.mean() == 0:
|
| 40 |
+
return 1.0
|
| 41 |
+
return float(x.std() / x.mean())
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _hhi(counts: pd.Series) -> float:
|
| 45 |
+
"""Herfindahl concentration in [0,1]; 1 = all one bucket."""
|
| 46 |
+
if counts.sum() == 0:
|
| 47 |
+
return 0.0
|
| 48 |
+
p = counts / counts.sum()
|
| 49 |
+
return float((p ** 2).sum())
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@dataclass
|
| 53 |
+
class PatternFeatures:
|
| 54 |
+
wallet: str
|
| 55 |
+
entry_band_tightness: float # 1 = all entries at same price
|
| 56 |
+
size_consistency: float # 1 = identical bet sizes
|
| 57 |
+
topic_concentration: float # 1 = single topic
|
| 58 |
+
cadence_regularity: float # 1 = evenly spaced over time
|
| 59 |
+
longshot_bias: float # mean(0.5 - entry_price), + = buys underdogs
|
| 60 |
+
dominant_topic: str
|
| 61 |
+
n_buys: int
|
| 62 |
+
repeatability: float # blended [0,1]
|
| 63 |
+
|
| 64 |
+
def to_dict(self) -> dict:
|
| 65 |
+
return asdict(self)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def extract(wallet: str, ledger: pd.DataFrame) -> PatternFeatures:
|
| 69 |
+
buys = ledger[ledger["side"].eq("BUY")].copy()
|
| 70 |
+
if len(buys) < 3:
|
| 71 |
+
return PatternFeatures(wallet, 0, 0, 0, 0, 0.0, "other", len(buys), 0.0)
|
| 72 |
+
|
| 73 |
+
# 1) entry-price band tightness: 1 - normalized std of entry prices
|
| 74 |
+
band_tightness = float(np.clip(1.0 - buys["price"].std() / 0.5, 0, 1))
|
| 75 |
+
|
| 76 |
+
# 2) sizing consistency: 1 - CV of trade notional (clipped)
|
| 77 |
+
size_consistency = float(np.clip(1.0 - _cv(buys["usdc"].values), 0, 1))
|
| 78 |
+
|
| 79 |
+
# 3) topic concentration via HHI
|
| 80 |
+
buys["topic"] = buys["title"].map(_topic)
|
| 81 |
+
topic_counts = buys["topic"].value_counts()
|
| 82 |
+
topic_conc = _hhi(topic_counts)
|
| 83 |
+
dominant_topic = str(topic_counts.index[0])
|
| 84 |
+
|
| 85 |
+
# 4) cadence regularity: 1 - CV of inter-trade gaps (regular => copyable)
|
| 86 |
+
gaps = buys["ts"].sort_values().diff().dropna().dt.total_seconds().values
|
| 87 |
+
cadence = float(np.clip(1.0 - _cv(gaps), 0, 1)) if len(gaps) >= 2 else 0.0
|
| 88 |
+
|
| 89 |
+
# 5) longshot bias (descriptive, not scored): + buys cheap underdogs
|
| 90 |
+
longshot = float((0.5 - buys["price"]).mean())
|
| 91 |
+
|
| 92 |
+
# volume confidence: patterns from few trades are unreliable; ramp 0->1 by ~50 buys
|
| 93 |
+
vol_conf = float(np.clip(np.log1p(len(buys)) / np.log1p(50), 0, 1))
|
| 94 |
+
|
| 95 |
+
repeatability = vol_conf * np.mean([
|
| 96 |
+
band_tightness, size_consistency, topic_conc, cadence
|
| 97 |
+
])
|
| 98 |
+
|
| 99 |
+
return PatternFeatures(
|
| 100 |
+
wallet=wallet,
|
| 101 |
+
entry_band_tightness=round(band_tightness, 3),
|
| 102 |
+
size_consistency=round(size_consistency, 3),
|
| 103 |
+
topic_concentration=round(topic_conc, 3),
|
| 104 |
+
cadence_regularity=round(cadence, 3),
|
| 105 |
+
longshot_bias=round(longshot, 4),
|
| 106 |
+
dominant_topic=dominant_topic,
|
| 107 |
+
n_buys=int(len(buys)),
|
| 108 |
+
repeatability=round(float(repeatability), 3),
|
| 109 |
+
)
|
pmct/post.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Turn a digest run into ready-to-post distribution assets.
|
| 2 |
+
|
| 3 |
+
The product's bottleneck is distribution, not code. This module converts the
|
| 4 |
+
same digest data into:
|
| 5 |
+
- an X / Twitter thread (list of <=280-char tweets), and
|
| 6 |
+
- a dark-theme PNG card of the top moves (for the first tweet).
|
| 7 |
+
|
| 8 |
+
Posting itself needs a human-owned account (or API keys) β this just produces
|
| 9 |
+
the assets so posting is one copy-paste / one API call away.
|
| 10 |
+
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
import pandas as pd
|
| 16 |
+
|
| 17 |
+
from .digest import Move
|
| 18 |
+
|
| 19 |
+
TWEET_LIMIT = 280
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _short(w: str) -> str:
|
| 23 |
+
return f"{w[:6]}β¦{w[-4:]}"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def x_thread(selected: pd.DataFrame, moves: list[Move], hours: int,
|
| 27 |
+
site_url: str = "") -> list[str]:
|
| 28 |
+
"""Compose the thread. Tweet 1 = hook, then top moves, then CTA."""
|
| 29 |
+
n_traders = len(selected)
|
| 30 |
+
hook = (
|
| 31 |
+
f"π Consistent Polymarket smart-money β last {hours}h\n\n"
|
| 32 |
+
f"The {n_traders} mid-size traders whale trackers ignore "
|
| 33 |
+
f"(too small to flag) β and their highest-conviction moves right now.\n\n"
|
| 34 |
+
f"A thread π§΅"
|
| 35 |
+
)
|
| 36 |
+
tweets = [hook]
|
| 37 |
+
|
| 38 |
+
# diversify: best move per wallet first, so the thread isn't 5 near-dupes
|
| 39 |
+
seen: set[str] = set()
|
| 40 |
+
diverse = [m for m in moves if not (m.wallet in seen or seen.add(m.wallet))]
|
| 41 |
+
if len(diverse) < 5:
|
| 42 |
+
diverse += [m for m in moves if m not in diverse]
|
| 43 |
+
|
| 44 |
+
for i, m in enumerate(diverse[:5], 1):
|
| 45 |
+
stars = "β
" * max(1, int(round(m.signal_quality * 5)))
|
| 46 |
+
title = (m.title[:70] + "β¦") if len(m.title) > 71 else m.title
|
| 47 |
+
t = (
|
| 48 |
+
f"{i}/ {stars} signal {m.signal_quality:.2f}\n"
|
| 49 |
+
f"{_short(m.wallet)} β {title} ({m.outcome})\n"
|
| 50 |
+
f"@ {m.price:.2f} Β· ${m.usdc:,.0f} Β· conviction {m.conviction:.0%}"
|
| 51 |
+
)
|
| 52 |
+
tweets.append(t[:TWEET_LIMIT])
|
| 53 |
+
|
| 54 |
+
best = selected.head(3)
|
| 55 |
+
lead = "Why these traders: picked for consistency (green most months) + a "
|
| 56 |
+
lead += "repeatable style, NOT size. Sample of who we track:\n\n"
|
| 57 |
+
lead += "\n".join(
|
| 58 |
+
f"β’ {_short(r['wallet'])} β score {r['trader_score']:.2f}, "
|
| 59 |
+
f"{float(r.get('monthly_profit_ratio',0)):.0%} green months"
|
| 60 |
+
for _, r in best.iterrows()
|
| 61 |
+
)
|
| 62 |
+
tweets.append(lead[:TWEET_LIMIT])
|
| 63 |
+
|
| 64 |
+
cta = "Score ANY Polymarket wallet free β consistent, whale, market-maker, "
|
| 65 |
+
cta += "or just lucky?"
|
| 66 |
+
if site_url:
|
| 67 |
+
cta += f"\n\n{site_url}"
|
| 68 |
+
cta += "\n\nFlow intelligence, not financial advice."
|
| 69 |
+
tweets.append(cta[:TWEET_LIMIT])
|
| 70 |
+
return tweets
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def table_png(moves: list[Move], out: Path, hours: int) -> Path | None:
|
| 74 |
+
"""Render the top moves as a shareable dark card. Returns path or None."""
|
| 75 |
+
if not moves:
|
| 76 |
+
return None
|
| 77 |
+
try:
|
| 78 |
+
import matplotlib
|
| 79 |
+
matplotlib.use("Agg")
|
| 80 |
+
import matplotlib.pyplot as plt
|
| 81 |
+
except Exception:
|
| 82 |
+
return None
|
| 83 |
+
|
| 84 |
+
# one clean row per wallet β no duplicate padding, so the card never shows
|
| 85 |
+
# the same trader three times when only a few distinct wallets are active
|
| 86 |
+
seen: set[str] = set()
|
| 87 |
+
top = [m for m in moves if not (m.wallet in seen or seen.add(m.wallet))][:8]
|
| 88 |
+
bg, ink, mut, acc = "#0b0e14", "#e6edf3", "#8b98a9", "#3fb950"
|
| 89 |
+
|
| 90 |
+
n = len(top)
|
| 91 |
+
fig, ax = plt.subplots(figsize=(10, 1.6 + 0.5 * n))
|
| 92 |
+
fig.patch.set_facecolor(bg)
|
| 93 |
+
ax.set_facecolor(bg)
|
| 94 |
+
ax.axis("off")
|
| 95 |
+
|
| 96 |
+
ax.text(0.02, 0.97, "β SharpFlow", color=acc, fontsize=17, fontweight="bold",
|
| 97 |
+
transform=ax.transAxes, va="top")
|
| 98 |
+
ax.text(0.02, 0.86, f"Consistent smart-money β top moves, last {hours}h",
|
| 99 |
+
color=ink, fontsize=13, transform=ax.transAxes, va="top")
|
| 100 |
+
|
| 101 |
+
y_hdr = 0.70
|
| 102 |
+
ax.text(0.02, y_hdr, "SIGNAL", color=mut, fontsize=9, transform=ax.transAxes)
|
| 103 |
+
ax.text(0.16, y_hdr, "TRADER", color=mut, fontsize=9, transform=ax.transAxes)
|
| 104 |
+
ax.text(0.34, y_hdr, "MOVE", color=mut, fontsize=9, transform=ax.transAxes)
|
| 105 |
+
ax.text(0.82, y_hdr, "SIZE", color=mut, fontsize=9, transform=ax.transAxes)
|
| 106 |
+
|
| 107 |
+
y_top, y_bot = 0.62, 0.10
|
| 108 |
+
step = (y_top - y_bot) / max(1, n - 1) if n > 1 else 0.0
|
| 109 |
+
for i, m in enumerate(top):
|
| 110 |
+
y = y_top - i * step
|
| 111 |
+
bar = "β" * max(1, int(round(m.signal_quality * 5)))
|
| 112 |
+
ax.text(0.02, y, f"{bar} {m.signal_quality:.2f}", color=acc, fontsize=10,
|
| 113 |
+
transform=ax.transAxes, family="monospace")
|
| 114 |
+
ax.text(0.16, y, _short(m.wallet), color=ink, fontsize=10,
|
| 115 |
+
transform=ax.transAxes, family="monospace")
|
| 116 |
+
title = (m.title[:34] + "β¦") if len(m.title) > 35 else m.title
|
| 117 |
+
ax.text(0.34, y, f"{title} ({m.outcome[:12]})", color=ink, fontsize=10,
|
| 118 |
+
transform=ax.transAxes)
|
| 119 |
+
ax.text(0.82, y, f"${m.usdc:,.0f}", color=ink, fontsize=10,
|
| 120 |
+
transform=ax.transAxes)
|
| 121 |
+
|
| 122 |
+
ax.text(0.02, 0.02, "Flow intelligence, not financial advice Β· sharpflow",
|
| 123 |
+
color=mut, fontsize=8, transform=ax.transAxes)
|
| 124 |
+
fig.savefig(out, dpi=150, facecolor=bg, pad_inches=0)
|
| 125 |
+
plt.close(fig)
|
| 126 |
+
return out
|
pmct/score.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Score a SINGLE arbitrary wallet live β the free lead-magnet endpoint.
|
| 2 |
+
|
| 3 |
+
Paste any Polymarket wallet -> we fetch its recent activity + open positions,
|
| 4 |
+
run the same metrics/patterns the digest uses, and return a consistency /
|
| 5 |
+
repeatability / copyability read plus a plain-English verdict.
|
| 6 |
+
|
| 7 |
+
This is the ungated hook: shareable, SEO-friendly, and it captures the exact
|
| 8 |
+
value prop (we judge *consistency*, not just size). Reuses the analysis engine
|
| 9 |
+
so there's one source of truth.
|
| 10 |
+
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
from dataclasses import dataclass, field, asdict
|
| 14 |
+
|
| 15 |
+
import pandas as pd
|
| 16 |
+
|
| 17 |
+
from .ledger import normalize_activity, attach_open_positions
|
| 18 |
+
from . import metrics as M
|
| 19 |
+
from . import patterns as P
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@dataclass
|
| 23 |
+
class WalletScore:
|
| 24 |
+
wallet: str
|
| 25 |
+
ok: bool
|
| 26 |
+
trader_score: float = 0.0
|
| 27 |
+
verdict: str = ""
|
| 28 |
+
verdict_tag: str = "" # one of: watch / whale / maker / inconsistent / thin
|
| 29 |
+
total_pnl: float = 0.0
|
| 30 |
+
roi: float = 0.0
|
| 31 |
+
monthly_profit_ratio: float = 0.0
|
| 32 |
+
repeatability: float = 0.0
|
| 33 |
+
rebate_share: float = 0.0
|
| 34 |
+
avg_trade_usdc: float = 0.0
|
| 35 |
+
n_trades: int = 0
|
| 36 |
+
n_resolved_markets: int = 0
|
| 37 |
+
active_days: int = 0
|
| 38 |
+
dominant_topic: str = ""
|
| 39 |
+
note: str = ""
|
| 40 |
+
|
| 41 |
+
def to_dict(self) -> dict:
|
| 42 |
+
return asdict(self)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
# thresholds mirror digest.SelectionConfig so the score and the digest agree
|
| 46 |
+
_WHALE_PROFIT = 2_000_000
|
| 47 |
+
_WHALE_AVG_TRADE = 5_000
|
| 48 |
+
_MAKER_REBATE_SHARE = 0.35
|
| 49 |
+
_CONSISTENT = 0.5
|
| 50 |
+
_REPEATABLE = 0.30
|
| 51 |
+
_MIN_TRADES = 10
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def _verdict(s: "pd.Series", trader_score: float) -> tuple[str, str]:
|
| 55 |
+
pnl = float(s["total_pnl"])
|
| 56 |
+
if s["n_trades"] < _MIN_TRADES:
|
| 57 |
+
return ("thin", "Too few trades to judge β not enough history to trust any pattern.")
|
| 58 |
+
if s["rebate_share"] >= _MAKER_REBATE_SHARE:
|
| 59 |
+
return ("maker", "Market-maker / rebate-driven. Profit comes from liquidity "
|
| 60 |
+
"rewards you can't copy β skip for copy-trading.")
|
| 61 |
+
if pnl >= _WHALE_PROFIT or s["avg_trade_usdc"] >= _WHALE_AVG_TRADE:
|
| 62 |
+
return ("whale", "Mega-whale sizing. Real trader, but bets are too big to "
|
| 63 |
+
"mirror at retail size β and every tracker already flags them.")
|
| 64 |
+
if s["monthly_profit_ratio"] >= _CONSISTENT and s["repeatability"] >= _REPEATABLE:
|
| 65 |
+
return ("watch", "Consistent mid-size trader with a repeatable style β the kind "
|
| 66 |
+
"whale trackers miss. Worth watching.")
|
| 67 |
+
return ("inconsistent", "Profitable at times but inconsistent or hard-to-replicate β "
|
| 68 |
+
"could be luck. Watch, don't follow blindly.")
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def score_wallet(client, wallet: str, page_limit: int = 500,
|
| 72 |
+
max_pages: int = 8) -> WalletScore:
|
| 73 |
+
wallet = wallet.strip().lower()
|
| 74 |
+
if not (wallet.startswith("0x") and len(wallet) == 42):
|
| 75 |
+
return WalletScore(wallet=wallet, ok=False,
|
| 76 |
+
note="Not a valid 0x⦠wallet address.")
|
| 77 |
+
try:
|
| 78 |
+
raw = list(client.iter_activity(wallet, page_limit=page_limit,
|
| 79 |
+
max_pages=max_pages))
|
| 80 |
+
except Exception as e: # noqa: BLE001
|
| 81 |
+
return WalletScore(wallet=wallet, ok=False,
|
| 82 |
+
note=f"Couldn't fetch activity: {type(e).__name__}.")
|
| 83 |
+
led = normalize_activity(raw)
|
| 84 |
+
if led.empty:
|
| 85 |
+
return WalletScore(wallet=wallet, ok=False,
|
| 86 |
+
note="No Polymarket activity found for this wallet.")
|
| 87 |
+
|
| 88 |
+
try:
|
| 89 |
+
pos = client.positions(wallet)
|
| 90 |
+
except Exception: # noqa: BLE001
|
| 91 |
+
pos = []
|
| 92 |
+
open_df = attach_open_positions(pos)
|
| 93 |
+
|
| 94 |
+
stats = M.compute(wallet, led, open_df)
|
| 95 |
+
pat = P.extract(wallet, led)
|
| 96 |
+
|
| 97 |
+
row = pd.Series({
|
| 98 |
+
"monthly_profit_ratio": stats.monthly_profit_ratio,
|
| 99 |
+
"repeatability": pat.repeatability,
|
| 100 |
+
"rebate_share": stats.rebate_share,
|
| 101 |
+
"roi": stats.roi,
|
| 102 |
+
"total_pnl": stats.total_pnl,
|
| 103 |
+
"avg_trade_usdc": stats.avg_trade_usdc,
|
| 104 |
+
"n_trades": stats.n_trades,
|
| 105 |
+
})
|
| 106 |
+
from .digest import _trader_score
|
| 107 |
+
tscore = _trader_score(row)
|
| 108 |
+
tag, verdict = _verdict(row, tscore)
|
| 109 |
+
|
| 110 |
+
return WalletScore(
|
| 111 |
+
wallet=wallet, ok=True, trader_score=tscore, verdict=verdict, verdict_tag=tag,
|
| 112 |
+
total_pnl=round(stats.total_pnl, 2), roi=round(stats.roi, 4),
|
| 113 |
+
monthly_profit_ratio=round(stats.monthly_profit_ratio, 4),
|
| 114 |
+
repeatability=round(pat.repeatability, 3),
|
| 115 |
+
rebate_share=round(stats.rebate_share, 4),
|
| 116 |
+
avg_trade_usdc=round(stats.avg_trade_usdc, 2),
|
| 117 |
+
n_trades=stats.n_trades, n_resolved_markets=stats.n_resolved_markets,
|
| 118 |
+
active_days=stats.active_days, dominant_topic=pat.dominant_topic,
|
| 119 |
+
note="Reconstructed from the wallet's most-recent ~3.5k activities "
|
| 120 |
+
"(Data API history cap). Consistency scoring β guaranteed profit.",
|
| 121 |
+
)
|
pmct/screen.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Filter the analyzed wallets down to a copy-worthy shortlist.
|
| 2 |
+
|
| 3 |
+
Two gates, matching the user's two rules:
|
| 4 |
+
A. long-term consistent profit -> pnl/roi/win-rate/drawdown/consistency + span
|
| 5 |
+
B. repeatable, replicable pattern -> repeatability score from patterns.py
|
| 6 |
+
|
| 7 |
+
Wallets must clear BOTH gates. Survivors are ranked by a composite score so the
|
| 8 |
+
strongest, most copyable traders float to the top.
|
| 9 |
+
"""
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import pandas as pd
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def _zscore(s: pd.Series) -> pd.Series:
|
| 16 |
+
if s.std(ddof=0) == 0:
|
| 17 |
+
return pd.Series(0.0, index=s.index)
|
| 18 |
+
return (s - s.mean()) / s.std(ddof=0)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def screen(df: pd.DataFrame, cfg: dict) -> pd.DataFrame:
|
| 22 |
+
"""`df` is the merged metrics+patterns table (one row per wallet)."""
|
| 23 |
+
if df.empty:
|
| 24 |
+
return df
|
| 25 |
+
df = df.copy()
|
| 26 |
+
|
| 27 |
+
# authoritative profit: leaderboard figure when the wallet is ranked, else
|
| 28 |
+
# our reconstructed total_pnl. Added by 02_analyze; fall back if absent.
|
| 29 |
+
if "profit_final" not in df.columns:
|
| 30 |
+
df["profit_final"] = df["total_pnl"]
|
| 31 |
+
df["profit_final"] = df["profit_final"].fillna(df["total_pnl"])
|
| 32 |
+
rebate_share = df.get("rebate_share", pd.Series(0.0, index=df.index)).fillna(0.0)
|
| 33 |
+
|
| 34 |
+
# Gate A β long-term consistent profit
|
| 35 |
+
gate_profit = (
|
| 36 |
+
(df["profit_final"] >= cfg["min_total_pnl_usd"]) &
|
| 37 |
+
(df["roi"] >= cfg["min_roi"]) &
|
| 38 |
+
(df["win_rate"] >= cfg["min_win_rate"]) &
|
| 39 |
+
(df["n_resolved_markets"] >= cfg["min_resolved_markets"]) &
|
| 40 |
+
(df["active_days"] >= cfg["min_active_days"]) &
|
| 41 |
+
(df["max_drawdown_pct"] <= cfg["max_drawdown_pct"]) &
|
| 42 |
+
(df["monthly_profit_ratio"] >= cfg["min_monthly_profit_ratio"])
|
| 43 |
+
)
|
| 44 |
+
# Gate B β repeatable pattern
|
| 45 |
+
gate_pattern = df["repeatability"] >= cfg["min_repeatability"]
|
| 46 |
+
# Gate C β copyable: reject market-maker / rebate-driven profit
|
| 47 |
+
gate_copyable = rebate_share <= cfg.get("max_rebate_share", 0.35)
|
| 48 |
+
|
| 49 |
+
kept = df[gate_profit & gate_pattern & gate_copyable].copy()
|
| 50 |
+
if kept.empty:
|
| 51 |
+
return kept
|
| 52 |
+
|
| 53 |
+
# composite rank: profit quality + consistency + copyability, penalize
|
| 54 |
+
# drawdown and rebate-dependence
|
| 55 |
+
kept["score"] = (
|
| 56 |
+
1.2 * _zscore(kept["roi"]) +
|
| 57 |
+
1.0 * _zscore(kept["win_rate"]) +
|
| 58 |
+
0.8 * _zscore(kept["monthly_profit_ratio"]) +
|
| 59 |
+
1.0 * _zscore(kept["repeatability"]) +
|
| 60 |
+
0.6 * _zscore(kept["profit_final"].clip(upper=kept["profit_final"].quantile(0.95))) -
|
| 61 |
+
0.8 * _zscore(kept["max_drawdown_pct"]) -
|
| 62 |
+
0.5 * _zscore(kept["rebate_share"].fillna(0.0))
|
| 63 |
+
)
|
| 64 |
+
kept = kept.sort_values("score", ascending=False)
|
| 65 |
+
top_n = cfg.get("top_n_shortlist", 25)
|
| 66 |
+
return kept.head(top_n).reset_index(drop=True)
|
pmct/sizing.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Conviction-based position sizing β εδ½θ·θζζ‘η¨εΊ¦θ΅°.
|
| 2 |
+
|
| 3 |
+
We never blindly copy the target's dollar amount. Instead we infer *how
|
| 4 |
+
convinced the target was* on each entry and scale OUR stake to that conviction,
|
| 5 |
+
inside hard risk caps sized for a small (<$1k), conservative bankroll.
|
| 6 |
+
|
| 7 |
+
Conviction β [0,1] blends two signals:
|
| 8 |
+
stake_signal : how large this bet was vs the target's own typical bet.
|
| 9 |
+
Betting 3x their usual size => they are unusually sure.
|
| 10 |
+
edge_signal : how far the entry price sits from a coin flip (|p-0.5|*2).
|
| 11 |
+
An extreme price means a strong directional view.
|
| 12 |
+
|
| 13 |
+
conviction = w_stake * stake_signal + w_edge * edge_signal
|
| 14 |
+
|
| 15 |
+
Our stake = bankroll * frac, where frac scales linearly from min_frac (no
|
| 16 |
+
conviction) to max_frac (full conviction), then is clamped by:
|
| 17 |
+
- kelly_cap * kelly_fraction (edge-aware ceiling)
|
| 18 |
+
- remaining room under max_frac_per_market
|
| 19 |
+
"""
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import math
|
| 23 |
+
from dataclasses import dataclass
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _logistic(x: float) -> float:
|
| 27 |
+
return 1.0 / (1.0 + math.exp(-x))
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def stake_signal(trade_usdc: float, rolling_avg_usdc: float) -> float:
|
| 31 |
+
"""0.5 at the target's average bet, ->1 for oversized, ->0 for tiny."""
|
| 32 |
+
if rolling_avg_usdc <= 0 or trade_usdc <= 0:
|
| 33 |
+
return 0.5
|
| 34 |
+
return _logistic(math.log(trade_usdc / rolling_avg_usdc))
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def edge_signal(price: float) -> float:
|
| 38 |
+
"""Distance from a coin flip, in [0,1]."""
|
| 39 |
+
return max(0.0, min(1.0, abs(price - 0.5) * 2.0))
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def conviction(trade_usdc: float, rolling_avg_usdc: float, price: float,
|
| 43 |
+
w_stake: float, w_edge: float) -> float:
|
| 44 |
+
s = stake_signal(trade_usdc, rolling_avg_usdc)
|
| 45 |
+
e = edge_signal(price)
|
| 46 |
+
tot = w_stake + w_edge or 1.0
|
| 47 |
+
return (w_stake * s + w_edge * e) / tot
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def kelly_fraction(price: float, assumed_edge: float) -> float:
|
| 51 |
+
"""Full-Kelly stake for buying a YES share at `price` that pays $1.
|
| 52 |
+
|
| 53 |
+
Buying at `price` costs `price` and returns 1 on win, so net decimal odds
|
| 54 |
+
b = (1/price) - 1. The catch: the market price already IS the implied
|
| 55 |
+
probability, so if we plug price in as our win prob the edge is zero and
|
| 56 |
+
Kelly is zero. Copying a sharp trader only makes sense if we believe the
|
| 57 |
+
true probability sits ABOVE the price β that gap is `assumed_edge`, which we
|
| 58 |
+
scale with conviction in position_fraction(). Returns a fraction in [0,1)."""
|
| 59 |
+
price = min(max(price, 1e-4), 1 - 1e-4)
|
| 60 |
+
p_true = min(price + max(0.0, assumed_edge), 0.999) # our belief
|
| 61 |
+
b = (1.0 / price) - 1.0
|
| 62 |
+
q = 1.0 - p_true
|
| 63 |
+
f = (b * p_true - q) / b if b > 0 else 0.0
|
| 64 |
+
return max(0.0, min(f, 1.0))
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@dataclass
|
| 68 |
+
class SizingConfig:
|
| 69 |
+
max_frac_per_trade: float = 0.05
|
| 70 |
+
max_frac_per_market: float = 0.15
|
| 71 |
+
min_frac_per_trade: float = 0.005
|
| 72 |
+
w_stake: float = 0.6
|
| 73 |
+
w_edge: float = 0.4
|
| 74 |
+
kelly_cap: float = 0.5
|
| 75 |
+
assumed_max_edge: float = 0.15 # max true-vs-price gap we ascribe at full conviction
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def position_fraction(trade_usdc: float, rolling_avg_usdc: float, price: float,
|
| 79 |
+
market_exposure_frac: float, cfg: SizingConfig) -> tuple[float, float]:
|
| 80 |
+
"""Return (fraction_of_bankroll_to_stake, conviction) for one copied entry.
|
| 81 |
+
|
| 82 |
+
market_exposure_frac = fraction of bankroll already committed to this market.
|
| 83 |
+
"""
|
| 84 |
+
conv = conviction(trade_usdc, rolling_avg_usdc, price, cfg.w_stake, cfg.w_edge)
|
| 85 |
+
|
| 86 |
+
# linear map conviction -> [min_frac, max_frac_per_trade]
|
| 87 |
+
frac = cfg.min_frac_per_trade + conv * (cfg.max_frac_per_trade - cfg.min_frac_per_trade)
|
| 88 |
+
|
| 89 |
+
# edge-aware Kelly ceiling: assumed edge scales with conviction
|
| 90 |
+
assumed_edge = conv * cfg.assumed_max_edge
|
| 91 |
+
frac = min(frac, cfg.kelly_cap * kelly_fraction(price, assumed_edge))
|
| 92 |
+
|
| 93 |
+
# respect aggregate per-market cap
|
| 94 |
+
room = max(0.0, cfg.max_frac_per_market - market_exposure_frac)
|
| 95 |
+
frac = min(frac, room)
|
| 96 |
+
|
| 97 |
+
return max(0.0, frac), conv
|
pmct/util.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Config loading and tiny on-disk JSON cache so re-runs don't re-hit the API."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
import yaml
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def load_config(path: str = "config.yaml") -> dict:
|
| 12 |
+
p = Path(path)
|
| 13 |
+
if not p.exists():
|
| 14 |
+
raise SystemExit(
|
| 15 |
+
f"{path} not found. Copy config.example.yaml -> config.yaml and edit it."
|
| 16 |
+
)
|
| 17 |
+
with p.open() as f:
|
| 18 |
+
return yaml.safe_load(f)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def data_dir(cfg: dict) -> Path:
|
| 22 |
+
d = Path(cfg.get("data_dir", "data"))
|
| 23 |
+
d.mkdir(parents=True, exist_ok=True)
|
| 24 |
+
return d
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def cache_path(cfg: dict, *parts: str) -> Path:
|
| 28 |
+
d = data_dir(cfg)
|
| 29 |
+
for part in parts[:-1]:
|
| 30 |
+
d = d / part
|
| 31 |
+
d.mkdir(parents=True, exist_ok=True)
|
| 32 |
+
return d / parts[-1]
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def read_json(path: Path):
|
| 36 |
+
if path.exists():
|
| 37 |
+
with path.open() as f:
|
| 38 |
+
return json.load(f)
|
| 39 |
+
return None
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def write_json(path: Path, obj) -> None:
|
| 43 |
+
tmp = path.with_suffix(path.suffix + ".tmp")
|
| 44 |
+
with tmp.open("w") as f:
|
| 45 |
+
json.dump(obj, f)
|
| 46 |
+
os.replace(tmp, path)
|
render.yaml
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
services:
|
| 2 |
+
- type: web
|
| 3 |
+
name: sharpflow
|
| 4 |
+
runtime: python
|
| 5 |
+
plan: free
|
| 6 |
+
buildCommand: pip install -r requirements.txt
|
| 7 |
+
startCommand: gunicorn webapp.app:app --bind 0.0.0.0:$PORT --workers 1 --threads 4 --timeout 120
|
| 8 |
+
envVars:
|
| 9 |
+
- key: PYTHON_VERSION
|
| 10 |
+
value: 3.11.0
|
requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
requests>=2.31
|
| 2 |
+
pandas>=2.0
|
| 3 |
+
numpy>=1.24
|
| 4 |
+
PyYAML>=6.0
|
| 5 |
+
tenacity>=8.2
|
| 6 |
+
matplotlib>=3.7
|
| 7 |
+
Flask>=3.0
|
| 8 |
+
gunicorn>=21.2
|
runtime.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
python-3.11.0
|
scripts/01_discover_wallets.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Step 1 β build a list of candidate wallets to analyze.
|
| 3 |
+
|
| 4 |
+
python scripts/01_discover_wallets.py
|
| 5 |
+
|
| 6 |
+
Writes data/candidates.json (a list of 0x addresses).
|
| 7 |
+
"""
|
| 8 |
+
import sys
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
| 12 |
+
|
| 13 |
+
from pmct.client import PolymarketClient
|
| 14 |
+
from pmct.discover import discover
|
| 15 |
+
from pmct.util import load_config, cache_path, write_json
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def main():
|
| 19 |
+
cfg = load_config()
|
| 20 |
+
client = PolymarketClient(sleep_sec=cfg["analyze"]["request_sleep_sec"])
|
| 21 |
+
print("Discovering candidate wallets...")
|
| 22 |
+
wallets = discover(client, cfg["discover"])
|
| 23 |
+
out = cache_path(cfg, "candidates.json")
|
| 24 |
+
write_json(out, wallets)
|
| 25 |
+
print(f"Saved {len(wallets)} candidates -> {out}")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
if __name__ == "__main__":
|
| 29 |
+
main()
|
scripts/02_analyze_wallets.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Step 2 β fetch history for each candidate and compute metrics + patterns.
|
| 3 |
+
|
| 4 |
+
python scripts/02_analyze_wallets.py
|
| 5 |
+
|
| 6 |
+
Reads data/candidates.json
|
| 7 |
+
Writes data/wallets.csv (one row per wallet: metrics + pattern features)
|
| 8 |
+
data/ledgers/<wallet>.parquet (cached raw ledgers for the backtester)
|
| 9 |
+
"""
|
| 10 |
+
import sys
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
import pandas as pd
|
| 14 |
+
|
| 15 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
| 16 |
+
|
| 17 |
+
from pmct.client import PolymarketClient
|
| 18 |
+
from pmct import ledger as ledger_mod
|
| 19 |
+
from pmct import metrics as metrics_mod
|
| 20 |
+
from pmct import patterns as patterns_mod
|
| 21 |
+
from pmct import discover as discover_mod
|
| 22 |
+
from pmct.util import load_config, cache_path, read_json
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def main():
|
| 26 |
+
cfg = load_config()
|
| 27 |
+
acfg = cfg["analyze"]
|
| 28 |
+
candidates = read_json(cache_path(cfg, "candidates.json")) or []
|
| 29 |
+
if not candidates:
|
| 30 |
+
raise SystemExit("No candidates. Run 01_discover_wallets.py first.")
|
| 31 |
+
client = PolymarketClient(sleep_sec=acfg["request_sleep_sec"])
|
| 32 |
+
|
| 33 |
+
# authoritative profit/volume from the leaderboard (one pass, reused for all)
|
| 34 |
+
dcfg = cfg["discover"]
|
| 35 |
+
lb_map = discover_mod.leaderboard_profit_map(
|
| 36 |
+
client, dcfg["leaderboard_windows"], dcfg["leaderboard_top_n"])
|
| 37 |
+
print(f"authoritative leaderboard entries: {len(lb_map)}")
|
| 38 |
+
|
| 39 |
+
# analyze leaderboard wallets first (authoritative profit = best copy targets),
|
| 40 |
+
# then fill the budget with the rest, so max_wallets isn't wasted on low-hex
|
| 41 |
+
# addresses that happen to sort first.
|
| 42 |
+
candidates.sort(key=lambda w: (0 if w in lb_map else 1, w))
|
| 43 |
+
candidates = candidates[: acfg["max_wallets"]]
|
| 44 |
+
|
| 45 |
+
rows = []
|
| 46 |
+
for i, w in enumerate(candidates, 1):
|
| 47 |
+
try:
|
| 48 |
+
raw = list(client.iter_activity(
|
| 49 |
+
w, acfg["activity_page_limit"], acfg["max_pages_per_wallet"]))
|
| 50 |
+
led = ledger_mod.normalize_activity(raw)
|
| 51 |
+
if led.empty:
|
| 52 |
+
continue
|
| 53 |
+
open_df = ledger_mod.attach_open_positions(client.positions(w))
|
| 54 |
+
stats = metrics_mod.compute(w, led, open_df)
|
| 55 |
+
feats = patterns_mod.extract(w, led)
|
| 56 |
+
row = {**stats.to_dict(), **feats.to_dict()}
|
| 57 |
+
row.pop("wallet", None)
|
| 58 |
+
|
| 59 |
+
lb = lb_map.get(w, {})
|
| 60 |
+
lb_profit = lb.get("lb_profit")
|
| 61 |
+
row["on_leaderboard"] = bool(lb)
|
| 62 |
+
row["lb_profit"] = lb_profit
|
| 63 |
+
row["lb_volume"] = lb.get("lb_volume")
|
| 64 |
+
# authoritative profit: trust the leaderboard when ranked, else our recon
|
| 65 |
+
row["profit_final"] = lb_profit if lb_profit is not None else row["total_pnl"]
|
| 66 |
+
# recompute rebate share against the AUTHORITATIVE profit so truncated
|
| 67 |
+
# (negative) reconstructions don't falsely flag profitable wallets
|
| 68 |
+
pf = row["profit_final"]
|
| 69 |
+
if pf and pf > 0:
|
| 70 |
+
row["rebate_share"] = round(min(max(row["rebate_pnl"] / pf, 0.0), 1.0), 4)
|
| 71 |
+
elif row["rebate_pnl"] > 0:
|
| 72 |
+
row["rebate_share"] = 1.0 # no net directional profit, only rebates
|
| 73 |
+
row = {"wallet": w, **row}
|
| 74 |
+
rows.append(row)
|
| 75 |
+
|
| 76 |
+
led.to_pickle(cache_path(cfg, "ledgers", f"{w}.pkl"))
|
| 77 |
+
print(f"[{i}/{len(candidates)}] {w} pnl=${stats.total_pnl:>10} "
|
| 78 |
+
f"wr={stats.win_rate:.2f} rep={feats.repeatability:.2f}")
|
| 79 |
+
except Exception as e: # noqa: BLE001 - keep going through the batch
|
| 80 |
+
print(f"[{i}/{len(candidates)}] {w} ERROR {e}")
|
| 81 |
+
|
| 82 |
+
df = pd.DataFrame(rows)
|
| 83 |
+
out = cache_path(cfg, "wallets.csv")
|
| 84 |
+
df.to_csv(out, index=False)
|
| 85 |
+
print(f"\nAnalyzed {len(df)} wallets -> {out}")
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
if __name__ == "__main__":
|
| 89 |
+
main()
|
scripts/03_screen.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Step 3 β filter to the copy-worthy shortlist.
|
| 3 |
+
|
| 4 |
+
python scripts/03_screen.py
|
| 5 |
+
|
| 6 |
+
Reads data/wallets.csv
|
| 7 |
+
Writes data/shortlist.csv (ranked survivors of both gates)
|
| 8 |
+
"""
|
| 9 |
+
import sys
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
import pandas as pd
|
| 13 |
+
|
| 14 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
| 15 |
+
|
| 16 |
+
from pmct.screen import screen
|
| 17 |
+
from pmct.util import load_config, cache_path
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def main():
|
| 21 |
+
cfg = load_config()
|
| 22 |
+
df = pd.read_csv(cache_path(cfg, "wallets.csv"))
|
| 23 |
+
print(f"Screening {len(df)} wallets against both gates...")
|
| 24 |
+
short = screen(df, cfg["screen"])
|
| 25 |
+
out = cache_path(cfg, "shortlist.csv")
|
| 26 |
+
short.to_csv(out, index=False)
|
| 27 |
+
|
| 28 |
+
if short.empty:
|
| 29 |
+
print("No wallets cleared both gates. Loosen thresholds in config.yaml "
|
| 30 |
+
"(screen:) or widen discovery.")
|
| 31 |
+
return
|
| 32 |
+
|
| 33 |
+
cols = ["wallet", "score", "profit_final", "on_leaderboard", "roi", "win_rate",
|
| 34 |
+
"monthly_profit_ratio", "max_drawdown_pct", "repeatability",
|
| 35 |
+
"rebate_share", "dominant_topic", "n_resolved_markets", "active_days"]
|
| 36 |
+
cols = [c for c in cols if c in short.columns]
|
| 37 |
+
print(f"\nTop {len(short)} copy candidates -> {out}\n")
|
| 38 |
+
with pd.option_context("display.max_columns", None, "display.width", 200):
|
| 39 |
+
print(short[cols].to_string(index=False))
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
if __name__ == "__main__":
|
| 43 |
+
main()
|
scripts/04_backtest.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Step 4 β backtest copy-trading a chosen wallet with conviction sizing.
|
| 3 |
+
|
| 4 |
+
python scripts/04_backtest.py <wallet_address>
|
| 5 |
+
python scripts/04_backtest.py # defaults to top of shortlist
|
| 6 |
+
|
| 7 |
+
Runs conviction sizing vs a flat-sizing baseline, prints stats, and saves an
|
| 8 |
+
equity-curve chart to data/backtest_<wallet>.png
|
| 9 |
+
"""
|
| 10 |
+
import sys
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
import pandas as pd
|
| 14 |
+
|
| 15 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
| 16 |
+
|
| 17 |
+
from pmct import backtest as bt
|
| 18 |
+
from pmct.sizing import SizingConfig
|
| 19 |
+
from pmct.util import load_config, cache_path
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _pick_wallet(cfg) -> str:
|
| 23 |
+
if len(sys.argv) > 1:
|
| 24 |
+
return sys.argv[1].lower()
|
| 25 |
+
short = pd.read_csv(cache_path(cfg, "shortlist.csv"))
|
| 26 |
+
if short.empty:
|
| 27 |
+
raise SystemExit("Shortlist empty and no wallet given. Run 03_screen.py.")
|
| 28 |
+
return short.iloc[0]["wallet"]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def main():
|
| 32 |
+
cfg = load_config()
|
| 33 |
+
bcfg = cfg["backtest"]
|
| 34 |
+
wallet = _pick_wallet(cfg)
|
| 35 |
+
|
| 36 |
+
led_path = cache_path(cfg, "ledgers", f"{wallet}.pkl")
|
| 37 |
+
if not led_path.exists():
|
| 38 |
+
raise SystemExit(f"No cached ledger for {wallet}. Run 02_analyze_wallets.py.")
|
| 39 |
+
led = pd.read_pickle(led_path)
|
| 40 |
+
|
| 41 |
+
sizing = SizingConfig(**bcfg["sizing"])
|
| 42 |
+
common = dict(bankroll=bcfg["our_bankroll_usd"], sizing=sizing,
|
| 43 |
+
slippage_bps=bcfg["slippage_bps"], fee_bps=bcfg["fee_bps"])
|
| 44 |
+
|
| 45 |
+
conv = bt.run(led, flat_sizing=False, **common)
|
| 46 |
+
flat = bt.run(led, flat_sizing=True, **common)
|
| 47 |
+
|
| 48 |
+
print(f"\nBacktest copy-trading {wallet}")
|
| 49 |
+
print(f" bankroll ${bcfg['our_bankroll_usd']} slippage {bcfg['slippage_bps']}bps\n")
|
| 50 |
+
print(" CONVICTION sizing:", conv.to_summary())
|
| 51 |
+
print(" FLAT sizing:", flat.to_summary())
|
| 52 |
+
|
| 53 |
+
try:
|
| 54 |
+
import matplotlib
|
| 55 |
+
matplotlib.use("Agg")
|
| 56 |
+
import matplotlib.pyplot as plt
|
| 57 |
+
|
| 58 |
+
fig, ax = plt.subplots(figsize=(10, 5))
|
| 59 |
+
ax.plot(conv.equity_curve["ts"], conv.equity_curve["equity"], label="conviction")
|
| 60 |
+
ax.plot(flat.equity_curve["ts"], flat.equity_curve["equity"], label="flat", alpha=0.7)
|
| 61 |
+
ax.axhline(bcfg["our_bankroll_usd"], ls="--", c="grey", lw=1, label="start")
|
| 62 |
+
ax.set_title(f"Copy-trade equity curve β {wallet[:10]}...")
|
| 63 |
+
ax.set_ylabel("equity (USD)")
|
| 64 |
+
ax.legend()
|
| 65 |
+
out = cache_path(cfg, f"backtest_{wallet}.png")
|
| 66 |
+
fig.tight_layout()
|
| 67 |
+
fig.savefig(out, dpi=120)
|
| 68 |
+
print(f"\n chart -> {out}")
|
| 69 |
+
except Exception as e: # noqa: BLE001
|
| 70 |
+
print(f" (plot skipped: {e})")
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
if __name__ == "__main__":
|
| 74 |
+
main()
|
scripts/05_digest.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Step 5 β generate the daily 'consistent smart-money' digest.
|
| 3 |
+
|
| 4 |
+
python scripts/05_digest.py # last 24h, live fresh moves
|
| 5 |
+
python scripts/05_digest.py --hours 48 # widen the window
|
| 6 |
+
python scripts/05_digest.py --no-live # skip live pull (traders only)
|
| 7 |
+
|
| 8 |
+
Reads the already-computed metrics table (data/wallets.csv), applies the
|
| 9 |
+
consistency wedge, optionally pulls each trader's recent moves live, scores
|
| 10 |
+
them, and writes a Markdown digest to data/digest_<date>.md β the content unit
|
| 11 |
+
for a newsletter / Telegram post / X thread.
|
| 12 |
+
"""
|
| 13 |
+
import argparse
|
| 14 |
+
import sys
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
|
| 17 |
+
import pandas as pd
|
| 18 |
+
|
| 19 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
| 20 |
+
|
| 21 |
+
from pmct import digest as dg
|
| 22 |
+
from pmct.client import PolymarketClient
|
| 23 |
+
from pmct.util import load_config, cache_path
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def main():
|
| 27 |
+
ap = argparse.ArgumentParser()
|
| 28 |
+
ap.add_argument("--hours", type=int, default=24)
|
| 29 |
+
ap.add_argument("--no-live", action="store_true",
|
| 30 |
+
help="skip the live fresh-moves pull")
|
| 31 |
+
args = ap.parse_args()
|
| 32 |
+
|
| 33 |
+
cfg = load_config()
|
| 34 |
+
wallets_csv = cache_path(cfg, "wallets.csv")
|
| 35 |
+
if not wallets_csv.exists():
|
| 36 |
+
raise SystemExit("No data/wallets.csv. Run 02_analyze_wallets.py first.")
|
| 37 |
+
df = pd.read_csv(wallets_csv)
|
| 38 |
+
|
| 39 |
+
sel_cfg = dg.SelectionConfig()
|
| 40 |
+
selected = dg.select_smart_money(df, sel_cfg)
|
| 41 |
+
print(f"Selected {len(selected)}/{len(df)} traders (consistency wedge).")
|
| 42 |
+
|
| 43 |
+
moves = []
|
| 44 |
+
if not args.no_live and not selected.empty:
|
| 45 |
+
client = PolymarketClient(sleep_sec=0.15)
|
| 46 |
+
print(f"Pulling fresh moves (last {args.hours}h) for {len(selected)} tradersβ¦")
|
| 47 |
+
moves = dg.fresh_moves(client, selected, hours=args.hours)
|
| 48 |
+
print(f" {len(moves)} fresh moves scored.")
|
| 49 |
+
|
| 50 |
+
md = dg.render_markdown(selected, moves, hours=args.hours)
|
| 51 |
+
out = cache_path(cfg, f"digest_{pd.Timestamp.now('UTC'):%Y%m%d_%H%M}.md")
|
| 52 |
+
out.write_text(md, encoding="utf-8")
|
| 53 |
+
print(f"\nDigest -> {out}\n")
|
| 54 |
+
print(md[:1600])
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
if __name__ == "__main__":
|
| 58 |
+
main()
|
scripts/06_post.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Step 6 β turn today's digest into ready-to-post distribution assets.
|
| 3 |
+
|
| 4 |
+
python scripts/06_post.py # last 24h
|
| 5 |
+
python scripts/06_post.py --hours 72 --url https://sharpflow.app
|
| 6 |
+
|
| 7 |
+
Writes:
|
| 8 |
+
data/thread_<date>.txt the X/Twitter thread (copy-paste or feed to an API)
|
| 9 |
+
data/card_<date>.png dark-theme image card for the first tweet
|
| 10 |
+
"""
|
| 11 |
+
import argparse
|
| 12 |
+
import sys
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
import pandas as pd
|
| 16 |
+
|
| 17 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
| 18 |
+
|
| 19 |
+
from pmct import digest as dg
|
| 20 |
+
from pmct import post as po
|
| 21 |
+
from pmct.client import PolymarketClient
|
| 22 |
+
from pmct.util import load_config, cache_path
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def main():
|
| 26 |
+
ap = argparse.ArgumentParser()
|
| 27 |
+
ap.add_argument("--hours", type=int, default=24)
|
| 28 |
+
ap.add_argument("--url", default="", help="site URL for the CTA tweet")
|
| 29 |
+
args = ap.parse_args()
|
| 30 |
+
|
| 31 |
+
cfg = load_config()
|
| 32 |
+
df = pd.read_csv(cache_path(cfg, "wallets.csv"))
|
| 33 |
+
selected = dg.select_smart_money(df, dg.SelectionConfig())
|
| 34 |
+
if selected.empty:
|
| 35 |
+
raise SystemExit("No traders passed the wedge filter.")
|
| 36 |
+
|
| 37 |
+
client = PolymarketClient(sleep_sec=0.15)
|
| 38 |
+
moves = dg.fresh_moves(client, selected, hours=args.hours)
|
| 39 |
+
print(f"{len(selected)} traders Β· {len(moves)} fresh moves.")
|
| 40 |
+
|
| 41 |
+
stamp = f"{pd.Timestamp.now('UTC'):%Y%m%d_%H%M}"
|
| 42 |
+
thread = po.x_thread(selected, moves, hours=args.hours, site_url=args.url)
|
| 43 |
+
txt = cache_path(cfg, f"thread_{stamp}.txt")
|
| 44 |
+
txt.write_text("\n\n---\n\n".join(thread), encoding="utf-8")
|
| 45 |
+
|
| 46 |
+
png = po.table_png(moves, cache_path(cfg, f"card_{stamp}.png"), hours=args.hours)
|
| 47 |
+
|
| 48 |
+
print(f"\nThread -> {txt}")
|
| 49 |
+
print(f"Card -> {png if png else '(no moves / matplotlib unavailable)'}\n")
|
| 50 |
+
for i, t in enumerate(thread, 1):
|
| 51 |
+
print(f"--- tweet {i} ({len(t)} chars) ---\n{t}\n")
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
if __name__ == "__main__":
|
| 55 |
+
main()
|
webapp/__init__.py
ADDED
|
File without changes
|
webapp/app.py
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Flask app β the shippable front end.
|
| 2 |
+
|
| 3 |
+
Routes:
|
| 4 |
+
/ landing + "paste a wallet" scorer form + email capture
|
| 5 |
+
/score GET ?wallet=0x⦠-> live consistency score card (lead magnet)
|
| 6 |
+
/digest latest daily digest rendered as HTML (SEO surface)
|
| 7 |
+
/subscribe POST email -> data/subscribers.csv
|
| 8 |
+
|
| 9 |
+
Run:
|
| 10 |
+
cd polymarket-copytrade && source .venv/bin/activate
|
| 11 |
+
python webapp/app.py # http://127.0.0.1:5000
|
| 12 |
+
"""
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import csv
|
| 16 |
+
import re
|
| 17 |
+
import os
|
| 18 |
+
import sys
|
| 19 |
+
from datetime import datetime, timezone
|
| 20 |
+
from html import escape
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
|
| 23 |
+
_ROOT = Path(__file__).resolve().parents[1]
|
| 24 |
+
sys.path.insert(0, str(_ROOT))
|
| 25 |
+
os.chdir(_ROOT) # so config.yaml + data/ resolve regardless of launch cwd
|
| 26 |
+
|
| 27 |
+
from flask import Flask, request, redirect, url_for
|
| 28 |
+
|
| 29 |
+
from pmct.client import PolymarketClient
|
| 30 |
+
from pmct.score import score_wallet
|
| 31 |
+
from pmct.util import load_config, cache_path
|
| 32 |
+
|
| 33 |
+
app = Flask(__name__)
|
| 34 |
+
_cfg = load_config()
|
| 35 |
+
_client = PolymarketClient(sleep_sec=0.1)
|
| 36 |
+
|
| 37 |
+
BRAND = "SharpFlow"
|
| 38 |
+
TAGLINE = "The Polymarket smart-money tracker whale trackers miss."
|
| 39 |
+
|
| 40 |
+
CSS = """
|
| 41 |
+
:root{--bg:#0b0e14;--card:#141a24;--ink:#e6edf3;--mut:#8b98a9;--acc:#3fb950;
|
| 42 |
+
--warn:#d29922;--bad:#f85149;--line:#232b38}
|
| 43 |
+
*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);
|
| 44 |
+
font:16px/1.55 -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif}
|
| 45 |
+
a{color:#58a6ff;text-decoration:none}.wrap{max-width:820px;margin:0 auto;padding:32px 20px}
|
| 46 |
+
.brand{font-weight:800;font-size:22px;letter-spacing:-.02em}.brand span{color:var(--acc)}
|
| 47 |
+
.hero{margin:28px 0 10px}.hero h1{font-size:34px;line-height:1.15;margin:0 0 10px;letter-spacing:-.02em}
|
| 48 |
+
.hero p{color:var(--mut);font-size:18px;margin:0}
|
| 49 |
+
.card{background:var(--card);border:1px solid var(--line);border-radius:14px;padding:22px;margin:18px 0}
|
| 50 |
+
input[type=text],input[type=email]{width:100%;padding:13px 14px;border-radius:10px;
|
| 51 |
+
border:1px solid var(--line);background:#0d1219;color:var(--ink);font-size:15px}
|
| 52 |
+
.row{display:flex;gap:10px;flex-wrap:wrap}.row>*{flex:1;min-width:180px}
|
| 53 |
+
button{background:var(--acc);color:#04130a;border:0;border-radius:10px;padding:13px 18px;
|
| 54 |
+
font-weight:700;font-size:15px;cursor:pointer;white-space:nowrap;flex:0 0 auto}
|
| 55 |
+
button.ghost{background:transparent;color:var(--ink);border:1px solid var(--line)}
|
| 56 |
+
.mut{color:var(--mut)}.small{font-size:13px}.mono{font-family:ui-monospace,SFMono-Regular,Menlo,monospace}
|
| 57 |
+
.tag{display:inline-block;padding:3px 10px;border-radius:999px;font-size:12px;font-weight:700}
|
| 58 |
+
.tag.watch{background:#12331d;color:var(--acc)}.tag.whale{background:#3a2f10;color:var(--warn)}
|
| 59 |
+
.tag.maker{background:#3a1414;color:var(--bad)}.tag.inconsistent{background:#2a2033;color:#c98bff}
|
| 60 |
+
.tag.thin,.tag.bad{background:#20262f;color:var(--mut)}
|
| 61 |
+
.grid{display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin-top:14px}
|
| 62 |
+
.metric{background:#0d1219;border:1px solid var(--line);border-radius:10px;padding:12px}
|
| 63 |
+
.metric .k{color:var(--mut);font-size:12px}.metric .v{font-size:20px;font-weight:700;margin-top:2px}
|
| 64 |
+
.bar{height:8px;background:#0d1219;border-radius:6px;overflow:hidden;margin-top:6px}
|
| 65 |
+
.bar>i{display:block;height:100%;background:var(--acc)}
|
| 66 |
+
table{border-collapse:collapse;width:100%;font-size:14px}th,td{border-bottom:1px solid var(--line);
|
| 67 |
+
padding:8px 6px;text-align:left}th{color:var(--mut);font-weight:600}
|
| 68 |
+
.foot{color:var(--mut);font-size:12px;margin-top:26px;border-top:1px solid var(--line);padding-top:16px}
|
| 69 |
+
.pill{border:1px solid var(--line);border-radius:999px;padding:4px 12px;font-size:13px;color:var(--mut)}
|
| 70 |
+
.nav{display:flex;align-items:center;justify-content:space-between;gap:16px;
|
| 71 |
+
padding-bottom:12px;border-bottom:1px solid var(--line)}
|
| 72 |
+
.nav .brand{text-decoration:none;color:var(--ink)}
|
| 73 |
+
.navlinks{display:flex;gap:20px}.navlinks a{color:var(--mut);font-weight:600;font-size:14px}
|
| 74 |
+
.navlinks a:hover{color:var(--ink)}
|
| 75 |
+
.examples{margin-top:14px;display:flex;flex-wrap:wrap;gap:8px;align-items:center}
|
| 76 |
+
.exlabel{color:var(--mut);font-size:13px;margin-right:2px}
|
| 77 |
+
.chip{border:1px solid var(--line);background:#0d1219;border-radius:999px;
|
| 78 |
+
padding:6px 12px;font-size:13px;color:var(--ink)}
|
| 79 |
+
.chip:hover{border-color:var(--acc);color:var(--acc)}
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
# Real wallets that showcase the product's judgement β one to follow, one too big
|
| 83 |
+
# to mirror, one uncopyable. Doubles as the "try it" hook so a first-time visitor
|
| 84 |
+
# never dead-ends on a random address with no Polymarket history.
|
| 85 |
+
EXAMPLES = [
|
| 86 |
+
("Consistent mid-size", "0x65018f9fc473f6e920b8929a375d39c26a461220"),
|
| 87 |
+
("Mega-whale", "0xd235973291b2b75ff4070e9c0b01728c520b0f29"),
|
| 88 |
+
("Market-maker", "0xa6cd8300ff70129ced69975180609e40a12b2f2c"),
|
| 89 |
+
]
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def example_chips(label: str = "Try a real trader:") -> str:
|
| 93 |
+
chips = "".join(
|
| 94 |
+
f'<a class=chip href="/score?wallet={w}">{escape(t)}</a>' for t, w in EXAMPLES
|
| 95 |
+
)
|
| 96 |
+
return f'<div class=examples><span class=exlabel>{escape(label)}</span>{chips}</div>'
|
| 97 |
+
|
| 98 |
+
TAGLABEL = {"watch": "WORTH WATCHING", "whale": "MEGA-WHALE",
|
| 99 |
+
"maker": "MARKET-MAKER", "inconsistent": "INCONSISTENT",
|
| 100 |
+
"thin": "TOO THIN", "bad": "INVALID"}
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def page(title: str, body: str) -> str:
|
| 104 |
+
return f"""<!doctype html><html lang=en><head><meta charset=utf-8>
|
| 105 |
+
<meta name=viewport content="width=device-width,initial-scale=1">
|
| 106 |
+
<title>{escape(title)}</title><meta name=description content="{escape(TAGLINE)}">
|
| 107 |
+
<style>{CSS}</style></head><body><div class=wrap>
|
| 108 |
+
<div class=nav><a class=brand href="/"><span>β</span> {BRAND}</a>
|
| 109 |
+
<div class=navlinks><a href="/">Score a wallet</a><a href="/digest">Daily digest</a></div></div>
|
| 110 |
+
{body}
|
| 111 |
+
<div class=foot>Built from Polymarket public data. <b>Flow intelligence, not financial
|
| 112 |
+
advice.</b> Consistency scoring β guaranteed profit. Past performance is not predictive.</div>
|
| 113 |
+
</div></body></html>"""
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def scorer_form(prefill: str = "") -> str:
|
| 117 |
+
return f"""<form action="/score" method=get class=row>
|
| 118 |
+
<input type=text name=wallet placeholder="Paste a Polymarket wallet: 0xβ¦"
|
| 119 |
+
value="{escape(prefill)}" autocomplete=off spellcheck=false>
|
| 120 |
+
<button type=submit>Score it β</button></form>"""
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
@app.route("/")
|
| 124 |
+
def home():
|
| 125 |
+
body = f"""
|
| 126 |
+
<div class=hero><h1>{escape(TAGLINE)}</h1>
|
| 127 |
+
<p>Paste any <b>Polymarket wallet</b> and we score it β consistent smart money, a whale,
|
| 128 |
+
a market-maker, or just lucky. Every tracker flags $10k whales; we surface the
|
| 129 |
+
<b>consistent mid-size Polymarket traders</b> they skip.</p></div>
|
| 130 |
+
<div class=card><h3 style="margin:0 0 12px">Score any wallet β free</h3>
|
| 131 |
+
{scorer_form()}
|
| 132 |
+
{example_chips()}
|
| 133 |
+
<p class="mut small" style="margin:12px 0 0">Paste any Polymarket address. We read its
|
| 134 |
+
history and tell you: consistent & copyable, a whale, a market-maker, or just lucky.</p>
|
| 135 |
+
</div>
|
| 136 |
+
<div class=card><h3 style="margin:0 0 8px">Get the daily digest</h3>
|
| 137 |
+
<p class="mut" style="margin:0 0 12px">The top consistent traders and their highest-conviction
|
| 138 |
+
moves, once a day. Free tier delayed 24h.</p>
|
| 139 |
+
<form action="/subscribe" method=post class=row>
|
| 140 |
+
<input type=email name=email placeholder="you@email.com" required>
|
| 141 |
+
<button type=submit>Subscribe free</button></form></div>
|
| 142 |
+
"""
|
| 143 |
+
return page(f"{BRAND} β {TAGLINE}", body)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
@app.route("/score")
|
| 147 |
+
def score():
|
| 148 |
+
wallet = (request.args.get("wallet") or "").strip()
|
| 149 |
+
if not wallet:
|
| 150 |
+
return redirect(url_for("home"))
|
| 151 |
+
r = score_wallet(_client, wallet)
|
| 152 |
+
if not r.ok:
|
| 153 |
+
body = f"""<div class=hero><h1>Nothing to score here</h1>
|
| 154 |
+
<p>{escape(r.note)} This wallet has no Polymarket trading history we can read β
|
| 155 |
+
try a real trader below.</p></div>
|
| 156 |
+
<div class=card>{scorer_form(wallet)}
|
| 157 |
+
{example_chips("Or try one of these:")}</div>"""
|
| 158 |
+
return page(f"{BRAND} β score", body)
|
| 159 |
+
|
| 160 |
+
tag = r.verdict_tag or "thin"
|
| 161 |
+
pct = int(round(r.trader_score * 100))
|
| 162 |
+
short = f"{r.wallet[:8]}β¦{r.wallet[-6:]}"
|
| 163 |
+
body = f"""
|
| 164 |
+
<div class=hero><div class="pill mono" style="display:inline-block;margin-bottom:10px">{escape(short)}</div>
|
| 165 |
+
<h1 style="margin:6px 0">Trader score: {r.trader_score:.2f}
|
| 166 |
+
<span class="tag {tag}">{TAGLABEL.get(tag,tag.upper())}</span></h1>
|
| 167 |
+
<div class=bar style="max-width:360px"><i style="width:{pct}%"></i></div>
|
| 168 |
+
<p style="margin-top:14px">{escape(r.verdict)}</p></div>
|
| 169 |
+
<div class=grid>
|
| 170 |
+
<div class=metric><div class=k>Consistency (green months)</div><div class=v>{r.monthly_profit_ratio:.0%}</div></div>
|
| 171 |
+
<div class=metric><div class=k>Repeatability</div><div class=v>{r.repeatability:.2f}</div></div>
|
| 172 |
+
<div class=metric><div class=k>Copyable (1 β rebate)</div><div class=v>{max(0,1-r.rebate_share):.0%}</div></div>
|
| 173 |
+
<div class=metric><div class=k>Reconstructed PnL</div><div class=v>${r.total_pnl:,.0f}</div></div>
|
| 174 |
+
<div class=metric><div class=k>Avg bet size</div><div class=v>${r.avg_trade_usdc:,.0f}</div></div>
|
| 175 |
+
<div class=metric><div class=k>Trades Β· resolved</div><div class=v>{r.n_trades:,} Β· {r.n_resolved_markets}</div></div>
|
| 176 |
+
</div>
|
| 177 |
+
<div class=card style="margin-top:18px"><b>Score another</b>{scorer_form()}</div>
|
| 178 |
+
<p class="mut small">{escape(r.note)}</p>
|
| 179 |
+
"""
|
| 180 |
+
return page(f"{BRAND} β {short} scored", body)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
_TABLE_RE = re.compile(r"^\|(.+)\|\s*$")
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def _md_to_html(md: str) -> str:
|
| 187 |
+
"""Tiny markdown renderer: headings, tables, hr, paragraphs. Enough for our
|
| 188 |
+
own digest output β not a general parser."""
|
| 189 |
+
out, rows = [], []
|
| 190 |
+
|
| 191 |
+
def flush_table():
|
| 192 |
+
if not rows:
|
| 193 |
+
return
|
| 194 |
+
cells = [[c.strip() for c in r.strip("|").split("|")] for r in rows]
|
| 195 |
+
body = cells[2:] if len(cells) > 1 and set("".join(cells[1])) <= set("-: ") else cells[1:]
|
| 196 |
+
head = cells[0]
|
| 197 |
+
h = "".join(f"<th>{escape(c)}</th>" for c in head)
|
| 198 |
+
b = "".join("<tr>" + "".join(f"<td>{escape(c)}</td>" for c in r) + "</tr>" for r in body)
|
| 199 |
+
out.append(f"<table><thead><tr>{h}</tr></thead><tbody>{b}</tbody></table>")
|
| 200 |
+
rows.clear()
|
| 201 |
+
|
| 202 |
+
for ln in md.splitlines():
|
| 203 |
+
if _TABLE_RE.match(ln):
|
| 204 |
+
rows.append(ln)
|
| 205 |
+
continue
|
| 206 |
+
flush_table()
|
| 207 |
+
s = ln.strip()
|
| 208 |
+
if not s:
|
| 209 |
+
continue
|
| 210 |
+
if s.startswith("### "):
|
| 211 |
+
out.append(f"<h3>{escape(s[4:])}</h3>")
|
| 212 |
+
elif s.startswith("## "):
|
| 213 |
+
out.append(f"<h2>{escape(s[3:])}</h2>")
|
| 214 |
+
elif s.startswith("# "):
|
| 215 |
+
out.append(f"<h1>{escape(s[2:])}</h1>")
|
| 216 |
+
elif s == "---":
|
| 217 |
+
out.append("<hr style='border:0;border-top:1px solid var(--line)'>")
|
| 218 |
+
else:
|
| 219 |
+
s = s.replace("**", "").replace("_", "")
|
| 220 |
+
out.append(f"<p class=mut>{escape(s)}</p>")
|
| 221 |
+
flush_table()
|
| 222 |
+
return "\n".join(out)
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
@app.route("/digest")
|
| 226 |
+
def digest():
|
| 227 |
+
files = sorted(cache_path(_cfg, ".").glob("digest_*.md"))
|
| 228 |
+
if not files:
|
| 229 |
+
return page(f"{BRAND} β digest",
|
| 230 |
+
"<div class=hero><h1>No digest yet</h1>"
|
| 231 |
+
"<p class=mut>Run <code>python scripts/05_digest.py</code> to generate one.</p></div>")
|
| 232 |
+
md = files[-1].read_text(encoding="utf-8")
|
| 233 |
+
body = f"<div class=card>{_md_to_html(md)}</div>" \
|
| 234 |
+
f"<div class=card><b>Want it daily by email?</b>" \
|
| 235 |
+
f"<form action='/subscribe' method=post class=row style='margin-top:10px'>" \
|
| 236 |
+
f"<input type=email name=email placeholder='you@email.com' required>" \
|
| 237 |
+
f"<button type=submit>Subscribe free</button></form></div>"
|
| 238 |
+
return page(f"{BRAND} β daily digest", body)
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
@app.route("/subscribe", methods=["POST"])
|
| 242 |
+
def subscribe():
|
| 243 |
+
email = (request.form.get("email") or "").strip().lower()
|
| 244 |
+
if "@" in email and "." in email:
|
| 245 |
+
path = cache_path(_cfg, "subscribers.csv")
|
| 246 |
+
new = not path.exists()
|
| 247 |
+
with path.open("a", newline="") as f:
|
| 248 |
+
w = csv.writer(f)
|
| 249 |
+
if new:
|
| 250 |
+
w.writerow(["email", "ts_utc"])
|
| 251 |
+
w.writerow([email, datetime.now(timezone.utc).isoformat()])
|
| 252 |
+
msg = "You're in. First digest lands next run."
|
| 253 |
+
else:
|
| 254 |
+
msg = "That email didn't look right β try again."
|
| 255 |
+
return page(f"{BRAND} β subscribed",
|
| 256 |
+
f"<div class=hero><h1>{escape(msg)}</h1></div>"
|
| 257 |
+
f"<div class=card>{scorer_form()}"
|
| 258 |
+
f"<p class='mut small' style='margin-top:10px'>Meanwhile, score any wallet above.</p></div>")
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
if __name__ == "__main__":
|
| 262 |
+
port = int(os.environ.get("PORT", "5055"))
|
| 263 |
+
app.run(host="127.0.0.1", port=port, debug=False)
|