File size: 5,722 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
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
"""Per-wallet performance metrics computed from the normalized ledger.

Everything here is derived from two inputs:
  - ledger  : normalized activity (see ledger.normalize_activity)
  - open_df : marked-to-market open positions (see ledger.attach_open_positions)

Key definitions:
  total_pnl   = realized cashflow over closed markets + MTM value of open ones
  roi         = total_pnl / capital_deployed (sum of buy cost basis)
  win_rate    = share of *resolved* markets that ended net-positive
  equity_curve= cumulative realized cashflow over time (+ running deposits view)
  max_dd      = worst peak-to-trough drawdown of the equity curve
  consistency = fraction of active months that were net green
"""
from __future__ import annotations

from dataclasses import dataclass, asdict

import numpy as np
import pandas as pd

from .ledger import REBATE_TYPES


@dataclass
class WalletStats:
    wallet: str
    total_pnl: float
    realized_pnl: float
    open_pnl: float
    capital_deployed: float
    roi: float
    win_rate: float
    n_trades: int
    n_markets: int
    n_resolved_markets: int
    active_days: int
    first_ts: str
    last_ts: str
    max_drawdown_pct: float
    monthly_profit_ratio: float
    avg_trade_usdc: float
    median_entry_price: float
    rebate_pnl: float          # income from liquidity rewards + maker/taker rebates
    rebate_share: float        # rebate_pnl / total_pnl -> high = market maker (uncopyable)

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


def _resolved_market_pnl(ledger: pd.DataFrame) -> pd.Series:
    """Net cashflow per market. A market is 'resolved' for our purposes when the
    trader has fully exited it (net share flow ~0) or redeemed it. We approximate
    resolution by net share balance: BUY adds shares, SELL/REDEEM remove them."""
    if ledger.empty:
        return pd.Series(dtype=float)
    signed_size = np.where(ledger["side"].eq("BUY"), ledger["size"], -ledger["size"])
    tmp = ledger.assign(signed_size=signed_size)
    pnl = tmp.groupby("market")["cashflow"].sum()
    net_shares = tmp.groupby("market")["signed_size"].sum().abs()
    # treat markets with a near-zero residual share balance as resolved/closed
    resolved = net_shares < 1e-6
    pnl.attrs["resolved_mask"] = resolved
    return pnl


def _empty(wallet: str) -> WalletStats:
    return WalletStats(
        wallet=wallet, total_pnl=0.0, realized_pnl=0.0, open_pnl=0.0,
        capital_deployed=0.0, roi=0.0, win_rate=0.0, n_trades=0, n_markets=0,
        n_resolved_markets=0, active_days=0, first_ts="", last_ts="",
        max_drawdown_pct=0.0, monthly_profit_ratio=0.0, avg_trade_usdc=0.0,
        median_entry_price=0.0, rebate_pnl=0.0, rebate_share=0.0,
    )


def compute(wallet: str, ledger: pd.DataFrame, open_df: pd.DataFrame) -> WalletStats:
    if ledger.empty:
        return _empty(wallet)

    market_pnl = _resolved_market_pnl(ledger)
    resolved_mask = market_pnl.attrs.get("resolved_mask", pd.Series(dtype=bool))

    realized_pnl = float(market_pnl.sum())
    open_pnl = float(open_df["cashPnl"].sum()) if not open_df.empty else 0.0
    total_pnl = realized_pnl + open_pnl

    buys = ledger.loc[ledger["side"].eq("BUY"), "usdc"]
    capital_deployed = float(buys.sum())
    roi = total_pnl / capital_deployed if capital_deployed > 0 else 0.0

    resolved_pnl = market_pnl[resolved_mask] if len(resolved_mask) else market_pnl
    n_resolved = int(len(resolved_pnl))
    win_rate = float((resolved_pnl > 0).mean()) if n_resolved else 0.0

    first_ts, last_ts = ledger["ts"].iloc[0], ledger["ts"].iloc[-1]
    active_days = int((last_ts - first_ts).days)

    # equity curve = cumulative realized cashflow through time
    eq = ledger.sort_values("ts")["cashflow"].cumsum()
    max_dd = _max_drawdown_pct(eq.values, capital_deployed)

    # monthly consistency
    monthly = (ledger.set_index("ts")["cashflow"]
               .resample("ME").sum())
    monthly_profit_ratio = float((monthly > 0).mean()) if len(monthly) else 0.0

    trade_rows = ledger[ledger["side"].isin(["BUY", "SELL"])]
    avg_trade_usdc = float(trade_rows["usdc"].mean()) if not trade_rows.empty else 0.0
    median_entry = float(ledger.loc[ledger["side"].eq("BUY"), "price"].median() or 0.0)

    # copyability: how much of the profit is protocol incentives (market-making)
    rebate_pnl = float(ledger.loc[ledger["type"].isin(REBATE_TYPES), "usdc"].sum())
    rebate_share = rebate_pnl / total_pnl if total_pnl > 0 else (1.0 if rebate_pnl > 0 else 0.0)

    return WalletStats(
        wallet=wallet,
        total_pnl=round(total_pnl, 2),
        realized_pnl=round(realized_pnl, 2),
        open_pnl=round(open_pnl, 2),
        capital_deployed=round(capital_deployed, 2),
        roi=round(roi, 4),
        win_rate=round(win_rate, 4),
        n_trades=int(len(trade_rows)),
        n_markets=int(ledger["market"].nunique()),
        n_resolved_markets=n_resolved,
        active_days=active_days,
        first_ts=str(first_ts),
        last_ts=str(last_ts),
        max_drawdown_pct=round(max_dd, 4),
        monthly_profit_ratio=round(monthly_profit_ratio, 4),
        avg_trade_usdc=round(avg_trade_usdc, 2),
        median_entry_price=round(median_entry, 4),
        rebate_pnl=round(rebate_pnl, 2),
        rebate_share=round(min(max(rebate_share, 0.0), 1.0), 4),
    )


def _max_drawdown_pct(equity: np.ndarray, denom: float) -> float:
    """Max peak-to-trough drop, normalized by capital deployed so it reads as a
    fraction. Returns 0..1 (higher = worse)."""
    if len(equity) == 0 or denom <= 0:
        return 0.0
    running_max = np.maximum.accumulate(equity)
    drawdown = running_max - equity
    return float(drawdown.max() / denom)