From 6fe9b3ce7449c310472c022412cb9054ea0d3115 Mon Sep 17 00:00:00 2001 From: ZhuLinsen Date: Sun, 22 Nov 2026 14:16:29 +0800 Subject: [PATCH] fix: harden shadow ledger, execution rules, portfolio accounting, and allocator --- src/alphaevo/backtest/allocator.py | 225 ++- src/alphaevo/backtest/engine.py | 189 ++- src/alphaevo/backtest/portfolio.py | 99 +- src/alphaevo/backtest/rules.py | 106 +- src/alphaevo/cli/commands/rsi.py | 21 +- src/alphaevo/forward/contracts.py | 15 +- src/alphaevo/forward/shadow_ledger.py | 1381 ++++++++++++----- ...ound2_to_6_quant_shadow_portfolio_rigor.py | 875 +++++++++++ 8 files changed, 2392 insertions(+), 519 deletions(-) create mode 100644 tests/unit/test_round2_to_6_quant_shadow_portfolio_rigor.py diff --git a/src/alphaevo/backtest/allocator.py b/src/alphaevo/backtest/allocator.py index 50964fa..87a995f 100644 --- a/src/alphaevo/backtest/allocator.py +++ b/src/alphaevo/backtest/allocator.py @@ -127,32 +127,38 @@ def _series_metrics(daily_returns: Sequence[float]) -> tuple[float, float, float def _apply_weight_cap(weights: list[float], cap: float) -> list[float]: - """Cap weights while preserving as much total unit budget as the cap allows.""" + """Cap weights cleanly, conserving budget across active strategies without reviving inactive ones.""" n = len(weights) if n == 0: return [] - if n * cap <= 1.0 + 1e-12: - return [min(w, cap) for w in weights] - out = list(weights) + if not any(w > cap + 1e-12 for w in out): + return out + + pool = 0.0 + for i in range(n): + if out[i] > cap + 1e-12: + pool += out[i] - cap + out[i] = cap + for _ in range(n): - over = [i for i, w in enumerate(out) if w > cap + 1e-12] - if not over: + if pool <= 1e-12: break - excess = sum(out[i] - cap for i in over) - for i in over: - out[i] = cap - under = [i for i, w in enumerate(out) if w < cap - 1e-12] - if not under: + under_active = [i for i, w in enumerate(out) if 1e-12 < w < cap - 1e-12] + if not under_active: break - under_total = sum(out[i] for i in under) + under_total = sum(out[i] for i in under_active) if under_total <= 0: - share = excess / len(under) - for i in under: - out[i] = min(cap, out[i] + share) - else: - for i in under: - out[i] = min(cap, out[i] + excess * (out[i] / under_total)) + break + used = 0.0 + for i in under_active: + room = max(0.0, cap - out[i]) + add = min(room, pool * (out[i] / under_total)) + out[i] += add + used += add + if used <= 1e-12: + break + pool -= used return out @@ -169,31 +175,79 @@ def _build_causal_market_proxy( cnt_ret = [0] * n_days sum_hi_ratio = [0.0] * n_days sum_lo_ratio = [0.0] * n_days + sum_co_ratio = [0.0] * n_days cnt_hl = [0] * n_days + cnt_co = [0] * n_days for df in market_data.values(): if df is None or df.empty or "date" not in df.columns or "close" not in df.columns: continue - pairs: list[tuple[date, float, float, float]] = [] + by_date: dict[date, tuple[float, float, float, float | None]] = {} + has_open = "open" in df.columns + has_high = "high" in df.columns + has_low = "low" in df.columns for idx in range(len(df)): - raw_d = pd.Timestamp(df["date"].iloc[idx]).date() - c_v = float(df["close"].iloc[idx]) - h_v = float(df["high"].iloc[idx]) if "high" in df.columns else c_v - l_v = float(df["low"].iloc[idx]) if "low" in df.columns else c_v - if c_v > 0: - pairs.append((raw_d, c_v, h_v, l_v)) - pairs.sort(key=lambda item: item[0]) - for pos, (bar_d, c_v, h_v, l_v) in enumerate(pairs): + ts = pd.to_datetime(df["date"].iloc[idx], errors="coerce") + if pd.isna(ts): + continue + bar_d = ts.date() + try: + c_v = float(df["close"].iloc[idx]) + except (TypeError, ValueError): + continue + if not (math.isfinite(c_v) and c_v > 0): + continue + o_v: float | None = None + if has_open: + try: + raw_o = float(df["open"].iloc[idx]) + if math.isfinite(raw_o) and raw_o > 0: + o_v = raw_o + except (TypeError, ValueError): + pass + h_v = c_v + l_v = c_v + if has_high: + try: + raw_h = float(df["high"].iloc[idx]) + if math.isfinite(raw_h) and raw_h > 0: + h_v = max(raw_h, c_v) + except (TypeError, ValueError): + pass + if has_low: + try: + raw_l = float(df["low"].iloc[idx]) + if math.isfinite(raw_l) and raw_l > 0: + l_v = min(raw_l, c_v) + except (TypeError, ValueError): + pass + by_date[bar_d] = (c_v, h_v, l_v, o_v) + + sorted_bars = sorted(by_date.items(), key=lambda item: item[0]) + prev_t_idx: int | None = None + prev_close: float | None = None + for bar_d, (c_v, h_v, l_v, o_v) in sorted_bars: t_idx = date_index.get(bar_d) if t_idx is None: continue sum_hi_ratio[t_idx] += h_v / c_v sum_lo_ratio[t_idx] += l_v / c_v cnt_hl[t_idx] += 1 - if pos > 0 and pairs[pos - 1][1] > 0: - sum_ret[t_idx] += (c_v / pairs[pos - 1][1]) - 1.0 + if o_v is not None and o_v > 0: + sum_co_ratio[t_idx] += c_v / o_v + cnt_co[t_idx] += 1 + if ( + prev_t_idx is not None + and prev_t_idx == t_idx - 1 + and prev_close is not None + and prev_close > 0 + ): + sum_ret[t_idx] += (c_v / prev_close) - 1.0 cnt_ret[t_idx] += 1 + prev_t_idx = t_idx + prev_close = c_v + opens: list[float] = [] closes: list[float] = [] highs: list[float] = [] lows: list[float] = [] @@ -201,22 +255,27 @@ def _build_causal_market_proxy( for t in range(n_days): if cnt_ret[t] > 0: level *= max(0.01, 1.0 + sum_ret[t] / cnt_ret[t]) + co_r = (sum_co_ratio[t] / cnt_co[t]) if cnt_co[t] > 0 else 1.0 + open_t = level / max(0.01, co_r) hi_r = (sum_hi_ratio[t] / cnt_hl[t]) if cnt_hl[t] > 0 else 1.0 lo_r = (sum_lo_ratio[t] / cnt_hl[t]) if cnt_hl[t] > 0 else 1.0 + opens.append(open_t) closes.append(level) - highs.append(level * hi_r) - lows.append(level * lo_r) + highs.append(max(level * hi_r, open_t)) + lows.append(min(level * lo_r, open_t)) return cast( "pd.DataFrame", pd.DataFrame( { "date": all_dates, - "open": closes, + "open": opens, "high": highs, "low": lows, "close": closes, "volume": [1_000_000.0] * n_days, + "observed_count": cnt_hl, + "return_count": cnt_ret, } ), ) @@ -274,21 +333,85 @@ def allocate( sampling_method=SamplingMethod.REPRESENTATIVE, ) - from alphaevo.evaluator.metrics import Evaluator + close_lookup: dict[str, tuple[list[date], list[float]]] = {} + for sym, df in market_data.items(): + if df is None or df.empty or "date" not in df.columns or "close" not in df.columns: + continue + sym_pairs: dict[date, float] = {} + for idx in range(len(df)): + ts = pd.to_datetime(df["date"].iloc[idx], errors="coerce") + if pd.isna(ts): + continue + try: + c_v = float(df["close"].iloc[idx]) + except (TypeError, ValueError): + continue + if math.isfinite(c_v) and c_v > 0: + sym_pairs[ts.date()] = c_v + if sym_pairs: + s_items = sorted(sym_pairs.items(), key=lambda it: it[0]) + close_lookup[sym] = ([it[0] for it in s_items], [it[1] for it in s_items]) strat_rets: list[list[float]] = [] standalone_stats: list[tuple[float, float, float, int]] = [] for strat in strategies: bt = bt_engine.run(strat, market_data, batch) executed = [s for s in bt.signals if s.exit_price is not None] - cal, rets, _act, _dd, _sh, _tot = Evaluator.compute_daily_mtm_series( - executed, market_data - ) - ret_by_date = dict(zip(cal, rets, strict=True)) if cal else {} + open_sigs = [s for s in bt.signals if s.exit_price is None] + # Aggregate EVERY position uniformly per-position per day so appending later + # open positions never alters earlier historical returns. + from bisect import bisect_left, bisect_right + + day_pos: dict[date, list[float]] = {} + for sig in executed: + if sig.symbol not in close_lookup or sig.entry_price <= 0: + continue + s_dates, s_closes = close_lookup[sig.symbol] + end_d = sig.exit_date or sig.signal_date + if end_d <= sig.signal_date: + day_pos.setdefault(end_d, []).append(float(sig.return_pct)) + continue + lo = bisect_left(s_dates, sig.signal_date) + hi = bisect_right(s_dates, end_d) + entry_p = float(sig.entry_price) + prev_mark = entry_p + target_end = entry_p * (1.0 + float(sig.return_pct)) + booked_exit = False + for pos in range(lo, hi): + bar_d = s_dates[pos] + close_p = s_closes[pos] + if bar_d == end_d: + bar_ret = (target_end / prev_mark) - 1.0 if prev_mark > 0 else 0.0 + booked_exit = True + elif prev_mark > 0: + bar_ret = (close_p / prev_mark) - 1.0 + prev_mark = close_p + else: + bar_ret = 0.0 + day_pos.setdefault(bar_d, []).append(bar_ret) + if not booked_exit: + day_pos.setdefault(end_d, []).append( + (target_end / prev_mark) - 1.0 if prev_mark > 0 else float(sig.return_pct) + ) + + for sig in open_sigs: + if sig.symbol not in close_lookup or sig.entry_price <= 0: + continue + s_dates, s_closes = close_lookup[sig.symbol] + prev_mark = float(sig.entry_price) + for bar_d, close_p in zip(s_dates, s_closes, strict=True): + if bar_d < sig.signal_date: + continue + bar_ret = (close_p / prev_mark) - 1.0 if prev_mark > 0 else 0.0 + prev_mark = close_p + day_pos.setdefault(bar_d, []).append(bar_ret) + + ret_by_date = {d: sum(vals) / len(vals) for d, vals in day_pos.items() if vals} + aligned = [float(ret_by_date.get(d, 0.0)) for d in all_dates] strat_rets.append(aligned) st_tot, st_dd, st_sh = _series_metrics(aligned) - standalone_stats.append((st_tot, st_sh, st_dd, len(executed))) + standalone_stats.append((st_tot, st_sh, st_dd, len(bt.signals))) cfg = self.config n_strats = len(strategies) @@ -311,14 +434,19 @@ def allocate( causal_regime: MarketRegime = regimes[t - 1] if t > 0 else regimes[0] regime_counts[regimes[t].value] += 1 + hists = [strat_rets[i][win_start:t] for i in range(n_strats)] + active_flags = [ + len(hists[i]) >= 2 and sum(1 for v in hists[i] if abs(v) > 1e-12) >= 2 + for i in range(n_strats) + ] + any_active = any(active_flags) + raw_scores: list[float] = [] for i in range(n_strats): - hist = strat_rets[i][win_start:t] - non_zero = sum(1 for v in hist if abs(v) > 1e-12) - if len(hist) >= 2 and non_zero >= 2: - vol_i = max(cfg.vol_floor, stdev(hist)) - else: - vol_i = cfg.vol_floor + if any_active and not active_flags[i]: + raw_scores.append(0.0) + continue + vol_i = max(cfg.vol_floor, stdev(hists[i])) if active_flags[i] else cfg.vol_floor score_i = 1.0 / vol_i pref = strategies[i].meta.preferred_regime if pref: @@ -330,14 +458,17 @@ def allocate( if n_strats > 1 and (t - win_start) >= 5: penalized = list(raw_scores) for i in range(n_strats): + if raw_scores[i] <= 0.0: + continue pos_rhos: list[float] = [] for j in range(n_strats): - if i == j: + if i == j or raw_scores[j] <= 0.0: continue rho = _pearson(strat_rets[i][win_start:t], strat_rets[j][win_start:t]) pos_rhos.append(max(0.0, rho)) - mean_pos = sum(pos_rhos) / len(pos_rhos) - penalized[i] /= 1.0 + cfg.correlation_penalty_strength * mean_pos + if pos_rhos: + mean_pos = sum(pos_rhos) / len(pos_rhos) + penalized[i] /= 1.0 + cfg.correlation_penalty_strength * mean_pos raw_scores = penalized total_score = sum(raw_scores) diff --git a/src/alphaevo/backtest/engine.py b/src/alphaevo/backtest/engine.py index 641701f..912cd71 100644 --- a/src/alphaevo/backtest/engine.py +++ b/src/alphaevo/backtest/engine.py @@ -87,6 +87,9 @@ def __init__( self._rule_checker_supports_meta = ( "symbol" in inspect.signature(self.rule_checker.can_buy).parameters ) + self._rule_checker_supports_price = ( + "price_col" in inspect.signature(self.rule_checker.can_buy).parameters + ) self._regime_cache: dict[tuple[int, int], MarketRegime | None] = {} self._regime_series_cache: dict[int, tuple[list[date] | None, list[MarketRegime]]] = {} @@ -178,7 +181,21 @@ def _can_buy( symbol: str, stock_name: str, is_st: bool | None, + *, + price_col: str = "close", + price: float | None = None, ) -> bool: + if self._rule_checker_supports_meta and self._rule_checker_supports_price: + return self.rule_checker.can_buy( + df, + idx, + rules, + symbol=symbol, + stock_name=stock_name, + is_st=is_st, + price_col=price_col, + price=price, + ) if self._rule_checker_supports_meta: return self.rule_checker.can_buy( df, @@ -199,7 +216,22 @@ def _can_sell( symbol: str, stock_name: str, is_st: bool | None, + *, + price_col: str = "close", + price: float | None = None, ) -> bool: + if self._rule_checker_supports_meta and self._rule_checker_supports_price: + return self.rule_checker.can_sell( + df, + idx, + entry_idx, + rules, + symbol=symbol, + stock_name=stock_name, + is_st=is_st, + price_col=price_col, + price=price, + ) if self._rule_checker_supports_meta: return self.rule_checker.can_sell( df, @@ -252,13 +284,26 @@ def _run_symbol( for idx in range(start_idx, len(df)): # ── Holding a position: check exit ── if position is not None: - if not self._can_sell( + if rules and rules.t_plus_1 and idx <= position.entry_idx: + continue + if rules and rules.suspension and _row_is_suspended(df, idx): + continue + if not (rules and rules.limit_up_down) and not self._can_sell( df, idx, position.entry_idx, rules, symbol, stock_name, is_st ): continue - exit_result = self._check_exit( - position, strategy, df, idx, ctx, precomputed=precomputed + exit_result = self._check_exit_with_rules( + position=position, + strategy=strategy, + df=df, + idx=idx, + ctx=ctx, + rules=rules, + symbol=symbol, + stock_name=stock_name, + is_st=is_st, + precomputed=precomputed, ) if exit_result is not None: reason, exit_price = exit_result @@ -316,12 +361,45 @@ def _run_symbol( precomputed=precomputed, ) - # Force close any remaining position at end + # Force close remaining position at end if permitted; else preserve unclosed TradeSignal if position is not None: - signal = self._close_position( - position, df, len(df) - 1, df["close"].iloc[-1], ExitReason.MAX_HOLD, slippage - ) - signals.append(signal) + last_idx = len(df) - 1 + if self._can_sell( + df, + last_idx, + position.entry_idx, + rules, + symbol, + stock_name, + is_st, + price_col="close", + ): + signal = self._close_position( + position, + df, + last_idx, + float(df["close"].iloc[-1]), + ExitReason.MAX_HOLD, + slippage, + ) + signals.append(signal) + else: + signals.append( + TradeSignal( + symbol=position.symbol, + signal_date=position.entry_date, + direction=SignalDirection.LONG, + entry_price=position.entry_price, + exit_price=None, + exit_date=None, + exit_reason=None, + return_pct=0.0, + holding_days=max(0, last_idx - position.entry_idx), + regime=position.regime, + sector=position.sector, + indicator_snapshot=position.indicator_snapshot or {}, + ) + ) return signals @@ -361,8 +439,17 @@ def _open_position( entry_idx = signal_idx + 1 entry_price = float(df["open"].iloc[entry_idx]) - # Enforce market rules on the actual entry bar - if rules is not None and not self._can_buy(df, entry_idx, rules, symbol, stock_name, is_st): + # Enforce market rules on the actual entry bar using execution price column + entry_price_col = "close" if timing == "close" else "open" + if rules is not None and not self._can_buy( + df, + entry_idx, + rules, + symbol, + stock_name, + is_st, + price_col=entry_price_col, + ): return None # Apply slippage (buy slightly higher) @@ -388,6 +475,80 @@ def _open_position( entry_atr=entry_atr, ) + def _check_exit_with_rules( + self, + *, + position: _Position, + strategy: Strategy, + df: pd.DataFrame, + idx: int, + ctx: IndicatorContext | None, + rules: MarketRuleConfig, + symbol: str, + stock_name: str, + is_st: bool | None, + precomputed: dict[str, list[IndicatorValue]] | None = None, + ) -> tuple[ExitReason, float] | None: + """Select highest-priority exit whose fill price complies with market rules.""" + exit_cfg = strategy.exit + current_price = float(df["close"].iloc[idx]) + holding_days = idx - position.entry_idx + + def _sellable(res: tuple[ExitReason, float] | None) -> bool: + if res is None: + return False + reason, px = res + sell_px = None if reason in {ExitReason.MAX_HOLD, ExitReason.SIGNAL} else px + return self._can_sell( + df, + idx, + position.entry_idx, + rules, + symbol, + stock_name, + is_st, + price_col="close", + price=sell_px, + ) + + # 1. Max holding days (at close) + if holding_days >= exit_cfg.max_holding_days and _sellable( + (ExitReason.MAX_HOLD, current_price) + ): + return (ExitReason.MAX_HOLD, current_price) + + # 2 & 3. Intraday stop-loss vs take-profit (fallback to the sellable leg if one is limit-locked) + stop_result = self._check_stop_loss( + position, strategy, df, idx, ctx, precomputed=precomputed + ) + take_profit_result = self._check_take_profit(position, strategy, df, idx, ctx) + stop_ok = _sellable(stop_result) + tp_ok = _sellable(take_profit_result) + if stop_ok and tp_ok: + assert stop_result is not None and take_profit_result is not None + return self._resolve_intrabar_conflict( + stop_result, + take_profit_result, + position, + current_price, + ) + if stop_ok: + return stop_result + if tp_ok: + return take_profit_result + + # 4. Explicit exit triggers (close execution) + for trigger in exit_cfg.triggers: + hit = ( + self.evaluator.evaluate_condition(trigger, df, idx, ctx, precomputed=precomputed) + if self._cond_supports_precomputed + else self.evaluator.evaluate_condition(trigger, df, idx, ctx) + ) + if hit and _sellable((ExitReason.SIGNAL, current_price)): + return (ExitReason.SIGNAL, current_price) + + return None + def _check_exit( self, position: _Position, @@ -878,6 +1039,14 @@ def _indicator_warmup(indicator_names: list[str]) -> int: return max(30, max_period + buffer) +def _row_is_suspended(df: pd.DataFrame, idx: int) -> bool: + """Return True when row *idx* has explicit zero trading volume.""" + if "volume" not in df.columns: + return False + val = df["volume"].iloc[idx] + return val is not None and pd.notna(val) and float(val) == 0.0 + + def _normalize_fill_policy(fill_policy: str) -> FillPolicy: normalized = _FILL_POLICY_ALIASES.get(fill_policy.strip().lower(), fill_policy.strip().lower()) if normalized not in {"conservative", "optimistic", "close_first"}: diff --git a/src/alphaevo/backtest/portfolio.py b/src/alphaevo/backtest/portfolio.py index 018a5e6..4df6216 100644 --- a/src/alphaevo/backtest/portfolio.py +++ b/src/alphaevo/backtest/portfolio.py @@ -103,9 +103,15 @@ def simulate( cash = cfg.initial_capital equity = cfg.initial_capital - # Sort signals chronologically by entry date + close_map = _build_close_map(market_data) + + # Include closed trades AND unclosed terminal holds that have daily MTM data signals = sorted( - [s for s in backtest_result.signals if s.exit_price is not None], + [ + s + for s in backtest_result.signals + if s.exit_price is not None or (close_map and s.symbol in close_map) + ], key=lambda s: (s.signal_date, s.symbol), ) @@ -119,10 +125,9 @@ def simulate( open_positions: list[tuple[TradeSignal, float, float]] = [] # (signal, shares, allocated) equity_curve: list[PortfolioSnapshot] = [] max_concurrent = 0 - total_capital_days = 0.0 + total_capital_util = 0.0 total_days = 0 - close_map = _build_close_map(market_data) event_dates: set[date] = {s.signal_date for s in signals} for s in signals: ex = _resolve_exit_date(s) @@ -133,18 +138,22 @@ def simulate( if close_map: for sym_dates, _ in close_map.values(): for d in sym_dates: - if min_d <= d <= max_d: + if d >= min_d: event_dates.add(d) + max_d = max(max_d, d) all_dates = sorted(event_dates) signal_idx = 0 for current_date in all_dates: - # Close positions that have reached or passed their exit date - still_open: list[tuple[TradeSignal, float, float]] = [] + # 1. Size today's morning/open entries using start-of-day equity and prior cash + start_of_day_equity = equity + + # Close any stale positions whose exit date strictly preceded current_date + stale_open: list[tuple[TradeSignal, float, float]] = [] for sig, shares, allocated in open_positions: exit_date = _resolve_exit_date(sig) - if exit_date is not None and exit_date <= current_date: + if exit_date is not None and exit_date < current_date: pnl_pct = sig.return_pct pnl = allocated * pnl_pct cash += allocated + pnl @@ -158,16 +167,10 @@ def simulate( ) ) else: - still_open.append((sig, shares, allocated)) - open_positions = still_open - - # Recompute current mark-to-market equity before sizing new entries - equity = cash + sum( - _mark_to_market(sig, shares, current_date, close_map=close_map) - for sig, shares, _alloc in open_positions - ) + stale_open.append((sig, shares, allocated)) + open_positions = stale_open - # Open new positions from today's signals + # 2. Open new positions BEFORE crediting today's exit proceeds or today's close MTM while signal_idx < len(signals) and signals[signal_idx].signal_date == current_date: sig = signals[signal_idx] signal_idx += 1 @@ -176,8 +179,8 @@ def simulate( continue # Skip — position limit reached allocation = min( - cash * cfg.position_size_pct, - equity * cfg.position_size_pct, + cash, + start_of_day_equity * cfg.position_size_pct, ) if allocation < sig.entry_price or sig.entry_price <= 0: continue # Not enough capital @@ -188,6 +191,28 @@ def simulate( max_concurrent = max(max_concurrent, len(open_positions)) + # 3. Close positions that reach their exit date at today's close/exit + still_open: list[tuple[TradeSignal, float, float]] = [] + for sig, shares, allocated in open_positions: + exit_date = _resolve_exit_date(sig) + if exit_date is not None and exit_date <= current_date: + pnl_pct = sig.return_pct + pnl = allocated * pnl_pct + cash += allocated + pnl + portfolio_trades.append( + PortfolioTrade( + signal=sig, + shares=shares, + capital_allocated=allocated, + pnl=pnl, + pnl_pct=pnl_pct, + ) + ) + else: + still_open.append((sig, shares, allocated)) + open_positions = still_open + + # 4. Compute end-of-day mark-to-market equity invested_mtm = 0.0 for sig, shares, _alloc in open_positions: invested_mtm += _mark_to_market(sig, shares, current_date, close_map=close_map) @@ -206,12 +231,20 @@ def simulate( ) ) - total_capital_days += len(open_positions) * cfg.position_size_pct + day_util = (invested_mtm / current_equity) if current_equity > 0 else 0.0 + total_capital_util += max(0.0, min(1.0, day_util)) total_days += 1 - # Close any remaining positions at their net trade returns + # Close or mark any remaining positions at final equity + end_mark_date = all_dates[-1] for sig, shares, allocated in open_positions: - pnl = allocated * sig.return_pct + if sig.exit_price is None and close_map and sig.symbol in close_map: + final_val = _mark_to_market(sig, shares, end_mark_date, close_map=close_map) + pnl = final_val - allocated + pnl_pct = (pnl / allocated) if allocated > 0 else 0.0 + else: + pnl_pct = sig.return_pct + pnl = allocated * pnl_pct cash += allocated + pnl portfolio_trades.append( PortfolioTrade( @@ -219,17 +252,15 @@ def simulate( shares=shares, capital_allocated=allocated, pnl=pnl, - pnl_pct=sig.return_pct, + pnl_pct=pnl_pct, ) ) final_equity = cash total_return = (final_equity / cfg.initial_capital - 1) if cfg.initial_capital > 0 else 0.0 - max_dd = _compute_max_drawdown(equity_curve) + max_dd = _compute_max_drawdown(equity_curve, initial_capital=cfg.initial_capital) sharpe = _compute_portfolio_sharpe(equity_curve) - cap_util = ( - (total_capital_days / (total_days * cfg.max_positions)) if total_days > 0 else 0.0 - ) + cap_util = (total_capital_util / total_days) if total_days > 0 else 0.0 return PortfolioResult( config=cfg, @@ -269,7 +300,9 @@ def _build_close_map( def _resolve_exit_date(signal: TradeSignal) -> date | None: - """Prefer actual realized exit_date over weekend-only estimate.""" + """Prefer actual realized exit_date; return None for still-open signals.""" + if signal.exit_price is None: + return None return signal.exit_date or _estimate_exit_date(signal) @@ -320,11 +353,15 @@ def _estimate_exit_date(signal: TradeSignal) -> date | None: return current -def _compute_max_drawdown(curve: list[PortfolioSnapshot]) -> float: - """Compute maximum drawdown from equity curve.""" +def _compute_max_drawdown( + curve: list[PortfolioSnapshot], + *, + initial_capital: float | None = None, +) -> float: + """Compute maximum drawdown from equity curve, anchored to initial_capital when provided.""" if not curve: return 0.0 - peak = curve[0].equity + peak = max(initial_capital, curve[0].equity) if initial_capital is not None else curve[0].equity max_dd = 0.0 for snap in curve: if snap.equity > peak: diff --git a/src/alphaevo/backtest/rules.py b/src/alphaevo/backtest/rules.py index d7e10b3..9e667fa 100644 --- a/src/alphaevo/backtest/rules.py +++ b/src/alphaevo/backtest/rules.py @@ -27,21 +27,30 @@ def can_buy( symbol: str = "", stock_name: str = "", is_st: bool | None = None, + price_col: str = "close", + price: float | None = None, ) -> bool: """Check if buying is allowed on this bar.""" if not rules: return True row = df.iloc[idx] + prev_close = _resolve_prev_close(df, idx, row) # Limit-up: can't buy at limit-up (price already ceiling) if rules.limit_up_down and self._is_limit_up( - row, symbol=symbol, stock_name=stock_name, is_st=is_st + row, + symbol=symbol, + stock_name=stock_name, + is_st=is_st, + prev_close=prev_close, + price_col=price_col, + price=price, ): return False - # Suspension: volume == 0 means suspended - return not (rules.suspension and _get(row, "volume", 0) == 0) + # Suspension: explicit volume == 0 means suspended + return not (rules.suspension and _is_zero_volume(row)) def can_sell( self, @@ -53,6 +62,8 @@ def can_sell( symbol: str = "", stock_name: str = "", is_st: bool | None = None, + price_col: str = "close", + price: float | None = None, ) -> bool: """Check if selling is allowed on this bar.""" if not rules: @@ -64,14 +75,22 @@ def can_sell( if rules.t_plus_1 and idx <= entry_idx: return False + prev_close = _resolve_prev_close(df, idx, row) + # Limit-down: can't sell at limit-down if rules.limit_up_down and self._is_limit_down( - row, symbol=symbol, stock_name=stock_name, is_st=is_st + row, + symbol=symbol, + stock_name=stock_name, + is_st=is_st, + prev_close=prev_close, + price_col=price_col, + price=price, ): return False # Suspension - return not (rules.suspension and _get(row, "volume", 0) == 0) + return not (rules.suspension and _is_zero_volume(row)) @staticmethod def _is_limit_up( @@ -80,18 +99,26 @@ def _is_limit_up( symbol: str = "", stock_name: str = "", is_st: bool | None = None, + prev_close: float | None = None, + price_col: str = "close", + price: float | None = None, ) -> bool: """A-share limit-up with board-specific thresholds. - Main board: ±10% (threshold 9.8%) - - STAR (688xxx) / ChiNext (300xxx): ±20% (threshold 19.6%) - - BSE (8xxxxx / 43xxxx): ±30% (threshold 29.4%) + - STAR (688xxx/689xxx) / ChiNext (300xxx/301xxx): ±20% (threshold 19.6%) + - BSE (8xxxxx / 43xxxx / 920xxx): ±30% (threshold 29.4%) - ST stocks: ±5% (threshold 4.8%) """ - prev = _get(row, "prev_close", 0) - if not prev or prev <= 0: + prev = prev_close if prev_close is not None else _safe_float(_get(row, "prev_close", 0)) + if prev <= 0: + return False + px = ( + price if price is not None else _safe_float(_get(row, price_col, _get(row, "close", 0))) + ) + if px <= 0: return False - change = (row["close"] - prev) / prev + change = (px - prev) / prev threshold = _limit_threshold(row, symbol=symbol, stock_name=stock_name, is_st=is_st) return bool(change >= threshold) @@ -102,12 +129,20 @@ def _is_limit_down( symbol: str = "", stock_name: str = "", is_st: bool | None = None, + prev_close: float | None = None, + price_col: str = "close", + price: float | None = None, ) -> bool: """A-share limit-down with board-specific thresholds.""" - prev = _get(row, "prev_close", 0) - if not prev or prev <= 0: + prev = prev_close if prev_close is not None else _safe_float(_get(row, "prev_close", 0)) + if prev <= 0: return False - change = (row["close"] - prev) / prev + px = ( + price if price is not None else _safe_float(_get(row, price_col, _get(row, "close", 0))) + ) + if px <= 0: + return False + change = (px - prev) / prev threshold = _limit_threshold(row, symbol=symbol, stock_name=stock_name, is_st=is_st) return bool(change <= -threshold) @@ -122,6 +157,41 @@ def default_rules(cls, market: str) -> MarketRuleConfig: return defaults.get(market, MarketRuleConfig()) +def _safe_float(val: Any) -> float: + """Convert scalar to finite float or return 0.0.""" + import math + + try: + out = float(val) + except (TypeError, ValueError): + return 0.0 + return out if math.isfinite(out) else 0.0 + + +def _is_zero_volume(row: Any) -> bool: + """Return True when row explicitly records zero traded volume.""" + import math + + vol = _get(row, "volume", None) + if vol is None: + return False + try: + num = float(vol) + except (TypeError, ValueError): + return False + return math.isfinite(num) and num == 0.0 + + +def _resolve_prev_close(df: pd.DataFrame, idx: int, row: Any) -> float: + """Resolve prior close from row['prev_close'] or previous bar df['close'][idx - 1].""" + prev = _safe_float(_get(row, "prev_close", 0)) + if prev > 0: + return prev + if idx > 0 and "close" in df.columns: + return _safe_float(df["close"].iloc[idx - 1]) + return 0.0 + + def _get(row: Any, key: str, default: Any = None) -> Any: """Safely get a value from a row (Series or dict-like).""" try: @@ -141,9 +211,9 @@ def _limit_threshold( """Return the limit-up/down threshold for a stock based on its code. Board identification (A-share conventions): - - 688xxx → STAR Market (科创板): 20% - - 300xxx → ChiNext (创业板): 20% - - 8xxxxx / 43xxxx → BSE (北交所): 30% + - 688xxx / 689xxx → STAR Market (科创板): 20% + - 300xxx / 301xxx → ChiNext (创业板): 20% + - 8xxxxx / 43xxxx / 920xxx → BSE (北交所): 30% - ST stocks: 5% (detected by name containing 'ST' or the ``st`` column/flag when present in the DataFrame row) - Otherwise → Main board: 10% @@ -170,10 +240,10 @@ def _limit_threshold( if "ST " in upper_name or upper_name.startswith("ST") or "*ST" in upper_name: return 0.048 # 5% with tolerance - if code.startswith(("688", "300")): + if code.startswith(("688", "689", "300", "301")): return 0.196 # 20% with tolerance - if code.startswith(("8", "43")): + if code.startswith(("8", "43", "920")): return 0.294 # 30% with tolerance return 0.098 # 10% with tolerance (main board default) diff --git a/src/alphaevo/cli/commands/rsi.py b/src/alphaevo/cli/commands/rsi.py index 92bb88e..c2ca946 100644 --- a/src/alphaevo/cli/commands/rsi.py +++ b/src/alphaevo/cli/commands/rsi.py @@ -629,15 +629,17 @@ def shadow_emit( for df in market_data.values() if not df.empty and "date" in df ) + if replay is False and not live: + raise typer.BadParameter("Live non-replay commitments require --live market data.") eval_date = datetime.strptime(as_of, "%Y-%m-%d").date() if as_of else max_avail - is_replay = replay if replay is not None else (as_of is not None) + is_replay = replay if replay is not None else (not live or as_of is not None) ledger = ShadowLedger(config.rsi.shadow_ledger_dir) commit = ledger.commit_signals( strat, market_data, as_of=eval_date, is_replay=is_replay, - enforce_wall_clock=not is_replay and live, + enforce_wall_clock=not is_replay, ) console.print( f"[green]✓ Committed[/green] {commit.commit_id} | as_of={commit.as_of} | " @@ -665,7 +667,14 @@ def shadow_backfill( ) eval_date = datetime.strptime(as_of, "%Y-%m-%d").date() if as_of else max_avail ledger = ShadowLedger(config.rsi.shadow_ledger_dir) - events = ledger.backfill_outcomes(market_data, evaluated_as_of=eval_date) + bench_df = ( + ShadowLedger.build_equal_weight_benchmark(market_data) if len(market_data) >= 2 else None + ) + events = ledger.backfill_outcomes( + market_data, + evaluated_as_of=eval_date, + benchmark_df=bench_df, + ) mature_10 = sum(1 for ev in events if 10 in ev.horizons and ev.horizons[10].mature) console.print( f"[green]✓ Backfilled[/green] {len(events)} signals as of {eval_date} " @@ -717,6 +726,11 @@ def shadow_status( def shadow_promote( strategy_id: str = typer.Argument(..., help="Registered strategy ID to evaluate for promotion"), horizon: int = typer.Option(10, "--horizon", help="Evaluation horizon: 5, 10, or 20"), + require_benchmark: bool = typer.Option( + False, + "--require-benchmark/--no-require-benchmark", + help="Require >=80% benchmark coverage for excess-return promotion gate", + ), ) -> None: """Evaluate asymmetric promotion/halt gates for a Forward Shadow candidate.""" from alphaevo.forward.shadow_ledger import ShadowLedger @@ -729,6 +743,7 @@ def shadow_promote( min_trading_days=config.rsi.min_shadow_trading_days, min_mature_signals=config.rsi.min_shadow_signals, min_effective_signals=float(config.rsi.min_effective_signals), + require_benchmark=require_benchmark, ) console.print( f"[bold]{decision.strategy_id}[/bold]: {decision.previous_stage.value} -> " diff --git a/src/alphaevo/forward/contracts.py b/src/alphaevo/forward/contracts.py index d71d6c0..ef2568c 100644 --- a/src/alphaevo/forward/contracts.py +++ b/src/alphaevo/forward/contracts.py @@ -3,7 +3,7 @@ from __future__ import annotations from datetime import date, datetime, timezone -from typing import Literal +from typing import Any, Literal from pydantic import BaseModel, Field @@ -32,6 +32,7 @@ class CandidateSpec(BaseModel): strategy_id: str family_id: str strategy_hash: str + market: str = "" stage: PromotionStage = PromotionStage.SHADOW backtest_avg_return: float = 0.0 backtest_win_rate: float = 0.0 @@ -60,6 +61,8 @@ class SetupInstance(BaseModel): quality_grade: Literal["A", "B", "C"] = "B" conviction_score: float = 0.5 ready_now: bool = True + stock_name: str = "" + is_st: bool | None = None class ForecastCommit(BaseModel): @@ -67,12 +70,16 @@ class ForecastCommit(BaseModel): commit_id: str strategy_id: str + strategy_hash: str = "" + market: str = "" + market_rules: dict[str, Any] = Field(default_factory=dict) as_of: date committed_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc)) market_temperature: Literal["normal", "cautious", "defensive"] = "normal" total_raw_candidates: int = 0 sector_capped_count: int = 0 is_replay: bool = False + wall_clock_enforced: bool = False signals: list[SetupInstance] = Field(default_factory=list) prev_hash: str = "0" * 64 record_hash: str = "" @@ -83,10 +90,13 @@ class OutcomeHorizon(BaseModel): horizon_days: Literal[5, 10, 20] mature: bool = False + entry_date: date | None = None + horizon_end_date: date | None = None exit_date: date | None = None raw_signal_return: float = 0.0 tradable_post_cost_return: float = 0.0 benchmark_return: float = 0.0 + benchmark_available: bool = False excess_return: float = 0.0 stopped_out: bool = False @@ -96,6 +106,8 @@ class OutcomeEvent(BaseModel): signal_id: str strategy_id: str + strategy_hash: str = "" + is_replay: bool = False symbol: str sector: str = "unknown" as_of: date @@ -114,6 +126,7 @@ class ForwardDecayReport(BaseModel): mature_signals: int = 0 immature_signals: int = 0 effective_signals: float = 0.0 + benchmark_coverage_ratio: float = 0.0 forward_win_rate: float = 0.0 forward_avg_post_cost_return: float = 0.0 forward_avg_excess_return: float = 0.0 diff --git a/src/alphaevo/forward/shadow_ledger.py b/src/alphaevo/forward/shadow_ledger.py index 0e26491..6116b62 100644 --- a/src/alphaevo/forward/shadow_ledger.py +++ b/src/alphaevo/forward/shadow_ledger.py @@ -6,12 +6,22 @@ import json import math import os +import re +import tempfile +import threading import uuid from collections import defaultdict +from collections.abc import Iterator +from contextlib import contextmanager, suppress from datetime import date, datetime, timedelta, timezone from pathlib import Path from typing import TYPE_CHECKING, Any, Literal, cast +try: + import fcntl as _fcntl +except ImportError: # pragma: no cover - non-POSIX fallback + _fcntl = None # type: ignore[assignment] + import pandas as pd # type: ignore[import-untyped] from alphaevo.backtest.condition import ConditionEvaluator @@ -31,6 +41,7 @@ StageTransition, ) from alphaevo.models.enums import MarketRegime, PromotionStage +from alphaevo.models.strategy import MarketRuleConfig from alphaevo.sampler.regime import RegimeDetector from alphaevo.truth.ledger import compute_strategy_hash @@ -41,12 +52,90 @@ _GENESIS_HASH = "0" * 64 _HORIZONS: tuple[Literal[5, 10, 20], ...] = (5, 10, 20) +_ASHARE_SYMBOL_RE = re.compile(r"^(?:sh|sz|bj)?\d{6}(?:\.(?:SH|SZ|SS|BJ))?$", re.IGNORECASE) +_PROCESS_LOCKS_GUARD = threading.Lock() +_PROCESS_LOCKS: dict[Path, threading.RLock] = {} +_THREAD_LOCK_DEPTH = threading.local() + + +def _get_process_lock(ledger_dir: Path) -> threading.RLock: + resolved = ledger_dir.resolve() + with _PROCESS_LOCKS_GUARD: + lock = _PROCESS_LOCKS.get(resolved) + if lock is None: + lock = threading.RLock() + _PROCESS_LOCKS[resolved] = lock + return lock + + +def _atomic_write_text(path: Path, content: str) -> None: + """Write *content* atomically via unique same-directory temp file and fsync.""" + path.parent.mkdir(parents=True, exist_ok=True) + fd, tmp_name = tempfile.mkstemp( + dir=str(path.parent), + prefix=f".{path.name}.", + suffix=".tmp", + ) + try: + with os.fdopen(fd, "w", encoding="utf-8") as fh: + fh.write(content) + fh.flush() + os.fsync(fh.fileno()) + os.replace(tmp_name, path) + except Exception: + with suppress(OSError): + os.unlink(tmp_name) + raise + + +def _finite_positive(value: Any) -> float | None: + try: + num = float(value) + except (TypeError, ValueError): + return None + if math.isfinite(num) and num > 0: + return num + return None + + +def _prior_horizon_valid_at( + prior_ev: OutcomeEvent | None, + prior_h: OutcomeHorizon | None, + cutoff: date, +) -> bool: + """Return True if *prior_h* already matured on or before *cutoff*.""" + if prior_ev is None or prior_h is None or not prior_h.mature: + return False + if prior_h.horizon_end_date is not None: + return prior_h.horizon_end_date <= cutoff + # Legacy records lack horizon_end_date; require evaluated_as_of <= cutoff so early stops + # do not expose closing T+H horizon returns before the horizon itself matured. + return prior_ev.evaluated_as_of <= cutoff + + +def _looks_like_ashare_symbol(symbol: str) -> bool: + return bool(_ASHARE_SYMBOL_RE.match(symbol.strip())) def _canonical_commit_hash(commit: ForecastCommit) -> str: """Compute SHA-256 over canonical ForecastCommit payload (excluding record_hash).""" payload = commit.model_dump(mode="json") payload["record_hash"] = "" + # Preserve exact pre-upgrade digests for commits lacking optional tracking fields. + if not payload.get("strategy_hash"): + payload.pop("strategy_hash", None) + if not payload.get("market"): + payload.pop("market", None) + if not payload.get("market_rules"): + payload.pop("market_rules", None) + if not payload.get("wall_clock_enforced"): + payload.pop("wall_clock_enforced", None) + for sig_dict in payload.get("signals", ()): + if isinstance(sig_dict, dict): + if not sig_dict.get("stock_name"): + sig_dict.pop("stock_name", None) + if sig_dict.get("is_st") is None: + sig_dict.pop("is_st", None) raw = json.dumps(payload, sort_keys=True, ensure_ascii=False, separators=(",", ":")) return hashlib.sha256(raw.encode("utf-8")).hexdigest() @@ -55,9 +144,13 @@ def _truncate_pit(df: pd.DataFrame, as_of: date) -> pd.DataFrame: """Strictly truncate OHLCV DataFrame so no row after ``as_of`` is visible.""" if df.empty or "date" not in df: return cast("pd.DataFrame", df.iloc[0:0].copy()) - dates = pd.to_datetime(df["date"]).dt.date - mask = dates <= as_of - out = df.loc[mask].copy().reset_index(drop=True) + parsed = pd.to_datetime(df["date"], errors="coerce").dt.date + mask = parsed.notna() & (parsed <= as_of) + out = df.loc[mask].copy() + if out.empty: + return cast("pd.DataFrame", out.reset_index(drop=True)) + out = out.assign(_pit_date=parsed.loc[mask]).sort_values("_pit_date", kind="mergesort") + out = out.drop(columns=["_pit_date"]).reset_index(drop=True) return cast("pd.DataFrame", out) @@ -74,6 +167,39 @@ def __init__(self, ledger_dir: str | Path) -> None: self._cond_eval = ConditionEvaluator() self._regime_detector = RegimeDetector() + @contextmanager + def _ledger_lock(self) -> Iterator[None]: + """Serialize mutating ledger operations across threads and OS processes.""" + self.ledger_dir.mkdir(parents=True, exist_ok=True) + resolved = self.ledger_dir.resolve() + depth_map: dict[Path, int] | None = getattr(_THREAD_LOCK_DEPTH, "depths", None) + if depth_map is None: + depth_map = {} + _THREAD_LOCK_DEPTH.depths = depth_map + + proc_lock = _get_process_lock(resolved) + lock_path = self.ledger_dir / ".ledger.lock" + with proc_lock: + cur_depth = depth_map.get(resolved, 0) + depth_map[resolved] = cur_depth + 1 + try: + if cur_depth == 0: + with lock_path.open("a+", encoding="utf-8") as lock_fh: + if _fcntl is not None: + _fcntl.flock(lock_fh.fileno(), _fcntl.LOCK_EX) + try: + yield + finally: + if _fcntl is not None: + _fcntl.flock(lock_fh.fileno(), _fcntl.LOCK_UN) + else: + yield + finally: + if cur_depth == 0: + depth_map.pop(resolved, None) + else: + depth_map[resolved] = cur_depth + # ── Candidate registration & persistence ─────────────────────────── def register_candidate( @@ -92,34 +218,36 @@ def register_candidate( f"Candidate '{strategy.meta.id}' failed anti-overfit veto; cannot enter {stage.value}" ) - candidates = self._load_candidates() - existing = candidates.get(strategy.meta.id) - if existing is not None and existing.stage == PromotionStage.HALTED and not force_reset: - raise ValueError( - f"Candidate '{strategy.meta.id}' is HALTED and cannot be overwritten without force_reset=True" - ) - - spec = CandidateSpec( - strategy_id=strategy.meta.id, - family_id=strategy.meta.family_id, - strategy_hash=compute_strategy_hash(strategy), - stage=stage, - backtest_avg_return=evaluation.overall.avg_return, - backtest_win_rate=evaluation.overall.win_rate, - backtest_sharpe=evaluation.overall.sharpe_ratio, - deflated_sharpe_prob=float(evaluation.deflated_sharpe_prob or 0.0), - null_control_passed=bool(evaluation.null_control_passed), - stage_history=[ - StageTransition( - from_stage=PromotionStage.VALIDATED, - to_stage=stage, - reason="Initial preregistration from offline RSI research gate", + with self._ledger_lock(): + candidates = self._load_candidates() + existing = candidates.get(strategy.meta.id) + if existing is not None and existing.stage == PromotionStage.HALTED and not force_reset: + raise ValueError( + f"Candidate '{strategy.meta.id}' is HALTED and cannot be overwritten without force_reset=True" ) - ], - ) - candidates[strategy.meta.id] = spec - self._save_candidates(candidates) - return spec + + spec = CandidateSpec( + strategy_id=strategy.meta.id, + family_id=strategy.meta.family_id, + strategy_hash=compute_strategy_hash(strategy), + market=strategy.meta.market.value, + stage=stage, + backtest_avg_return=evaluation.overall.avg_return, + backtest_win_rate=evaluation.overall.win_rate, + backtest_sharpe=evaluation.overall.sharpe_ratio, + deflated_sharpe_prob=float(evaluation.deflated_sharpe_prob or 0.0), + null_control_passed=bool(evaluation.null_control_passed), + stage_history=[ + StageTransition( + from_stage=PromotionStage.VALIDATED, + to_stage=stage, + reason="Initial preregistration from offline RSI research gate", + ) + ], + ) + candidates[strategy.meta.id] = spec + self._save_candidates(candidates) + return spec def get_candidate(self, strategy_id: str) -> CandidateSpec | None: """Return candidate record by strategy_id if preregistered.""" @@ -145,126 +273,141 @@ def commit_signals( allow_same_day: bool = True, ) -> ForecastCommit: """Generate & hash-chain forward stock setups strictly using data <= ``as_of``.""" - registered = self.get_candidate(strategy.meta.id) - if registered is not None: - current_hash = compute_strategy_hash(strategy) - if current_hash != registered.strategy_hash: + current_hash = compute_strategy_hash(strategy) + market_key = strategy.meta.market.value + + with self._ledger_lock(): + registered = self.get_candidate(strategy.meta.id) + if registered is not None and current_hash != registered.strategy_hash: raise ValueError( f"Strategy '{strategy.meta.id}' hash mismatch ({current_hash[:12]} != {registered.strategy_hash[:12]})" ) - existing_for_strat = self.load_commits(strategy.meta.id) - if existing_for_strat: - latest_as_of = existing_for_strat[-1].as_of - if as_of < latest_as_of or (not allow_same_day and as_of <= latest_as_of): - raise ValueError( - f"Non-monotonic commit date {as_of} < latest committed {latest_as_of}" - ) + existing_for_strat = [ + c + for c in self.load_commits(strategy.meta.id) + if not c.strategy_hash or c.strategy_hash == current_hash + ] + if existing_for_strat: + latest_as_of = existing_for_strat[-1].as_of + if as_of < latest_as_of or (not allow_same_day and as_of <= latest_as_of): + raise ValueError( + f"Non-monotonic commit date {as_of} < latest committed {latest_as_of}" + ) - if enforce_wall_clock and not is_replay: - today_utc = datetime.now(timezone.utc).date() - if (today_utc - as_of).days > 3 or as_of > today_utc + timedelta(days=1): - raise ValueError( - f"Live commit date {as_of} deviates from UTC wall-clock {today_utc} without is_replay=True" - ) + if enforce_wall_clock and not is_replay: + today_utc = datetime.now(timezone.utc).date() + if (today_utc - as_of).days > 3 or as_of > today_utc + timedelta(days=1): + raise ValueError( + f"Live commit date {as_of} deviates from UTC wall-clock {today_utc} without is_replay=True" + ) - raw_setups: list[SetupInstance] = [] - sector_map = sectors or {} - rule_checker = MarketRuleChecker() - market_key = strategy.meta.market.value - rules = strategy.market_rules.get(market_key, MarketRuleChecker.default_rules(market_key)) - preferred_regimes = set(strategy.meta.preferred_regime) + raw_setups: list[SetupInstance] = [] + sector_map = sectors or {} + rule_checker = MarketRuleChecker() + rules = strategy.market_rules.get( + market_key, MarketRuleChecker.default_rules(market_key) + ) + preferred_regimes = set(strategy.meta.preferred_regime) - for symbol in sorted(market_data): - pit_df = _truncate_pit(market_data[symbol], as_of) - if pit_df.empty or len(pit_df) < 15: - continue - last_bar_date = pd.to_datetime(pit_df["date"].iloc[-1]).date() - if (as_of - last_bar_date).days > 5: - continue + for symbol in sorted(market_data): + pit_df = _truncate_pit(market_data[symbol], as_of) + if pit_df.empty or len(pit_df) < 15: + continue + last_bar_date = pd.to_datetime(pit_df["date"].iloc[-1]).date() + if (as_of - last_bar_date).days > 5: + continue - idx = len(pit_df) - 1 - ctx = contexts.get(symbol) if contexts else None - stock_name = ctx.stock_info.name if ctx and ctx.stock_info else "" - is_st = ctx.stock_info.is_st if ctx and ctx.stock_info else None - if not rule_checker.can_buy( - pit_df, idx, rules, symbol=symbol, stock_name=stock_name, is_st=is_st - ): - continue + idx = len(pit_df) - 1 + ctx = contexts.get(symbol) if contexts else None + stock_name = ctx.stock_info.name if ctx and ctx.stock_info else "" + is_st = ctx.stock_info.is_st if ctx and ctx.stock_info else None + if not rule_checker.can_buy( + pit_df, idx, rules, symbol=symbol, stock_name=stock_name, is_st=is_st + ): + continue - detected_regime = market_regime or self._regime_detector.detect(pit_df) - if preferred_regimes and detected_regime.value not in preferred_regimes: - continue + detected_regime = market_regime or self._regime_detector.detect(pit_df) + if preferred_regimes and detected_regime.value not in preferred_regimes: + continue - if not self._cond_eval.evaluate_entry(strategy.entry, pit_df, idx, ctx): - continue + if not self._cond_eval.evaluate_entry(strategy.entry, pit_df, idx, ctx): + continue - close_price = float(pit_df["close"].iloc[idx]) - if close_price <= 0: - continue + close_price = float(pit_df["close"].iloc[idx]) + if not math.isfinite(close_price) or close_price <= 0: + continue - stop_pct = self._resolve_stop_pct(strategy) - planned_stop = round(close_price * (1.0 - stop_pct), 4) - planned_rr = self._resolve_planned_rr(strategy, stop_pct) - min_rr = strategy.setup.min_rr if strategy.setup is not None else 1.0 - if planned_rr < min_rr: - continue + stop_pct = self._resolve_stop_pct(strategy) + planned_stop = round(close_price * (1.0 - stop_pct), 4) + planned_rr = self._resolve_planned_rr(strategy, stop_pct) + min_rr = strategy.setup.min_rr if strategy.setup is not None else 1.0 + if planned_rr < min_rr: + continue - target_price = round(close_price * (1.0 + stop_pct * planned_rr), 4) - conviction = self._score_setup_conviction(strategy, pit_df, idx, ctx) - grade: Literal["A", "B", "C"] = ( - "A" if conviction >= 0.70 else ("B" if conviction >= 0.45 else "C") - ) - invalidation = ( - strategy.setup.structural_invalidation - if strategy.setup is not None and strategy.setup.structural_invalidation - else f"stop<{planned_stop:.2f}" - ) - raw_setups.append( - SetupInstance( - signal_id=f"sig_{as_of.strftime('%Y%m%d')}_{symbol}_{uuid.uuid4().hex[:6]}", - strategy_id=strategy.meta.id, - symbol=symbol, - sector=sector_map.get(symbol, "unknown"), - regime=detected_regime.value, - envelope=BitemporalEnvelope(as_of=as_of), - entry_reference_price=round(close_price, 4), - planned_stop_price=planned_stop, - target_price=target_price, - planned_rr=round(planned_rr, 2), - structural_invalidation=invalidation, - quality_grade=grade, - conviction_score=round(conviction, 4), - ready_now=True, + target_price = round(close_price * (1.0 + stop_pct * planned_rr), 4) + conviction = self._score_setup_conviction(strategy, pit_df, idx, ctx) + grade: Literal["A", "B", "C"] = ( + "A" if conviction >= 0.70 else ("B" if conviction >= 0.45 else "C") + ) + invalidation = ( + strategy.setup.structural_invalidation + if strategy.setup is not None and strategy.setup.structural_invalidation + else f"stop<{planned_stop:.2f}" + ) + raw_setups.append( + SetupInstance( + signal_id=f"sig_{as_of.strftime('%Y%m%d')}_{symbol}_{uuid.uuid4().hex[:6]}", + strategy_id=strategy.meta.id, + symbol=symbol, + sector=sector_map.get(symbol, "unknown"), + regime=detected_regime.value, + envelope=BitemporalEnvelope(as_of=as_of), + entry_reference_price=round(close_price, 4), + planned_stop_price=planned_stop, + target_price=target_price, + planned_rr=round(planned_rr, 2), + structural_invalidation=invalidation, + quality_grade=grade, + conviction_score=round(conviction, 4), + ready_now=True, + stock_name=stock_name, + is_st=is_st, + ) ) - ) - temp_label, capped = self._apply_portfolio_profile( - strategy=strategy, - setups=raw_setups, - market_regime=market_regime, - ) + temp_label, capped = self._apply_portfolio_profile( + strategy=strategy, + setups=raw_setups, + market_regime=market_regime, + ) - commits = self.load_commits() - prev_hash = commits[-1].record_hash if commits else _GENESIS_HASH - commit = ForecastCommit( - commit_id=f"cmt_{as_of.strftime('%Y%m%d')}_{uuid.uuid4().hex[:8]}", - strategy_id=strategy.meta.id, - as_of=as_of, - market_temperature=temp_label, - total_raw_candidates=len(raw_setups), - sector_capped_count=len(capped), - is_replay=is_replay, - signals=capped, - prev_hash=prev_hash, - record_hash="", - ) - commit.record_hash = _canonical_commit_hash(commit) + commits = self.load_commits() + prev_hash = commits[-1].record_hash if commits else _GENESIS_HASH + commit = ForecastCommit( + commit_id=f"cmt_{as_of.strftime('%Y%m%d')}_{uuid.uuid4().hex[:8]}", + strategy_id=strategy.meta.id, + strategy_hash=current_hash, + market=market_key, + market_rules={market_key: rules.model_dump(mode="json")}, + as_of=as_of, + market_temperature=temp_label, + total_raw_candidates=len(raw_setups), + sector_capped_count=len(capped), + is_replay=is_replay, + wall_clock_enforced=bool(enforce_wall_clock and not is_replay), + signals=capped, + prev_hash=prev_hash, + record_hash="", + ) + commit.record_hash = _canonical_commit_hash(commit) - with self.commits_file.open("a", encoding="utf-8") as fh: - fh.write(commit.model_dump_json() + "\n") - self.head_hash_file.write_text(commit.record_hash + "\n", encoding="utf-8") - return commit + with self.commits_file.open("a", encoding="utf-8") as fh: + fh.write(commit.model_dump_json() + "\n") + fh.flush() + os.fsync(fh.fileno()) + _atomic_write_text(self.head_hash_file, commit.record_hash + "\n") + return commit def load_commits(self, strategy_id: str | None = None) -> list[ForecastCommit]: """Load committed ForecastCommit history from JSONL.""" @@ -281,38 +424,41 @@ def load_commits(self, strategy_id: str | None = None) -> list[ForecastCommit]: def verify_chain(self) -> tuple[bool, list[str]]: """Verify SHA-256 hash chain linkage across every committed line.""" - if not self.commits_file.is_file(): - return True, [] - errors: list[str] = [] - expected_prev = _GENESIS_HASH - last_hash = _GENESIS_HASH - for idx, line in enumerate( - self.commits_file.read_text(encoding="utf-8").splitlines(), start=1 - ): - if not line.strip(): - continue - try: - cmt = ForecastCommit.model_validate_json(line) - except Exception as exc: - errors.append(f"Line {idx}: invalid commit JSON ({exc})") - continue - if cmt.prev_hash != expected_prev: - errors.append( - f"Line {idx} ({cmt.commit_id}): prev_hash mismatch " - f"(expected {expected_prev[:12]}, got {cmt.prev_hash[:12]})" - ) - recomputed = _canonical_commit_hash(cmt) - if cmt.record_hash != recomputed: - errors.append(f"Line {idx} ({cmt.commit_id}): record_hash tampered or corrupted") - expected_prev = cmt.record_hash - last_hash = cmt.record_hash + with self._ledger_lock(): + if not self.commits_file.is_file(): + return True, [] + errors: list[str] = [] + expected_prev = _GENESIS_HASH + last_hash = _GENESIS_HASH + for idx, line in enumerate( + self.commits_file.read_text(encoding="utf-8").splitlines(), start=1 + ): + if not line.strip(): + continue + try: + cmt = ForecastCommit.model_validate_json(line) + except Exception as exc: + errors.append(f"Line {idx}: invalid commit JSON ({exc})") + continue + if cmt.prev_hash != expected_prev: + errors.append( + f"Line {idx} ({cmt.commit_id}): prev_hash mismatch " + f"(expected {expected_prev[:12]}, got {cmt.prev_hash[:12]})" + ) + recomputed = _canonical_commit_hash(cmt) + if cmt.record_hash != recomputed: + errors.append( + f"Line {idx} ({cmt.commit_id}): record_hash tampered or corrupted" + ) + expected_prev = cmt.record_hash + last_hash = cmt.record_hash - if self.head_hash_file.is_file() and last_hash != _GENESIS_HASH: - recorded_head = self.head_hash_file.read_text(encoding="utf-8").strip() - if recorded_head != last_hash: - errors.append("commits.sha256 head pointer mismatch with commits.jsonl") + if self.head_hash_file.is_file() and last_hash != _GENESIS_HASH: + recorded_head = self.head_hash_file.read_text(encoding="utf-8").strip() + if recorded_head != last_hash: + errors.append("commits.sha256 head pointer mismatch with commits.jsonl") - return len(errors) == 0, errors + return len(errors) == 0, errors # ── Forward T+N Outcome Backfill & Decay Diagnostics ────────────── @@ -323,6 +469,8 @@ def backfill_outcomes( evaluated_as_of: date, benchmark_df: pd.DataFrame | None = None, round_trip_cost: float = 0.0026, + contexts: dict[str, IndicatorContext] | None = None, + market_rules: MarketRuleConfig | None = None, ) -> list[OutcomeEvent]: """Compute matured vs immature T+5/10/20 outcomes up to ``evaluated_as_of``.""" truncated_market = { @@ -331,112 +479,336 @@ def backfill_outcomes( truncated_bench = ( _truncate_pit(benchmark_df, evaluated_as_of) if benchmark_df is not None else None ) + rule_checker = MarketRuleChecker() + + with self._ledger_lock(): + candidates_map = self._load_candidates() + prior_events = {ev.signal_id: ev for ev in self.load_outcomes()} + view_events: list[OutcomeEvent] = [] + disk_events: list[OutcomeEvent] = [] + for commit in self.load_commits(): + cand_spec = candidates_map.get(commit.strategy_id) + eff_market = commit.market or (cand_spec.market if cand_spec is not None else "") + for sig in commit.signals: + prior_ev = prior_events.get(sig.signal_id) + sym_df = truncated_market.get(sig.symbol) + view_horizons: dict[int, OutcomeHorizon] = {} + disk_horizons: dict[int, OutcomeHorizon] = {} + resolved_market = eff_market or ( + "a_share" if _looks_like_ashare_symbol(sig.symbol) else "us" + ) + if market_rules is not None: + rules = market_rules + elif resolved_market in commit.market_rules: + rules = MarketRuleConfig.model_validate( + commit.market_rules[resolved_market] + ) + else: + rules = MarketRuleChecker.default_rules(resolved_market) + ctx = contexts.get(sig.symbol) if contexts else None + stock_name = ( + ctx.stock_info.name + if ctx and ctx.stock_info and ctx.stock_info.name + else sig.stock_name + ) + is_st = ( + ctx.stock_info.is_st + if ctx and ctx.stock_info and ctx.stock_info.is_st is not None + else sig.is_st + ) + + def _attach_late_benchmark( + hor_obj: OutcomeHorizon, + *, + ent_d: date | None, + h_days: int, + ) -> OutcomeHorizon: + resolved_ent = hor_obj.entry_date or ent_d + if ( + resolved_ent is None + or hor_obj.benchmark_available + or truncated_bench is None + ): + return hor_obj + b_ret, b_ok = self._compute_benchmark_return( + truncated_bench, + entry_date=resolved_ent, + exit_date=hor_obj.exit_date or hor_obj.horizon_end_date, + horizon_days=h_days, + ) + if not b_ok: + return hor_obj + return hor_obj.model_copy( + update={ + "entry_date": resolved_ent, + "benchmark_return": round(b_ret, 6), + "benchmark_available": True, + "excess_return": round( + hor_obj.tradable_post_cost_return - b_ret, 6 + ), + } + ) + + if sym_df is None or sym_df.empty or "date" not in sym_df: + for h in _HORIZONS: + prior_h = prior_ev.horizons.get(h) if prior_ev else None + valid_view = prior_h is not None and _prior_horizon_valid_at( + prior_ev, prior_h, evaluated_as_of + ) + if prior_h is not None and valid_view: + updated_h = _attach_late_benchmark( + prior_h, ent_d=prior_h.entry_date, h_days=h + ) + view_horizons[h] = updated_h + disk_horizons[h] = updated_h + else: + view_horizons[h] = OutcomeHorizon(horizon_days=h, mature=False) + disk_horizons[h] = ( + prior_h + if prior_h is not None and prior_h.mature + else view_horizons[h] + ) + view_events.append( + OutcomeEvent( + signal_id=sig.signal_id, + strategy_id=sig.strategy_id, + strategy_hash=commit.strategy_hash, + is_replay=commit.is_replay, + symbol=sig.symbol, + sector=sig.sector, + as_of=sig.envelope.as_of, + evaluated_as_of=evaluated_as_of, + horizons=view_horizons, + ) + ) + disk_events.append( + OutcomeEvent( + signal_id=sig.signal_id, + strategy_id=sig.strategy_id, + strategy_hash=commit.strategy_hash, + is_replay=commit.is_replay, + symbol=sig.symbol, + sector=sig.sector, + as_of=sig.envelope.as_of, + evaluated_as_of=( + max(prior_ev.evaluated_as_of, evaluated_as_of) + if prior_ev is not None + else evaluated_as_of + ), + horizons=disk_horizons, + ) + ) + continue + + dates_series = pd.to_datetime(sym_df["date"], errors="coerce").dt.date + min_fwd_date = sig.envelope.as_of + timedelta(days=1) + if commit.wall_clock_enforced and not commit.is_replay: + min_fwd_date = max( + min_fwd_date, + commit.committed_at.astimezone(timezone.utc).date() + timedelta(days=1), + ) + future_indices = [ + pos + for pos, d_val in enumerate(dates_series.tolist()) + if isinstance(d_val, date) and d_val >= min_fwd_date + ] + entry_offset: int | None = None + for offset, sym_pos in enumerate(future_indices): + if rule_checker.can_buy( + sym_df, + sym_pos, + rules, + symbol=sig.symbol, + stock_name=stock_name, + is_st=is_st, + price_col="open", + ): + entry_offset = offset + break + tradable_future = ( + future_indices[entry_offset:] if entry_offset is not None else [] + ) - prior_events = {ev.signal_id: ev for ev in self.load_outcomes()} - events: list[OutcomeEvent] = [] - for commit in self.load_commits(): - for sig in commit.signals: - prior_ev = prior_events.get(sig.signal_id) - sym_df = truncated_market.get(sig.symbol) - horizons_out: dict[int, OutcomeHorizon] = {} - if sym_df is None or sym_df.empty or "date" not in sym_df: for h in _HORIZONS: prior_h = prior_ev.horizons.get(h) if prior_ev else None - horizons_out[h] = ( - prior_h - if prior_h is not None and prior_h.mature - else OutcomeHorizon(horizon_days=h, mature=False) + if prior_h is not None and _prior_horizon_valid_at( + prior_ev, prior_h, evaluated_as_of + ): + ent_d: date | None = ( + cast("date", dates_series.iloc[tradable_future[0]]) + if tradable_future + else prior_h.entry_date + ) + updated_h = _attach_late_benchmark(prior_h, ent_d=ent_d, h_days=h) + view_horizons[h] = updated_h + disk_horizons[h] = updated_h + continue + + if prior_h is not None and prior_h.mature: + # Already matured in the future relative to this earlier cutoff: keep + # immutable disk copy untouched while returning an immature cutoff view. + disk_horizons[h] = prior_h + view_horizons[h] = OutcomeHorizon(horizon_days=h, mature=False) + continue + + if len(tradable_future) < h: + immature_h = OutcomeHorizon(horizon_days=h, mature=False) + view_horizons[h] = immature_h + disk_horizons[h] = immature_h + continue + + entry_sym_idx = tradable_future[0] + window_indices = tradable_future[:h] + horizon_end_idx = window_indices[-1] + entry_date = cast("date", dates_series.iloc[entry_sym_idx]) + horizon_end_date = cast("date", dates_series.iloc[horizon_end_idx]) + + entry_open = ( + _finite_positive(sym_df["open"].iloc[entry_sym_idx]) + if "open" in sym_df + else None + ) or sig.entry_reference_price + horizon_close = _finite_positive(sym_df["close"].iloc[horizon_end_idx]) + if entry_open <= 0 or horizon_close is None: + immature_h = OutcomeHorizon(horizon_days=h, mature=False) + view_horizons[h] = immature_h + disk_horizons[h] = immature_h + continue + + raw_ret = (horizon_close / max(1e-6, sig.entry_reference_price)) - 1.0 + stopped_out = False + effective_exit: float | None = None + exit_date: date | None = None + + if sig.planned_stop_price is not None and "low" in sym_df: + stop_lvl = float(sig.planned_stop_price) + for bar_idx in window_indices: + if rules.t_plus_1 and bar_idx <= entry_sym_idx: + continue + raw_low = sym_df["low"].iloc[bar_idx] + if pd.isna(raw_low): + continue + bar_low = float(raw_low) + if not math.isfinite(bar_low) or bar_low > stop_lvl: + continue + bar_open = ( + _finite_positive(sym_df["open"].iloc[bar_idx]) + if "open" in sym_df + else None + ) + cand_exit = ( + min(stop_lvl, bar_open) if bar_open is not None else stop_lvl + ) + if not rule_checker.can_sell( + sym_df, + bar_idx, + entry_sym_idx, + rules, + symbol=sig.symbol, + stock_name=stock_name, + is_st=is_st, + price=cand_exit, + ): + continue + stopped_out = True + effective_exit = cand_exit + exit_date = cast("date", dates_series.iloc[bar_idx]) + break + + if not stopped_out: + for cand_exit_idx in tradable_future[h - 1 :]: + if not rule_checker.can_sell( + sym_df, + cand_exit_idx, + entry_sym_idx, + rules, + symbol=sig.symbol, + stock_name=stock_name, + is_st=is_st, + price_col="close", + ): + continue + cand_close = _finite_positive(sym_df["close"].iloc[cand_exit_idx]) + if cand_close is not None: + effective_exit = cand_close + exit_date = cast("date", dates_series.iloc[cand_exit_idx]) + horizon_end_date = max(horizon_end_date, exit_date) + break + + if effective_exit is None or exit_date is None: + immature_h = OutcomeHorizon(horizon_days=h, mature=False) + view_horizons[h] = immature_h + disk_horizons[h] = immature_h + continue + + tradable_ret = ( + (effective_exit / max(1e-6, entry_open)) - 1.0 + ) - round_trip_cost + bench_ret, bench_ok = self._compute_benchmark_return( + truncated_bench, + entry_date=entry_date, + exit_date=exit_date, + horizon_days=h, ) - events.append( + computed_h = OutcomeHorizon( + horizon_days=h, + mature=True, + entry_date=entry_date, + horizon_end_date=horizon_end_date, + exit_date=exit_date, + raw_signal_return=round(raw_ret, 6), + tradable_post_cost_return=round(tradable_ret, 6), + benchmark_return=round(bench_ret, 6), + benchmark_available=bench_ok, + excess_return=round(tradable_ret - bench_ret, 6), + stopped_out=stopped_out, + ) + view_horizons[h] = computed_h + disk_horizons[h] = computed_h + + view_events.append( OutcomeEvent( signal_id=sig.signal_id, strategy_id=sig.strategy_id, + strategy_hash=commit.strategy_hash, + is_replay=commit.is_replay, symbol=sig.symbol, sector=sig.sector, as_of=sig.envelope.as_of, evaluated_as_of=evaluated_as_of, - horizons=horizons_out, - ) - ) - continue - - dates = pd.to_datetime(sym_df["date"]).dt.date - future_bars = sym_df.loc[dates > sig.envelope.as_of].reset_index(drop=True) - for h in _HORIZONS: - prior_h = prior_ev.horizons.get(h) if prior_ev else None - if len(future_bars) < h: - horizons_out[h] = ( - prior_h - if prior_h is not None and prior_h.mature - else OutcomeHorizon(horizon_days=h, mature=False) + horizons=view_horizons, ) - continue - window = future_bars.iloc[:h] - entry_open = ( - float(window["open"].iloc[0]) - if "open" in window - else sig.entry_reference_price ) - entry_open = entry_open if entry_open > 0 else sig.entry_reference_price - exit_close = float(window["close"].iloc[-1]) - exit_date = pd.to_datetime(window["date"].iloc[-1]).date() - - raw_ret = (exit_close / max(1e-6, sig.entry_reference_price)) - 1.0 - stopped_out = False - effective_exit = exit_close - if sig.planned_stop_price is not None and "low" in window: - hit_mask = ( - pd.to_numeric(window["low"], errors="coerce") <= sig.planned_stop_price + disk_events.append( + OutcomeEvent( + signal_id=sig.signal_id, + strategy_id=sig.strategy_id, + strategy_hash=commit.strategy_hash, + is_replay=commit.is_replay, + symbol=sig.symbol, + sector=sig.sector, + as_of=sig.envelope.as_of, + evaluated_as_of=( + max(prior_ev.evaluated_as_of, evaluated_as_of) + if prior_ev is not None + else evaluated_as_of + ), + horizons=disk_horizons, ) - if bool(hit_mask.any()): - stopped_out = True - effective_exit = float(sig.planned_stop_price) - hit_pos = int(hit_mask.to_numpy().argmax()) - exit_date = pd.to_datetime(window["date"].iloc[hit_pos]).date() - - tradable_ret = ( - (effective_exit / max(1e-6, entry_open)) - 1.0 - ) - round_trip_cost - bench_ret = self._compute_benchmark_return( - truncated_bench, - start_after=sig.envelope.as_of, - horizon_days=h, - ) - horizons_out[h] = OutcomeHorizon( - horizon_days=h, - mature=True, - exit_date=exit_date, - raw_signal_return=round(raw_ret, 6), - tradable_post_cost_return=round(tradable_ret, 6), - benchmark_return=round(bench_ret, 6), - excess_return=round(tradable_ret - bench_ret, 6), - stopped_out=stopped_out, ) - events.append( - OutcomeEvent( - signal_id=sig.signal_id, - strategy_id=sig.strategy_id, - symbol=sig.symbol, - sector=sig.sector, - as_of=sig.envelope.as_of, - evaluated_as_of=evaluated_as_of, - horizons=horizons_out, - ) - ) + # Preserve any out-of-commit outcome records and write atomically + seen_ids = {ev.signal_id for ev in disk_events} + for sig_id, prior_ev in prior_events.items(): + if sig_id not in seen_ids: + disk_events.append(prior_ev) + view_events.append(prior_ev) - # Preserve any out-of-commit outcome records and write atomically - seen_ids = {ev.signal_id for ev in events} - for sig_id, prior_ev in prior_events.items(): - if sig_id not in seen_ids: - events.append(prior_ev) - - tmp_path = self.outcomes_file.with_suffix(".jsonl.tmp") - with tmp_path.open("w", encoding="utf-8") as fh: - for ev in events: - fh.write(ev.model_dump_json() + "\n") - os.replace(tmp_path, self.outcomes_file) - return events + _atomic_write_text( + self.outcomes_file, + "".join(ev.model_dump_json() + "\n" for ev in disk_events), + ) + return view_events def load_outcomes(self, strategy_id: str | None = None) -> list[OutcomeEvent]: """Load persisted forward OutcomeEvents.""" @@ -480,20 +852,82 @@ def compute_effective_sample_size( total_eff += day_sum / (1.0 + max(0.0, day_sum - 1.0) * day_corr) return round(total_eff, 2) + def _resolve_active_commits_and_outcomes( + self, + strategy_id: str, + *, + active_hash: str | None, + live_only: bool, + as_of_cutoff: date | None = None, + ) -> tuple[list[ForecastCommit], list[OutcomeEvent]]: + """Filter commits and outcomes to the active registered strategy hash (and live mode).""" + all_commits = self.load_commits(strategy_id) + if as_of_cutoff is not None: + all_commits = [c for c in all_commits if c.as_of <= as_of_cutoff] + sig_meta: dict[str, tuple[str, bool]] = {} + for cmt in all_commits: + for sig in cmt.signals: + sig_meta[sig.signal_id] = (cmt.strategy_hash, cmt.is_replay) + + active_commits = [ + c for c in all_commits if not active_hash or c.strategy_hash == active_hash + ] + if live_only: + active_commits = [c for c in active_commits if not c.is_replay] + active_sig_ids = {sig.signal_id for cmt in active_commits for sig in cmt.signals} + has_commit_history = bool(all_commits) + + all_outcomes = self.load_outcomes(strategy_id) + active_outcomes: list[OutcomeEvent] = [] + for ev in all_outcomes: + if as_of_cutoff is not None and ev.as_of > as_of_cutoff: + continue + if has_commit_history and ev.signal_id not in active_sig_ids: + continue + meta_hash, meta_replay = sig_meta.get(ev.signal_id, ("", False)) + eff_hash = ev.strategy_hash or meta_hash + eff_replay = ev.is_replay or meta_replay + if active_hash and eff_hash != active_hash and has_commit_history: + continue + if active_hash and eff_hash and eff_hash != active_hash: + continue + if live_only and eff_replay: + continue + if as_of_cutoff is not None: + filtered_horizons = { + h_key: hor + for h_key, hor in ev.horizons.items() + if _prior_horizon_valid_at(ev, hor, as_of_cutoff) + } + if not filtered_horizons: + continue + ev = ev.model_copy( + update={"evaluated_as_of": as_of_cutoff, "horizons": filtered_horizons} + ) + active_outcomes.append(ev) + return active_commits, active_outcomes + def build_decay_report( self, strategy_id: str, *, horizon_days: int = 10, + live_only: bool = False, + as_of_cutoff: date | None = None, ) -> ForwardDecayReport: """Compute Backtest -> Forward Decay Ratio and drawdown/expectancy bounds.""" candidate = self.get_candidate(strategy_id) stage = candidate.stage if candidate is not None else PromotionStage.SHADOW backtest_avg = candidate.backtest_avg_return if candidate is not None else 0.0 + active_hash = candidate.strategy_hash if candidate is not None else None - commits = self.load_commits(strategy_id) + commits, outcomes = self._resolve_active_commits_and_outcomes( + strategy_id, + active_hash=active_hash, + live_only=live_only, + as_of_cutoff=as_of_cutoff, + ) total_committed = sum(len(c.signals) for c in commits) - outcomes = self.load_outcomes(strategy_id) mature_pairs: list[tuple[OutcomeEvent, OutcomeHorizon]] = [] for ev in outcomes: @@ -516,14 +950,21 @@ def build_decay_report( mature_signals=0, immature_signals=immature_count, effective_signals=0.0, + benchmark_coverage_ratio=0.0, backtest_avg_return=backtest_avg, decay_ratio=None, ) rets = [hor.tradable_post_cost_return for _, hor in mature_pairs] excess_rets = [hor.excess_return for _, hor in mature_pairs] + covered_excess = [hor.excess_return for _, hor in mature_pairs if hor.benchmark_available] + bench_cov = len(covered_excess) / len(mature_pairs) avg_ret = sum(rets) / len(rets) - avg_excess = sum(excess_rets) / len(excess_rets) + avg_excess = ( + sum(covered_excess) / len(covered_excess) + if covered_excess + else sum(excess_rets) / len(excess_rets) + ) win_rate = sum(1 for r in rets if r > 0) / len(rets) var = sum((r - avg_ret) ** 2 for r in rets) / max(1, len(rets) - 1) std_r = math.sqrt(max(0.0, var)) @@ -562,6 +1003,7 @@ def build_decay_report( mature_signals=mature_count, immature_signals=immature_count, effective_signals=n_eff, + benchmark_coverage_ratio=round(bench_cov, 4), forward_win_rate=round(win_rate, 4), forward_avg_post_cost_return=round(avg_ret, 6), forward_avg_excess_return=round(avg_excess, 6), @@ -583,167 +1025,209 @@ def evaluate_promotion( min_mature_signals: int = 100, min_effective_signals: float = 30.0, max_drawdown_halt: float = 0.25, + require_benchmark: bool = False, + as_of_cutoff: date | None = None, ) -> PromotionDecision: """Apply asymmetric promotion rules (Slow-Promote / Instant-Halt).""" - candidates = self._load_candidates() - cand = candidates.get(strategy_id) - if cand is None: - raise ValueError(f"Strategy '{strategy_id}' is not registered in ShadowLedger") + with self._ledger_lock(): + candidates = self._load_candidates() + cand = candidates.get(strategy_id) + if cand is None: + raise ValueError(f"Strategy '{strategy_id}' is not registered in ShadowLedger") + + prev_stage = cand.stage + if prev_stage == PromotionStage.HALTED: + return PromotionDecision( + strategy_id=strategy_id, + previous_stage=prev_stage, + new_stage=prev_stage, + action="hold", + blocking_reasons=[ + "Candidate is HALTED and requires explicit force_reset before promotion" + ], + ) - prev_stage = cand.stage - if prev_stage == PromotionStage.HALTED: - return PromotionDecision( - strategy_id=strategy_id, - previous_stage=prev_stage, - new_stage=prev_stage, - action="hold", - blocking_reasons=[ - "Candidate is HALTED and requires explicit force_reset before promotion" - ], + # Resolve active/live histories first; never let replay losses halt live or CANARY/ACTIVE candidates + all_active_commits, all_active_outcomes = self._resolve_active_commits_and_outcomes( + strategy_id, + active_hash=cand.strategy_hash, + live_only=False, + as_of_cutoff=as_of_cutoff, ) - - decay = self.build_decay_report(strategy_id, horizon_days=horizon_days) - chain_ok, chain_errors = self.verify_chain() - - # Instant halt on severe forward drawdown or systematic post-cost bleeding - halt_reasons: list[str] = [] - if decay.max_forward_drawdown > max_drawdown_halt: - halt_reasons.append( - f"Forward max drawdown {decay.max_forward_drawdown:.1%} exceeds redline {max_drawdown_halt:.1%}" + live_commits, live_outcomes = self._resolve_active_commits_and_outcomes( + strategy_id, + active_hash=cand.strategy_hash, + live_only=True, + as_of_cutoff=as_of_cutoff, ) - if decay.mature_signals >= 15 and decay.forward_avg_post_cost_return < -0.03: - halt_reasons.append( - f"Forward post-cost expectancy {decay.forward_avg_post_cost_return:.2%} < -3.0% over {decay.mature_signals} signals" + has_live_history = bool(live_commits) or ( + not all_active_commits and any(not ev.is_replay for ev in all_active_outcomes) ) - if halt_reasons: - new_stage = PromotionStage.HALTED - cand.stage = new_stage - cand.stage_history.append( - StageTransition( - from_stage=prev_stage, - to_stage=new_stage, - reason="; ".join(halt_reasons), - ) + halt_live_only = has_live_history or prev_stage in { + PromotionStage.CANARY, + PromotionStage.ACTIVE, + } + decay_halt = self.build_decay_report( + strategy_id, + horizon_days=horizon_days, + live_only=halt_live_only, + as_of_cutoff=as_of_cutoff, ) - candidates[strategy_id] = cand - self._save_candidates(candidates) - return PromotionDecision( - strategy_id=strategy_id, - previous_stage=prev_stage, - new_stage=new_stage, - action="halt", - blocking_reasons=halt_reasons, + chain_ok, chain_errors = self.verify_chain() + + # Instant halt on severe forward drawdown or systematic post-cost bleeding + halt_reasons: list[str] = [] + if decay_halt.max_forward_drawdown > max_drawdown_halt: + halt_reasons.append( + f"Forward max drawdown {decay_halt.max_forward_drawdown:.1%} exceeds redline {max_drawdown_halt:.1%}" + ) + if decay_halt.mature_signals >= 15 and decay_halt.forward_avg_post_cost_return < -0.03: + halt_reasons.append( + f"Forward post-cost expectancy {decay_halt.forward_avg_post_cost_return:.2%} < -3.0% over {decay_halt.mature_signals} signals" + ) + if halt_reasons: + new_stage = PromotionStage.HALTED + cand.stage = new_stage + cand.stage_history.append( + StageTransition( + from_stage=prev_stage, + to_stage=new_stage, + reason="; ".join(halt_reasons), + ) + ) + candidates[strategy_id] = cand + self._save_candidates(candidates) + return PromotionDecision( + strategy_id=strategy_id, + previous_stage=prev_stage, + new_stage=new_stage, + action="halt", + blocking_reasons=halt_reasons, + ) + + decay = self.build_decay_report( + strategy_id, + horizon_days=horizon_days, + live_only=True, + as_of_cutoff=as_of_cutoff, ) - passed: list[str] = [] - blocking: list[str] = [] + passed: list[str] = [] + blocking: list[str] = [] - if chain_ok: - passed.append("hash_chain_verified") - else: - blocking.append(f"Hash chain verification failed: {'; '.join(chain_errors)}") - - commits = self.load_commits(strategy_id) - if commits and all(c.is_replay for c in commits): - blocking.append("Replay-only commits cannot trigger live stage promotion") - - if prev_stage == PromotionStage.CANARY and cand.stage_entered_as_of is not None: - post_stage_days = { - ev.as_of - for ev in self.load_outcomes(strategy_id) - if ev.as_of > cand.stage_entered_as_of - and horizon_days in ev.horizons - and ev.horizons[horizon_days].mature - } - if len(post_stage_days) < min_trading_days: + if chain_ok: + passed.append("hash_chain_verified") + else: + blocking.append(f"Hash chain verification failed: {'; '.join(chain_errors)}") + + if all_active_commits and all(c.is_replay for c in all_active_commits): + blocking.append("Replay-only commits cannot trigger live stage promotion") + + if prev_stage == PromotionStage.CANARY and cand.stage_entered_as_of is not None: + post_stage_days = { + ev.as_of + for ev in live_outcomes + if ev.as_of > cand.stage_entered_as_of + and horizon_days in ev.horizons + and ev.horizons[horizon_days].mature + } + if len(post_stage_days) < min_trading_days: + blocking.append( + f"Canary dwell days {len(post_stage_days)} < {min_trading_days} since {cand.stage_entered_as_of}" + ) + + if decay.mature_trading_days >= min_trading_days: + passed.append(f"mature_trading_days>={min_trading_days}") + else: blocking.append( - f"Canary dwell days {len(post_stage_days)} < {min_trading_days} since {cand.stage_entered_as_of}" + f"Mature trading days {decay.mature_trading_days} < {min_trading_days}" ) - if decay.mature_trading_days >= min_trading_days: - passed.append(f"mature_trading_days>={min_trading_days}") - else: - blocking.append(f"Mature trading days {decay.mature_trading_days} < {min_trading_days}") + if decay.mature_signals >= min_mature_signals: + passed.append(f"mature_signals>={min_mature_signals}") + else: + blocking.append(f"Mature signals {decay.mature_signals} < {min_mature_signals}") - if decay.mature_signals >= min_mature_signals: - passed.append(f"mature_signals>={min_mature_signals}") - else: - blocking.append(f"Mature signals {decay.mature_signals} < {min_mature_signals}") + if decay.effective_signals >= min_effective_signals: + passed.append(f"effective_signals>={min_effective_signals}") + else: + blocking.append( + f"Cluster-adjusted effective signals {decay.effective_signals:.1f} < {min_effective_signals}" + ) - if decay.effective_signals >= min_effective_signals: - passed.append(f"effective_signals>={min_effective_signals}") - else: - blocking.append( - f"Cluster-adjusted effective signals {decay.effective_signals:.1f} < {min_effective_signals}" - ) + if require_benchmark and decay.benchmark_coverage_ratio < 0.8: + blocking.append( + f"Benchmark coverage {decay.benchmark_coverage_ratio:.0%} < 80% for excess-return gate" + ) + elif decay.forward_avg_excess_return > 0.0: + passed.append("positive_forward_excess_return") + else: + blocking.append( + f"Forward excess return {decay.forward_avg_excess_return:.2%} <= 0%" + ) - if decay.forward_avg_excess_return > 0.0: - passed.append("positive_forward_excess_return") - else: - blocking.append(f"Forward excess return {decay.forward_avg_excess_return:.2%} <= 0%") + if decay.forward_lower_bound_90 > 0.0: + passed.append("positive_90pct_confidence_lower_bound") + else: + blocking.append(f"90% lower bound {decay.forward_lower_bound_90:.2%} <= 0%") + + if blocking: + return PromotionDecision( + strategy_id=strategy_id, + previous_stage=prev_stage, + new_stage=prev_stage, + action="hold", + passed_gates=passed, + blocking_reasons=blocking, + ) - if decay.forward_lower_bound_90 > 0.0: - passed.append("positive_90pct_confidence_lower_bound") - else: - blocking.append(f"90% lower bound {decay.forward_lower_bound_90:.2%} <= 0%") + next_map = { + PromotionStage.DRAFT: PromotionStage.VALIDATED, + PromotionStage.VALIDATED: PromotionStage.SHADOW, + PromotionStage.SHADOW: PromotionStage.CANARY, + PromotionStage.CANARY: PromotionStage.ACTIVE, + PromotionStage.ACTIVE: PromotionStage.ACTIVE, + PromotionStage.HALTED: PromotionStage.HALTED, + PromotionStage.RETIRED: PromotionStage.RETIRED, + } + new_stage = next_map[prev_stage] + if new_stage == prev_stage: + return PromotionDecision( + strategy_id=strategy_id, + previous_stage=prev_stage, + new_stage=prev_stage, + action="hold", + passed_gates=passed, + ) - if blocking: - return PromotionDecision( - strategy_id=strategy_id, - previous_stage=prev_stage, - new_stage=prev_stage, - action="hold", - passed_gates=passed, - blocking_reasons=blocking, + maturity_dates = [ + hor.horizon_end_date or hor.exit_date or ev.evaluated_as_of + for ev in live_outcomes + if horizon_days in ev.horizons and (hor := ev.horizons[horizon_days]).mature + ] + cand.stage = new_stage + cand.stage_entered_as_of = as_of_cutoff or ( + max(maturity_dates) + if maturity_dates + else (live_commits[-1].as_of if live_commits else datetime.now(timezone.utc).date()) ) - - next_map = { - PromotionStage.DRAFT: PromotionStage.VALIDATED, - PromotionStage.VALIDATED: PromotionStage.SHADOW, - PromotionStage.SHADOW: PromotionStage.CANARY, - PromotionStage.CANARY: PromotionStage.ACTIVE, - PromotionStage.ACTIVE: PromotionStage.ACTIVE, - PromotionStage.HALTED: PromotionStage.HALTED, - PromotionStage.RETIRED: PromotionStage.RETIRED, - } - new_stage = next_map[prev_stage] - if new_stage == prev_stage: + cand.stage_history.append( + StageTransition( + from_stage=prev_stage, + to_stage=new_stage, + reason="Passed forward shadow-ledger statistical & chain gates", + ) + ) + candidates[strategy_id] = cand + self._save_candidates(candidates) return PromotionDecision( strategy_id=strategy_id, previous_stage=prev_stage, - new_stage=prev_stage, - action="hold", + new_stage=new_stage, + action="promote", passed_gates=passed, ) - mature_dates = [ - ev.as_of - for ev in self.load_outcomes(strategy_id) - if horizon_days in ev.horizons and ev.horizons[horizon_days].mature - ] - cand.stage = new_stage - cand.stage_entered_as_of = ( - max(mature_dates) - if mature_dates - else (commits[-1].as_of if commits else datetime.now(timezone.utc).date()) - ) - cand.stage_history.append( - StageTransition( - from_stage=prev_stage, - to_stage=new_stage, - reason="Passed forward shadow-ledger statistical & chain gates", - ) - ) - candidates[strategy_id] = cand - self._save_candidates(candidates) - return PromotionDecision( - strategy_id=strategy_id, - previous_stage=prev_stage, - new_stage=new_stage, - action="promote", - passed_gates=passed, - ) - # ── Rolling Bitemporal Out-of-Sample Simulation ────────────────── def simulate_rolling( @@ -761,6 +1245,8 @@ def simulate_rolling( max_drawdown_halt: float = 0.25, is_replay: bool = False, auto_register: bool = True, + benchmark_df: pd.DataFrame | None = None, + require_benchmark: bool = False, ) -> ShadowRollingSimulationReport: """Replay chronological point-in-time commits, backfills & promotion gates.""" unique_dates: set[date] = set() @@ -840,7 +1326,7 @@ def simulate_rolling( cand_now = self.get_candidate(strategy.meta.id) stage_before = cand_now.stage if cand_now is not None else initial_stage - self.backfill_outcomes(market_data, evaluated_as_of=sim_date) + self.backfill_outcomes(market_data, evaluated_as_of=sim_date, benchmark_df=benchmark_df) commit_id: str | None = None committed_count = 0 @@ -864,8 +1350,15 @@ def simulate_rolling( min_mature_signals=min_mature_signals, min_effective_signals=min_effective_signals, max_drawdown_halt=max_drawdown_halt, + require_benchmark=require_benchmark, + as_of_cutoff=sim_date, + ) + rep = self.build_decay_report( + strategy.meta.id, + horizon_days=horizon_days, + live_only=False, + as_of_cutoff=sim_date, ) - rep = self.build_decay_report(strategy.meta.id, horizon_days=horizon_days) step_action: Literal["promote", "hold", "halt"] = ( "promote" if decision.action == "promote" @@ -887,7 +1380,12 @@ def simulate_rolling( ) chain_ok, _ = self.verify_chain() - final_decay = self.build_decay_report(strategy.meta.id, horizon_days=horizon_days) + final_decay = self.build_decay_report( + strategy.meta.id, + horizon_days=horizon_days, + live_only=False, + as_of_cutoff=sim_dates[-1], + ) final_cand = self.get_candidate(strategy.meta.id) final_stage = final_cand.stage if final_cand is not None else initial_stage halted = final_stage == PromotionStage.HALTED @@ -1041,25 +1539,90 @@ def _apply_portfolio_profile( selected.append(item) return temp, selected + @staticmethod + def build_equal_weight_benchmark(market_data: dict[str, pd.DataFrame]) -> pd.DataFrame | None: + """Build a causal equal-weight benchmark OHLCV frame from a universe mapping.""" + if not market_data: + return None + from alphaevo.backtest.allocator import _build_causal_market_proxy + + date_set: set[date] = set() + for df in market_data.values(): + if df is None or df.empty or "date" not in df.columns: + continue + for item in pd.to_datetime(df["date"], errors="coerce").dt.date.dropna().tolist(): + if isinstance(item, date): + date_set.add(item) + all_dates = sorted(date_set) + if len(all_dates) < 2: + return None + return _build_causal_market_proxy(all_dates, market_data) + @staticmethod def _compute_benchmark_return( bench_df: pd.DataFrame | None, *, - start_after: date, + entry_date: date, + exit_date: date | None, horizon_days: int, - ) -> float: + ) -> tuple[float, bool]: if bench_df is None or bench_df.empty or "close" not in bench_df or "date" not in bench_df: - return 0.0 - dates = pd.to_datetime(bench_df["date"]).dt.date - pre = bench_df.loc[dates <= start_after] - fut = bench_df.loc[dates > start_after] - if pre.empty or len(fut) < horizon_days: - return 0.0 - start_c = float(pre["close"].iloc[-1]) - end_c = float(fut["close"].iloc[horizon_days - 1]) - if start_c <= 0: - return 0.0 - return (end_c / start_c) - 1.0 + return (0.0, False) + work = bench_df.copy() + work["_bdate"] = pd.to_datetime(work["date"], errors="coerce").dt.date + work = work.loc[work["_bdate"].notna()].sort_values("_bdate", kind="mergesort") + if "observed_count" in work.columns: + work = work.loc[pd.to_numeric(work["observed_count"], errors="coerce").fillna(0) > 0] + if work.empty: + return (0.0, False) + + pre = work.loc[work["_bdate"] < entry_date] + fut = work.loc[work["_bdate"] >= entry_date].reset_index(drop=True) + if fut.empty: + return (0.0, False) + + start_p = _finite_positive(fut["open"].iloc[0]) if "open" in fut else None + if start_p is None and not pre.empty: + start_p = _finite_positive(pre["close"].iloc[-1]) + if start_p is None: + return (0.0, False) + + if exit_date is not None: + if fut["_bdate"].iloc[0] > exit_date or (fut["_bdate"].iloc[0] - entry_date).days > 5: + return (0.0, False) + matched = fut.loc[fut["_bdate"] <= exit_date] + if matched.empty: + return (0.0, False) + matched_date = matched["_bdate"].iloc[-1] + if (exit_date - matched_date).days > 5: + return (0.0, False) + if "return_count" in matched.columns and exit_date > entry_date: + ret_rows = ( + matched.loc[matched["_bdate"] > entry_date] + if (matched["_bdate"] > entry_date).any() + else matched + ) + if pd.to_numeric(ret_rows["return_count"], errors="coerce").fillna(0).sum() <= 0: + return (0.0, False) + end_c = _finite_positive(matched["close"].iloc[-1]) + if end_c is None: + return (0.0, False) + return ((end_c / start_p) - 1.0, True) + + if len(fut) < horizon_days: + return (0.0, False) + if "return_count" in fut.columns: + head_ret = ( + pd.to_numeric(fut.iloc[:horizon_days]["return_count"], errors="coerce") + .fillna(0) + .sum() + ) + if head_ret <= 0: + return (0.0, False) + end_c = _finite_positive(fut["close"].iloc[horizon_days - 1]) + if end_c is None: + return (0.0, False) + return ((end_c / start_p) - 1.0, True) def _load_candidates(self) -> dict[str, CandidateSpec]: if not self.candidates_file.is_file(): @@ -1069,9 +1632,9 @@ def _load_candidates(self) -> dict[str, CandidateSpec]: def _save_candidates(self, candidates: dict[str, CandidateSpec]) -> None: payload = {k: v.model_dump(mode="json") for k, v in sorted(candidates.items())} - self.candidates_file.write_text( + _atomic_write_text( + self.candidates_file, json.dumps(payload, indent=2, ensure_ascii=False), - encoding="utf-8", ) diff --git a/tests/unit/test_round2_to_6_quant_shadow_portfolio_rigor.py b/tests/unit/test_round2_to_6_quant_shadow_portfolio_rigor.py new file mode 100644 index 0000000..e724b77 --- /dev/null +++ b/tests/unit/test_round2_to_6_quant_shadow_portfolio_rigor.py @@ -0,0 +1,875 @@ +"""Regression tests for Rounds 2-6: ShadowLedger, MarketRuleChecker, BacktestEngine, PortfolioBacktester, Allocator.""" + +from __future__ import annotations + +from concurrent.futures import ThreadPoolExecutor +from datetime import date, timedelta +from pathlib import Path + +import pandas as pd # type: ignore[import-untyped] +import pytest + +from alphaevo.backtest.allocator import ( + RegimeAdaptiveAllocator, + RiskBudgetConfig, + _build_causal_market_proxy, +) +from alphaevo.backtest.engine import BacktestEngine +from alphaevo.backtest.portfolio import PortfolioBacktester, PortfolioConfig +from alphaevo.backtest.rules import MarketRuleChecker +from alphaevo.forward.contracts import OutcomeHorizon +from alphaevo.forward.shadow_ledger import ShadowLedger +from alphaevo.models.enums import ( + ExitReason, + MarketType, + PromotionStage, + SignalDirection, + StrategyCategory, +) +from alphaevo.models.execution import ( + AntiFitMetrics, + BacktestResult, + EvaluationReport, + OverallMetrics, + SampleBatch, + TradeSignal, +) +from alphaevo.models.strategy import ( + ExecutionConfig, + MarketRuleConfig, + SetupSpec, + StopLossConfig, + Strategy, + StrategyCondition, + StrategyEntry, + StrategyExit, + StrategyMeta, + TakeProfitConfig, +) + + +def _eval_report() -> EvaluationReport: + return EvaluationReport( + strategy_id="test_strat", + batch_id="b1", + overall=OverallMetrics( + win_rate=0.60, + avg_return=0.02, + sharpe_ratio=1.5, + signal_count=40, + ), + anti_overfit=AntiFitMetrics( + train_val_gap=0.01, + val_test_gap=0.01, + param_sensitivity=0.05, + ), + deflated_sharpe_prob=0.90, + null_control_passed=True, + ) + + +def _make_strategy( + *, + sid: str = "r2_strat", + market: MarketType = MarketType.US, + rsi_max: float = 100.0, + stop_pct: float = 0.05, + timing: str = "next_open", +) -> Strategy: + return Strategy( + meta=StrategyMeta( + id=sid, + name=sid, + market=market, + category=StrategyCategory.REVERSAL, + ), + description="Deterministic test strategy", + setup=SetupSpec( + trigger_rule="rsi_14 <= cap", + planned_stop_pct=stop_pct, + target_rr=2.0, + min_rr=1.0, + ), + entry=StrategyEntry( + logic="and", + triggers=[StrategyCondition(indicator="rsi_14", op="<=", value=rsi_max)], + execution=ExecutionConfig(timing=timing, slippage=0.0), # type: ignore[arg-type] + ), + exit=StrategyExit( + stop_loss=StopLossConfig(type="pct", value=stop_pct), + take_profit=TakeProfitConfig(type="rr", value=2.0), + max_holding_days=10, + ), + ) + + +def _make_bars( + start: date, + n_bars: int, + *, + step: float = 0.008, + base_price: float = 100.0, +) -> pd.DataFrame: + rows = [] + price = base_price + cur = start + while len(rows) < n_bars: + if cur.weekday() < 5: + prev_c = price + price = prev_c * (1.0 + step) + rows.append( + { + "date": cur, + "open": round(prev_c, 4), + "high": round(max(prev_c, price) * 1.005, 4), + "low": round(min(prev_c, price) * 0.998, 4), + "close": round(price, 4), + "prev_close": round(prev_c, 4), + "volume": 1_000_000.0, + } + ) + cur += timedelta(days=1) + return pd.DataFrame(rows) + + +def test_round2_mixed_replay_and_live_cannot_promote_and_hash_re_reg_isolates( + tmp_path: Path, +) -> None: + ledger = ShadowLedger(tmp_path / "ledger") + strat_v1 = _make_strategy(sid="mixed_strat", market=MarketType.US, rsi_max=100.0) + ledger.register_candidate(strat_v1, _eval_report()) + + bars = _make_bars(date(2025, 1, 2), 90, step=0.008) + trading_days = pd.to_datetime(bars["date"]).dt.date.tolist() + market = {f"US{i}": bars.copy() for i in range(4)} + + # 20 replay commits yielding plenty of positive mature outcomes + for d in trading_days[20:40]: + ledger.commit_signals(strat_v1, market, as_of=d, is_replay=True) + + # 1 live commit so all(c.is_replay for c in commits) is False, yet live samples < gate! + ledger.commit_signals(strat_v1, market, as_of=trading_days[41], is_replay=False) + ledger.backfill_outcomes(market, evaluated_as_of=trading_days[-1]) + + dec = ledger.evaluate_promotion( + strat_v1.meta.id, + horizon_days=5, + min_trading_days=5, + min_mature_signals=5, + min_effective_signals=2.0, + ) + assert dec.action == "hold" + assert dec.new_stage == PromotionStage.SHADOW + assert any("Mature trading days 1 < 5" in r for r in dec.blocking_reasons) + + # Re-register SAME strategy_id with changed rule -> decay report must NOT pool old hash outcomes + strat_v2 = _make_strategy(sid="mixed_strat", market=MarketType.US, rsi_max=95.0) + spec_v2 = ledger.register_candidate(strat_v2, _eval_report(), force_reset=True) + assert spec_v2.strategy_hash != ledger.load_commits("mixed_strat")[0].strategy_hash + rep_v2 = ledger.build_decay_report("mixed_strat", horizon_days=5, live_only=False) + assert rep_v2.mature_signals == 0 + assert rep_v2.total_committed_signals == 0 + + +def test_round3_concurrent_commits_and_cutoff_safe_non_overwriting_backfill( + tmp_path: Path, +) -> None: + ledger = ShadowLedger(tmp_path / "conc_ledger") + bars = _make_bars(date(2025, 1, 2), 65, step=0.006) + trading_days = pd.to_datetime(bars["date"]).dt.date.tolist() + market = {"AAPL": bars.copy(), "MSFT": bars.copy()} + + strats = [_make_strategy(sid=f"conc_{i}", market=MarketType.US) for i in range(6)] + as_of_d = trading_days[22] + + def _emit(s: Strategy) -> str: + return ledger.commit_signals(s, market, as_of=as_of_d, is_replay=False).commit_id + + with ThreadPoolExecutor(max_workers=6) as pool: + commit_ids = list(pool.map(_emit, strats)) + assert len(commit_ids) == 6 + + ok, errs = ledger.verify_chain() + assert ok is True, errs + assert len(ledger.load_commits()) == 6 + + # Earlier-cutoff safety & immutability of already matured outcomes + ledger_cut = ShadowLedger(tmp_path / "cut_ledger") + s_cut = _make_strategy(sid="cut_strat", market=MarketType.US) + ledger_cut.commit_signals(s_cut, {"AAPL": bars}, as_of=trading_days[20], is_replay=False) + + # Mature up to day 35 (T+5 and T+10 both mature) + ev_late = ledger_cut.backfill_outcomes({"AAPL": bars}, evaluated_as_of=trading_days[35]) + assert ev_late[0].horizons[5].mature is True + assert ev_late[0].horizons[10].mature is True + orig_ret_5 = ev_late[0].horizons[5].tradable_post_cost_return + + # Re-evaluate at EARLIER cutoff day 27: T+5 matured at day 25 (<=27), T+10 at day 30 (>27 must NOT leak!) + ev_early = ledger_cut.backfill_outcomes({"AAPL": bars}, evaluated_as_of=trading_days[27]) + assert ev_early[0].horizons[5].mature is True + assert ev_early[0].horizons[10].mature is False + + # Mutate BOTH T+5 (bar 25) and T+10 (bar 30) prices after earlier cutoff -> both stay immutable! + orig_ret_10 = ev_late[0].horizons[10].tradable_post_cost_return + mutated = bars.copy() + mutated.loc[25, "close"] = 1.0 + mutated.loc[30, "close"] = 1.0 + ev_mutated = ledger_cut.backfill_outcomes({"AAPL": mutated}, evaluated_as_of=trading_days[45]) + assert ev_mutated[0].horizons[5].tradable_post_cost_return == pytest.approx(orig_ret_5) + assert ev_mutated[0].horizons[10].tradable_post_cost_return == pytest.approx(orig_ret_10) + + # Pre-upgrade legacy commit JSON (without strategy_hash/market fields) still passes verify_chain() + legacy_ledger = ShadowLedger(tmp_path / "legacy_ledger") + import hashlib + import json + + legacy_payload = { + "commit_id": "cmt_20240101_00000001", + "strategy_id": "legacy_v1", + "as_of": "2024-01-01", + "committed_at": "2024-01-01T00:00:00Z", + "market_temperature": "normal", + "total_raw_candidates": 0, + "sector_capped_count": 0, + "is_replay": False, + "signals": [], + "prev_hash": "0" * 64, + "record_hash": "", + } + legacy_raw = json.dumps( + legacy_payload, sort_keys=True, ensure_ascii=False, separators=(",", ":") + ) + legacy_payload["record_hash"] = hashlib.sha256(legacy_raw.encode("utf-8")).hexdigest() + legacy_ledger.commits_file.write_text(json.dumps(legacy_payload) + "\n", encoding="utf-8") + legacy_ledger.head_hash_file.write_text(legacy_payload["record_hash"] + "\n", encoding="utf-8") + ok_leg, errs_leg = legacy_ledger.verify_chain() + assert ok_leg is True, errs_leg + + # Replay losses must NOT halt a candidate that already has live commits + live_safe = ShadowLedger(tmp_path / "live_safe") + s_live = _make_strategy(sid="live_safe_v1", market=MarketType.US) + live_safe.register_candidate(s_live, _eval_report()) + live_bars_up = _make_bars(date(2025, 1, 2), 65, step=0.008) + up_days = pd.to_datetime(live_bars_up["date"]).dt.date.tolist() + live_bars_down = _make_bars(date(2025, 1, 2), 65, step=-0.018) + # 16 losing replay commits earlier, then 2 live commits on winning bars + for d in up_days[20:36]: + live_safe.commit_signals(s_live, {"AAPL": live_bars_down}, as_of=d, is_replay=True) + live_safe.commit_signals(s_live, {"AAPL": live_bars_up}, as_of=up_days[37], is_replay=False) + live_safe.backfill_outcomes({"AAPL": live_bars_up}, evaluated_as_of=up_days[-1]) + dec_safe = live_safe.evaluate_promotion( + s_live.meta.id, + horizon_days=5, + min_trading_days=5, + min_mature_signals=5, + min_effective_signals=2.0, + ) + assert dec_safe.action == "hold" + assert dec_safe.new_stage == PromotionStage.SHADOW + + +def test_round3_t_plus_1_gap_down_stop_and_benchmark_coverage_gate( + tmp_path: Path, +) -> None: + ledger = ShadowLedger(tmp_path / "t1_ledger") + s_cn = _make_strategy(sid="cn_t1", market=MarketType.A_SHARE, stop_pct=0.05) + ledger.register_candidate(s_cn, _eval_report()) + + bars = _make_bars(date(2025, 1, 2), 55, step=0.003) + commit_idx = 20 + commit_date = bars["date"].iloc[commit_idx] + market_cn = {"600519": bars.copy()} + ledger.commit_signals(s_cut := s_cn, market_cn, as_of=commit_date, is_replay=False) + + entry_ref = float(bars["close"].iloc[commit_idx]) + stop_lvl = round(entry_ref * 0.95, 4) + + # Bar 21 (pos=0, purchase day under next_open): intraday low dips -> MUST NOT trigger under T+1! + bars.loc[21, "open"] = entry_ref + bars.loc[21, "low"] = stop_lvl * 0.92 + bars.loc[21, "close"] = entry_ref + + # Bar 22 (pos=1, T+1): tradable gap-down open (-6.9% inside +-10% main board!) -> fills at gap_open! + gap_open = round(stop_lvl * 0.98, 4) + bars.loc[22, "open"] = gap_open + bars.loc[22, "high"] = gap_open * 1.01 + bars.loc[22, "low"] = gap_open * 0.99 + bars.loc[22, "close"] = gap_open + + bench = _make_bars(date(2025, 1, 2), 55, step=0.001) + bench.loc[21, "open"] = 100.0 + bench.loc[22, "close"] = 102.0 + + events = ledger.backfill_outcomes( + {"600519": bars}, + evaluated_as_of=bars["date"].iloc[-1], + benchmark_df=bench, + round_trip_cost=0.0, + ) + hor5 = events[0].horizons[5] + assert hor5.mature is True + assert hor5.stopped_out is True + assert hor5.exit_date == bars["date"].iloc[22] + assert hor5.horizon_end_date == bars["date"].iloc[25] + expected_tradable = (gap_open / entry_ref) - 1.0 + assert hor5.tradable_post_cost_return == pytest.approx(expected_tradable, abs=1e-4) + assert hor5.benchmark_available is True + assert hor5.benchmark_return == pytest.approx(0.02, abs=1e-4) + + # Early-stopped T+20 horizon MUST NOT leak as mature into an earlier T+3 cutoff! + early_view = ledger.backfill_outcomes( + {"600519": bars}, + evaluated_as_of=bars["date"].iloc[24], + benchmark_df=bench, + round_trip_cost=0.0, + ) + assert early_view[0].horizons[20].mature is False + + # Benchmark missing on early stop before first bench bar -> benchmark_available=False (fresh ledger) + ledger_late_bm = ShadowLedger(tmp_path / "late_bm") + ledger_late_bm.register_candidate(s_cn, _eval_report()) + ledger_late_bm.commit_signals(s_cn, market_cn, as_of=commit_date, is_replay=False) + bench_late = bench.iloc[25:].copy() + events_late_bm = ledger_late_bm.backfill_outcomes( + {"600519": bars}, + evaluated_as_of=bars["date"].iloc[-1], + benchmark_df=bench_late, + round_trip_cost=0.0, + ) + assert events_late_bm[0].horizons[5].benchmark_available is False + + # require_benchmark=True blocks promotion when benchmark_df is missing despite positive committed returns + ledger_nobm = ShadowLedger(tmp_path / "nobm") + s_us = _make_strategy(sid="nobm_us", market=MarketType.US, stop_pct=0.05) + ledger_nobm.register_candidate(s_us, _eval_report()) + us_bars = _make_bars(date(2025, 1, 2), 65, step=0.006) + us_days = pd.to_datetime(us_bars["date"]).dt.date.tolist() + us_mkt = {f"U{i}": us_bars.copy() for i in range(4)} + for d in us_days[20:28]: + ledger_nobm.commit_signals(s_us, us_mkt, as_of=d, is_replay=False) + ledger_nobm.backfill_outcomes(us_mkt, evaluated_as_of=us_days[-1], benchmark_df=None) + dec_req = ledger_nobm.evaluate_promotion( + s_us.meta.id, + horizon_days=5, + min_trading_days=5, + min_mature_signals=5, + min_effective_signals=2.0, + require_benchmark=True, + ) + assert dec_req.action == "hold" + assert any("Benchmark coverage" in r for r in dec_req.blocking_reasons) + + # Uncommitted orphan outcomes in outcomes.jsonl are ignored once commits exist + from alphaevo.forward.contracts import OutcomeEvent + + with ledger_nobm.outcomes_file.open("a", encoding="utf-8") as fh: + ev_orphan = OutcomeEvent( + signal_id="orphan_fake_1", + strategy_id=s_us.meta.id, + symbol="FAKE", + sector="tech", + as_of=date(2025, 6, 1), + evaluated_as_of=date(2025, 6, 15), + horizons={ + 5: OutcomeHorizon(horizon_days=5, mature=True, tradable_post_cost_return=0.5) + }, + ) + fh.write(ev_orphan.model_dump_json() + "\n") + dec_after_orphan = ledger_nobm.build_decay_report(s_us.meta.id, horizon_days=5, live_only=True) + assert dec_after_orphan.mature_signals <= 32 + _ = s_cut + + +def test_round4_rules_prev_close_fallback_boards_open_buy_and_eod_t1() -> None: + checker = MarketRuleChecker() + rules = MarketRuleConfig(t_plus_1=True, limit_up_down=True, suspension=True) + + # Missing prev_close column -> falls back to df['close'].iloc[idx - 1] + df_no_prev = pd.DataFrame( + [ + { + "date": date(2025, 1, 2), + "open": 10.0, + "high": 10.2, + "low": 9.8, + "close": 10.0, + "volume": 1000.0, + }, + { + "date": date(2025, 1, 3), + "open": 10.5, + "high": 11.5, + "low": 10.5, + "close": 11.5, + "volume": 1000.0, + }, + { + "date": date(2025, 1, 4), + "open": 11.5, + "high": 15.0, + "low": 11.5, + "close": 15.0, + "volume": 1000.0, + }, + ] + ) + assert ( + checker.can_buy(df_no_prev, 1, rules, symbol="600519") is False + ) # +15% main board blocked + assert ( + checker.can_buy(df_no_prev, 1, rules, symbol="301001") is True + ) # +15% ChiNext 301 allowed (20%) + assert ( + checker.can_buy(df_no_prev, 1, rules, symbol="689009") is True + ) # +15% STAR 689 allowed (20%) + assert checker.can_buy(df_no_prev, 2, rules, symbol="920001") is False # +30.4% BSE 920 blocked + + # BacktestEngine: next_open uses open price check (not EOD close lookahead!) + rows_buy = [] + for i in range(42): + d = date(2025, 1, 1) + timedelta(days=i) + o = h = lo = c = 100.0 + if i == 31: + # Opens flat at 100 (tradable!), closes limit-up at 110 + o = 100.0 + h = 110.0 + lo = 99.5 + c = 110.0 + rows_buy.append( + {"date": d, "open": o, "high": h, "low": lo, "close": c, "volume": 1_000_000.0} + ) + df_buy = pd.DataFrame(rows_buy) + strat_buy = _make_strategy( + sid="cn_open", market=MarketType.A_SHARE, stop_pct=0.05, timing="next_open" + ) + bt_buy = BacktestEngine(slippage=0.0, commission=0.0, min_data_days=25).run( + strat_buy, + {"600519": df_buy}, + SampleBatch( + batch_id="cn_open", + strategy_id=strat_buy.meta.id, + symbols=["600519"], + date_range=(date(2025, 1, 1), date(2025, 2, 20)), + ), + ) + assert any(s.signal_date == date(2025, 2, 1) for s in bt_buy.signals) + + # Intraday stop fills at -5% (above -10% limit-down) even when EOD closes limit-down (-11%) + rows_stop = [] + for i in range(42): + d = date(2025, 1, 1) + timedelta(days=i) + o = h = lo = c = 100.0 + if i == 32: + o = 99.0 + h = 99.5 + lo = 94.0 + c = 89.0 + rows_stop.append( + {"date": d, "open": o, "high": h, "low": lo, "close": c, "volume": 1_000_000.0} + ) + df_stop = pd.DataFrame(rows_stop) + bt_stop = BacktestEngine(slippage=0.0, commission=0.0, min_data_days=25).run( + strat_buy, + {"600519": df_stop}, + SampleBatch( + batch_id="cn_stop", + strategy_id=strat_buy.meta.id, + symbols=["600519"], + date_range=(date(2025, 1, 1), date(2025, 2, 20)), + ), + ) + assert any( + s.signal_date == date(2025, 2, 1) and s.exit_reason == ExitReason.STOP_LOSS + for s in bt_stop.signals + ) + + # End-of-data last-bar entry must NOT close with holding_days=0 under A-share T+1 + df_last = _make_bars(date(2025, 1, 2), 36, step=0.0) + # Only allow entry on bar 34 -> opens at bar 35 (very last bar!) + df_last["close"] = 100.0 + df_last["open"] = 100.0 + df_last.loc[34, "close"] = ( + 70.0 # artificial drop won't trigger rsi_14<=100; force signal via volume ratio + ) + strat_last = Strategy( + meta=StrategyMeta( + id="last_bar_t1", + name="last", + market=MarketType.A_SHARE, + category=StrategyCategory.TREND, + ), + description="Trigger only on high volume spike", + entry=StrategyEntry( + logic="and", + triggers=[StrategyCondition(indicator="volume_ratio_1d_5d", op=">", value=3.0)], + execution=ExecutionConfig(timing="next_open", slippage=0.0), + ), + exit=StrategyExit( + stop_loss=StopLossConfig(type="pct", value=0.05), + take_profit=TakeProfitConfig(type="rr", value=2.0), + max_holding_days=5, + ), + ) + df_last.loc[34, "volume"] = 10_000_000.0 + bt_last = BacktestEngine(slippage=0.0, commission=0.0, min_data_days=25).run( + strat_last, + {"600519": df_last}, + SampleBatch( + batch_id="last_t1", + strategy_id=strat_last.meta.id, + symbols=["600519"], + date_range=(date(2025, 1, 2), date(2025, 3, 15)), + ), + ) + assert len(bt_last.signals) == 1 + assert bt_last.signals[0].exit_price is None + assert bt_last.executed_signals == 0 + + # Same-day limit-down stop + sellable take-profit falls back to take-profit + rows_fb = [] + for i in range(36): + d = date(2025, 1, 1) + timedelta(days=i) + o = h = lo = c = 100.0 + if i == 32: + # Opens limit-down at 89 (below 5% stop -> unfillable!), then rallies to 110 TP target! + o = 89.0 + lo = 89.0 + h = 110.0 + c = 109.0 + rows_fb.append( + {"date": d, "open": o, "high": h, "low": lo, "close": c, "volume": 1_000_000.0} + ) + bt_fb = BacktestEngine(slippage=0.0, commission=0.0, min_data_days=25).run( + strat_buy, + {"600519": pd.DataFrame(rows_fb)}, + SampleBatch( + batch_id="cn_fb", + strategy_id=strat_buy.meta.id, + symbols=["600519"], + date_range=(date(2025, 1, 1), date(2025, 2, 20)), + ), + ) + assert any( + s.signal_date == date(2025, 2, 1) and s.exit_reason == ExitReason.TAKE_PROFIT + for s in bt_fb.signals + ) + + +def test_round5_portfolio_causal_sizing_and_utilization() -> None: + sigs = [ + TradeSignal( + symbol=f"S{i}", + signal_date=date(2024, 6, 3), + direction=SignalDirection.LONG, + entry_price=50.0, + exit_price=55.0, + exit_date=date(2024, 6, 10), + return_pct=0.10, + holding_days=5, + exit_reason=ExitReason.TAKE_PROFIT, + ) + for i in range(5) + ] + market_bars = { + f"S{i}": pd.DataFrame([{"date": date(2024, 6, d), "close": 50.0} for d in range(3, 11)]) + for i in range(5) + } + res = PortfolioBacktester( + PortfolioConfig(initial_capital=100_000.0, max_positions=5, position_size_pct=0.20) + ).simulate( + BacktestResult( + strategy_id="p5", batch_id="b5", signals=sigs, total_signals=5, executed_signals=5 + ), + market_data=market_bars, + ) + assert res.total_trades == 5 + # Equal 20% slices from start-of-day equity (no geometric decay!) + assert all(t.capital_allocated == pytest.approx(20_000.0) for t in res.trades) + assert res.capital_utilization > 0.80 + + # Same-day causality: max_positions=1, pos A exits on June 10, signal B enters June 10 -> skipped! + sig_a = TradeSignal( + symbol="A", + signal_date=date(2024, 6, 3), + direction=SignalDirection.LONG, + entry_price=50.0, + exit_price=75.0, + exit_date=date(2024, 6, 10), + return_pct=0.50, + holding_days=5, + exit_reason=ExitReason.TAKE_PROFIT, + ) + sig_b = TradeSignal( + symbol="B", + signal_date=date(2024, 6, 10), + direction=SignalDirection.LONG, + entry_price=50.0, + exit_price=55.0, + exit_date=date(2024, 6, 14), + return_pct=0.10, + holding_days=4, + exit_reason=ExitReason.TAKE_PROFIT, + ) + res_causal = PortfolioBacktester( + PortfolioConfig(initial_capital=100_000.0, max_positions=1, position_size_pct=1.0) + ).simulate( + BacktestResult( + strategy_id="p_causal", + batch_id="b_causal", + signals=[sig_a, sig_b], + total_signals=2, + executed_signals=2, + ) + ) + assert res_causal.total_trades == 1 + assert res_causal.trades[0].signal.symbol == "A" + + +def test_round6_allocator_zero_weight_dead_strategy_and_proxy_gap_nat() -> None: + bars = _make_bars(date(2025, 1, 2), 90, step=0.004) + market = {"AAPL": bars, "MSFT": _make_bars(date(2025, 1, 2), 90, step=0.003)} + + active_s = _make_strategy(sid="active_s", market=MarketType.US, rsi_max=100.0) + dead_s = _make_strategy(sid="dead_s", market=MarketType.US, rsi_max=-50.0) + + rep = RegimeAdaptiveAllocator( + RiskBudgetConfig(lookback_days=20, max_strategy_weight=0.60) + ).allocate([active_s, dead_s], market) + + # Once active_s accumulates non-zero returns, dead_s gets 0.0 weight (not 60% or cap excess!) + tail_weights = [p.weights["dead_s"] for p in rep.daily_curve[-15:]] + assert all(w == 0.0 for w in tail_weights) + assert rep.strategies[1].signal_count == 0 + + # Proxy builder tolerates NaT rows and does NOT spike +100% across a multi-day suspension gap + all_dates = [date(2025, 1, 2) + timedelta(days=i) for i in range(6)] + gap_df = pd.DataFrame( + [ + {"date": all_dates[0], "open": 10.0, "high": 10.0, "low": 10.0, "close": 10.0}, + {"date": pd.NaT, "open": 99.0, "high": 99.0, "low": 99.0, "close": 99.0}, + {"date": all_dates[5], "open": 20.0, "high": 20.0, "low": 20.0, "close": 20.0}, + ] + ) + proxy = _build_causal_market_proxy(all_dates, {"GAP": gap_df}) + assert len(proxy) == 6 + assert proxy["close"].iloc[-1] == pytest.approx(100.0) + + # _apply_weight_cap conserves budget across multiple active under-cap strategies without waking inactive 0s + from alphaevo.backtest.allocator import _apply_weight_cap + + capped = _apply_weight_cap([0.70, 0.25, 0.05, 0.0], 0.40) + assert capped == pytest.approx([0.40, 0.40, 0.20, 0.0], abs=1e-9) + + +def test_round2_to_6_codex_followup_invariants(tmp_path: Path) -> None: + # 1. ACTIVE candidate with zero live commits must NOT be halted by replay losses + act_ledger = ShadowLedger(tmp_path / "act_ledger") + s_act = _make_strategy(sid="act_strat", market=MarketType.US) + act_ledger.register_candidate(s_act, _eval_report(), stage=PromotionStage.ACTIVE) + down_bars = _make_bars(date(2025, 1, 2), 65, step=-0.018) + down_days = pd.to_datetime(down_bars["date"]).dt.date.tolist() + for d in down_days[20:36]: + act_ledger.commit_signals(s_act, {"AAPL": down_bars}, as_of=d, is_replay=True) + act_ledger.backfill_outcomes({"AAPL": down_bars}, evaluated_as_of=down_days[-1]) + dec_act = act_ledger.evaluate_promotion(s_act.meta.id, horizon_days=5) + assert dec_act.action != "halt" + assert dec_act.new_stage == PromotionStage.ACTIVE + + # 2. Late benchmark arrival upgrades benchmark_available=False -> True on previously matured horizon + late_bm_ledger = ShadowLedger(tmp_path / "late_bm_upgrade") + s_bm = _make_strategy(sid="bm_up", market=MarketType.US) + late_bm_ledger.register_candidate(s_bm, _eval_report()) + up_bars = _make_bars(date(2025, 1, 2), 45, step=0.005) + bm_bars = _make_bars(date(2025, 1, 2), 45, step=0.002) + commit_d = up_bars["date"].iloc[20] + late_bm_ledger.commit_signals(s_bm, {"AAPL": up_bars}, as_of=commit_d, is_replay=False) + ev1 = late_bm_ledger.backfill_outcomes( + {"AAPL": up_bars}, evaluated_as_of=up_bars["date"].iloc[-1], benchmark_df=None + ) + assert ev1[0].horizons[5].mature is True + assert ev1[0].horizons[5].benchmark_available is False + ev2 = late_bm_ledger.backfill_outcomes( + {"AAPL": up_bars}, evaluated_as_of=up_bars["date"].iloc[-1], benchmark_df=bm_bars + ) + assert ev2[0].horizons[5].benchmark_available is True + + # 3. Synthetic zero-observation proxy window returns benchmark_available=False + zero_obs_dates = [date(2025, 1, 2) + timedelta(days=i) for i in range(6)] + gap_df = pd.DataFrame( + [ + {"date": zero_obs_dates[0], "close": 100.0}, + {"date": zero_obs_dates[5], "close": 100.0}, + ] + ) + proxy_bm = _build_causal_market_proxy(zero_obs_dates, {"GAP": gap_df}) + _, ok_zero_obs = ShadowLedger._compute_benchmark_return( + proxy_bm, entry_date=zero_obs_dates[1], exit_date=zero_obs_dates[4], horizon_days=3 + ) + assert ok_zero_obs is False + + # 4. PortfolioBacktester marks unclosed terminal holdings when market_data is provided + open_sig = TradeSignal( + symbol="600519", + signal_date=date(2025, 1, 2), + direction=SignalDirection.LONG, + entry_price=100.0, + exit_price=None, + exit_date=None, + exit_reason=None, + return_pct=0.0, + holding_days=0, + ) + open_mkt = { + "600519": pd.DataFrame( + [ + {"date": date(2025, 1, 2), "close": 100.0}, + {"date": date(2025, 1, 3), "close": 80.0}, + ] + ) + } + res_open = PortfolioBacktester( + PortfolioConfig(initial_capital=100_000.0, max_positions=1, position_size_pct=1.0) + ).simulate( + BacktestResult( + strategy_id="open_mtm", + batch_id="b_open", + signals=[open_sig], + total_signals=1, + executed_signals=0, + ), + market_data=open_mkt, + ) + assert res_open.final_equity == pytest.approx(80_000.0) + assert res_open.max_drawdown == pytest.approx(0.20, abs=1e-4) + + # 5. CLI shadow emit rejects --no-replay on offline bundled data + from typer.testing import CliRunner + + from alphaevo.cli.main import app + + r_bad = CliRunner().invoke( + app, ["shadow", "emit", "ma_crossover_v1", "--no-replay"], env={"NO_COLOR": "1"} + ) + assert r_bad.exit_code != 0 + + # 6. Day-1 drawdown from initial_capital is captured (100k -> 70k reports 0.30, not 0.0) + day1_loss = TradeSignal( + symbol="AAPL", + signal_date=date(2025, 1, 2), + direction=SignalDirection.LONG, + entry_price=100.0, + exit_price=70.0, + exit_date=date(2025, 1, 2), + return_pct=-0.30, + holding_days=0, + exit_reason=ExitReason.STOP_LOSS, + ) + res_day1 = PortfolioBacktester( + PortfolioConfig(initial_capital=100_000.0, max_positions=1, position_size_pct=1.0) + ).simulate( + BacktestResult( + strategy_id="d1_dd", + batch_id="d1_dd", + signals=[day1_loss], + total_signals=1, + executed_signals=1, + ) + ) + assert res_day1.max_drawdown == pytest.approx(0.30, abs=1e-4) + + # 7. Equal-weight benchmark proxy preserves entry-day intraday open->close return + proxy_dates = [date(2025, 1, 2), date(2025, 1, 3), date(2025, 1, 6)] + intraday_mkt = { + sym: pd.DataFrame( + [ + { + "date": proxy_dates[0], + "open": 100.0, + "high": 100.0, + "low": 100.0, + "close": 100.0, + }, + { + "date": proxy_dates[1], + "open": 100.0, + "high": 110.0, + "low": 100.0, + "close": 110.0, + }, + { + "date": proxy_dates[2], + "open": 110.0, + "high": 110.0, + "low": 110.0, + "close": 110.0, + }, + ] + ) + for sym in ("S1", "S2") + } + ew_bench = ShadowLedger.build_equal_weight_benchmark(intraday_mkt) + ew_ret, ew_ok = ShadowLedger._compute_benchmark_return( + ew_bench, entry_date=proxy_dates[1], exit_date=proxy_dates[2], horizon_days=2 + ) + assert ew_ok is True + assert ew_ret == pytest.approx(0.10, abs=1e-4) + + # 8. Live commit fill date is strictly > committed_at.date() while Monday still accepts Friday session + from datetime import datetime, timezone + from unittest.mock import patch + + from alphaevo.forward import shadow_ledger as sl_mod + from alphaevo.forward.contracts import BitemporalEnvelope, ForecastCommit, SetupInstance + + mon_dt = datetime(2025, 1, 6, 8, 0, tzinfo=timezone.utc) + with patch.object(sl_mod, "datetime") as mock_dt: + mock_dt.now.return_value = mon_dt + mock_dt.strptime = datetime.strptime + friday_cmt = late_bm_ledger.commit_signals( + _make_strategy(sid="mon_fri_ok", market=MarketType.US), + {"AAPL": _make_bars(date(2024, 12, 1), 30, step=0.002)}, + as_of=date(2025, 1, 3), + enforce_wall_clock=True, + ) + assert friday_cmt.as_of == date(2025, 1, 3) + + wc_ledger = ShadowLedger(tmp_path / "wc_post_close") + s_wc = _make_strategy(sid="wc_post", market=MarketType.US) + wc_bars = _make_bars(date(2025, 1, 6), 15, step=0.002) + wc_sig = SetupInstance( + signal_id="wc_1", + strategy_id=s_wc.meta.id, + symbol="AAPL", + envelope=BitemporalEnvelope(as_of=date(2025, 1, 5)), + entry_reference_price=100.0, + planned_stop_price=95.0, + ) + wc_cmt = ForecastCommit( + commit_id="cmt_wc_1", + strategy_id=s_wc.meta.id, + market="us", + as_of=date(2025, 1, 5), + committed_at=datetime(2025, 1, 6, 22, 0, tzinfo=timezone.utc), + is_replay=False, + wall_clock_enforced=True, + signals=[wc_sig], + prev_hash="0" * 64, + record_hash="", + ) + wc_cmt.record_hash = sl_mod._canonical_commit_hash(wc_cmt) + wc_ledger.commits_file.write_text(wc_cmt.model_dump_json() + "\n", encoding="utf-8") + wc_ledger.head_hash_file.write_text(wc_cmt.record_hash + "\n", encoding="utf-8") + wc_evs = wc_ledger.backfill_outcomes( + {"AAPL": wc_bars}, evaluated_as_of=wc_bars["date"].iloc[-1] + ) + assert wc_evs[0].horizons[5].entry_date == date(2025, 1, 7) + + # 9. Allocator MTM does NOT book stop loss on bar -2 when final stop bar has NaN close + nan_bars = _make_bars(date(2025, 1, 2), 69, step=0.001) + nan_bars.loc[68, ["open", "low", "close"]] = [100.0, 90.0, float("nan")] + s_nan = _make_strategy(sid="nan_stop", stop_pct=0.05, market=MarketType.US) + s_nan.entry.triggers = [StrategyCondition(indicator="close_above_ma20", op="==", value=True)] + s_nan.exit.max_holding_days = 100 + r_nan = RegimeAdaptiveAllocator().allocate([s_nan], {"AAPL": nan_bars}) + assert r_nan.daily_curve[-2].portfolio_return >= 0.0 + assert r_nan.daily_curve[-1].portfolio_return < 0.0