Builds a full synthetic market data pipeline to test strategies against
12 diverse market regimes (bull/bear/crash/chop/rotation/liquidity drought)
that may not exist in historical data. Computes Regime Robustness Score (RRS)
to detect overfitting and environment-specific fragility.
- libs/backtest/scenarios/: price_gen, macro_gen, event_gen, coupling,
store_builder, scenarios (12 pre-built), robustness (RRS)
- apps/scenario/cli.py: `fithia2 scenario-test` with Rich output
- apps/tracker/cli.py: scenario-test command routing
- tests/: 83 unit tests across 3 new test files
- docs/scenario_test.md: usage guide and result interpretation
- docs/research_workflow_and_handoff.md: Step 5.5 scenario test added
Fix: no_signal scenario uses drift=0% (was +10%) for fair signal integrity scoring.
Fix: synthetic candidates now carry macro_vix/macro_hy_spread from macro_by_date
to pass selector engine filters.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Additional tracker/leaderboard updates, overlay leaderboard, and
documentation improvements.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Replaces per-experiment rglob with single-pass manifest/metrics indexing
and adds lru_cache. Removes rarely-used commands from help display.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Extends selector with new scoring model support, adds execution
enhancements, and improves snapshot store loading and split handling.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Adds earnings surprise extraction to parser/features/labeler pipeline,
improves filing fetcher robustness, and extends snapshot export with
new field support.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Bounce engine (buy negative reaction, bet on mean reversion) could not
execute: system architecture ties scoring to single model per backtest,
and selector/store indexes are optimized for positive-reaction PEAD.
Negative-reaction candidates get score=0 from PEAD scoring, blocking
engine selection regardless of engine-level threshold overrides.
Implementing bounce trades requires: dual scoring model support,
selector changes for negative-reaction candidate routing, and
store indexing changes. Deferred to future refactor.
Current best CW return: 293.2% (v6new.255)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Data analysis revealed OBV Q1 (distribution) has 56.4% WR vs Q5 51.2% —
contrarian signal confirmed. Previous OBV bonus was applied in wrong
direction. Corrected with v15 scoring models.
Best result: v6new.185 (entropy + risk 0.058) CW 274.4% but SQS 72.2,
still below v6new.122 (72.4). WFV/robustness offsets CW gains.
v6new.122 confirmed as optimal under current SQS v4 formula.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Previously only used rows[0].keys() — columns present in later rows
(like earnings_surprise_pct from sparse features) were silently dropped.
Now collects all unique keys across all rows.
YoY earnings surprise tested: WR spread only 2.5pp (55.2% vs 52.7%).
Not actionable — YoY growth != analyst consensus surprise.
v6new.30 remains the framework optimum.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
New data source integration:
- EarningsSurpriseService: GET /api/v1/earnings/surprise/{symbol}
Returns actual vs estimated EPS with surprise_percentage
- Feature builder: creates earnings_surprise_v1 snapshots for earnings events
- Backfill script runs for existing 1,273 tickers (Alpha Vantage rate limited)
New scoring (v11):
- Small beat (0-3% surprise): +10% bonus (82.4% WR in sample)
- Medium beat (3-8%): +5% bonus
- Big beat (>8%): no bonus (already priced in)
- Miss (<=0%): -5% penalty
Signal validation (n=66 sample):
Small beat: 82.4% WR, +1.79% mean 5d return
Big beat: 54.8% WR, +0.47%
Miss: 55.6% WR, -0.10%
Backfill running (~4 hours). Experiment pending data completion.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
FilledTrade now carries event_type and score from the Candidate.
These fields are written to trade_blotter.parquet and displayed in
paper backtest trade logs.
Previously score showed as 0.00 for all trades because the field
wasn't propagated from Candidate → FilledTrade → Parquet.
Score=0.00 is valid for trades from engines with score_threshold_override=0.0
(e.g. guidance_unknown_orderly) where engine gates, not score, determine entry.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Phase 1-4 of engine unification to eliminate research/live divergence.
Phase 1 — Scoring (event_detector.py):
EventDetector now uses config's scoring_model (v5/v9 etc.) when
event_v1 features are present (parse_confidence_overall not null).
Falls back to compute_entry_score only for incomplete events.
Phase 2 — Execution config (execution.py):
Extracted build_effective_execution_config() as shared function.
BacktestRunner delegates to it. PaperTradingEngine can now use
identical per-engine overrides, adaptive exit, tiered targets.
Phase 3 — Attention filtering (attention.py):
New AttentionFilterService class extracted from BacktestRunner.
Provides: engine_requires_attention, apply_filters, rescoring.
BacktestRunner now delegates to this service.
PaperTradingEngine can import and use the same service.
Phase 4 — Gap cap (execution.py):
check_next_open_gap_cap() shared function for next-open gap rejection.
All 450 unit tests pass. Paper backtest verified working.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
New in allocator.py:
- vix_pead mode: boosts sizing at VIX>18 (PEAD favorable), penalizes VIX 15-18
- Fixed vix_scaler application to support boost (scaler > 1.0)
Results:
- v6new.19 (spy_qqq risk_off=0.55): SQS 62.8 — reduces size in favorable PEAD regime
- v6new.21 (vix_pead boost+penalty): SQS 46.9 — penalty too aggressive, kills trades
VIX signal is real (62.3% vs 48.2% WR) but sizing alone can't capture it:
- Boosting doesn't help because same trades just get bigger
- Penalizing shrinks or drops trades, losing count
- Need the signal in TRADE SELECTION, not just sizing
v6new.9 (SQS 63.3) remains best.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
New features:
- _enrich_macro_features() in snapshot_export: adds macro_vix, macro_hy_spread from FRED
- compute_return_max_long_score_v10: +12% bonus in favorable regime (VIX>18+HY>3.25)
- _macro_regime_score(): regime-aware scoring component
Findings:
- VIX signal is statistically strong: 62.3% WR (VIX>18+HY>3.25) vs 50.8% (other)
- But scoring bonus promotes marginal trades, diluting OOS quality
- Same pattern as eps_growth, drift bonus: raw signal ≠ scoring improvement
- v6new.17 SQS 59.1 < v6new.9 SQS 63.3
v6new.9 remains best at SQS 63.3 after 17 experiments.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Track experiment cycles with SQS scoring (0-100), JSONL journal, and
auto-generated leaderboard to prevent duplicate experiments and enable
data-driven strategy decisions.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Remove 5 non-alpha features (earnings surprise, risk penalty, parse confidence,
direction clarity, LM sentiment) from composite score to eliminate double-counting
with hard gates and noise sources. Redistribute weights to 5 alpha features.
Add default-deny for unknown event types, no-follow-through early exit (D+1),
kill switch log-only mode, macro regime size scaler. Remove SUE gate (Gate 8).
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Flip scoring weights so event/document quality is primary signal (55%)
and market confirmation is secondary (35%). Add research mode with
kill-switch cooldown/reset, veto gates for bad events, reduced portfolio
risk, and 4 diagnostic analysis scripts.
Phase A: Research mode kill-switch reset, risk reduction (0.5%/trade,
max 4 positions), bullish-only direction for all event types.
Phase B: 2 new sub-scorers (parse_confidence, direction_clarity),
4 veto gates (oneoff risk, parse confidence, unknown/bearish direction).
Phase C: signal_quality, event_type_decomposition, kill_switch_impact,
concurrent_position analysis scripts.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Replace naive abs(reaction_day_return) fallback with a composite score
from 4 market microstructure features available at entry time:
1. Reaction quality (35%) — moderate positive return (PEAD zone) is
ideal; extreme positives penalized as "priced in"
2. Close strength (30%) — close near session high = buyers won
3. Volume conviction (20%) — 1.2-2x is healthy; >3x is exhaustion
4. Gap quality (15%) — small positive gap = orderly strength
Real data results (14 events, b1868603 snapshot):
- Score filters out 6 of 10 losers (DDOG -11.7%, META -9.1%, etc.)
- With threshold 0.5: return -2.63% → +0.27%, drawdown 4.24% → 0.86%
- Profit factor 0.44 → 1.16 (turns profitable)
- MSFT loss (-8.7%) is macro-driven, not predictable from stock features
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- BacktestRunner.run() now iterates all NYSE trading days (not just candidate
days) via SnapshotStore.all_trading_days() so stop/target/time exits are
checked every day, not only on days with new candidates
- Record initial DailyPortfolioState before simulation loop starts so
total_return_pct is computed relative to the true initial equity (100k),
not the first post-entry equity snapshot
- SnapshotStore._fetch_event_metadata() now synthesises event_timestamp from
event_date + 21:00 UTC when filed_at_utc is NULL (transparent enrichment at
loader boundary, not silent substitution in selector)
- SnapshotStore._async_load() maps event_close → entry_price_est when the
column is absent, and derives score from abs(reaction_day_return) when the
Parquet snapshot has no score column
- Add --snapshot-dir CLI flag to BacktestRunner to override the default
parquet_dir base path (needed for non-standard snapshot locations)
- Fix integration test assertion: total_trading_days >= 2 (was == 2)
- Add configs/experiments/realdata_test_v1.json for real Phase 3 snapshot runs
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Add `think: False` and `num_ctx: 8192` to Ollama payload:
Qwen3.5 extended thinking mode generated 1300+ internal reasoning
tokens before each response, adding 30-60s latency per LLM call.
Disabling it reduces parse time from 600s timeout to ~13s.
- Rewrite OllamaClient to use sync httpx.Client inside asyncio.to_thread():
Async httpx inside an active asyncpg SQLAlchemy session context on
Python 3.13 hung indefinitely. Synchronous httpx in a thread pool
completely isolates Ollama I/O from the asyncio event loop.
- Fix filing_poller to set issuer_id/symbol_id on Document records:
Missing FK caused feature_builder to reject all events with
event_no_symbol warning. Now looks up IssuerMaster/SymbolMaster
by ticker before creating Document rows.
- Update test_llm_client to mock _sync_call instead of _client attr.
- Raise ollama_timeout default to 600s for large document processing.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Oracle 서비스 어댑터 5개를 실제 API 포맷에 맞게 수정
- 모든 경로에 /api/v1/ prefix 추가
- price: data[] → bars 매핑, volume float→int
- filings: accession_number→accession_no, total_count→total
- financial: financial_data[] → periods, period_date 파싱
- finra: entries[] → data 매핑
- fred: data.observations 언패킹, value string→float (버그 수정 포함)
- fixtures 6개를 실제 Oracle 응답 포맷으로 전면 교체
- 통합 테스트에서 httpx_mock 완전 제거 → 실제 Oracle 직접 호출
- 신규 단위 테스트 3개 파일 추가 (logging, fred_service, llm_parser_stub)
- test_retries.py에 exhaustion 테스트 추가
- test_oracle_client.py에 connection/timeout/no-ctx 테스트 추가
- Phase 1/2 testing_checklist.md 실제 구현 기준으로 전면 재작성
- 전체 114 tests pass (unit 100 + replay 5 + integration 9)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- filing_poller: add --start-date/--end-date CLI args for historical backfill
(defaults to 7 days ago when omitted)
- OracleClient.get/post: apply with_retry(max_attempts=3) so transient
connection errors, timeouts, and 5xx responses are automatically retried
with exponential backoff (0.1s→0.2s→fail)
- financial_features: new compute_financial_features() extracting latest_eps,
latest_gross_margin, latest_operating_margin, eps_growth_qoq,
revenue_growth_qoq from FinancialDataResponse
- feature_builder: wire FinancialService into build_features_for_event(),
persisting financial_v1 FeatureSnapshot (non-fatal if unavailable)
- tests: 94 pass (81→89 unit + 5 replay); +8 new tests covering financial
features and retry success path
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Fix all JSONB/text server_default values to use sa.text() wrapper to
prevent double-escaping in Alembic-generated SQL
- Replace testcontainers with direct docker-compose postgres connection in
integration conftest, removing asyncio.run() from async fixture context
- Change db_engine/db_session to function-scoped with explicit transaction
rollback for proper per-test isolation
- Flush IssuerMaster before Document insert to respect FK ordering
All 94 tests pass.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>