quantbt-engine 1.0.7__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.
- quantbt/__init__.py +862 -0
- quantbt/adapters/__init__.py +5 -0
- quantbt/adapters/nautilus/__init__.py +42 -0
- quantbt/adapters/nautilus/_dependency.py +53 -0
- quantbt/adapters/nautilus/backend.py +639 -0
- quantbt/adapters/nautilus/instruments.py +275 -0
- quantbt/adapters/nautilus/options.py +465 -0
- quantbt/adapters/nautilus/reports.py +231 -0
- quantbt/backends/__init__.py +29 -0
- quantbt/backends/_native_event_rust.py +2168 -0
- quantbt/backends/native_event.py +5048 -0
- quantbt/backends/native_option.py +796 -0
- quantbt/backends/native_portfolio.py +928 -0
- quantbt/backends/native_vectorized.py +1299 -0
- quantbt/backtester.py +485 -0
- quantbt/benchmarks/__init__.py +1 -0
- quantbt/benchmarks/compare_phase9_parity.py +302 -0
- quantbt/benchmarks/gamma_scalping_backtestsample.py +802 -0
- quantbt/benchmarks/profile_phase7.py +415 -0
- quantbt/benchmarks/run_arbitrage_phase_e.py +160 -0
- quantbt/benchmarks/run_optimization_overhead.py +195 -0
- quantbt/benchmarks/run_options_engine.py +272 -0
- quantbt/benchmarks/run_pct_equity_nautilus_smoke.py +227 -0
- quantbt/benchmarks/run_phase12_arbitrage_cert.py +402 -0
- quantbt/benchmarks/run_phase12_benchmark_nautilus_cert.py +430 -0
- quantbt/benchmarks/run_phase13_portfolio_report.py +97 -0
- quantbt/benchmarks/run_phase13_wfo_cache.py +162 -0
- quantbt/benchmarks/run_phase14_service_loop.py +694 -0
- quantbt/benchmarks/run_phase15a_nautilus_certification.py +514 -0
- quantbt/benchmarks/run_phase15b_synthetic_depth.py +175 -0
- quantbt/benchmarks/run_phase16_performance_debt.py +389 -0
- quantbt/benchmarks/run_phase30e_reactive_runner.py +161 -0
- quantbt/benchmarks/run_phase31_intrabar.py +441 -0
- quantbt/benchmarks/run_phase34a_native_event_memory.py +179 -0
- quantbt/benchmarks/run_phase34b_native_event_prepared_score.py +173 -0
- quantbt/benchmarks/run_phase34c_native_event_single_pass.py +176 -0
- quantbt/benchmarks/run_phase7.py +654 -0
- quantbt/benchmarks/run_portfolio_real_parity.py +537 -0
- quantbt/core/__init__.py +323 -0
- quantbt/core/arbitrage.py +767 -0
- quantbt/core/basket.py +234 -0
- quantbt/core/certification.py +274 -0
- quantbt/core/constraints.py +155 -0
- quantbt/core/engine.py +1144 -0
- quantbt/core/event.py +869 -0
- quantbt/core/execution_contract.py +197 -0
- quantbt/core/execution_depth.py +613 -0
- quantbt/core/intrabar_kernel.py +1906 -0
- quantbt/core/intrabar_reference.py +907 -0
- quantbt/core/intrabar_session.py +156 -0
- quantbt/core/market_tape.py +480 -0
- quantbt/core/native_event_capabilities.py +121 -0
- quantbt/core/native_event_parity.py +336 -0
- quantbt/core/order_compiler.py +422 -0
- quantbt/core/orders.py +319 -0
- quantbt/core/portfolio.py +392 -0
- quantbt/core/preprocessor.py +256 -0
- quantbt/core/reactive.py +173 -0
- quantbt/core/results.py +341 -0
- quantbt/core/schema.py +211 -0
- quantbt/core/scopes.py +96 -0
- quantbt/core/structured_orders.py +378 -0
- quantbt/core/types.py +87 -0
- quantbt/core/vectorized.py +203 -0
- quantbt/endpoint.py +4465 -0
- quantbt/engines.py +1014 -0
- quantbt/metrics/__init__.py +45 -0
- quantbt/metrics/options_analytics.py +46 -0
- quantbt/metrics/performance.py +541 -0
- quantbt/optimization/__init__.py +94 -0
- quantbt/optimization/callbacks.py +116 -0
- quantbt/optimization/candidate_selection.py +397 -0
- quantbt/optimization/config.py +84 -0
- quantbt/optimization/constraints.py +22 -0
- quantbt/optimization/evaluator.py +21 -0
- quantbt/optimization/evaluators/__init__.py +32 -0
- quantbt/optimization/evaluators/arbitrage.py +22 -0
- quantbt/optimization/evaluators/generic.py +34 -0
- quantbt/optimization/evaluators/grid_dca.py +22 -0
- quantbt/optimization/evaluators/intrabar.py +54 -0
- quantbt/optimization/evaluators/native_event.py +51 -0
- quantbt/optimization/evaluators/options.py +22 -0
- quantbt/optimization/evaluators/portfolio.py +42 -0
- quantbt/optimization/evaluators/signal.py +43 -0
- quantbt/optimization/multiseed.py +176 -0
- quantbt/optimization/objectives.py +221 -0
- quantbt/optimization/optimizer.py +500 -0
- quantbt/optimization/result.py +80 -0
- quantbt/optimization/samplers.py +84 -0
- quantbt/optimization/space.py +223 -0
- quantbt/options/__init__.py +215 -0
- quantbt/options/cache.py +116 -0
- quantbt/options/conventions.py +158 -0
- quantbt/options/data.py +177 -0
- quantbt/options/execution.py +600 -0
- quantbt/options/fees.py +135 -0
- quantbt/options/greeks.py +173 -0
- quantbt/options/hedging.py +232 -0
- quantbt/options/iv.py +188 -0
- quantbt/options/ledger.py +263 -0
- quantbt/options/lifecycle.py +94 -0
- quantbt/options/margin.py +311 -0
- quantbt/options/packages.py +147 -0
- quantbt/options/pricing.py +191 -0
- quantbt/options/schema.py +227 -0
- quantbt/options/selectors.py +281 -0
- quantbt/options/strategy.py +249 -0
- quantbt/options/surface.py +142 -0
- quantbt/options/tape.py +226 -0
- quantbt/options/templates/__init__.py +33 -0
- quantbt/options/templates/packages.py +354 -0
- quantbt/portfolio.py +606 -0
- quantbt/py.typed +1 -0
- quantbt/reporting/__init__.py +38 -0
- quantbt/reporting/arbitrage_audit.py +211 -0
- quantbt/reporting/nautilus_bundle.py +758 -0
- quantbt/reporting/nautilus_certification.py +226 -0
- quantbt/reporting/nautilus_diagnostics.py +225 -0
- quantbt/reporting/parity.py +496 -0
- quantbt/reporting/portfolio_audit.py +206 -0
- quantbt/reporting/portfolio_nautilus.py +140 -0
- quantbt/sizing/__init__.py +3 -0
- quantbt/sizing/fast.py +67 -0
- quantbt/sizing/modes.py +162 -0
- quantbt/viz/__init__.py +4 -0
- quantbt/viz/plots.py +310 -0
- quantbt/viz/themes.py +102 -0
- quantbt/walkforward.py +3136 -0
- quantbt_engine-1.0.7.dist-info/METADATA +891 -0
- quantbt_engine-1.0.7.dist-info/RECORD +133 -0
- quantbt_engine-1.0.7.dist-info/WHEEL +5 -0
- quantbt_engine-1.0.7.dist-info/licenses/LICENSE +21 -0
- quantbt_engine-1.0.7.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,402 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
Phase 12A arbitrage production-certification smoke runner.
|
|
4
|
+
|
|
5
|
+
The runner uses deterministic realistic market data inspired by the local
|
|
6
|
+
Arbops Binance basis-arb alpha, but it does not import or commit that private
|
|
7
|
+
alpha. The copied alpha sandbox, if present, must live under
|
|
8
|
+
`.local_arbitrage_sandboxes/` and is intentionally git-ignored.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import argparse
|
|
14
|
+
import json
|
|
15
|
+
import sys
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Dict, List, Optional
|
|
18
|
+
|
|
19
|
+
import numpy as np
|
|
20
|
+
import pandas as pd
|
|
21
|
+
|
|
22
|
+
PACKAGE_DIR = Path(__file__).resolve().parents[1]
|
|
23
|
+
PROJECT_DIR = PACKAGE_DIR.parent
|
|
24
|
+
if str(PROJECT_DIR) not in sys.path:
|
|
25
|
+
sys.path.insert(0, str(PROJECT_DIR))
|
|
26
|
+
|
|
27
|
+
from quantbt import ( # noqa: E402
|
|
28
|
+
AccountConfig,
|
|
29
|
+
ArbExecutionPolicy,
|
|
30
|
+
ArbitrageLeg,
|
|
31
|
+
BasisArbitrageSpec,
|
|
32
|
+
ContractType,
|
|
33
|
+
CrossExchangeArbSpec,
|
|
34
|
+
ExecutionConfig,
|
|
35
|
+
HedgePolicy,
|
|
36
|
+
HedgePolicyKind,
|
|
37
|
+
IndexBasketArbSpec,
|
|
38
|
+
NativeEventBackend,
|
|
39
|
+
NativeEventConfig,
|
|
40
|
+
NativeVectorizedBackend,
|
|
41
|
+
NativeVectorizedConfig,
|
|
42
|
+
OptionsVolArbSpec,
|
|
43
|
+
PackageExecutionKind,
|
|
44
|
+
SignalModel,
|
|
45
|
+
SignalModelKind,
|
|
46
|
+
SizingPolicy,
|
|
47
|
+
SizingPolicyKind,
|
|
48
|
+
StatArbPairSpec,
|
|
49
|
+
TriangularArbSpec,
|
|
50
|
+
build_arbitrage_order_plan,
|
|
51
|
+
compare_native_arbitrage_results,
|
|
52
|
+
build_arbitrage_domain_audit,
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def generate_basis_market(rows: int = 900, seed: int = 42):
|
|
57
|
+
rng = np.random.default_rng(seed)
|
|
58
|
+
idx = pd.date_range("2023-01-01", periods=rows, freq="1h", tz="UTC")
|
|
59
|
+
base_ret = rng.normal(0.0, 0.006, size=rows)
|
|
60
|
+
perp = 25_000.0 * np.exp(np.cumsum(base_ret))
|
|
61
|
+
basis = 550.0 * np.exp(-np.linspace(0.0, 4.5, rows)) + 65.0 * np.sin(np.linspace(0.0, 18.0, rows))
|
|
62
|
+
basis += rng.normal(0.0, 18.0, size=rows)
|
|
63
|
+
quarterly = np.maximum(perp + basis, 1.0)
|
|
64
|
+
spread = pd.Series(perp - quarterly, index=idx)
|
|
65
|
+
z = (spread - spread.rolling(48, min_periods=12).mean()) / spread.rolling(48, min_periods=12).std()
|
|
66
|
+
signal = pd.Series(np.where(z > 1.0, 1.0, np.where(z < -1.0, -1.0, 0.0)), index=idx).ffill().fillna(0.0)
|
|
67
|
+
# Force a terminal flat state so audit can verify package flattening.
|
|
68
|
+
signal.iloc[-3:] = 0.0
|
|
69
|
+
|
|
70
|
+
closes = {
|
|
71
|
+
"perpetual": pd.Series(perp, index=idx),
|
|
72
|
+
"quarterly": pd.Series(quarterly, index=idx),
|
|
73
|
+
}
|
|
74
|
+
highs = {symbol: series * 1.002 for symbol, series in closes.items()}
|
|
75
|
+
lows = {symbol: series * 0.998 for symbol, series in closes.items()}
|
|
76
|
+
funding = {
|
|
77
|
+
"perpetual": pd.Series(0.00004 + rng.normal(0.0, 0.00001, size=rows), index=idx),
|
|
78
|
+
"quarterly": pd.Series(0.0, index=idx),
|
|
79
|
+
}
|
|
80
|
+
return idx, signal, closes, highs, lows, funding
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def basis_spec() -> BasisArbitrageSpec:
|
|
84
|
+
return BasisArbitrageSpec(
|
|
85
|
+
arb_id="PHASE12_BTC_PERP_QUARTERLY",
|
|
86
|
+
legs=(
|
|
87
|
+
ArbitrageLeg(
|
|
88
|
+
"perpetual",
|
|
89
|
+
1.0,
|
|
90
|
+
role="perp",
|
|
91
|
+
contract_type=ContractType.LINEAR,
|
|
92
|
+
contract_size=1.0,
|
|
93
|
+
funding_enabled=True,
|
|
94
|
+
),
|
|
95
|
+
ArbitrageLeg(
|
|
96
|
+
"quarterly",
|
|
97
|
+
-1.0,
|
|
98
|
+
role="quarterly",
|
|
99
|
+
contract_type=ContractType.LINEAR,
|
|
100
|
+
contract_size=1.0,
|
|
101
|
+
funding_enabled=False,
|
|
102
|
+
),
|
|
103
|
+
),
|
|
104
|
+
hedge_policy=HedgePolicy(kind=HedgePolicyKind.BASE_QTY_EQUAL, freeze_on_entry=True),
|
|
105
|
+
sizing_policy=SizingPolicy(
|
|
106
|
+
kind=SizingPolicyKind.TARGET_NOTIONAL_TO_BASE_QTY,
|
|
107
|
+
notional=20_000.0,
|
|
108
|
+
reference_symbol="perpetual",
|
|
109
|
+
),
|
|
110
|
+
execution_policy=ArbExecutionPolicy(kind=PackageExecutionKind.ATOMIC_ALL_OR_NONE),
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def stat_spec() -> StatArbPairSpec:
|
|
115
|
+
return StatArbPairSpec(
|
|
116
|
+
arb_id="PHASE12_STAT_PAIR",
|
|
117
|
+
legs=(
|
|
118
|
+
ArbitrageLeg("asset_a", 1.0, role="base", contract_type=ContractType.LINEAR),
|
|
119
|
+
ArbitrageLeg("asset_b", -1.0, role="hedge", contract_type=ContractType.LINEAR),
|
|
120
|
+
),
|
|
121
|
+
hedge_policy=HedgePolicy(kind=HedgePolicyKind.BASE_QTY_EQUAL, freeze_on_entry=True),
|
|
122
|
+
sizing_policy=SizingPolicy(kind=SizingPolicyKind.TARGET_GROSS_NOTIONAL, notional=30_000.0),
|
|
123
|
+
signal_model=SignalModel(kind=SignalModelKind.ZSCORE),
|
|
124
|
+
execution_policy=ArbExecutionPolicy(kind=PackageExecutionKind.ATOMIC_ALL_OR_NONE),
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def run_certification(rows: int = 900, include_nautilus: bool = False) -> Dict:
|
|
129
|
+
idx, signal, closes, highs, lows, funding = generate_basis_market(rows=rows)
|
|
130
|
+
account = AccountConfig(initial_capital=100_000.0, leverage=8.0, maintenance_ratio=0.005)
|
|
131
|
+
execution = ExecutionConfig(slippage_bps=0.0)
|
|
132
|
+
event = NativeEventBackend(NativeEventConfig(account=account, execution=execution, fee_rate=0.0002, use_funding=True))
|
|
133
|
+
vector = NativeVectorizedBackend(NativeVectorizedConfig(account=account, execution=execution, fee_rate=0.0002, use_funding=True))
|
|
134
|
+
|
|
135
|
+
spec = basis_spec()
|
|
136
|
+
event_result = event.run_basis_arbitrage(idx, spec, signal, closes, highs=highs, lows=lows, funding_rate=funding)
|
|
137
|
+
vector_result = vector.run_basis_arbitrage(idx, spec, signal, closes, highs=highs, lows=lows, funding_rate=funding)
|
|
138
|
+
basis_audit = build_arbitrage_domain_audit(event_result, raise_on_fail=False)
|
|
139
|
+
basis_parity = compare_native_arbitrage_results(event_result, vector_result, raise_on_fail=False)
|
|
140
|
+
|
|
141
|
+
stat_idx, stat_signal, stat_closes, stat_highs, stat_lows, stat_funding = _stat_market(rows=rows)
|
|
142
|
+
stat_event = event.run_stat_arb_pair_arbitrage(stat_idx, stat_spec(), stat_signal, stat_closes, highs=stat_highs, lows=stat_lows, funding_rate=stat_funding)
|
|
143
|
+
stat_vector = vector.run_stat_arb_pair_arbitrage(stat_idx, stat_spec(), stat_signal, stat_closes, highs=stat_highs, lows=stat_lows, funding_rate=stat_funding)
|
|
144
|
+
stat_audit = build_arbitrage_domain_audit(stat_event, raise_on_fail=False)
|
|
145
|
+
stat_parity = compare_native_arbitrage_results(stat_event, stat_vector, raise_on_fail=False)
|
|
146
|
+
|
|
147
|
+
basket_report = _index_basket_smoke(event, vector, rows)
|
|
148
|
+
schema_report = _schema_only_report(event, vector, idx, signal, closes)
|
|
149
|
+
nautilus_report = _optional_nautilus_report(idx, spec, signal, closes, include_nautilus)
|
|
150
|
+
|
|
151
|
+
passed = bool(
|
|
152
|
+
basis_audit["passed"]
|
|
153
|
+
and basis_parity["passed"]
|
|
154
|
+
and _accounting_parity_passed(stat_parity)
|
|
155
|
+
and basket_report["passed"]
|
|
156
|
+
and schema_report["passed"]
|
|
157
|
+
and nautilus_report["status"] in {"pass", "skipped"}
|
|
158
|
+
)
|
|
159
|
+
return {
|
|
160
|
+
"status": "pass" if passed else "fail",
|
|
161
|
+
"sandbox_path": str(PACKAGE_DIR / ".local_arbitrage_sandboxes" / "binance_basis_arb"),
|
|
162
|
+
"basis": _result_summary(event_result, vector_result, basis_audit, basis_parity),
|
|
163
|
+
"stat_pair": {
|
|
164
|
+
"event_final_equity": float(stat_event.equity.iloc[-1]),
|
|
165
|
+
"vectorized_final_equity": float(stat_vector.equity.iloc[-1]),
|
|
166
|
+
"accounting_parity_passed": _accounting_parity_passed(stat_parity),
|
|
167
|
+
"audit": stat_audit,
|
|
168
|
+
"parity": stat_parity,
|
|
169
|
+
"package_report_columns": list(stat_event.metadata["package_pnl_report"].columns),
|
|
170
|
+
"max_package_residual": float(stat_event.metadata["package_pnl_report"]["pnl_residual"].abs().max()),
|
|
171
|
+
},
|
|
172
|
+
"index_basket": basket_report,
|
|
173
|
+
"schema_only": schema_report,
|
|
174
|
+
"nautilus": nautilus_report,
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def make_markdown(report: Dict) -> str:
|
|
179
|
+
basis = report["basis"]
|
|
180
|
+
lines = [
|
|
181
|
+
"# Phase 12A Arbitrage Production Certification",
|
|
182
|
+
"",
|
|
183
|
+
f"Status: **{report['status']}**",
|
|
184
|
+
f"Sandbox path: `{report['sandbox_path']}`",
|
|
185
|
+
"",
|
|
186
|
+
"## Basis Perp-Quarterly",
|
|
187
|
+
"",
|
|
188
|
+
f"- Event final equity: `{basis['event_final_equity']:.6f}`",
|
|
189
|
+
f"- Vectorized final equity: `{basis['vectorized_final_equity']:.6f}`",
|
|
190
|
+
f"- Max equity diff: `{basis['parity']['max_abs_equity_diff']}`",
|
|
191
|
+
f"- Audit status: `{basis['audit']['status']}`",
|
|
192
|
+
f"- Orders: `{basis['order_count']}`",
|
|
193
|
+
f"- Fills: `{basis['fill_count']}`",
|
|
194
|
+
f"- Fees: `{basis['fee_total']:.6f}`",
|
|
195
|
+
f"- Funding: `{basis['funding_total']:.6f}`",
|
|
196
|
+
"",
|
|
197
|
+
"## Other Certification Checks",
|
|
198
|
+
"",
|
|
199
|
+
f"- Stat pair accounting parity: `{report['stat_pair']['accounting_parity_passed']}`",
|
|
200
|
+
f"- Stat pair audit status: `{report['stat_pair']['audit']['status']}`",
|
|
201
|
+
f"- Stat pair package-residual report: `{report['stat_pair']['parity']['checks'].get('package_residuals_ok')}`",
|
|
202
|
+
f"- Stat pair max package residual: `{report['stat_pair']['max_package_residual']}`",
|
|
203
|
+
f"- Index basket package smoke: `{report['index_basket']['status']}`",
|
|
204
|
+
f"- Schema-only guardrails: `{report['schema_only']['status']}`",
|
|
205
|
+
f"- Nautilus package parity: `{report['nautilus']['status']}`",
|
|
206
|
+
]
|
|
207
|
+
return "\n".join(lines) + "\n"
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _stat_market(rows: int):
|
|
211
|
+
idx = pd.date_range("2023-01-01", periods=rows, freq="1h", tz="UTC")
|
|
212
|
+
t = np.linspace(0.0, 12.0, rows)
|
|
213
|
+
a = 100.0 + np.cumsum(np.sin(t) * 0.05 + 0.1)
|
|
214
|
+
b = 50.0 + np.cumsum(np.sin(t + 0.4) * 0.025 + 0.05)
|
|
215
|
+
spread = pd.Series(a - 2.0 * b, index=idx)
|
|
216
|
+
z = (spread - spread.rolling(36, min_periods=12).mean()) / spread.rolling(36, min_periods=12).std()
|
|
217
|
+
signal = pd.Series(np.where(z > 1.0, -1.0, np.where(z < -1.0, 1.0, 0.0)), index=idx).fillna(0.0)
|
|
218
|
+
signal.iloc[-3:] = 0.0
|
|
219
|
+
closes = {"asset_a": pd.Series(a, index=idx), "asset_b": pd.Series(b, index=idx)}
|
|
220
|
+
highs = {s: c * 1.001 for s, c in closes.items()}
|
|
221
|
+
lows = {s: c * 0.999 for s, c in closes.items()}
|
|
222
|
+
funding = {s: pd.Series(0.0, index=idx) for s in closes}
|
|
223
|
+
return idx, signal, closes, highs, lows, funding
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _index_basket_smoke(event: NativeEventBackend, vector: NativeVectorizedBackend, rows: int) -> Dict:
|
|
227
|
+
idx = pd.date_range("2023-01-01", periods=rows, freq="1h", tz="UTC")
|
|
228
|
+
closes = {
|
|
229
|
+
"ETF": pd.Series(100.0 + np.linspace(0.0, 3.0, rows), index=idx),
|
|
230
|
+
"A": pd.Series(30.0 + np.linspace(0.0, 1.0, rows), index=idx),
|
|
231
|
+
"B": pd.Series(70.0 + np.linspace(0.0, 2.0, rows), index=idx),
|
|
232
|
+
}
|
|
233
|
+
signal = pd.Series(0.0, index=idx)
|
|
234
|
+
signal.iloc[20: rows // 2] = 1.0
|
|
235
|
+
signal.iloc[-3:] = 0.0
|
|
236
|
+
spec = IndexBasketArbSpec(
|
|
237
|
+
arb_id="PHASE12_INDEX_BASKET",
|
|
238
|
+
legs=(ArbitrageLeg("ETF", -1.0), ArbitrageLeg("A", 1.0), ArbitrageLeg("B", 1.0)),
|
|
239
|
+
hedge_policy=HedgePolicy(kind=HedgePolicyKind.NOTIONAL_NEUTRAL, freeze_on_entry=True),
|
|
240
|
+
sizing_policy=SizingPolicy(kind=SizingPolicyKind.TARGET_GROSS_NOTIONAL, notional=30_000.0),
|
|
241
|
+
execution_policy=ArbExecutionPolicy(kind=PackageExecutionKind.ATOMIC_ALL_OR_NONE),
|
|
242
|
+
)
|
|
243
|
+
event_result = event.run_package_arbitrage(idx, spec, signal, closes)
|
|
244
|
+
vector_result = vector.run_package_arbitrage(idx, spec, signal, closes)
|
|
245
|
+
parity = compare_native_arbitrage_results(event_result, vector_result, raise_on_fail=False)
|
|
246
|
+
return {"status": "pass" if parity["passed"] else "fail", "passed": bool(parity["passed"]), "parity": parity}
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _schema_only_report(event: NativeEventBackend, vector: NativeVectorizedBackend, idx, signal, closes) -> Dict:
|
|
250
|
+
probes = {}
|
|
251
|
+
specs = {
|
|
252
|
+
"cross_exchange": CrossExchangeArbSpec(
|
|
253
|
+
arb_id="X",
|
|
254
|
+
legs=(
|
|
255
|
+
ArbitrageLeg("BINANCE_BTCUSDT", 1.0, venue="BINANCE"),
|
|
256
|
+
ArbitrageLeg("OKX_BTCUSDT", -1.0, venue="OKX"),
|
|
257
|
+
),
|
|
258
|
+
hedge_policy=HedgePolicy(kind=HedgePolicyKind.NOTIONAL_NEUTRAL),
|
|
259
|
+
sizing_policy=SizingPolicy(kind=SizingPolicyKind.TARGET_GROSS_NOTIONAL, notional=10_000.0),
|
|
260
|
+
),
|
|
261
|
+
"triangular": TriangularArbSpec(
|
|
262
|
+
arb_id="T",
|
|
263
|
+
legs=(
|
|
264
|
+
ArbitrageLeg("BTCUSDT", 1.0, base_currency="BTC", quote_currency="USDT"),
|
|
265
|
+
ArbitrageLeg("ETHBTC", 1.0, base_currency="ETH", quote_currency="BTC"),
|
|
266
|
+
ArbitrageLeg("ETHUSDT", -1.0, base_currency="ETH", quote_currency="USDT"),
|
|
267
|
+
),
|
|
268
|
+
hedge_policy=HedgePolicy(kind=HedgePolicyKind.NOTIONAL_NEUTRAL),
|
|
269
|
+
sizing_policy=SizingPolicy(kind=SizingPolicyKind.TARGET_GROSS_NOTIONAL, notional=10_000.0),
|
|
270
|
+
),
|
|
271
|
+
"options_vol": OptionsVolArbSpec(
|
|
272
|
+
arb_id="O",
|
|
273
|
+
legs=(
|
|
274
|
+
ArbitrageLeg("BTC_CALL", 1.0, contract_type=ContractType.OPTION),
|
|
275
|
+
ArbitrageLeg("BTC_PERP", -0.5, contract_type=ContractType.LINEAR),
|
|
276
|
+
),
|
|
277
|
+
hedge_policy=HedgePolicy(kind=HedgePolicyKind.VEGA_NEUTRAL),
|
|
278
|
+
sizing_policy=SizingPolicy(kind=SizingPolicyKind.TARGET_GROSS_NOTIONAL, notional=10_000.0),
|
|
279
|
+
),
|
|
280
|
+
}
|
|
281
|
+
for name, spec in specs.items():
|
|
282
|
+
backend_rejections = {}
|
|
283
|
+
for backend_name, backend in (("native_event", event), ("native_vectorized", vector)):
|
|
284
|
+
try:
|
|
285
|
+
backend.run_package_arbitrage(idx, spec, signal, closes)
|
|
286
|
+
backend_rejections[backend_name] = {"rejected": False, "error": None}
|
|
287
|
+
except NotImplementedError as exc:
|
|
288
|
+
backend_rejections[backend_name] = {"rejected": True, "error": type(exc).__name__, "message": str(exc)}
|
|
289
|
+
probes[name] = backend_rejections
|
|
290
|
+
passed = all(
|
|
291
|
+
all(route["rejected"] for route in backend_rejections.values())
|
|
292
|
+
for backend_rejections in probes.values()
|
|
293
|
+
)
|
|
294
|
+
return {"status": "pass" if passed else "fail", "passed": passed, "probes": probes}
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _optional_nautilus_report(idx, spec, signal, closes, include_nautilus: bool) -> Dict:
|
|
298
|
+
if not include_nautilus:
|
|
299
|
+
return {"status": "skipped", "reason": "run with --include-nautilus"}
|
|
300
|
+
try:
|
|
301
|
+
from quantbt import QuantBTEndpoint
|
|
302
|
+
from quantbt.adapters.nautilus import NautilusBackendConfig
|
|
303
|
+
|
|
304
|
+
nt_symbols = ("BTCUSDT-PERP.BINANCE", "ETHUSDT-PERP.BINANCE")
|
|
305
|
+
nt_spec = BasisArbitrageSpec(
|
|
306
|
+
arb_id="PHASE12_NAUTILUS_PACKAGE_SMOKE",
|
|
307
|
+
legs=(
|
|
308
|
+
ArbitrageLeg(nt_symbols[0], 1.0, role="perp", contract_type=ContractType.LINEAR),
|
|
309
|
+
ArbitrageLeg(nt_symbols[1], -1.0, role="quarterly", contract_type=ContractType.LINEAR),
|
|
310
|
+
),
|
|
311
|
+
hedge_policy=HedgePolicy(kind=HedgePolicyKind.BASE_QTY_EQUAL, freeze_on_entry=True),
|
|
312
|
+
sizing_policy=SizingPolicy(
|
|
313
|
+
kind=SizingPolicyKind.TARGET_NOTIONAL_TO_BASE_QTY,
|
|
314
|
+
notional=50_000.0,
|
|
315
|
+
reference_symbol=nt_symbols[0],
|
|
316
|
+
),
|
|
317
|
+
execution_policy=ArbExecutionPolicy(kind=PackageExecutionKind.ATOMIC_ALL_OR_NONE),
|
|
318
|
+
metadata={"certification_note": "Nautilus supported-instrument package smoke; not a quarterly venue model."},
|
|
319
|
+
)
|
|
320
|
+
source_series = [closes["perpetual"], closes["quarterly"]]
|
|
321
|
+
data = {
|
|
322
|
+
symbol: pd.DataFrame(
|
|
323
|
+
{
|
|
324
|
+
"open": close,
|
|
325
|
+
"close": close,
|
|
326
|
+
"high": close * 1.001,
|
|
327
|
+
"low": close * 0.999,
|
|
328
|
+
"volume": 10_000.0,
|
|
329
|
+
},
|
|
330
|
+
index=idx,
|
|
331
|
+
)
|
|
332
|
+
for symbol, close in zip(nt_symbols, source_series)
|
|
333
|
+
}
|
|
334
|
+
endpoint = QuantBTEndpoint.arbitrage(
|
|
335
|
+
arb_type="basis",
|
|
336
|
+
spec=nt_spec,
|
|
337
|
+
backend="nautilus",
|
|
338
|
+
initial_capital=100_000.0,
|
|
339
|
+
leverage=8.0,
|
|
340
|
+
fee_rate=0.0002,
|
|
341
|
+
use_funding=False,
|
|
342
|
+
nautilus_config=NautilusBackendConfig(timeframe="1h", instrument_id=nt_symbols[0], bypass_risk=True),
|
|
343
|
+
)
|
|
344
|
+
result = endpoint.simulate(data=data, signal=signal, symbols=list(nt_symbols))
|
|
345
|
+
return {"status": "pass", "orders": int(result.metadata.get("orders_count", 0)), "fills": int(result.metadata.get("fills_count", 0))}
|
|
346
|
+
except Exception as exc:
|
|
347
|
+
return {"status": "skipped", "reason": f"{type(exc).__name__}: {exc}"}
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def _result_summary(event_result, vector_result, audit, parity):
|
|
351
|
+
return {
|
|
352
|
+
"event_final_equity": float(event_result.equity.iloc[-1]),
|
|
353
|
+
"vectorized_final_equity": float(vector_result.equity.iloc[-1]),
|
|
354
|
+
"order_count": int(len(event_result.metadata.get("order_report", []))),
|
|
355
|
+
"fill_count": int(len(event_result.fills)),
|
|
356
|
+
"fee_total": float(event_result.fees.sum()),
|
|
357
|
+
"funding_total": float(event_result.funding.sum()),
|
|
358
|
+
"audit": audit,
|
|
359
|
+
"parity": parity,
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def _accounting_parity_passed(parity: Dict) -> bool:
|
|
364
|
+
checks = parity.get("checks", {})
|
|
365
|
+
return bool(
|
|
366
|
+
checks.get("equity_matches")
|
|
367
|
+
and checks.get("positions_match")
|
|
368
|
+
and checks.get("target_units_match")
|
|
369
|
+
and checks.get("package_residuals_ok")
|
|
370
|
+
)
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def _json_default(value):
|
|
374
|
+
if isinstance(value, (np.bool_,)):
|
|
375
|
+
return bool(value)
|
|
376
|
+
if isinstance(value, (np.integer,)):
|
|
377
|
+
return int(value)
|
|
378
|
+
if isinstance(value, (np.floating,)):
|
|
379
|
+
return float(value)
|
|
380
|
+
if isinstance(value, pd.Timestamp):
|
|
381
|
+
return value.isoformat()
|
|
382
|
+
raise TypeError(f"{type(value).__name__} is not JSON serializable")
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def main(argv: Optional[List[str]] = None) -> int:
|
|
386
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
387
|
+
parser.add_argument("--rows", type=int, default=900)
|
|
388
|
+
parser.add_argument("--include-nautilus", action="store_true")
|
|
389
|
+
parser.add_argument("--json-out", type=Path, default=PACKAGE_DIR / "benchmarks" / "phase12_arbitrage_cert.json")
|
|
390
|
+
parser.add_argument("--md-out", type=Path, default=PACKAGE_DIR / "benchmarks" / "phase12_arbitrage_cert.md")
|
|
391
|
+
args = parser.parse_args(argv)
|
|
392
|
+
report = run_certification(rows=args.rows, include_nautilus=args.include_nautilus)
|
|
393
|
+
args.json_out.parent.mkdir(parents=True, exist_ok=True)
|
|
394
|
+
args.md_out.parent.mkdir(parents=True, exist_ok=True)
|
|
395
|
+
args.json_out.write_text(json.dumps(report, indent=2, default=_json_default) + "\n", encoding="utf-8")
|
|
396
|
+
args.md_out.write_text(make_markdown(report), encoding="utf-8")
|
|
397
|
+
print(make_markdown(report))
|
|
398
|
+
return 0 if report["status"] == "pass" else 1
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
if __name__ == "__main__":
|
|
402
|
+
raise SystemExit(main())
|