uracle-oracle 0.1.2__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.
- historical_backtest.py +392 -0
- self_evolving_oracle.py +646 -0
- uracle_features/__init__.py +21 -0
- uracle_features/arbitrage.py +319 -0
- uracle_features/cli.py +155 -0
- uracle_features/common.py +704 -0
- uracle_features/copy_trading.py +241 -0
- uracle_features/hedging.py +326 -0
- uracle_features/line_movement.py +265 -0
- uracle_features/portfolio.py +395 -0
- uracle_features/props.py +360 -0
- uracle_features/sentiment.py +367 -0
- uracle_features/settlement.py +315 -0
- uracle_features/triggers.py +245 -0
- uracle_features/whale.py +479 -0
- uracle_features/workflow.py +427 -0
- uracle_modules/__init__.py +20 -0
- uracle_modules/bootstrap.py +99 -0
- uracle_modules/conformal.py +123 -0
- uracle_modules/drawdown.py +143 -0
- uracle_modules/drift.py +141 -0
- uracle_modules/ensemble.py +148 -0
- uracle_modules/liquidity.py +99 -0
- uracle_modules/pipeline.py +258 -0
- uracle_modules/regime.py +107 -0
- uracle_modules/replay.py +167 -0
- uracle_modules/shadow.py +126 -0
- uracle_modules/tail_risk.py +115 -0
- uracle_oracle-0.1.2.dist-info/METADATA +194 -0
- uracle_oracle-0.1.2.dist-info/RECORD +33 -0
- uracle_oracle-0.1.2.dist-info/WHEEL +5 -0
- uracle_oracle-0.1.2.dist-info/entry_points.txt +3 -0
- uracle_oracle-0.1.2.dist-info/top_level.txt +4 -0
historical_backtest.py
ADDED
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
"""Research backtests on daily OHLC price bars, with a one-session signal gap.
|
|
2
|
+
|
|
3
|
+
No market-data connection or orders. An order is hypothetically fixed after an
|
|
4
|
+
older close and fully filled at a future day's open, then closed at its close.
|
|
5
|
+
Only intraday (open-to-close) asset returns drive learning and forecasts.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import csv
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from datetime import date, datetime
|
|
13
|
+
import hashlib
|
|
14
|
+
import json
|
|
15
|
+
import math
|
|
16
|
+
import platform
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
import sys
|
|
19
|
+
from typing import Any, Sequence, TYPE_CHECKING
|
|
20
|
+
|
|
21
|
+
import numpy as np
|
|
22
|
+
|
|
23
|
+
if TYPE_CHECKING:
|
|
24
|
+
from self_evolving_oracle import SelfEvolvingOracle
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True)
|
|
28
|
+
class Bar:
|
|
29
|
+
date: date
|
|
30
|
+
open: float
|
|
31
|
+
close: float
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _positive_int(name: str, value: int, minimum: int = 1) -> int:
|
|
35
|
+
if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, np.integer)) or value < minimum:
|
|
36
|
+
raise ValueError(f"{name} must be an integer >= {minimum}")
|
|
37
|
+
return int(value)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _validated_bars(bars: Sequence[Bar]) -> list[Bar]:
|
|
41
|
+
try:
|
|
42
|
+
bars = list(bars)
|
|
43
|
+
except TypeError as exc:
|
|
44
|
+
raise ValueError("bars must be an iterable of Bar objects") from exc
|
|
45
|
+
previous = None
|
|
46
|
+
normalized = []
|
|
47
|
+
for i, b in enumerate(bars):
|
|
48
|
+
if not isinstance(b, Bar) or not isinstance(b.date, date) or isinstance(b.date, datetime):
|
|
49
|
+
raise ValueError(f"bar {i} must be a Bar with a date (not datetime)")
|
|
50
|
+
if isinstance(b.open, (bool, np.bool_)) or isinstance(b.close, (bool, np.bool_)):
|
|
51
|
+
raise ValueError(f"bar {i} has invalid prices")
|
|
52
|
+
try:
|
|
53
|
+
op, cl = float(b.open), float(b.close)
|
|
54
|
+
except (TypeError, ValueError, OverflowError) as exc:
|
|
55
|
+
raise ValueError(f"bar {i} has invalid prices") from exc
|
|
56
|
+
if not np.isfinite([op, cl]).all() or op <= 0 or cl <= 0:
|
|
57
|
+
raise ValueError(f"bar {i} requires finite, strictly positive open and close")
|
|
58
|
+
if previous is not None and b.date <= previous:
|
|
59
|
+
raise ValueError("bar dates must be strictly increasing and unique")
|
|
60
|
+
with np.errstate(over='ignore', divide='ignore', invalid='ignore'):
|
|
61
|
+
r = np.float64(cl) / np.float64(op) - 1.0
|
|
62
|
+
if not np.isfinite(r) or r <= -1:
|
|
63
|
+
raise ValueError(f"bar {i} has an invalid open-to-close return")
|
|
64
|
+
previous = b.date
|
|
65
|
+
normalized.append(Bar(b.date, op, cl))
|
|
66
|
+
return normalized
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def load_bars(path: str | Path) -> list[Bar]:
|
|
70
|
+
"""Read a CSV with Date, Open, Close columns. Dates must be ISO YYYY-MM-DD.
|
|
71
|
+
|
|
72
|
+
Fail on malformed rows, missing prices, duplicates, or unsorted dates;
|
|
73
|
+
never forward fill. This does not verify exchange calendars, tradability,
|
|
74
|
+
adjustment basis, or whether a provider revised its historical records.
|
|
75
|
+
"""
|
|
76
|
+
bars: list[Bar] = []
|
|
77
|
+
with Path(path).open(newline='', encoding='utf-8-sig') as f:
|
|
78
|
+
reader = csv.DictReader(f)
|
|
79
|
+
if not reader.fieldnames:
|
|
80
|
+
raise ValueError("CSV needs a header")
|
|
81
|
+
normalized = [x.strip().lower() if x is not None else '' for x in reader.fieldnames]
|
|
82
|
+
if len(set(normalized)) != len(normalized):
|
|
83
|
+
raise ValueError("CSV has duplicate column names")
|
|
84
|
+
columns = dict(zip(normalized, reader.fieldnames))
|
|
85
|
+
if not {'date', 'open', 'close'}.issubset(columns):
|
|
86
|
+
raise ValueError("CSV needs Date, Open, and Close columns")
|
|
87
|
+
for line, row in enumerate(reader, start=2):
|
|
88
|
+
try:
|
|
89
|
+
if None in row:
|
|
90
|
+
raise ValueError('row has too many columns')
|
|
91
|
+
text_date = row[columns['date']].strip()
|
|
92
|
+
if len(text_date) != 10:
|
|
93
|
+
raise ValueError("date must use YYYY-MM-DD")
|
|
94
|
+
dt = date.fromisoformat(text_date)
|
|
95
|
+
if dt.isoformat() != text_date:
|
|
96
|
+
raise ValueError("date must use YYYY-MM-DD")
|
|
97
|
+
op = float(row[columns['open']])
|
|
98
|
+
cl = float(row[columns['close']])
|
|
99
|
+
except (ValueError, TypeError, AttributeError, KeyError) as exc:
|
|
100
|
+
raise ValueError(f"invalid data on CSV line {line}") from exc
|
|
101
|
+
bars.append(Bar(dt, op, cl))
|
|
102
|
+
if not bars:
|
|
103
|
+
raise ValueError("CSV contains no data rows")
|
|
104
|
+
return _validated_bars(bars)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
@dataclass
|
|
108
|
+
class BacktestResult:
|
|
109
|
+
daily: list[dict[str, Any]]
|
|
110
|
+
summary: dict[str, Any]
|
|
111
|
+
|
|
112
|
+
def write_daily_csv(self, path: str | Path) -> None:
|
|
113
|
+
with Path(path).open('w', newline='', encoding='utf-8') as f:
|
|
114
|
+
writer = csv.DictWriter(f, fieldnames=list(self.daily[0]))
|
|
115
|
+
writer.writeheader()
|
|
116
|
+
writer.writerows(self.daily)
|
|
117
|
+
|
|
118
|
+
def write_summary_json(self, path: str | Path) -> None:
|
|
119
|
+
with Path(path).open('w', encoding='utf-8') as f:
|
|
120
|
+
json.dump(self.summary, f, indent=2, allow_nan=False)
|
|
121
|
+
f.write('\n')
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _performance(returns: list[float], dates: list[str], ppy: int) -> dict[str, Any]:
|
|
125
|
+
x = np.asarray(returns, dtype=float)
|
|
126
|
+
wealth = np.concatenate(([1.0], np.cumprod(1.0 + x)))
|
|
127
|
+
running_peak = np.maximum.accumulate(wealth)
|
|
128
|
+
drawdowns = wealth / running_peak - 1.0
|
|
129
|
+
trough = int(np.argmin(drawdowns))
|
|
130
|
+
max_dd = float(drawdowns[trough])
|
|
131
|
+
peak_date = trough_date = recovery_date = None
|
|
132
|
+
if max_dd < 0:
|
|
133
|
+
peak = int(np.argmax(wealth[:trough + 1]))
|
|
134
|
+
peak_date = dates[max(0, peak - 1)]
|
|
135
|
+
trough_date = dates[trough - 1]
|
|
136
|
+
recovery = np.flatnonzero(wealth[trough + 1:] >= wealth[peak])
|
|
137
|
+
if recovery.size:
|
|
138
|
+
recovery_date = dates[trough + int(recovery[0])]
|
|
139
|
+
vol = float(np.std(x, ddof=1) * np.sqrt(ppy)) if len(x) >= 2 else None
|
|
140
|
+
sharpe = float(np.mean(x) / np.std(x, ddof=1) * np.sqrt(ppy)) if len(x) >= 2 and np.std(x, ddof=1) > 0 else None
|
|
141
|
+
days = (date.fromisoformat(dates[-1]) - date.fromisoformat(dates[0])).days
|
|
142
|
+
cagr = float(np.expm1(np.log(wealth[-1]) * 365.0 / days)) if days > 0 and wealth[-1] > 0 else None
|
|
143
|
+
return {"total_return": float(wealth[-1] - 1.0), "cagr_calendar_365": cagr,
|
|
144
|
+
"annualized_volatility": vol, "sharpe_zero_rf": sharpe,
|
|
145
|
+
"max_drawdown": max_dd, "drawdown_peak_date": peak_date,
|
|
146
|
+
"drawdown_trough_date": trough_date, "drawdown_recovery_date": recovery_date}
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def run_backtest(oracle: SelfEvolvingOracle, bars: Sequence[Bar], *,
|
|
150
|
+
training_sessions: int = 252, embargo_sessions: int = 1,
|
|
151
|
+
min_history: int = 20, lookback: int = 60,
|
|
152
|
+
signal_lag_sessions: int = 2, periods_per_year: int = 252) -> BacktestResult:
|
|
153
|
+
"""Run a nonoverlapping, chronological, online-learning backtest.
|
|
154
|
+
|
|
155
|
+
A decision for session i uses history only through close i-L, L>=2. It is
|
|
156
|
+
assumed to fill its chosen dollar notional at i's open and exit at i's
|
|
157
|
+
close, then it learns from that outcome. With one pending decision allowed,
|
|
158
|
+
the next opportunity is no sooner than i+L. Thus a full session lies
|
|
159
|
+
between the signal close and entry, and returns in that gap are unavailable
|
|
160
|
+
to that decision. The split has a separate embargo of >=1 sessions.
|
|
161
|
+
The test phase continues updating online; it is not a frozen-policy test.
|
|
162
|
+
The input object's equity and learned state are updated in place.
|
|
163
|
+
"""
|
|
164
|
+
bars = _validated_bars(bars)
|
|
165
|
+
training_sessions = _positive_int('training_sessions', training_sessions)
|
|
166
|
+
embargo_sessions = _positive_int('embargo_sessions', embargo_sessions)
|
|
167
|
+
min_history = _positive_int('min_history', min_history, 2)
|
|
168
|
+
lookback = _positive_int('lookback', lookback, min_history)
|
|
169
|
+
signal_lag_sessions = _positive_int('signal_lag_sessions', signal_lag_sessions, 2)
|
|
170
|
+
periods_per_year = _positive_int('periods_per_year', periods_per_year)
|
|
171
|
+
if lookback > 60:
|
|
172
|
+
raise ValueError('lookback must be <= 60, matching oracle state handling')
|
|
173
|
+
if training_sessions < min_history + signal_lag_sessions:
|
|
174
|
+
raise ValueError('training_sessions must allow a completed training decision')
|
|
175
|
+
eval_start_idx = training_sessions + embargo_sessions
|
|
176
|
+
if eval_start_idx >= len(bars):
|
|
177
|
+
raise ValueError('bars must include at least one post-embargo evaluation session')
|
|
178
|
+
if getattr(oracle, '_pending', None) is not None:
|
|
179
|
+
raise RuntimeError('oracle has an unresolved decision')
|
|
180
|
+
if not np.isfinite(oracle.capital) or oracle.capital <= 0:
|
|
181
|
+
raise ValueError('oracle capital must be positive and finite')
|
|
182
|
+
dt = 1.0 / periods_per_year
|
|
183
|
+
if not 1e-12 <= dt <= 10:
|
|
184
|
+
raise ValueError('periods_per_year implies an unsupported horizon')
|
|
185
|
+
|
|
186
|
+
price_returns = np.array([float(b.close / b.open - 1.0) for b in bars], dtype=float)
|
|
187
|
+
initial_equity = float(oracle.capital)
|
|
188
|
+
next_opportunity = min_history - 1 + signal_lag_sessions
|
|
189
|
+
pipeline = getattr(oracle, 'research_pipeline', None)
|
|
190
|
+
c = oracle.transaction_cost_rate
|
|
191
|
+
baseline_fraction = min(oracle.core.risk_tolerance, (1.0 - 1e-9) / (1.0 + c))
|
|
192
|
+
baseline_wealth = 1.0
|
|
193
|
+
eval_initial_equity = None
|
|
194
|
+
rows: list[dict[str, Any]] = []
|
|
195
|
+
for i, b in enumerate(bars):
|
|
196
|
+
if i < min_history:
|
|
197
|
+
phase = 'history'
|
|
198
|
+
elif i < training_sessions:
|
|
199
|
+
phase = 'training'
|
|
200
|
+
elif i < eval_start_idx:
|
|
201
|
+
phase = 'embargo'
|
|
202
|
+
else:
|
|
203
|
+
phase = 'evaluation'
|
|
204
|
+
if eval_initial_equity is None:
|
|
205
|
+
eval_initial_equity = float(oracle.capital)
|
|
206
|
+
|
|
207
|
+
signal_date = action = decision_id = asset_return = projected_profit = actual_profit = None
|
|
208
|
+
exploratory = None
|
|
209
|
+
market_mu_before = market_sigma_before = decision_mu = decision_sigma = None
|
|
210
|
+
allocation = strategy_return = baseline_return = 0.0
|
|
211
|
+
decision_diagnostics = None
|
|
212
|
+
decision_cost = None
|
|
213
|
+
if i >= next_opportunity and phase in ('training', 'evaluation'):
|
|
214
|
+
cutoff = i - signal_lag_sessions
|
|
215
|
+
history = price_returns[max(0, cutoff + 1 - lookback):cutoff + 1]
|
|
216
|
+
signal_date = bars[cutoff].date.isoformat()
|
|
217
|
+
market_mu_before, market_sigma_before = float(oracle.mu), float(oracle.sigma)
|
|
218
|
+
# This call cannot read the current open/close or gap-session return.
|
|
219
|
+
d = oracle.decide(history, horizon_years=dt)
|
|
220
|
+
decision_mu, decision_sigma = float(d.mu), float(d.sigma)
|
|
221
|
+
decision_diagnostics, decision_cost = d.diagnostics, d.cost_rate_per_side
|
|
222
|
+
asset_return = float(price_returns[i])
|
|
223
|
+
outcome = oracle.observe(d.decision_id, asset_return)
|
|
224
|
+
decision_id, action, exploratory = d.decision_id, d.action, d.exploratory
|
|
225
|
+
allocation, projected_profit = d.allocation, d.projected_profit
|
|
226
|
+
strategy_return, actual_profit = outcome.actual_net_return, outcome.actual_profit
|
|
227
|
+
if phase == 'evaluation':
|
|
228
|
+
baseline_return = baseline_fraction * ((1.0 - c) * asset_return - 2.0*c)
|
|
229
|
+
next_opportunity = i + signal_lag_sessions
|
|
230
|
+
if phase == 'evaluation':
|
|
231
|
+
baseline_wealth *= 1.0 + baseline_return
|
|
232
|
+
rows.append({
|
|
233
|
+
'date': b.date.isoformat(), 'phase': phase, 'signal_date': signal_date,
|
|
234
|
+
'decision_id': decision_id, 'action': action, 'exploratory': exploratory,
|
|
235
|
+
'open': float(b.open), 'close': float(b.close), 'asset_return': asset_return,
|
|
236
|
+
'allocation': float(allocation), 'projected_profit': projected_profit,
|
|
237
|
+
'actual_profit': actual_profit, 'strategy_return': float(strategy_return),
|
|
238
|
+
'equity': float(oracle.capital), 'baseline_intraday_return': float(baseline_return),
|
|
239
|
+
'baseline_intraday_equity_factor': float(baseline_wealth),
|
|
240
|
+
'market_mu_before': market_mu_before, 'market_sigma_before': market_sigma_before,
|
|
241
|
+
'decision_mu': decision_mu, 'decision_sigma': decision_sigma,
|
|
242
|
+
'mu_after': float(oracle.mu), 'sigma_after': float(oracle.sigma),
|
|
243
|
+
})
|
|
244
|
+
if pipeline is not None:
|
|
245
|
+
rows[-1].update({
|
|
246
|
+
'decision_cost_rate_per_side': decision_cost,
|
|
247
|
+
'regime_label': decision_diagnostics['regime']['label'] if decision_diagnostics else None,
|
|
248
|
+
'scenario_expected_shortfall': decision_diagnostics['tail_risk']['expected_shortfall'] if decision_diagnostics else None,
|
|
249
|
+
'research_diagnostics_json': json.dumps(decision_diagnostics, sort_keys=True, allow_nan=False) if decision_diagnostics else None,
|
|
250
|
+
})
|
|
251
|
+
|
|
252
|
+
evaluation = rows[eval_start_idx:]
|
|
253
|
+
dates = [r['date'] for r in evaluation]
|
|
254
|
+
strat = _performance([r['strategy_return'] for r in evaluation], dates, periods_per_year)
|
|
255
|
+
baseline = _performance([r['baseline_intraday_return'] for r in evaluation], dates, periods_per_year)
|
|
256
|
+
trades = [r for r in evaluation if r['decision_id'] is not None and r['allocation'] > 0]
|
|
257
|
+
opportunities = [r for r in evaluation if r['decision_id'] is not None]
|
|
258
|
+
if not math.isclose(strat['total_return'], float(oracle.capital / eval_initial_equity - 1.0), rel_tol=1e-9, abs_tol=1e-9):
|
|
259
|
+
raise ArithmeticError('equity and compounded evaluation returns do not reconcile')
|
|
260
|
+
|
|
261
|
+
# Price-only benchmark: buy at first evaluation open and sell at final close.
|
|
262
|
+
# No dividend, split, financing or corporate-action ledger is implied.
|
|
263
|
+
hold_f = (1.0 - 1e-9) / (1.0 + c)
|
|
264
|
+
hold_r = float(bars[-1].close / bars[eval_start_idx].open - 1.0)
|
|
265
|
+
hold_net = hold_f * ((1.0 - c) * hold_r - 2.0*c)
|
|
266
|
+
summary = {
|
|
267
|
+
'training_sessions': training_sessions, 'embargo_sessions': embargo_sessions,
|
|
268
|
+
'evaluation_sessions': len(evaluation), 'evaluation_start': dates[0],
|
|
269
|
+
'evaluation_end': dates[-1], 'lookback': lookback, 'min_history': min_history,
|
|
270
|
+
'signal_lag_sessions': signal_lag_sessions, 'periods_per_year': periods_per_year,
|
|
271
|
+
'transaction_cost_rate_per_side': c, 'initial_capital': initial_equity,
|
|
272
|
+
'evaluation_initial_capital': eval_initial_equity, 'ending_capital': float(oracle.capital),
|
|
273
|
+
'training_total_return': float(eval_initial_equity / initial_equity - 1.0),
|
|
274
|
+
'evaluation_total_return': strat['total_return'],
|
|
275
|
+
'baseline_intraday_total_return': baseline['total_return'],
|
|
276
|
+
'buy_and_hold_price_only_total_return': float(hold_net),
|
|
277
|
+
'cash_total_return': 0.0, 'total_trades': len(trades),
|
|
278
|
+
'evaluation_opportunities': len(opportunities),
|
|
279
|
+
'winning_trade_fraction': float(sum(r['actual_profit'] > 0 for r in trades) / len(trades)) if trades else None,
|
|
280
|
+
'average_invested_fraction_all_sessions': float(np.mean([r['allocation'] for r in evaluation])),
|
|
281
|
+
'max_drawdown': strat['max_drawdown'], 'strategy_metrics': strat,
|
|
282
|
+
'baseline_intraday_metrics': baseline, 'baseline_intraday_allocation': baseline_fraction,
|
|
283
|
+
'baseline_intraday_average_invested_fraction_all_sessions': float(baseline_fraction * len(opportunities) / len(evaluation)),
|
|
284
|
+
'execution': 'signal after earlier close; full same-day open-to-close notional fills; flat overnight',
|
|
285
|
+
'evaluation_mode': 'out-of-sample chronological evaluation with online learning',
|
|
286
|
+
'calibration_mode': 'unperturbed_market_baseline_v2',
|
|
287
|
+
'effective_learning_rates': {'alpha_mu': oracle.alpha_mu, 'alpha_q': oracle.alpha_q, 'beta': oracle.beta},
|
|
288
|
+
'limitations': 'research-only; prices are not executable quotes; no volume, halts, dividends, corporate actions, taxes or market-impact model',
|
|
289
|
+
}
|
|
290
|
+
if pipeline is not None:
|
|
291
|
+
summary['research_pipeline'] = pipeline.summary()
|
|
292
|
+
summary['benchmark_cost_note'] = 'benchmarks use base fees only; enhanced strategy also pays configurable liquidity stress'
|
|
293
|
+
summary['limitations'] += '; enhanced costs are configurable proxies, not measured liquidity or fills'
|
|
294
|
+
return BacktestResult(rows, summary)
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def main() -> None:
|
|
298
|
+
from self_evolving_oracle import SelfEvolvingOracle
|
|
299
|
+
parser = argparse.ArgumentParser(description='Run a research-only daily-bar oracle backtest.')
|
|
300
|
+
parser.add_argument('csv_path', type=Path, help='CSV with Date, Open, Close columns')
|
|
301
|
+
parser.add_argument('--output-dir', type=Path, default=Path('backtest_output'))
|
|
302
|
+
parser.add_argument('--training-sessions', type=int, default=252)
|
|
303
|
+
parser.add_argument('--embargo-sessions', type=int, default=1)
|
|
304
|
+
parser.add_argument('--min-history', type=int, default=20)
|
|
305
|
+
parser.add_argument('--lookback', type=int, default=60)
|
|
306
|
+
parser.add_argument('--signal-lag-sessions', type=int, default=2)
|
|
307
|
+
parser.add_argument('--periods-per-year', type=int, default=252)
|
|
308
|
+
parser.add_argument('--capital', type=float, default=100_000)
|
|
309
|
+
parser.add_argument('--risk-tolerance', type=float, default=0.25)
|
|
310
|
+
parser.add_argument('--mu', type=float, default=0.10)
|
|
311
|
+
parser.add_argument('--sigma', type=float, default=0.20)
|
|
312
|
+
parser.add_argument('--alpha', type=float, default=0.02, help='legacy shared rate and fallback')
|
|
313
|
+
parser.add_argument('--alpha-mu', type=float, default=None, help='drift learning rate; defaults to --alpha')
|
|
314
|
+
parser.add_argument('--alpha-q', type=float, default=None, help='Q learning rate; defaults to --alpha')
|
|
315
|
+
parser.add_argument('--beta', type=float, default=0.02)
|
|
316
|
+
parser.add_argument('--epsilon', type=float, default=0.10)
|
|
317
|
+
parser.add_argument('--cost-bps-per-side', type=float, default=3.0)
|
|
318
|
+
parser.add_argument('--n-simulations', type=int, default=2000)
|
|
319
|
+
parser.add_argument('--seed', type=int, default=42)
|
|
320
|
+
parser.add_argument('--enhanced', action='store_true', help='enable all ten optional research modules')
|
|
321
|
+
parser.add_argument('--module-config', type=Path, help='JSON object of module constructor parameters; requires --enhanced')
|
|
322
|
+
parser.add_argument('--checkpoint-in', type=Path, help='restore model state as initialization, not a dataset/cursor resume')
|
|
323
|
+
parser.add_argument('--checkpoint-out', type=Path, help='save final complete model state as tamper-evident JSON')
|
|
324
|
+
args = parser.parse_args()
|
|
325
|
+
if args.module_config and not args.enhanced:
|
|
326
|
+
parser.error('--module-config requires --enhanced')
|
|
327
|
+
model_options = {'--capital', '--risk-tolerance', '--mu', '--sigma', '--alpha', '--alpha-mu',
|
|
328
|
+
'--alpha-q', '--beta', '--epsilon', '--cost-bps-per-side', '--n-simulations', '--seed'}
|
|
329
|
+
explicitly_supplied = {token.split('=', 1)[0] for token in sys.argv[1:]}
|
|
330
|
+
if args.checkpoint_in and (args.enhanced or args.module_config or explicitly_supplied & model_options):
|
|
331
|
+
parser.error('--checkpoint-in restores model configuration; do not combine it with model overrides or --enhanced')
|
|
332
|
+
bars = load_bars(args.csv_path)
|
|
333
|
+
if args.checkpoint_in:
|
|
334
|
+
oracle = SelfEvolvingOracle.load_checkpoint(args.checkpoint_in)
|
|
335
|
+
else:
|
|
336
|
+
research_pipeline = None
|
|
337
|
+
if args.enhanced:
|
|
338
|
+
from uracle_modules.pipeline import ResearchPipeline, load_module_config
|
|
339
|
+
module_config = load_module_config(args.module_config) if args.module_config else None
|
|
340
|
+
research_pipeline = ResearchPipeline.for_capital(args.capital, seed=args.seed, config=module_config)
|
|
341
|
+
oracle = SelfEvolvingOracle(args.capital, risk_tolerance=args.risk_tolerance,
|
|
342
|
+
mu=args.mu, sigma=args.sigma, alpha=args.alpha, beta=args.beta,
|
|
343
|
+
alpha_mu=args.alpha_mu, alpha_q=args.alpha_q,
|
|
344
|
+
epsilon=args.epsilon, transaction_cost_rate=args.cost_bps_per_side/10_000,
|
|
345
|
+
n_simulations=args.n_simulations, seed=args.seed,
|
|
346
|
+
research_pipeline=research_pipeline)
|
|
347
|
+
initial_model_config = oracle.state_dict()['config']
|
|
348
|
+
initial_model_sha256 = hashlib.sha256(json.dumps(oracle.state_dict(), sort_keys=True, allow_nan=False).encode()).hexdigest()
|
|
349
|
+
result = run_backtest(oracle, bars, training_sessions=args.training_sessions,
|
|
350
|
+
embargo_sessions=args.embargo_sessions, min_history=args.min_history,
|
|
351
|
+
lookback=args.lookback, signal_lag_sessions=args.signal_lag_sessions,
|
|
352
|
+
periods_per_year=args.periods_per_year)
|
|
353
|
+
result.summary['input_file'] = str(args.csv_path)
|
|
354
|
+
result.summary['input_sha256'] = hashlib.sha256(args.csv_path.read_bytes()).hexdigest()
|
|
355
|
+
source_file = Path(__file__).with_name('self_evolving_oracle.py')
|
|
356
|
+
result.summary['implementation'] = {
|
|
357
|
+
'calibration': 'unperturbed_market_baseline_v2',
|
|
358
|
+
'oracle_source_sha256': hashlib.sha256(source_file.read_bytes()).hexdigest(),
|
|
359
|
+
'python_version': platform.python_version(), 'numpy_version': np.__version__,
|
|
360
|
+
'rng_bit_generator': type(oracle.core.rng.bit_generator).__name__,
|
|
361
|
+
'rng_streams': 'shared core policy/simulation; separate research stream' if oracle.research_pipeline else 'shared policy and simulation stream',
|
|
362
|
+
'initial_model_state_sha256': initial_model_sha256,
|
|
363
|
+
'checkpoint_in': str(args.checkpoint_in) if args.checkpoint_in else None,
|
|
364
|
+
'note': 'checkpoint input initializes a new backtest; it does not resume an input dataset cursor',
|
|
365
|
+
}
|
|
366
|
+
if oracle.research_pipeline is not None:
|
|
367
|
+
module_dir = Path(__file__).with_name('uracle_modules')
|
|
368
|
+
result.summary['implementation']['module_source_sha256'] = {
|
|
369
|
+
p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted(module_dir.glob('*.py'))}
|
|
370
|
+
result.summary['module_config'] = oracle.research_pipeline.config
|
|
371
|
+
if args.checkpoint_in:
|
|
372
|
+
result.summary['model_config'] = initial_model_config
|
|
373
|
+
else:
|
|
374
|
+
result.summary['model_config'] = {
|
|
375
|
+
'risk_tolerance': initial_model_config['risk_tolerance'],
|
|
376
|
+
'mu_initial': initial_model_config['mu'], 'sigma_initial': initial_model_config['sigma'],
|
|
377
|
+
'alpha': initial_model_config['alpha'], 'beta': initial_model_config['beta'],
|
|
378
|
+
'alpha_mu': initial_model_config['alpha_mu'], 'alpha_q': initial_model_config['alpha_q'],
|
|
379
|
+
'epsilon': initial_model_config['epsilon'], 'mu_step': initial_model_config['mu_step'],
|
|
380
|
+
'sigma_log_step': initial_model_config['sigma_log_step'],
|
|
381
|
+
'n_simulations': initial_model_config['n_simulations'], 'seed': args.seed,
|
|
382
|
+
}
|
|
383
|
+
args.output_dir.mkdir(parents=True, exist_ok=True)
|
|
384
|
+
result.write_daily_csv(args.output_dir/'daily.csv')
|
|
385
|
+
result.write_summary_json(args.output_dir/'summary.json')
|
|
386
|
+
if args.checkpoint_out:
|
|
387
|
+
oracle.save_checkpoint(args.checkpoint_out)
|
|
388
|
+
print(json.dumps(result.summary, indent=2, allow_nan=False))
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
if __name__ == '__main__':
|
|
392
|
+
main()
|