stratforge 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. stratforge/__init__.py +17 -0
  2. stratforge/ccxt_bridge.py +478 -0
  3. stratforge/cfm/__init__.py +3 -0
  4. stratforge/cfm/bars.py +115 -0
  5. stratforge/cfm/download_cde.py +159 -0
  6. stratforge/cfm/isolation.py +14 -0
  7. stratforge/cfm/ledger.py +332 -0
  8. stratforge/cfm/replay.py +224 -0
  9. stratforge/cfm/run_cde_dozen.py +111 -0
  10. stratforge/cfm/run_cde_replay.py +107 -0
  11. stratforge/cfm/run_cde_universe.py +112 -0
  12. stratforge/cfm/run_research.py +110 -0
  13. stratforge/cfm/run_round2.py +78 -0
  14. stratforge/cfm/run_validate.py +196 -0
  15. stratforge/cfm/strats.py +427 -0
  16. stratforge/cfm/strats_cde.py +681 -0
  17. stratforge/cfm/test_isolation.py +43 -0
  18. stratforge/cfm/test_ledger.py +76 -0
  19. stratforge/cfm/test_venue.py +36 -0
  20. stratforge/cfm/venue.py +36 -0
  21. stratforge/live.py +15 -0
  22. stratforge/paper_family.py +15 -0
  23. stratforge/risk_limits.py +337 -0
  24. stratforge/short/__init__.py +5 -0
  25. stratforge/short/backfill_spot_gap.py +90 -0
  26. stratforge/short/engine.py +227 -0
  27. stratforge/short/indicators.py +58 -0
  28. stratforge/short/ledger.py +273 -0
  29. stratforge/short/regime_occupancy.py +156 -0
  30. stratforge/short/regime_stretches.py +50 -0
  31. stratforge/short/replay.py +390 -0
  32. stratforge/short/run_backtest.py +153 -0
  33. stratforge/short/run_regime_gates.py +105 -0
  34. stratforge/short/run_tsmom12.py +263 -0
  35. stratforge/short/test_short.py +269 -0
  36. stratforge/short/test_tsmom.py +139 -0
  37. stratforge/short/tsmom.py +160 -0
  38. stratforge/state.py +20 -0
  39. stratforge/strategies/bar_apply.py +36 -0
  40. stratforge/strategies/bar_freshness.py +53 -0
  41. stratforge/strategies/buy_protect.py +78 -0
  42. stratforge/strategies/config_load.py +82 -0
  43. stratforge/strategies/daily_data_feed.py +341 -0
  44. stratforge/strategies/day_risk.py +51 -0
  45. stratforge/strategies/display_time.py +72 -0
  46. stratforge/strategies/live_data_feed.py +353 -0
  47. stratforge/strategies/live_executor.py +1346 -0
  48. stratforge/strategies/live_node.py +430 -0
  49. stratforge/strategies/live_reconcile.py +358 -0
  50. stratforge/strategies/node_lock.py +48 -0
  51. stratforge/strategies/paper_executor.py +492 -0
  52. stratforge/strategies/paper_family_node.py +304 -0
  53. stratforge/strategies/qty_precision.py +44 -0
  54. stratforge/strategies/research_families.py +335 -0
  55. stratforge/strategies/research_replay.py +681 -0
  56. stratforge/strategies/signal_engine.py +606 -0
  57. stratforge/strategies/universe.py +60 -0
  58. stratforge/viz/__init__.py +1 -0
  59. stratforge/viz/projector.py +402 -0
  60. stratforge-0.1.0.dist-info/METADATA +51 -0
  61. stratforge-0.1.0.dist-info/RECORD +64 -0
  62. stratforge-0.1.0.dist-info/WHEEL +5 -0
  63. stratforge-0.1.0.dist-info/licenses/LICENSE +21 -0
  64. stratforge-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,224 @@
