"""Detect *repeatable* trading patterns in a wallet's ledger. The user's second screen is "反覆出現、可複製的交易模式" — recurring, replicable behavior. A wallet that made money once by luck is useless to copy; a wallet that does the same identifiable thing over and over is copyable. We reduce each wallet to a handful of style features, then collapse them into a single `repeatability` score in [0, 1]. High score = tight entry-price band, consistent bet sizing, topical concentration, and steady cadence over many trades — i.e. a strategy, not noise. """ from __future__ import annotations from dataclasses import dataclass, asdict import numpy as np import pandas as pd # crude topic buckets from title keywords; used when Gamma tags are absent _TOPICS = { "sports": ["nba", "nfl", "mlb", "soccer", "ufc", "game", "vs ", "win the", "match"], "crypto": ["btc", "bitcoin", "eth", "ethereum", "crypto", "solana", "coin"], "politics": ["election", "president", "senate", "trump", "biden", "poll", "governor"], "econ": ["fed", "rate", "cpi", "inflation", "gdp", "recession", "jobs"], } def _topic(title: str) -> str: t = (title or "").lower() for name, kws in _TOPICS.items(): if any(k in t for k in kws): return name return "other" def _cv(x: np.ndarray) -> float: """Coefficient of variation, guarded against zero mean.""" x = x[x > 0] if len(x) < 2 or x.mean() == 0: return 1.0 return float(x.std() / x.mean()) def _hhi(counts: pd.Series) -> float: """Herfindahl concentration in [0,1]; 1 = all one bucket.""" if counts.sum() == 0: return 0.0 p = counts / counts.sum() return float((p ** 2).sum()) @dataclass class PatternFeatures: wallet: str entry_band_tightness: float # 1 = all entries at same price size_consistency: float # 1 = identical bet sizes topic_concentration: float # 1 = single topic cadence_regularity: float # 1 = evenly spaced over time longshot_bias: float # mean(0.5 - entry_price), + = buys underdogs dominant_topic: str n_buys: int repeatability: float # blended [0,1] def to_dict(self) -> dict: return asdict(self) def extract(wallet: str, ledger: pd.DataFrame) -> PatternFeatures: buys = ledger[ledger["side"].eq("BUY")].copy() if len(buys) < 3: return PatternFeatures(wallet, 0, 0, 0, 0, 0.0, "other", len(buys), 0.0) # 1) entry-price band tightness: 1 - normalized std of entry prices band_tightness = float(np.clip(1.0 - buys["price"].std() / 0.5, 0, 1)) # 2) sizing consistency: 1 - CV of trade notional (clipped) size_consistency = float(np.clip(1.0 - _cv(buys["usdc"].values), 0, 1)) # 3) topic concentration via HHI buys["topic"] = buys["title"].map(_topic) topic_counts = buys["topic"].value_counts() topic_conc = _hhi(topic_counts) dominant_topic = str(topic_counts.index[0]) # 4) cadence regularity: 1 - CV of inter-trade gaps (regular => copyable) gaps = buys["ts"].sort_values().diff().dropna().dt.total_seconds().values cadence = float(np.clip(1.0 - _cv(gaps), 0, 1)) if len(gaps) >= 2 else 0.0 # 5) longshot bias (descriptive, not scored): + buys cheap underdogs longshot = float((0.5 - buys["price"]).mean()) # volume confidence: patterns from few trades are unreliable; ramp 0->1 by ~50 buys vol_conf = float(np.clip(np.log1p(len(buys)) / np.log1p(50), 0, 1)) repeatability = vol_conf * np.mean([ band_tightness, size_consistency, topic_conc, cadence ]) return PatternFeatures( wallet=wallet, entry_band_tightness=round(band_tightness, 3), size_consistency=round(size_consistency, 3), topic_concentration=round(topic_conc, 3), cadence_regularity=round(cadence, 3), longshot_bias=round(longshot, 4), dominant_topic=dominant_topic, n_buys=int(len(buys)), repeatability=round(float(repeatability), 3), )