statera 1.0.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.
statera/__init__.py ADDED
@@ -0,0 +1,10 @@
1
+ """Statera: research, validation and simulated (paper/replay) execution of rule-based crypto spot strategies.
2
+
3
+ The supported public API is everything listed in ``statera.__all__`` (defined in :mod:`statera.api`).
4
+ """
5
+ __version__ = "1.0.0"
6
+
7
+ from .api import * # noqa: E402,F401,F403
8
+ from .api import __all__ as _api_all # noqa: E402
9
+
10
+ __all__ = ["__version__", *_api_all]
statera/api.py ADDED
@@ -0,0 +1,499 @@
1
+ """Statera public Python API.
2
+
3
+ Everything in ``__all__`` (re-exported from the top-level ``statera`` package) is the supported interface.
4
+ Other modules are internal implementation details and may change without notice.
5
+
6
+ The functions here are thin wrappers over the same engine, research, risk, plan and trader code used by
7
+ the CLI; there is no second implementation of any trading rule.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import logging
13
+ import shutil
14
+ import uuid
15
+ from dataclasses import dataclass, field
16
+ from datetime import datetime, timezone
17
+ from pathlib import Path
18
+ from typing import Callable, Mapping
19
+
20
+ import pandas as pd
21
+
22
+ from .approval import APPROVED, INSUFFICIENT, REJECTED
23
+ from .config import (iso_to_ms, load_config, ms_to_iso, resolve_path, timeframe_ms, utc_now_ms, write_json)
24
+ from .data import (COLUMNS, DataError, MarketData, data_quality_ok, dataset_identity, filter_closed, load_market_data,
25
+ load_market_rules, validate_ohlcv)
26
+ from .engine import CostModel, Engine, ExecParams, MarketRules
27
+ from .indicators import Bars
28
+ from .execution.trader import Trader, TraderError
29
+ from .plan import PlanError, load_plan, validate_plan
30
+ from .risk import check_limits, select_risk, simulate
31
+ from .store import Store
32
+ from .strategies import (Param, Signals, Strategy, available_strategies, load_strategy, register_strategy,
33
+ strategy_fingerprint, unregister_strategy)
34
+
35
+ STATUSES = (APPROVED, REJECTED, INSUFFICIENT)
36
+
37
+ __all__ = [
38
+ # configuration & data
39
+ "load_config", "MarketData", "market_data_from_frame", "load_market_data", "load_market_rules", "DataError",
40
+ "MarketRules", "CostModel", "ExecParams", "COLUMNS",
41
+ # strategies
42
+ "Strategy", "Param", "Signals", "Bars", "register_strategy", "unregister_strategy", "load_strategy",
43
+ "available_strategies", "strategy_fingerprint",
44
+ # backtest / research / risk
45
+ "backtest", "BacktestResult", "research", "ResearchResult", "load_research_result", "analyze_risk",
46
+ "position_size", "PositionSize", "simulate", "check_limits", "select_risk",
47
+ # approval, plans, execution
48
+ "APPROVED", "REJECTED", "INSUFFICIENT", "STATUSES", "load_plan", "validate_plan", "activate_plan", "PlanError",
49
+ "run_replay", "run_paper", "Trader", "TraderError", "Store",
50
+ ]
51
+
52
+ log = logging.getLogger("statera.api")
53
+
54
+
55
+ # ---------------------------------------------------------------------------------------------- helpers
56
+ def _cfg(cfg: dict | None) -> dict:
57
+ return load_config() if cfg is None else cfg
58
+
59
+
60
+ def _open_store(cfg: dict, store: Store | None) -> tuple[Store, bool]:
61
+ return (store, False) if store is not None else (Store(cfg["project"]["state_db"]), True)
62
+
63
+
64
+ def _rules_dict(r) -> dict:
65
+ if isinstance(r, MarketRules):
66
+ return dict(r.__dict__)
67
+ if isinstance(r, Mapping):
68
+ return dict(r)
69
+ raise TypeError(f"market rules must be MarketRules or a mapping, got {type(r).__name__}")
70
+
71
+
72
+ def _rules_loader(cfg: dict, rules) -> Callable[[str], dict]:
73
+ if rules is None:
74
+ return lambda s: load_market_rules(cfg, s)
75
+ if callable(rules) and not isinstance(rules, (MarketRules, Mapping)):
76
+ return lambda s: _rules_dict(rules(s))
77
+ if isinstance(rules, MarketRules) or (isinstance(rules, Mapping) and "amount_step" in rules):
78
+ single = _rules_dict(rules)
79
+ return lambda s: single
80
+ per = {k: _rules_dict(v) for k, v in rules.items()}
81
+
82
+ def get(s):
83
+ if s not in per:
84
+ raise KeyError(f"no market rules supplied for {s}")
85
+ return per[s]
86
+ return get
87
+
88
+
89
+ def market_data_from_frame(df: pd.DataFrame, symbol: str, timeframe: str, cfg: dict | None = None,
90
+ source: str = "user", now_ms: int | None = None) -> MarketData:
91
+ """Wrap caller-supplied OHLCV in a validated MarketData (never forward-filled).
92
+
93
+ ``df`` needs columns open, high, low, close, volume and a candle **open time** either as column ``ts``
94
+ (int UTC milliseconds or timezone-aware datetimes) or as a timezone-aware DatetimeIndex. Candles whose
95
+ close time is after ``now_ms`` (default: now) are dropped as not yet closed. Quality problems are reported
96
+ in ``meta["quality_ok"]`` / ``meta["quality_reasons"]``; research then excludes the market (fail closed).
97
+ Raises DataError for missing columns or naive timestamps.
98
+ """
99
+ cfg = _cfg(cfg)
100
+ tf_ms = timeframe_ms(timeframe)
101
+ d = df.copy()
102
+ if "ts" not in d.columns:
103
+ if not isinstance(d.index, pd.DatetimeIndex):
104
+ raise DataError("OHLCV needs a 'ts' column or a DatetimeIndex (candle open time, UTC)")
105
+ d = d.rename_axis("ts").reset_index()
106
+ missing = [c for c in COLUMNS if c not in d.columns]
107
+ if missing:
108
+ raise DataError(f"OHLCV frame missing columns {missing}")
109
+ if pd.api.types.is_datetime64_any_dtype(d["ts"]):
110
+ if d["ts"].dt.tz is None:
111
+ raise DataError("datetime timestamps must be timezone-aware (UTC); naive times are ambiguous")
112
+ d["ts"] = (d["ts"].dt.tz_convert("UTC") - pd.Timestamp(0, tz="UTC")) // pd.Timedelta(milliseconds=1)
113
+ d = filter_closed(d[COLUMNS].astype({"ts": "int64"}), tf_ms, now_ms or utc_now_ms())
114
+ clean, report = validate_ohlcv(d, tf_ms)
115
+ ok, reasons = data_quality_ok(report, cfg["data"])
116
+ meta = {
117
+ "source": source, "symbol": symbol, "timeframe": timeframe,
118
+ "first_bar": ms_to_iso(int(clean["ts"].iloc[0])) if len(clean) else None,
119
+ "last_bar": ms_to_iso(int(clean["ts"].iloc[-1])) if len(clean) else None,
120
+ "dataset_id": dataset_identity(clean, symbol, timeframe, source) if len(clean) else None,
121
+ "validation": report, "quality_ok": ok, "quality_reasons": reasons,
122
+ "timestamps": "UTC candle open time (ms); only closed candles",
123
+ }
124
+ return MarketData(symbol, timeframe, clean, meta)
125
+
126
+
127
+ def _market_data(cfg, data, symbol, timeframe, offline) -> MarketData:
128
+ if isinstance(data, MarketData):
129
+ return data
130
+ symbol = symbol or cfg["data"]["symbols"][0]
131
+ timeframe = timeframe or cfg["data"]["timeframes"][0]
132
+ if isinstance(data, pd.DataFrame):
133
+ return market_data_from_frame(data, symbol, timeframe, cfg)
134
+ if data is None:
135
+ return load_market_data(cfg, symbol, timeframe, refresh=not offline)
136
+ raise TypeError("data must be MarketData, a pandas DataFrame or None")
137
+
138
+
139
+ def _record_inspection(cfg, store, run_id, m, md, full: bool):
140
+ st, own = _open_store(cfg, store)
141
+ try:
142
+ ts = md.df["ts"]
143
+ if full:
144
+ st.record_holdout_use(run_id, m.symbol, m.tf, md.meta["dataset_id"], int(ts.iloc[m.split]),
145
+ int(ts.iloc[-1]) + m.tf_ms, "manual_backtest")
146
+ else: # a later research holdout overlapping this inspected window is not independent
147
+ st.record_holdout_use(run_id, m.symbol, m.tf, md.meta["dataset_id"], int(ts.iloc[0]),
148
+ int(ts.iloc[m.split - 1]) + m.tf_ms, "manual_dev_backtest")
149
+ finally:
150
+ if own:
151
+ st.close()
152
+
153
+
154
+ def _new_id() -> str:
155
+ return datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") + "_" + uuid.uuid4().hex[:6]
156
+
157
+
158
+ # ---------------------------------------------------------------------------------------------- backtest
159
+ @dataclass(frozen=True)
160
+ class BacktestResult:
161
+ """Outcome of :func:`backtest`. ``report`` is the full metrics dict; ``trades`` one row per closed trade."""
162
+ run_id: str
163
+ strategy: str
164
+ symbol: str
165
+ timeframe: str
166
+ params: dict
167
+ risk_per_trade: float
168
+ segment: str
169
+ period: tuple[str, str]
170
+ report: dict
171
+ trades: pd.DataFrame
172
+ equity: pd.DataFrame
173
+ data_meta: dict
174
+ engine_result: dict = field(repr=False)
175
+
176
+ @property
177
+ def metrics(self) -> dict:
178
+ """Trade statistics: trades, expectancy_R, win_rate, profit_factor, ... (None = undefined)."""
179
+ return self.report["trades"]
180
+
181
+ @property
182
+ def equity_metrics(self) -> dict:
183
+ """MTM equity statistics: total_return, max_drawdown, CAGR, sharpe, sortino, ... (None = undefined)."""
184
+ return self.report["equity"]
185
+
186
+ def to_dict(self) -> dict:
187
+ return {"run_id": self.run_id, "strategy": self.strategy, "symbol": self.symbol, "timeframe": self.timeframe,
188
+ "params": self.params, "risk_per_trade": self.risk_per_trade, "segment": self.segment,
189
+ "period": list(self.period), **self.report, "data": self.data_meta}
190
+
191
+ def save(self, out_dir: str | Path, chart: bool = True) -> Path:
192
+ """Write performance_report.json, trades.csv and (optionally) equity_drawdown.png into ``out_dir``."""
193
+ from .reports import equity_chart, write_trades_csv
194
+
195
+ out = Path(out_dir)
196
+ out.mkdir(parents=True, exist_ok=True)
197
+ rep = dict(self.report)
198
+ rep["meta"] = {"strategy": self.strategy, "params": self.params, "risk_per_trade": self.risk_per_trade,
199
+ "symbol": self.symbol, "timeframe": self.timeframe, "period": list(self.period),
200
+ "includes_holdout": self.segment == "full", "data": self.data_meta}
201
+ write_json(out / "performance_report.json", rep)
202
+ write_trades_csv(out / "trades.csv", {"backtest": self.engine_result["trades"]})
203
+ if chart:
204
+ bt = self.engine_result
205
+ equity_chart(out / "equity_drawdown.png", {"backtest": (bt["ts"], bt["equity"], bt["initial_capital"])},
206
+ f"Backtest {self.strategy} {self.symbol} {self.timeframe}")
207
+ return out
208
+
209
+
210
+ def backtest(strategy, data=None, *, cfg: dict | None = None, symbol: str | None = None, timeframe: str | None = None,
211
+ params: dict | None = None, tp_r: float | None = 2.0, risk_per_trade: float = 0.005, rules=None,
212
+ segment: str = "development", store: Store | None = None, record_usage: bool = True,
213
+ offline: bool = False) -> BacktestResult:
214
+ """Single backtest with the shared engine (next-bar fills, fees, slippage, gaps, MTM equity).
215
+
216
+ strategy: name, Strategy class or instance. data: MarketData, OHLCV DataFrame (needs symbol/timeframe)
217
+ or None (load configured exchange data; ``offline=True`` uses the cache only).
218
+ params: strategy parameters merged over ``strategy.default_params()``; ``tp_r`` is the take-profit
219
+ R-multiple (None = no take profit). segment: "development" (first 1-holdout_fraction of bars, default)
220
+ or "full" (includes the holdout window; recorded as a holdout inspection).
221
+ record_usage: record the inspected window in the state DB holdout registry (default True), so a later
222
+ research holdout overlapping it is flagged as non-independent.
223
+ Raises ValueError for unknown strategies/segments or invalid engine parameters.
224
+ """
225
+ from .metrics import full_report
226
+ from .reports import trades_frame
227
+ from .pipeline import costs_from, evaluate, prepare_market
228
+
229
+ cfg = _cfg(cfg)
230
+ if segment not in ("development", "full"):
231
+ raise ValueError("segment must be 'development' or 'full'")
232
+ strat = load_strategy(strategy, cfg)
233
+ md = _market_data(cfg, data, symbol, timeframe, offline)
234
+ if len(md.df) == 0:
235
+ raise DataError(f"no bars for {md.symbol} {md.timeframe}")
236
+ m = prepare_market(md, _rules_loader(cfg, rules)(md.symbol), cfg)
237
+ p = {**strat.default_params(), **(params or {}), "tp_r": tp_r}
238
+ run_id = _new_id()
239
+ bars, start, end = (Bars(md.df), 0, len(md.df)) if segment == "full" else (m.dev, 0, len(m.dev))
240
+ if end == 0:
241
+ raise DataError("development segment is empty")
242
+ if record_usage:
243
+ _record_inspection(cfg, store, f"backtest_{run_id}", m, md, segment == "full")
244
+ bt = evaluate(strat, bars, start, end, p, cfg, m, risk_per_trade)
245
+ rep = full_report(bt, bars, start, end, costs_from(cfg), m.tf_ms, cfg["research"], cfg["project"]["seed"])
246
+ period = (ms_to_iso(int(bars.ts[start])), ms_to_iso(int(bars.ts[end - 1]) + m.tf_ms))
247
+ eq = pd.DataFrame({"ts": bt["ts"], "equity": bt["equity"], "in_position": bt["in_position"]})
248
+ return BacktestResult(run_id, strat.name, md.symbol, md.timeframe, p, risk_per_trade, segment, period, rep,
249
+ trades_frame(bt["trades"], "backtest"), eq, md.meta, bt)
250
+
251
+
252
+ # ---------------------------------------------------------------------------------------------- research
253
+ @dataclass(frozen=True)
254
+ class ResearchResult:
255
+ """Outcome of :func:`research`. All report files live in ``report_dir``."""
256
+ run_id: str
257
+ decision: str # APPROVED_FOR_PAPER | REJECTED | INSUFFICIENT_DATA
258
+ reasons: list
259
+ selected: dict | None # {"market": "BTC/USDT|15m", "params": {...}} or None
260
+ holdout_facts: dict | None # None when the holdout was not inspected
261
+ report_dir: Path
262
+ plan_path: Path
263
+
264
+ @property
265
+ def approved(self) -> bool:
266
+ return self.decision == APPROVED
267
+
268
+ def _json(self, name: str) -> dict:
269
+ return json.loads((self.report_dir / name).read_text())
270
+
271
+ def plan(self) -> dict:
272
+ return self._json("trading_plan.json")
273
+
274
+ def performance(self) -> dict:
275
+ return self._json("performance_report.json")
276
+
277
+ def validation(self) -> dict:
278
+ return self._json("validation_report.json")
279
+
280
+ def risk(self) -> dict:
281
+ return self._json("risk_report.json")
282
+
283
+ def trials(self) -> pd.DataFrame:
284
+ """Every recorded evaluation (optimisation, sensitivity, stress, risk calibration)."""
285
+ return pd.read_csv(self.report_dir / "optimization_results.csv")
286
+
287
+ def trades(self) -> pd.DataFrame:
288
+ return pd.read_csv(self.report_dir / "trades.csv")
289
+
290
+ def to_dict(self) -> dict:
291
+ return {"run_id": self.run_id, "decision": self.decision, "reasons": list(self.reasons),
292
+ "selected": self.selected, "holdout_facts": self.holdout_facts,
293
+ "report_dir": str(self.report_dir), "plan_path": str(self.plan_path)}
294
+
295
+
296
+ def load_research_result(report_dir: str | Path) -> ResearchResult:
297
+ """Re-open a finished research run from its report directory (reads summary.json)."""
298
+ d = Path(report_dir)
299
+ s = json.loads((d / "summary.json").read_text())
300
+ return ResearchResult(s["run_id"], s["decision"], s["reasons"], s["selected"], s["holdout_facts"], d,
301
+ d / "trading_plan.json")
302
+
303
+
304
+ def research(strategy, *, cfg: dict | None = None, data=None, rules=None, store: Store | None = None,
305
+ symbols: list[str] | None = None, timeframes: list[str] | None = None, offline: bool = False,
306
+ run_dir: str | Path | None = None) -> ResearchResult:
307
+ """Full pipeline: optimisation -> walk-forward -> dev gates -> risk sizing -> freeze -> single holdout test
308
+ -> approval -> versioned plan. Writes reports to ``run_dir`` (default ``<reports_dir>/research_<run_id>``).
309
+
310
+ data: None (configured exchange data), a mapping ``{(symbol, timeframe): MarketData | DataFrame}``, or a
311
+ callable ``(symbol, timeframe) -> MarketData``. With a mapping, symbols/timeframes default to its keys.
312
+ rules: None (exchange metadata), one MarketRules/mapping for all symbols, ``{symbol: rules}``, or a callable.
313
+ store: state DB holding the holdout-usage registry and plan authorisations (default: ``project.state_db``).
314
+ Use one state DB per isolated tenant/session; plans are only executable against the DB that registered them.
315
+ """
316
+ from .pipeline import run_research
317
+
318
+ cfg = _cfg(cfg)
319
+ if data is None:
320
+ loader = lambda s, tf: load_market_data(cfg, s, tf, refresh=not offline) # noqa: E731
321
+ elif callable(data):
322
+ loader = data
323
+ elif isinstance(data, Mapping):
324
+ frames = dict(data)
325
+ if symbols is None:
326
+ symbols = list(dict.fromkeys(k[0] for k in frames))
327
+ if timeframes is None:
328
+ timeframes = list(dict.fromkeys(k[1] for k in frames))
329
+
330
+ def loader(s, tf):
331
+ if (s, tf) not in frames:
332
+ raise KeyError(f"no data supplied for {(s, tf)}")
333
+ v = frames[(s, tf)]
334
+ return v if isinstance(v, MarketData) else market_data_from_frame(v, s, tf, cfg)
335
+ else:
336
+ raise TypeError("data must be None, a {(symbol, timeframe): data} mapping or a callable")
337
+ st, own = _open_store(cfg, store)
338
+ try:
339
+ s = run_research(cfg, strategy, loader, _rules_loader(cfg, rules), st, run_dir=run_dir,
340
+ symbols=symbols, timeframes=timeframes)
341
+ finally:
342
+ if own:
343
+ st.close()
344
+ return ResearchResult(s["run_id"], s["decision"], s["reasons"], s["selected"], s["holdout_facts"],
345
+ Path(s["report_dir"]), Path(s["plan_path"]))
346
+
347
+
348
+ # ---------------------------------------------------------------------------------------------- risk
349
+ def analyze_risk(strategy, data=None, params: dict | None = None, *, cfg: dict | None = None, symbol: str | None = None,
350
+ timeframe: str | None = None, rules=None, store: Store | None = None, record_usage: bool = True,
351
+ offline: bool = False) -> dict:
352
+ """Risk-per-trade calibration on DEVELOPMENT data only, exactly as research does it.
353
+
354
+ Re-runs the engine at each ``risk.risk_per_trade_candidates`` with ``risk.cost_stress_multiplier`` costs,
355
+ block-bootstraps per-trade equity returns (``risk.simulations`` paths, intra-trade MTM included) and
356
+ applies ``risk_limits`` as hard constraints. ``params`` may include ``tp_r``. Returns the risk report dict
357
+ (``selected_risk_per_trade`` is None when no candidate is feasible or expectancy is non-positive).
358
+ Simulated estimates are not guarantees.
359
+ """
360
+ from .pipeline import calibrate_risk, prepare_market
361
+
362
+ cfg = _cfg(cfg)
363
+ strat = load_strategy(strategy, cfg)
364
+ md = _market_data(cfg, data, symbol, timeframe, offline)
365
+ m = prepare_market(md, _rules_loader(cfg, rules)(md.symbol), cfg)
366
+ if len(m.dev) == 0:
367
+ raise DataError("development segment is empty")
368
+ if record_usage:
369
+ _record_inspection(cfg, store, f"risk_{_new_id()}", m, md, False)
370
+ p = {**strat.default_params(), "tp_r": 2.0, **(params or {})}
371
+ return calibrate_risk(strat, m, p, cfg)
372
+
373
+
374
+ @dataclass(frozen=True)
375
+ class PositionSize:
376
+ qty: float
377
+ initial_risk: float # planned net loss at the stop incl. fees and stop slippage (quote ccy)
378
+ skip_reason: str | None # None, "non_positive_risk" or "below_exchange_minimum"
379
+
380
+
381
+ def position_size(entry_price: float, stop_price: float, equity: float, risk_per_trade: float, *,
382
+ cash: float | None = None, cfg: dict | None = None, rules=None) -> PositionSize:
383
+ """Engine sizing rule: qty = equity*risk / (entry - stop_fill + fees), capped by cash, floored to the
384
+ exchange step, zero if below exchange minimums. ``entry_price`` is the expected fill (after slippage)."""
385
+ cfg = _cfg(cfg)
386
+ r = MarketRules.from_dict(_rules_dict(rules)) if rules is not None else MarketRules()
387
+ e = cfg["execution"]
388
+ eng = Engine(CostModel(cfg["costs"]["fee_rate"], cfg["costs"]["slippage_rate"]), r,
389
+ ExecParams(risk_pct=risk_per_trade, max_cash_utilization=e["max_cash_utilization"]),
390
+ 60_000, max(equity, 1e-12))
391
+ eng.cash = float(equity if cash is None else cash)
392
+ return PositionSize(*eng.size(float(entry_price), float(stop_price), float(equity)))
393
+
394
+
395
+ # ---------------------------------------------------------------------------------------------- execution
396
+ def _plan(plan) -> dict:
397
+ return plan if isinstance(plan, dict) else load_plan(plan)
398
+
399
+
400
+ def activate_plan(plan, *, cfg: dict | None = None, store: Store | None = None, strategy=None) -> Path:
401
+ """Validate an APPROVED_FOR_PAPER plan and copy it to ``<plans_dir>/active_plan.json``. Raises PlanError."""
402
+ cfg = _cfg(cfg)
403
+ st, own = _open_store(cfg, store)
404
+ try:
405
+ p = validate_plan(_plan(plan), cfg, st, strategy=strategy)
406
+ finally:
407
+ if own:
408
+ st.close()
409
+ dst = resolve_path(cfg["project"]["plans_dir"]) / "active_plan.json"
410
+ dst.parent.mkdir(parents=True, exist_ok=True)
411
+ if isinstance(plan, dict):
412
+ write_json(dst, p)
413
+ else:
414
+ shutil.copyfile(plan, dst)
415
+ return dst
416
+
417
+
418
+ def _active_or(cfg, plan):
419
+ if plan is not None:
420
+ return _plan(plan)
421
+ p = resolve_path(cfg["project"]["plans_dir"]) / "active_plan.json"
422
+ if not p.exists():
423
+ raise PlanError(f"no plan given and no active plan at {p}")
424
+ return load_plan(p)
425
+
426
+
427
+ def run_replay(plan=None, *, cfg: dict | None = None, data=None, start: str | None = None, max_bars: int | None = None,
428
+ resume: bool = False, store: Store | None = None, strategy=None) -> dict:
429
+ """Replay an approved plan bar-by-bar through the paper trader (same engine, persistence and kill switches).
430
+
431
+ plan: dict, path, or None (active plan). data: OHLCV DataFrame/MarketData, or None (cached exchange CSV).
432
+ start: ISO UTC start (default: the plan's holdout start). resume: continue the previous replay session
433
+ instead of starting fresh. Returns the session status dict. Raises PlanError / TraderError.
434
+ """
435
+ from .execution.feeds import ReplayFeed
436
+
437
+ cfg = _cfg(cfg)
438
+ st, own = _open_store(cfg, store)
439
+ try:
440
+ p = validate_plan(_active_or(cfg, plan), cfg, st, strategy=strategy)
441
+ c = p["config"]
442
+ sid = f"replay-{p['plan_id']}"
443
+ if not resume and st.get_session(sid):
444
+ st.delete_session(sid)
445
+ if data is None:
446
+ cache = resolve_path(cfg["project"]["data_dir"]) / f"{c['exchange']}_{c['symbol'].replace('/', '-')}_{c['timeframe']}.csv"
447
+ if not cache.exists():
448
+ raise DataError(f"no cached data at {cache}; download it first (statera data)")
449
+ df = pd.read_csv(cache, dtype={"ts": "int64"})[COLUMNS]
450
+ else:
451
+ df = data.df if isinstance(data, MarketData) else market_data_from_frame(data, c["symbol"], c["timeframe"], cfg).df
452
+ df, _ = validate_ohlcv(df, timeframe_ms(c["timeframe"]))
453
+ start_iso = start or c["data"].get("holdout_start")
454
+ start_idx = int((df["ts"] < iso_to_ms(start_iso)).sum()) if start_iso else 0
455
+ trader = Trader(p, cfg, st, "replay", sid, switch_plan=True, strategy=strategy)
456
+ return trader.run_replay(ReplayFeed(df, c["timeframe"], start_idx, cfg["trading"]["history_bars"]), max_bars)
457
+ finally:
458
+ if own:
459
+ st.close()
460
+
461
+
462
+ def run_paper(plan=None, *, cfg: dict | None = None, iterations: int | None = None, poll_seconds: float | None = None,
463
+ store: Store | None = None, strategy=None, switch_plan: bool = False, reset_kill_switch: bool = False,
464
+ adapter=None) -> dict:
465
+ """Paper-trade an approved plan on live public candles with simulated fills. Never places real orders.
466
+
467
+ iterations: number of polls (None = until interrupted). adapter: an ExchangeAdapter (default: public
468
+ CCXT market data). An expired plan may only keep managing an existing open paper position. Returns the
469
+ session status dict. Raises PlanError / TraderError.
470
+ """
471
+ from .execution.adapter import CcxtPublicAdapter
472
+ from .execution.feeds import LiveFeed
473
+
474
+ cfg = _cfg(cfg)
475
+ st, own = _open_store(cfg, store)
476
+ try:
477
+ raw = _active_or(cfg, plan)
478
+ try:
479
+ p = validate_plan(raw, cfg, st, strategy=strategy)
480
+ except PlanError as e:
481
+ sess = st.get_session(f"paper-{raw.get('plan_id')}")
482
+ if "expired" in str(e) and sess and (sess["engine_state"] or {}).get("pos"):
483
+ p = validate_plan(raw, cfg, st, allow_expired=True, strategy=strategy) # manage-only
484
+ log.warning("plan expired; managing the open position only (no new entries)")
485
+ else:
486
+ raise
487
+ c = p["config"]
488
+ trader = Trader(p, cfg, st, "paper", switch_plan=switch_plan, strategy=strategy)
489
+ if reset_kill_switch:
490
+ trader.reset_kill_switch()
491
+ adapter = adapter or CcxtPublicAdapter(c["exchange"], cfg["data"]["page_limit"])
492
+ feed = LiveFeed(adapter, c["symbol"], c["timeframe"], cfg["trading"]["history_bars"])
493
+ try:
494
+ return trader.run_paper(feed, iterations, poll_seconds or cfg["trading"]["poll_seconds"])
495
+ except KeyboardInterrupt:
496
+ return trader.status()
497
+ finally:
498
+ if own:
499
+ st.close()
statera/approval.py ADDED
@@ -0,0 +1,71 @@
1
+ """Approval engine. Fails closed.
2
+
3
+ Each check has a category:
4
+ * "data" - data quality, sample size, holdout independence -> INSUFFICIENT_DATA if failing
5
+ * "performance" - expectancy, robustness, stress, risk limits -> REJECTED if failing
6
+ Decision: any failing performance check with a defined value -> REJECTED; else any failing check
7
+ (data, or undefined/None metric) -> INSUFFICIENT_DATA; else APPROVED_FOR_PAPER. None never passes.
8
+ APPROVED_FOR_PAPER authorises simulated trading only.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ APPROVED = "APPROVED_FOR_PAPER"
13
+ REJECTED = "REJECTED"
14
+ INSUFFICIENT = "INSUFFICIENT_DATA"
15
+
16
+
17
+ def check(name: str, value, op: str, threshold, category: str) -> dict:
18
+ if value is None:
19
+ passed = False
20
+ elif op == ">":
21
+ passed = value > threshold
22
+ elif op == ">=":
23
+ passed = value >= threshold
24
+ elif op == "<=":
25
+ passed = value <= threshold
26
+ elif op == "==":
27
+ passed = value == threshold
28
+ else:
29
+ raise ValueError(op)
30
+ return {"name": name, "value": value, "op": op, "threshold": threshold, "category": category, "passed": bool(passed)}
31
+
32
+
33
+ def decide(checks: list[dict]) -> tuple[str, list[str]]:
34
+ failed = [c for c in checks if not c["passed"]]
35
+ reasons = [f"{c['name']}: {c['value']!r} not {c['op']} {c['threshold']!r} [{c['category']}]" for c in failed]
36
+ # an undefined (None) metric is missing evidence, not a measured failure
37
+ if any(c["category"] == "performance" and c["value"] is not None for c in failed):
38
+ return REJECTED, reasons
39
+ if failed:
40
+ return INSUFFICIENT, reasons
41
+ if not checks:
42
+ return INSUFFICIENT, ["no checks evaluated"]
43
+ notes = [c["note"] for c in checks if c.get("note")]
44
+ return APPROVED, ["all approval checks passed (paper trading only; not evidence of future profitability)"] + notes
45
+
46
+
47
+ def dev_gate_checks(g: dict, a: dict) -> list[dict]:
48
+ return [
49
+ check("dev_expectancy_R", g.get("dev_expectancy_R"), ">=", a["min_dev_expectancy_R"], "performance"),
50
+ check("dev_positive_fold_fraction", g.get("positive_fold_fraction"), ">=", a["min_positive_fold_fraction"], "performance"),
51
+ check("walk_forward_oos_expectancy_R", g.get("wf_oos_expectancy_R"), ">", a["min_wf_oos_expectancy_R"], "performance"),
52
+ check("sensitivity_positive_fraction", g.get("sensitivity_positive_fraction"), ">=", a["min_sensitivity_positive_fraction"], "performance"),
53
+ check("dev_cost_stress_expectancy_R", g.get("dev_cost_stress_expectancy_R"), ">", a["min_dev_stress_expectancy_R"], "performance"),
54
+ check("dev_delay_stress_expectancy_R", g.get("dev_delay_stress_expectancy_R"), ">", a["min_dev_stress_expectancy_R"], "performance"),
55
+ ]
56
+
57
+
58
+ def holdout_checks(h: dict, a: dict, limits: dict) -> list[dict]:
59
+ return [
60
+ (check("holdout_independent", h.get("holdout_independent"), "==", True, "data")
61
+ if not a.get("allow_reused_holdout", False) or h.get("holdout_independent") else
62
+ {"name": "holdout_reuse_override", "value": False, "op": "==", "threshold": True, "category": "override",
63
+ "passed": True, "note": "holdout REUSED (override enabled): not fresh out-of-sample evidence"}),
64
+ check("holdout_trades", h.get("trades"), ">=", a["min_holdout_trades"], "data"),
65
+ check("holdout_expectancy_R", h.get("expectancy_R"), ">", a["min_holdout_expectancy_R"], "performance"),
66
+ check("holdout_expectancy_ci_low_R", h.get("ci_low_R"), ">=", a["min_holdout_ci_low_R"], "performance"),
67
+ check("holdout_max_drawdown", h.get("max_drawdown"), "<=", a["max_holdout_drawdown"], "performance"),
68
+ check("holdout_cost_stress_expectancy_R", h.get("cost_stress_expectancy_R"), ">", a["min_holdout_cost_stress_expectancy_R"], "performance"),
69
+ check("holdout_delay_stress_expectancy_R", h.get("delay_stress_expectancy_R"), ">", a["min_holdout_delay_stress_expectancy_R"], "performance"),
70
+ check("risk_per_trade_within_limit", h.get("risk_per_trade"), "<=", limits["max_risk_per_trade"], "performance"),
71
+ ]