1
+ """Drive FuturesLedger + strategy intents. Next-open fills. Intra-bar liq/stops.
2
+
3
+ Does not import strategies.* or short.*.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ from datetime import datetime, timezone
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ from cfm.bars import load_4h_bars, load_cde_4h
14
+ from cfm.ledger import FuturesLedger
15
+ from cfm.strats import Intent
16
+ from cfm.venue import cde_multipliers, load_venue, multiplier
17
+
18
+ ROOT = Path(__file__).resolve().parents[1]
19
+
20
+
21
+ def _align(bar_map: dict[str, list[dict]]) -> list[tuple[int, dict[str, dict]]]:
22
+ """Union of timestamps → {sym: bar}."""
23
+ ts_set: set[int] = set()
24
+ by_ts: dict[str, dict[int, dict]] = {}
25
+ for sym, bars in bar_map.items():
26
+ by_ts[sym] = {}
27
+ for b in bars:
28
+ by_ts[sym][b["ts"]] = b
29
+ ts_set.add(b["ts"])
30
+ out = []
31
+ for ts in sorted(ts_set):
32
+ row = {sym: by_ts[sym][ts] for sym in bar_map if ts in by_ts[sym]}
33
+ if row:
34
+ out.append((ts, row))
35
+ return out
36
+
37
+
38
+ def _max_dd(curve: list[tuple[int, float]]) -> float:
39
+ if not curve:
40
+ return 0.0
41
+ peak = curve[0][1]
42
+ worst = 0.0
43
+ for _, eq in curve:
44
+ if eq > peak:
45
+ peak = eq
46
+ if peak > 0:
47
+ worst = max(worst, (peak - eq) / peak)
48
+ return float(worst)
49
+
50
+
51
+ def btc_buyhold_multiple(bars: list[dict], trade_start_ns: int) -> dict:
52
+ w = [b for b in bars if b["ts"] >= trade_start_ns]
53
+ if not w:
54
+ return {"btc_start": 0.0, "btc_end": 0.0, "btc_multiple": 1.0}
55
+ a, b = float(w[0]["close"]), float(w[-1]["close"])
56
+ return {"btc_start": a, "btc_end": b, "btc_multiple": (b / a if a > 0 else 1.0)}
57
+
58
+
59
+ def run_replay(
60
+ strategy,
61
+ symbols: list[str],
62
+ start: str,
63
+ end: str,
64
+ start_usd: float = 1000.0,
65
+ max_leverage: float = 4.0,
66
+ fee_rate: float = 0.0004,
67
+ funding_per_8h: float = 0.00003,
68
+ integer_contracts: bool = True,
69
+ warmup_days: int = 400,
70
+ signal_lag_bars: int = 0,
71
+ tape: str = "spot",
72
+ funding_interval_hours: float = 8.0,
73
+ ) -> dict[str, Any]:
74
+ venue = load_venue()
75
+ if tape == "cde":
76
+ all_m = cde_multipliers()
77
+ mults = {s.upper(): all_m.get(s.upper(), multiplier(s, venue)) for s in symbols}
78
+ else:
79
+ mults = {s.upper(): multiplier(s, venue) for s in symbols}
80
+ start_dt = datetime.strptime(start, "%Y-%m-%d").replace(tzinfo=timezone.utc)
81
+ from datetime import timedelta
82
+
83
+ warm = (start_dt - timedelta(days=int(warmup_days))).strftime("%Y-%m-%d")
84
+ warm_ns = int((start_dt - timedelta(days=int(warmup_days))).timestamp() * 1_000_000_000)
85
+ end_dt = datetime.strptime(end, "%Y-%m-%d").replace(tzinfo=timezone.utc, hour=23, minute=59)
86
+ end_ns = int(end_dt.timestamp() * 1_000_000_000)
87
+ bar_map = {}
88
+ for s in symbols:
89
+ if tape == "cde":
90
+ full = load_cde_4h(s.upper())
91
+ else:
92
+ full = load_4h_bars(s.upper(), None, None)
93
+ bar_map[s.upper()] = [b for b in full if warm_ns <= b["ts"] <= end_ns]
94
+ aligned = _align(bar_map)
95
+ trade_start_ns = int(start_dt.timestamp() * 1_000_000_000)
96
+ ledger = FuturesLedger(
97
+ start_usd=float(start_usd),
98
+ max_leverage=float(max_leverage),
99
+ fee_rate=float(fee_rate),
100
+ funding_per_8h=float(funding_per_8h),
101
+ funding_interval_hours=float(funding_interval_hours),
102
+ integer_contracts=bool(integer_contracts),
103
+ multipliers=mults,
104
+ )
105
+ pending: list[Intent] = []
106
+ last_intents: list[Intent] = []
107
+ curve: list[tuple[int, float]] = []
108
+ n_bars = 0
109
+ last_row: dict[str, dict] = {}
110
+ live_started = False
111
+ lag_left = 0
112
+
113
+ for ts, row in aligned:
114
+ n_bars += 1
115
+ last_row = row
116
+ for sym, b in row.items():
117
+ ledger.update_price(sym, float(b["close"]), ts)
118
+ if ts >= trade_start_ns:
119
+ ledger.apply_funding(ts)
120
+ for sym, b in row.items():
121
+ ledger.maybe_liquidate_bar(sym, float(b["high"]), float(b["low"]), ts)
122
+ ledger.maybe_stop_bar(sym, float(b["high"]), float(b["low"]), ts)
123
+ if not live_started:
124
+ pending = list(last_intents)
125
+ live_started = True
126
+ lag_left = 0
127
+ if lag_left > 0:
128
+ lag_left -= 1
129
+ elif pending:
130
+ for it in pending:
131
+ px = float(row[it.symbol]["open"]) if it.symbol in row else 0.0
132
+ if px <= 0:
133
+ continue
134
+ eq = max(ledger.equity(), 0.0)
135
+ notion = eq * float(it.leverage)
136
+ if it.hold_contracts:
137
+ lot = ledger.lots.get(it.symbol)
138
+ if lot and lot.side == it.side:
139
+ continue
140
+ if it.side == "FLAT" or it.leverage <= 0:
141
+ ledger.rebalance(
142
+ it.symbol, "FLAT", px, ts, 0.0, reason=it.reason, stop_px=it.stop_px
143
+ )
144
+ continue
145
+ ledger.rebalance(
146
+ it.symbol, it.side, px, ts, notion, reason=it.reason, stop_px=it.stop_px
147
+ )
148
+ pending = []
149
+ eq = ledger.equity()
150
+ curve.append((ts, eq))
151
+ if eq <= 1e-6:
152
+ break
153
+ closes = {sym: float(b["close"]) for sym, b in row.items()}
154
+ highs = {sym: float(b["high"]) for sym, b in row.items()}
155
+ lows = {sym: float(b["low"]) for sym, b in row.items()}
156
+ intents = strategy.on_close(ts, closes, highs, lows)
157
+ if intents:
158
+ last_intents = intents
159
+ if ts >= trade_start_ns:
160
+ pending = intents
161
+ lag_left = int(signal_lag_bars)
162
+
163
+ # flatten at last close
164
+ if last_row:
165
+ ts = last_row[next(iter(last_row))]["ts"]
166
+ pxmap = {s: float(b["close"]) for s, b in last_row.items()}
167
+ ledger.flatten_all(pxmap, ts, reason="eod")
168
+
169
+ end_eq = float(ledger.equity())
170
+ btc_bars = bar_map.get("BTC") or []
171
+ bh = btc_buyhold_multiple(btc_bars, trade_start_ns)
172
+ multiple = end_eq / float(start_usd) if start_usd else 0.0
173
+ vs_btc = multiple / bh["btc_multiple"] if bh["btc_multiple"] else 0.0
174
+ return {
175
+ "strategy_id": getattr(strategy, "strategy_id", type(strategy).__name__),
176
+ "account_type": "MARGIN_OVERNIGHT_4X_CAP",
177
+ "symbols": [s.upper() for s in symbols],
178
+ "start": start,
179
+ "end": end,
180
+ "start_usd": float(start_usd),
181
+ "end_equity": end_eq,
182
+ "multiple": multiple,
183
+ "return_pct": (multiple - 1.0) * 100.0,
184
+ "max_dd": _max_dd(curve),
185
+ "fees_paid": ledger.fees_paid,
186
+ "funding_paid": ledger.funding_paid,
187
+ "liquidations": ledger.liquidations,
188
+ "stop_exits": ledger.stop_exits,
189
+ "trades": ledger.trades,
190
+ "wins": ledger.wins,
191
+ "losses": ledger.losses,
192
+ "n_bars": n_bars,
193
+ "curve_points": len(curve),
194
+ "max_leverage": float(max_leverage),
195
+ "fee_rate": float(fee_rate),
196
+ "funding_per_8h": float(funding_per_8h),
197
+ "funding_interval_hours": float(funding_interval_hours),
198
+ "integer_contracts": bool(integer_contracts),
199
+ "tape": tape,
200
+ "price_proxy": "cde_1h_to_4h" if tape == "cde" else "spot_5m_to_4h",
201
+ "btc_multiple": bh["btc_multiple"],
202
+ "btc_start": bh["btc_start"],
203
+ "btc_end": bh["btc_end"],
204
+ "vs_btc_multiple": vs_btc,
205
+ "hit_10x_btc_multiple": vs_btc >= 10.0,
206
+ "hit_10x_btc_return": (multiple - 1.0) >= 10.0 * (bh["btc_multiple"] - 1.0),
207
+ "flips": int(getattr(strategy, "flips", 0) or 0),
208
+ "weeks": int(getattr(strategy, "weeks", 0) or 0),
209
+ "signal_lag_bars": int(signal_lag_bars),
210
+ "assumptions": [
211
+ "spot 5m→4h proxy; BIP/ETP/SLP/XPP basis unmodeled",
212
+ "overnight IM 25% (4x) cap; 10x intraday not used",
213
+ "funding constant debit both sides, never credited",
214
+ "next-open fills; intra-bar liq and stops on high/low",
215
+ "integer nano lots",
216
+ ],
217
+ }
218
+
219
+
220
+ def write_json(obj: dict, path: str | Path) -> Path:
221
+ p = Path(path)
222
+ p.parent.mkdir(parents=True, exist_ok=True)
223
+ p.write_text(json.dumps(obj, indent=2, default=str) + "\n")
224
+ return p
@@ -0,0 +1,111 @@
1
+ #!/usr/bin/env python3
2
+ """Dozen-plus distinct identities on CDE BIP (and ETH where needed)."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ ROOT = Path(__file__).resolve().parents[1]
10
+ sys.path.insert(0, str(ROOT))
11
+
12
+ from cfm.replay import run_replay, write_json
13
+ from cfm.strats import DonchianTurtle, Hold1x, WeeklySma
14
+ from cfm.strats_cde import (
15
+ AtrVolBreak,
16
+ BollBreak,
17
+ BollMeanRev,
18
+ ChandelierLong,
19
+ ConnorsRsi2,
20
+ DonchianWeeks,
21
+ DualBtcEthMom,
22
+ HullTrend,
23
+ IchimokuTJ,
24
+ KeltnerBreak,
25
+ MacdCross,
26
+ RocWeeks,
27
+ SeasonNovApr,
28
+ Supertrend,
29
+ TripleWeeklyMA,
30
+ TsmomWeeks,
31
+ )
32
+
33
+ OUT = ROOT / "results" / "backtests" / "cfm" / "cde_dozen"
34
+ START, END = "2025-07-19", "2026-08-27"
35
+
36
+
37
+ def run(strat, symbols=None, start_usd=1000.0):
38
+ r = run_replay(
39
+ strat,
40
+ symbols=symbols or ["BTC"],
41
+ start=START,
42
+ end=END,
43
+ start_usd=start_usd,
44
+ max_leverage=4.0,
45
+ fee_rate=0.0004,
46
+ funding_per_8h=0.000012,
47
+ funding_interval_hours=1.0,
48
+ integer_contracts=True,
49
+ warmup_days=1,
50
+ tape="cde",
51
+ )
52
+ rec = {
53
+ "id": r["strategy_id"],
54
+ "mult": round(r["multiple"], 3),
55
+ "vs_bip": round(r["vs_btc_multiple"], 3),
56
+ "bip_m": round(r["btc_multiple"], 3),
57
+ "dd": round(r["max_dd"] * 100, 1),
58
+ "liq": r["liquidations"],
59
+ "trades": r["trades"],
60
+ "flips": r.get("flips", 0),
61
+ "fund": round(r["funding_paid"], 1),
62
+ "end_eq": round(r["end_equity"], 2),
63
+ "usd": start_usd,
64
+ }
65
+ print(
66
+ f"{rec['id'][:56]:56} vs={rec['vs_bip']:5.2f} mult={rec['mult']:5.2f} "
67
+ f"dd={rec['dd']:5.1f}% liq={rec['liq']} tr={rec['trades']:3d} flips={rec['flips']:3d}",
68
+ flush=True,
69
+ )
70
+ write_json(r, OUT / f"{r['strategy_id']}.json")
71
+ return rec
72
+
73
+
74
+ def main():
75
+ rows = []
76
+ print("=== yardstick + frozen ===", flush=True)
77
+ rows.append(run(Hold1x(["BTC"]), start_usd=2500))
78
+ rows.append(run(WeeklySma(["BTC"], 40, 3.0, False, True)))
79
+ print("=== 16 distinct families ===", flush=True)
80
+ specs = [
81
+ TsmomWeeks(13, 3.0, False),
82
+ TsmomWeeks(26, 3.0, False),
83
+ TsmomWeeks(13, 3.0, True),
84
+ TripleWeeklyMA(3.0),
85
+ DonchianWeeks(20, 10, 3.0),
86
+ RocWeeks(12, 3.0),
87
+ SeasonNovApr(2.0),
88
+ IchimokuTJ(54, 156, 3.0),
89
+ Supertrend(10, 3.0, 3.0),
90
+ BollBreak(20, 2.0, 3.0),
91
+ BollMeanRev(20, 2.0, 50, 2.0),
92
+ ConnorsRsi2(2.0),
93
+ HullTrend(32, 3.0),
94
+ MacdCross(12, 26, 9, 3.0),
95
+ KeltnerBreak(20, 20, 2.0, 3.0),
96
+ ChandelierLong(22, 22, 3.0, 3.0),
97
+ DualBtcEthMom(12, 1.5),
98
+ AtrVolBreak(14, 1.5, 2.0, 12),
99
+ DonchianTurtle(["BTC"], 330, 120, 120, 0.02, 2.0, 4.0, False),
100
+ ]
101
+ for s in specs:
102
+ syms = ["BTC", "ETH"] if "btc_eth" in getattr(s, "strategy_id", "") else ["BTC"]
103
+ rows.append(run(s, symbols=syms))
104
+ write_json({"tape": "cde", "start": START, "end": END, "rows": rows}, OUT / "summary.json")
105
+ print("\n=== rank vs BIP ===")
106
+ for r in sorted(rows, key=lambda x: -x["vs_bip"]):
107
+ print(f" {r['vs_bip']:5.2f}xBIP {r['mult']:5.2f}x dd={r['dd']:5.1f}% liq={r['liq']} tr={r['trades']:3d} {r['id']}")
108
+
109
+
110
+ if __name__ == "__main__":
111
+ main()
@@ -0,0 +1,107 @@
1
+ #!/usr/bin/env python3
2
+ """Replay CFM identities on CDE BIP 1h→4h tape (listing → now).
3
+
4
+ Venue-honest knobs: hourly funding 0.0012% debit, overnight cap 4x, 4 bps.
5
+ Not a 3y window. Not paper.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import sys
11
+ from pathlib import Path
12
+
13
+ ROOT = Path(__file__).resolve().parents[1]
14
+ sys.path.insert(0, str(ROOT))
15
+
16
+ from cfm.replay import run_replay, write_json
17
+ from cfm.strats import DonchianTurtle, EmaRegimeLev, Hold1x, MonthlySma, VolTargetLong, WeeklySma
18
+
19
+ OUT = ROOT / "results" / "backtests" / "cfm" / "cde_tape"
20
+ START = "2025-07-19"
21
+ END = "2026-08-27"
22
+ KW = dict(
23
+ symbols=["BTC"],
24
+ start=START,
25
+ end=END,
26
+ start_usd=1000.0,
27
+ max_leverage=4.0,
28
+ fee_rate=0.0004,
29
+ funding_per_8h=0.000012, # per interval
30
+ funding_interval_hours=1.0, # CDE hourly
31
+ integer_contracts=True,
32
+ warmup_days=1,
33
+ tape="cde",
34
+ )
35
+
36
+
37
+ def go(strat) -> dict:
38
+ r = run_replay(strat, **KW)
39
+ rec = {
40
+ "id": r["strategy_id"],
41
+ "mult": round(r["multiple"], 3),
42
+ "vs_bip": round(r["vs_btc_multiple"], 3),
43
+ "bip_m": round(r["btc_multiple"], 3),
44
+ "dd": round(r["max_dd"] * 100, 1),
45
+ "liq": r["liquidations"],
46
+ "trades": r["trades"],
47
+ "flips": r.get("flips", 0),
48
+ "fees": round(r["fees_paid"], 2),
49
+ "funding": round(r["funding_paid"], 2),
50
+ "end_eq": round(r["end_equity"], 2),
51
+ "bip_start": round(r["btc_start"], 2),
52
+ "bip_end": round(r["btc_end"], 2),
53
+ }
54
+ print(
55
+ f"{rec['id'][:58]:58} vs={rec['vs_bip']:6.2f} mult={rec['mult']:6.2f} "
56
+ f"dd={rec['dd']:5.1f}% liq={rec['liq']} tr={rec['trades']} fund={rec['funding']:.0f}",
57
+ flush=True,
58
+ )
59
+ write_json(r, OUT / f"{r['strategy_id']}.json")
60
+ return rec
61
+
62
+
63
+ def main() -> None:
64
+ rows = []
65
+ print("=== frozen + yardstick on CDE BIP ===", flush=True)
66
+ rows.append(go(Hold1x(["BTC"])))
67
+ rows.append(go(WeeklySma(["BTC"], n=40, leverage=3.0, short_enabled=False, hold_contracts=True)))
68
+ rows.append(go(WeeklySma(["BTC"], n=40, leverage=3.0, short_enabled=True, hold_contracts=True)))
69
+ print("=== shorter lookbacks / other DNA ===", flush=True)
70
+ for n in (10, 20, 30):
71
+ rows.append(go(WeeklySma(["BTC"], n=n, leverage=3.0, short_enabled=False, hold_contracts=True)))
72
+ rows.append(go(WeeklySma(["BTC"], n=n, leverage=2.0, short_enabled=False, hold_contracts=True)))
73
+ rows.append(go(WeeklySma(["BTC"], n=10, leverage=3.0, short_enabled=True, hold_contracts=True)))
74
+ rows.append(go(WeeklySma(["BTC"], n=20, leverage=3.0, short_enabled=True, hold_contracts=True)))
75
+ rows.append(go(MonthlySma(["BTC"], n=10, leverage=3.0, hold_contracts=True)))
76
+ rows.append(go(DonchianTurtle(["BTC"], 330, 120, 120, 0.02, 2.0, 4.0, False)))
77
+ rows.append(go(DonchianTurtle(["BTC"], 120, 60, 60, 0.02, 2.0, 4.0, False)))
78
+ rows.append(go(EmaRegimeLev(["BTC"], leverage=2.0, fast=300, slow=1200, short_enabled=False)))
79
+ rows.append(go(EmaRegimeLev(["BTC"], leverage=3.0, fast=75, slow=300, short_enabled=False))) # ~12.5d/50d on 4h
80
+ rows.append(go(VolTargetLong(["BTC"], target_vol=0.40)))
81
+ rows.append(go(VolTargetLong(["BTC"], target_vol=0.80)))
82
+ # 3x hold-contracts always-on = Hold1x but lev 3 via wsma that is always long? use Hold-like
83
+ class HoldLev:
84
+ def __init__(self, lev: float):
85
+ self.strategy_id = f"cfm_bip_hold_lev{lev:g}"
86
+ self._done = False
87
+ self.lev = lev
88
+
89
+ def on_close(self, ts, closes, highs, lows):
90
+ if self._done or "BTC" not in closes:
91
+ return []
92
+ self._done = True
93
+ from cfm.strats import Intent
94
+
95
+ return [Intent("BTC", "LONG", self.lev, reason="hold", hold_contracts=True)]
96
+
97
+ rows.append(go(HoldLev(3.0)))
98
+ rows.append(go(HoldLev(2.0)))
99
+ write_json({"start": START, "end": END, "tape": "cde", "funding": "0.000012/hour debit", "rows": rows}, OUT / "summary.json")
100
+ rows_sorted = sorted(rows, key=lambda x: -x["vs_bip"])
101
+ print("\n=== rank vs BIP buy-hold ===")
102
+ for r in rows_sorted:
103
+ print(f" {r['vs_bip']:6.2f}xBIP {r['mult']:6.2f}x dd={r['dd']:5.1f}% {r['id']}")
104
+
105
+
106
+ if __name__ == "__main__":
107
+ main()
@@ -0,0 +1,112 @@
1
+ #!/usr/bin/env python3
2
+ """CDE full-universe CFM identities vs same-window spot SSOT.
3
+
4
+ SSOT bar (CASH trend_rotation_25_max8_rotate, $1000, 2025-07-19→2026-08-27): $1219.68 (+22%).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import sys
10
+ from pathlib import Path
11
+
12
+ ROOT = Path(__file__).resolve().parents[1]
13
+ sys.path.insert(0, str(ROOT))
14
+
15
+ from cfm.bars import load_cde_4h
16
+ from cfm.replay import run_replay, write_json
17
+ from cfm.strats import WeeklySma
18
+ from cfm.strats_cde import CrossSectionMom, TsmomCapLong
19
+ from cfm.venue import cde_symbols
20
+
21
+ OUT = ROOT / "results" / "backtests" / "cfm" / "cde_universe"
22
+ START, END = "2025-07-19", "2026-08-27"
23
+ SSOT_END = 1219.68
24
+
25
+
26
+ def coin_bh():
27
+ print("=== CDE buy-hold (first→last 4h close) ===")
28
+ rows = []
29
+ for s in cde_symbols():
30
+ b = load_cde_4h(s)
31
+ if len(b) < 10:
32
+ print(s, "too short", len(b))
33
+ continue
34
+ a, z = b[0]["close"], b[-1]["close"]
35
+ rows.append((z / a, s, a, z, len(b)))
36
+ rows.sort(reverse=True)
37
+ for m, s, a, z, n in rows:
38
+ print(f" {s:6} {m:6.2f}x {a:g} -> {z:g} bars={n}")
39
+ return rows
40
+
41
+
42
+ def go(strat, symbols, usd):
43
+ r = run_replay(
44
+ strat,
45
+ symbols=symbols,
46
+ start=START,
47
+ end=END,
48
+ start_usd=usd,
49
+ max_leverage=4.0,
50
+ fee_rate=0.0004,
51
+ funding_per_8h=0.000012,
52
+ funding_interval_hours=1.0,
53
+ integer_contracts=True,
54
+ warmup_days=1,
55
+ tape="cde",
56
+ )
57
+ rec = {
58
+ "id": r["strategy_id"],
59
+ "usd": usd,
60
+ "end_eq": round(r["end_equity"], 2),
61
+ "mult": round(r["multiple"], 3),
62
+ "vs_bip": round(r["vs_btc_multiple"], 3),
63
+ "dd": round(r["max_dd"] * 100, 1),
64
+ "liq": r["liquidations"],
65
+ "trades": r["trades"],
66
+ "flips": r.get("flips", 0),
67
+ "fund": round(r["funding_paid"], 1),
68
+ "beats_ssot_mult": r["multiple"] > 1.21968,
69
+ "ssot_1000_scaled": round(1.21968 * usd, 2),
70
+ }
71
+ # compare dollars at same start
72
+ rec["vs_ssot_$"] = round(rec["end_eq"] - rec["ssot_1000_scaled"], 2)
73
+ print(
74
+ f"{rec['id'][:52]:52} ${usd:.0f}->${rec['end_eq']:.0f} {rec['mult']:.2f}x "
75
+ f"dd={rec['dd']:.0f}% liq={rec['liq']} tr={rec['trades']} vsSSOT${rec['vs_ssot_$']:+.0f}",
76
+ flush=True,
77
+ )
78
+ write_json(r, OUT / f"{r['strategy_id']}_usd{int(usd)}.json")
79
+ return rec
80
+
81
+
82
+ def main():
83
+ coin_bh()
84
+ syms = cde_symbols()
85
+ print("\n=== strategies (CDE tape, hourly funding) ===", flush=True)
86
+ print(f"SSOT same window $1000 -> $1219.68 (scale linearly for other starts)", flush=True)
87
+ rows = []
88
+ for usd in (1000.0, 5000.0):
89
+ specs = [
90
+ CrossSectionMom(syms, 12, 4, 0, 0.5),
91
+ CrossSectionMom(syms, 12, 4, 4, 0.4),
92
+ CrossSectionMom(syms, 8, 6, 0, 0.4),
93
+ CrossSectionMom(syms, 8, 4, 4, 0.4),
94
+ TsmomCapLong(syms, 12, 8, 0.375),
95
+ TsmomCapLong(syms, 8, 8, 0.375),
96
+ TsmomCapLong(syms, 12, 4, 0.6),
97
+ WeeklySma(["BTC"], 40, 3.0, False, True),
98
+ ]
99
+ for sp in specs:
100
+ sy = ["BTC"] if "wsma40" in getattr(sp, "strategy_id", "") else syms
101
+ rows.append(go(sp, sy, usd))
102
+ write_json({"ssot": {"start": 1000, "end": SSOT_END, "mult": 1.21968}, "rows": rows}, OUT / "summary.json")
103
+ print("\n=== beat SSOT multiple 1.22x ===")
104
+ hits = [r for r in rows if r["beats_ssot_mult"]]
105
+ if not hits:
106
+ print(" none")
107
+ for r in sorted(hits, key=lambda x: -x["mult"]):
108
+ print(f" {r['mult']:.2f}x ${r['usd']:.0f}->${r['end_eq']:.0f} {r['id']}")
109
+
110
+
111
+ if __name__ == "__main__":
112
+ main()
@@ -0,0 +1,110 @@
1
+ #!/usr/bin/env python3
2
+ """Battery of isolated CFM research identities vs BTC buy-and-hold.
3
+
4
+ Literature params frozen before looking at 3y scores. Not trend_rotation.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import sys
11
+ from pathlib import Path
12
+
13
+ ROOT = Path(__file__).resolve().parents[1]
14
+ sys.path.insert(0, str(ROOT))
15
+
16
+ from cfm.replay import run_replay, write_json
17
+ from cfm.strats import DonchianTurtle, EmaRegimeLev, Hold1x, Tsmom12, VolTargetLong
18
+
19
+ OUT = ROOT / "results" / "backtests" / "cfm"
20
+
21
+ WINDOWS = {
22
+ "3y": ("2023-08-28", "2026-08-27"),
23
+ "2022": ("2022-01-01", "2022-12-31"),
24
+ "full": ("2021-01-01", "2026-08-27"),
25
+ }
26
+
27
+
28
+ def specs() -> list[tuple[object, list[str], float]]:
29
+ """(strategy, symbols, max_leverage_cap)."""
30
+ out: list[tuple[object, list[str], float]] = []
31
+ out.append((Hold1x(["BTC"]), ["BTC"], 4.0))
32
+ for lev in (1.0, 2.0, 3.0, 4.0):
33
+ out.append((Tsmom12(["BTC"], leverage=lev, short_enabled=True), ["BTC"], 4.0))
34
+ out.append((Tsmom12(["BTC"], leverage=lev, short_enabled=False), ["BTC"], 4.0))
35
+ out.append((Tsmom12(["BTC", "ETH"], leverage=3.0, short_enabled=True), ["BTC", "ETH"], 4.0))
36
+ out.append((Tsmom12(["BTC", "ETH", "SOL", "XRP"], leverage=3.0, short_enabled=True), ["BTC", "ETH", "SOL", "XRP"], 4.0))
37
+ out.append((Tsmom12(["BTC", "ETH", "SOL", "XRP"], leverage=4.0, short_enabled=True), ["BTC", "ETH", "SOL", "XRP"], 4.0))
38
+ out.append((Tsmom12(["SOL"], leverage=3.0, short_enabled=True), ["SOL"], 4.0))
39
+ # 55d/20d turtle on 4h = 330/120
40
+ out.append((DonchianTurtle(["BTC"], 330, 120, 120, 0.02, 2.0, 4.0, True), ["BTC"], 4.0))
41
+ out.append((DonchianTurtle(["BTC"], 330, 120, 120, 0.02, 2.0, 4.0, False), ["BTC"], 4.0))
42
+ out.append((DonchianTurtle(["BTC", "ETH", "SOL"], 330, 120, 120, 0.02, 2.0, 4.0, True), ["BTC", "ETH", "SOL"], 4.0))
43
+ # faster 20d/10d turtle (still literature)
44
+ out.append((DonchianTurtle(["BTC"], 120, 60, 60, 0.02, 2.0, 4.0, True), ["BTC"], 4.0))
45
+ for lev in (2.0, 3.0, 4.0):
46
+ out.append((EmaRegimeLev(["BTC"], leverage=lev, short_enabled=True), ["BTC"], 4.0))
47
+ out.append((EmaRegimeLev(["BTC"], leverage=lev, short_enabled=False), ["BTC"], 4.0))
48
+ out.append((EmaRegimeLev(["BTC", "ETH", "SOL"], leverage=3.0, short_enabled=True), ["BTC", "ETH", "SOL"], 4.0))
49
+ for tv in (0.40, 0.80, 1.20):
50
+ out.append((VolTargetLong(["BTC"], target_vol=tv), ["BTC"], 4.0))
51
+ return out
52
+
53
+
54
+ def keys(r: dict) -> dict:
55
+ return {
56
+ "strategy_id": r["strategy_id"],
57
+ "window": f"{r['start']}..{r['end']}",
58
+ "start_usd": r["start_usd"],
59
+ "end_equity": round(r["end_equity"], 2),
60
+ "multiple": round(r["multiple"], 3),
61
+ "return_pct": round(r["return_pct"], 1),
62
+ "max_dd": round(r["max_dd"] * 100, 1),
63
+ "btc_multiple": round(r["btc_multiple"], 3),
64
+ "vs_btc": round(r["vs_btc_multiple"], 3),
65
+ "hit_10x_mult": r["hit_10x_btc_multiple"],
66
+ "hit_10x_ret": r["hit_10x_btc_return"],
67
+ "liq": r["liquidations"],
68
+ "trades": r["trades"],
69
+ "fees": round(r["fees_paid"], 2),
70
+ "funding": round(r["funding_paid"], 2),
71
+ }
72
+
73
+
74
+ def main() -> None:
75
+ start_usd = 1000.0
76
+ rows = []
77
+ for wname, (a, b) in WINDOWS.items():
78
+ for strat, syms, cap in specs():
79
+ r = run_replay(
80
+ strat,
81
+ symbols=syms,
82
+ start=a,
83
+ end=b,
84
+ start_usd=start_usd,
85
+ max_leverage=cap,
86
+ warmup_days=420,
87
+ )
88
+ r["window_name"] = wname
89
+ rec = keys(r)
90
+ rec["window_name"] = wname
91
+ rec["symbols"] = ",".join(syms)
92
+ rows.append(rec)
93
+ print(
94
+ f"{wname:5} {rec['strategy_id'][:56]:56} vsBTC={rec['vs_btc']:7.2f} "
95
+ f"mult={rec['multiple']:7.2f} dd={rec['max_dd']:5.1f}% liq={rec['liq']} "
96
+ f"hit10m={rec['hit_10x_mult']}",
97
+ flush=True,
98
+ )
99
+ write_json(r, OUT / wname / f"{r['strategy_id']}.json")
100
+ write_json({"start_usd": start_usd, "rows": rows}, OUT / "battery.json")
101
+ # 3y ranking
102
+ y3 = [x for x in rows if x["window_name"] == "3y"]
103
+ y3.sort(key=lambda x: -x["vs_btc"])
104
+ print("\n=== 3y rank by vs BTC multiple ===")
105
+ for x in y3[:15]:
106
+ print(f" {x['vs_btc']:7.2f}xBTC {x['multiple']:7.2f}x dd={x['max_dd']:5.1f}% {x['strategy_id']}")
107
+
108
+
109
+ if __name__ == "__main__":
110
+ main()