File size: 2,560 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
#!/usr/bin/env python3
"""Step 4 — backtest copy-trading a chosen wallet with conviction sizing.

    python scripts/04_backtest.py <wallet_address>
    python scripts/04_backtest.py            # defaults to top of shortlist

Runs conviction sizing vs a flat-sizing baseline, prints stats, and saves an
equity-curve chart to data/backtest_<wallet>.png
"""
import sys
from pathlib import Path

import pandas as pd

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from pmct import backtest as bt
from pmct.sizing import SizingConfig
from pmct.util import load_config, cache_path


def _pick_wallet(cfg) -> str:
    if len(sys.argv) > 1:
        return sys.argv[1].lower()
    short = pd.read_csv(cache_path(cfg, "shortlist.csv"))
    if short.empty:
        raise SystemExit("Shortlist empty and no wallet given. Run 03_screen.py.")
    return short.iloc[0]["wallet"]


def main():
    cfg = load_config()
    bcfg = cfg["backtest"]
    wallet = _pick_wallet(cfg)

    led_path = cache_path(cfg, "ledgers", f"{wallet}.pkl")
    if not led_path.exists():
        raise SystemExit(f"No cached ledger for {wallet}. Run 02_analyze_wallets.py.")
    led = pd.read_pickle(led_path)

    sizing = SizingConfig(**bcfg["sizing"])
    common = dict(bankroll=bcfg["our_bankroll_usd"], sizing=sizing,
                  slippage_bps=bcfg["slippage_bps"], fee_bps=bcfg["fee_bps"])

    conv = bt.run(led, flat_sizing=False, **common)
    flat = bt.run(led, flat_sizing=True, **common)

    print(f"\nBacktest copy-trading {wallet}")
    print(f"  bankroll ${bcfg['our_bankroll_usd']}  slippage {bcfg['slippage_bps']}bps\n")
    print("  CONVICTION sizing:", conv.to_summary())
    print("  FLAT       sizing:", flat.to_summary())

    try:
        import matplotlib
        matplotlib.use("Agg")
        import matplotlib.pyplot as plt

        fig, ax = plt.subplots(figsize=(10, 5))
        ax.plot(conv.equity_curve["ts"], conv.equity_curve["equity"], label="conviction")
        ax.plot(flat.equity_curve["ts"], flat.equity_curve["equity"], label="flat", alpha=0.7)
        ax.axhline(bcfg["our_bankroll_usd"], ls="--", c="grey", lw=1, label="start")
        ax.set_title(f"Copy-trade equity curve — {wallet[:10]}...")
        ax.set_ylabel("equity (USD)")
        ax.legend()
        out = cache_path(cfg, f"backtest_{wallet}.png")
        fig.tight_layout()
        fig.savefig(out, dpi=120)
        print(f"\n  chart -> {out}")
    except Exception as e:  # noqa: BLE001
        print(f"  (plot skipped: {e})")


if __name__ == "__main__":
    main()