File size: 9,535 Bytes
d4c51f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18838c8
 
 
 
 
573e473
 
 
 
 
 
 
 
 
 
 
 
 
 
18838c8
 
d4c51f2
 
 
 
 
 
 
 
 
 
 
 
 
 
573e473
 
 
 
18838c8
 
d4c51f2
 
 
 
573e473
 
d4c51f2
 
573e473
d4c51f2
 
573e473
18838c8
d4c51f2
 
 
18838c8
 
 
 
d4c51f2
 
 
 
18838c8
d4c51f2
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
"""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


@dataclass
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)


@dataclass
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)