Spaces:
Running
Running
Download pmct/digest.py from sharpflowapp/web: direct link, hf CLI and curl.
- Browser
- Download file 9.54 kB
-
https://huggingface.co/spaces/sharpflowapp/web/resolve/main/pmct/digest.py
- Command line
-
hf download hf://spaces/sharpflowapp/web/pmct/digest.py
-
curl -L -o digest.py https://huggingface.co/spaces/sharpflowapp/web/resolve/main/pmct/digest.py
9.54 kB
| """Daily 'consistent smart-money' digest engine. | |
| Product wedge (from surveying the crowded Polymarket-tracker market): existing | |
| whale trackers only flag $10k+ whales and just dump raw trades. Two documented | |
| gaps we target instead: | |
| 1. COVERAGE β surface *consistent mid-size* traders the whale filters miss. | |
| 2. JUDGEMENT β attach a signal-quality score so a move comes with context, | |
| not just "someone bought." | |
| Inputs are the already-computed metrics table (data/wallets.csv, produced by | |
| 02_analyze_wallets.py) plus a live pull of each selected wallet's most recent | |
| activity. We deliberately EXCLUDE mega-whales and market-makers β the opposite | |
| of what the incumbents rank on. | |
| This is market-intelligence tooling, NOT a profit promise. The underlying copy | |
| edge is unproven (see README caveats); we sell flow context, like TradingView | |
| sells charts, not guaranteed returns. | |
| """ | |
| from __future__ import annotations | |
| from dataclasses import dataclass, field | |
| import numpy as np | |
| import pandas as pd | |
| from .ledger import normalize_activity | |
| class SelectionConfig: | |
| # the wedge: consistent, repeatable, copyable, NOT a mega-whale / market-maker | |
| min_monthly_profit_ratio: float = 0.5 # green in >=half of active months | |
| min_repeatability: float = 0.30 | |
| max_rebate_share: float = 0.35 # reject market-makers (uncopyable) | |
| min_profit_usd: float = 5_000 # must be actually profitable... | |
| max_profit_usd: float = 2_000_000 # ...but NOT a mega-whale (coverage gap) | |
| max_avg_trade_usdc: float = 5_000 # mid-size, not size-you-can't-mirror | |
| min_active_days: int = 20 | |
| min_resolved_markets: int = 5 | |
| top_n: int = 15 | |
| def _profit(row: pd.Series) -> float: | |
| """Authoritative profit if on leaderboard, else reconstructed total_pnl.""" | |
| p = row.get("profit_final") | |
| if p is None or (isinstance(p, float) and np.isnan(p)): | |
| p = row.get("total_pnl", 0.0) | |
| return float(p or 0.0) | |
| def _trader_score(row: pd.Series) -> float: | |
| """Blend the trustworthy signals into one 0..1 quality score for a trader. | |
| Leans on consistency + repeatability + copyability (NOT raw size or the noisy | |
| win-rate / reconstructed-PnL fields).""" | |
| consistency = float(row.get("monthly_profit_ratio", 0.0) or 0.0) | |
| repeat = float(row.get("repeatability", 0.0) or 0.0) | |
| copyable = 1.0 - min(1.0, float(row.get("rebate_share", 0.0) or 0.0)) | |
| roi = float(row.get("roi", 0.0) or 0.0) | |
| roi_signal = float(np.clip(roi / 0.5, 0.0, 1.0)) # 50% ROI -> full | |
| return round(float(np.mean([consistency, repeat, copyable, roi_signal])), 4) | |
| def select_smart_money(df: pd.DataFrame, cfg: SelectionConfig) -> pd.DataFrame: | |
| """Apply the wedge filter and rank. Returns a copy with `trader_score`.""" | |
| if df.empty: | |
| return df.assign(trader_score=[]) | |
| d = df.copy() | |
| d["profit"] = d.apply(_profit, axis=1) | |
| d["trader_score"] = d.apply(_trader_score, axis=1) | |
| m = ( | |
| (d["monthly_profit_ratio"].fillna(0) >= cfg.min_monthly_profit_ratio) | |
| & (d["repeatability"].fillna(0) >= cfg.min_repeatability) | |
| & (d["rebate_share"].fillna(1) <= cfg.max_rebate_share) | |
| & (d["profit"] >= cfg.min_profit_usd) | |
| & (d["profit"] <= cfg.max_profit_usd) # <-- excludes mega-whales | |
| & (d["avg_trade_usdc"].fillna(1e12) <= cfg.max_avg_trade_usdc) | |
| & (d["active_days"].fillna(0) >= cfg.min_active_days) | |
| & (d["n_resolved_markets"].fillna(0) >= cfg.min_resolved_markets) | |
| ) | |
| out = d[m].sort_values("trader_score", ascending=False).head(cfg.top_n) | |
| return out.reset_index(drop=True) | |
| class Move: | |
| wallet: str | |
| trader_score: float | |
| title: str | |
| outcome: str | |
| price: float | |
| usdc: float | |
| ts: pd.Timestamp | |
| conviction: float # this bet vs the trader's own typical size | |
| signal_quality: float # trader_score blended with conviction+edge | |
| dominant_topic: str = "" | |
| def _conviction(usdc: float, avg_usdc: float) -> float: | |
| """How big is this bet relative to the trader's own average? >1 means an | |
| above-typical, higher-conviction entry. Squashed to 0..1.""" | |
| if avg_usdc <= 0: | |
| return 0.5 | |
| ratio = usdc / avg_usdc | |
| return float(np.clip(ratio / 3.0, 0.0, 1.0)) # 3x avg -> max conviction | |
| def fresh_moves(client, selected: pd.DataFrame, hours: int = 24, | |
| page_limit: int = 200, per_wallet_cap: int = 3) -> list[Move]: | |
| """Pull each selected wallet's recent BUYs inside the window, scored.""" | |
| cutoff = pd.Timestamp.now("UTC") - pd.Timedelta(hours=hours) | |
| moves: list[Move] = [] | |
| for _, row in selected.iterrows(): | |
| wallet = row["wallet"] | |
| try: | |
| raw = client.activity(wallet, limit=page_limit, offset=0) | |
| except Exception: | |
| continue | |
| led = normalize_activity(raw) | |
| if led.empty: | |
| continue | |
| led = led[(led["side"] == "BUY") & (led["ts"] >= cutoff)] | |
| if led.empty: | |
| continue | |
| avg_usdc = float(row.get("avg_trade_usdc", 0.0) or 0.0) | |
| tscore = float(row["trader_score"]) | |
| picked = 0 | |
| for t in led.sort_values("usdc", ascending=False).itertuples(index=False): | |
| conv = _conviction(float(t.usdc), avg_usdc) | |
| edge = abs(float(t.price) - 0.5) * 2.0 | |
| sig = round(float(np.mean([tscore, tscore, conv, edge])), 4) # trader weighted 2x | |
| moves.append(Move( | |
| wallet=wallet, trader_score=tscore, title=str(t.title), | |
| outcome=str(t.outcome), price=float(t.price), usdc=float(t.usdc), | |
| ts=t.ts, conviction=round(conv, 3), signal_quality=sig, | |
| dominant_topic=str(row.get("dominant_topic", "") or ""), | |
| )) | |
| picked += 1 | |
| if picked >= per_wallet_cap: | |
| break | |
| moves.sort(key=lambda m: m.signal_quality, reverse=True) | |
| return moves | |
| def _wallet_md(w: str) -> str: | |
| """Short label, full address preserved as a verifiable Polymarket link.""" | |
| return f"[{w[:6]}β¦{w[-4:]}](https://polymarket.com/profile/{w})" | |
| def _rank_dots(vals: list[float]) -> list[str]: | |
| """Relative 1β5 dot rank WITHIN the shown batch, so the bars actually spread | |
| instead of clustering (raw signals bunch around 0.5β0.7). Weakest shown move | |
| gets βββββ, strongest βββββ, the rest spaced by percentile rank.""" | |
| n = len(vals) | |
| if n == 0: | |
| return [] | |
| order = sorted(range(n), key=lambda i: vals[i]) | |
| dots = [""] * n | |
| for pos, i in enumerate(order): | |
| pct = pos / (n - 1) if n > 1 else 1.0 | |
| k = 1 + int(round(pct * 4)) # 1..5 | |
| dots[i] = "β" * k + "β" * (5 - k) | |
| return dots | |
| def render_markdown(selected: pd.DataFrame, moves: list[Move], | |
| hours: int, top_moves: int = 12) -> str: | |
| date = pd.Timestamp.now("UTC").strftime("%Y-%m-%d %H:%M UTC") | |
| lines = [ | |
| f"# Consistent Smart-Money Digest β {date}", | |
| "", | |
| f"_Mid-size, consistently-profitable Polymarket traders (the ones whale " | |
| f"trackers skip) and their highest-conviction moves in the last {hours}h. " | |
| f"Flow intelligence, not financial advice._", | |
| "", | |
| f"**Tracking {len(selected)} vetted traders Β· {len(moves)} fresh moves scored**", | |
| "", | |
| "## Top moves right now", | |
| "", | |
| "_Signal = our quality score for a move: the trader's consistency blended " | |
| "with how big this bet is for them (conviction) and how far the price is " | |
| "from a coin-flip (edge). Dots are a **relative rank among today's moves** β " | |
| "βββββ = strongest signal in this list, βββββ = weakest. Tap any address to " | |
| "verify it on Polymarket._", | |
| "", | |
| ] | |
| if not moves: | |
| lines.append("_No qualifying fresh moves in the window. Check back next run._") | |
| else: | |
| shown = moves[:top_moves] | |
| dot_bars = _rank_dots([m.signal_quality for m in shown]) | |
| lines.append("| Signal | Trader | Move | Price | Size | Conviction |") | |
| lines.append("|---|---|---|---|---|---|") | |
| for m, bar in zip(shown, dot_bars): | |
| title = (m.title[:46] + "β¦") if len(m.title) > 47 else m.title | |
| lines.append( | |
| f"| {bar} {m.signal_quality:.2f} " | |
| f"| {_wallet_md(m.wallet)} | {title} " | |
| f"({m.outcome}) | {m.price:.2f} | ${m.usdc:,.0f} | {m.conviction:.0%} |" | |
| ) | |
| lines += ["", "## The traders we're tracking", "", | |
| "_The mid-size, consistently-profitable wallets that passed our filter β " | |
| "the ones we pull fresh moves from. Score blends consistency, " | |
| "repeatability and copyability (not size). Tap to verify on Polymarket._", | |
| "", | |
| "| Trader | Score | Profit | Consistency | Repeatability | Topic |", | |
| "|---|---|---|---|---|---|"] | |
| for _, r in selected.iterrows(): | |
| lines.append( | |
| f"| {_wallet_md(r['wallet'])} | {r['trader_score']:.2f} | ${_profit(r):,.0f} | " | |
| f"{float(r.get('monthly_profit_ratio',0)):.0%} | " | |
| f"{float(r.get('repeatability',0)):.2f} | " | |
| f"{r.get('dominant_topic','')} |" | |
| ) | |
| lines += ["", "---", | |
| "_Built from Polymarket public data. Past performance is not " | |
| "predictive; consistency scoring β guaranteed profit._"] | |
| return "\n".join(lines) | |