File size: 4,819 Bytes
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
"""Score a SINGLE arbitrary wallet live — the free lead-magnet endpoint.

Paste any Polymarket wallet -> we fetch its recent activity + open positions,
run the same metrics/patterns the digest uses, and return a consistency /
repeatability / copyability read plus a plain-English verdict.

This is the ungated hook: shareable, SEO-friendly, and it captures the exact
value prop (we judge *consistency*, not just size). Reuses the analysis engine
so there's one source of truth.
"""
from __future__ import annotations

from dataclasses import dataclass, field, asdict

import pandas as pd

from .ledger import normalize_activity, attach_open_positions
from . import metrics as M
from . import patterns as P


@dataclass
class WalletScore:
    wallet: str
    ok: bool
    trader_score: float = 0.0
    verdict: str = ""
    verdict_tag: str = ""            # one of: watch / whale / maker / inconsistent / thin
    total_pnl: float = 0.0
    roi: float = 0.0
    monthly_profit_ratio: float = 0.0
    repeatability: float = 0.0
    rebate_share: float = 0.0
    avg_trade_usdc: float = 0.0
    n_trades: int = 0
    n_resolved_markets: int = 0
    active_days: int = 0
    dominant_topic: str = ""
    note: str = ""

    def to_dict(self) -> dict:
        return asdict(self)


# thresholds mirror digest.SelectionConfig so the score and the digest agree
_WHALE_PROFIT = 2_000_000
_WHALE_AVG_TRADE = 5_000
_MAKER_REBATE_SHARE = 0.35
_CONSISTENT = 0.5
_REPEATABLE = 0.30
_MIN_TRADES = 10


def _verdict(s: "pd.Series", trader_score: float) -> tuple[str, str]:
    pnl = float(s["total_pnl"])
    if s["n_trades"] < _MIN_TRADES:
        return ("thin", "Too few trades to judge — not enough history to trust any pattern.")
    if s["rebate_share"] >= _MAKER_REBATE_SHARE:
        return ("maker", "Market-maker / rebate-driven. Profit comes from liquidity "
                          "rewards you can't copy — skip for copy-trading.")
    if pnl >= _WHALE_PROFIT or s["avg_trade_usdc"] >= _WHALE_AVG_TRADE:
        return ("whale", "Mega-whale sizing. Real trader, but bets are too big to "
                         "mirror at retail size — and every tracker already flags them.")
    if s["monthly_profit_ratio"] >= _CONSISTENT and s["repeatability"] >= _REPEATABLE:
        return ("watch", "Consistent mid-size trader with a repeatable style — the kind "
                         "whale trackers miss. Worth watching.")
    return ("inconsistent", "Profitable at times but inconsistent or hard-to-replicate — "
                            "could be luck. Watch, don't follow blindly.")


def score_wallet(client, wallet: str, page_limit: int = 500,
                 max_pages: int = 8) -> WalletScore:
    wallet = wallet.strip().lower()
    if not (wallet.startswith("0x") and len(wallet) == 42):
        return WalletScore(wallet=wallet, ok=False,
                           note="Not a valid 0x… wallet address.")
    try:
        raw = list(client.iter_activity(wallet, page_limit=page_limit,
                                        max_pages=max_pages))
    except Exception as e:  # noqa: BLE001
        return WalletScore(wallet=wallet, ok=False,
                           note=f"Couldn't fetch activity: {type(e).__name__}.")
    led = normalize_activity(raw)
    if led.empty:
        return WalletScore(wallet=wallet, ok=False,
                           note="No Polymarket activity found for this wallet.")

    try:
        pos = client.positions(wallet)
    except Exception:  # noqa: BLE001
        pos = []
    open_df = attach_open_positions(pos)

    stats = M.compute(wallet, led, open_df)
    pat = P.extract(wallet, led)

    row = pd.Series({
        "monthly_profit_ratio": stats.monthly_profit_ratio,
        "repeatability": pat.repeatability,
        "rebate_share": stats.rebate_share,
        "roi": stats.roi,
        "total_pnl": stats.total_pnl,
        "avg_trade_usdc": stats.avg_trade_usdc,
        "n_trades": stats.n_trades,
    })
    from .digest import _trader_score
    tscore = _trader_score(row)
    tag, verdict = _verdict(row, tscore)

    return WalletScore(
        wallet=wallet, ok=True, trader_score=tscore, verdict=verdict, verdict_tag=tag,
        total_pnl=round(stats.total_pnl, 2), roi=round(stats.roi, 4),
        monthly_profit_ratio=round(stats.monthly_profit_ratio, 4),
        repeatability=round(pat.repeatability, 3),
        rebate_share=round(stats.rebate_share, 4),
        avg_trade_usdc=round(stats.avg_trade_usdc, 2),
        n_trades=stats.n_trades, n_resolved_markets=stats.n_resolved_markets,
        active_days=stats.active_days, dominant_topic=pat.dominant_topic,
        note="Reconstructed from the wallet's most-recent ~3.5k activities "
             "(Data API history cap). Consistency scoring ≠ guaranteed profit.",
    )