Repository navigation
Cumulative branch since 2026-04-17: Phase 1 infra + fills ledger + weather v2 + cross-bracket - #2
Merged
Merged
Conversation
Replaces the monolithic systemd-oneshot MM with a persistent daemon
architecture. Captures ~6 weeks of in-flight refactoring as a single
baseline so Phase 1 work can proceed on stable ground.
Architecture change
-------------------
- New bot/daemon/ package: supervisor (main.py), in-process CycleRunner
(replaces forking trade.main() every 2 min), event-driven METARPoller
on its own thread, Scheduler with periodic tasks, WAL DB connection
under DB_WRITE_LOCK, WeatherQuoter + smart_gates ready for event-
driven cancel-replace (on_result not yet wired).
- Old bot/market_maker/ package deleted (~2.3K lines): core, quotes,
fills, inventory, liquidation, selection, adverse_selection,
series_profitability, family_caps. Superseded by daemon-era equivalents.
- bot/orchestrator.py deleted; trade.py trimmed by ~2K lines (legacy
MM phases removed; Safe Compounder gated on SC_ENABLED=off).
- bot/db.py, bot/api.py, bot/signals/ensemble.py now import locks from
bot/daemon/locks to coordinate writes across poller/cycle threads.
New signal sources (Phase 2 weather stitching prep)
---------------------------------------------------
- bot/signals/sources/: nws_point, ndfd_nbm, madis, hrrr, afd, gdpnow,
adp_nfp, commodity_futures
- bot/signals/weather_ensemble.py, family_routers.py
- bot/core/categorization.py
Backtest + analysis
-------------------
- backtest_comprehensive.py: 12-section analysis with per-family Brier,
calibration curves, edge-vs-winrate, source accuracy, MM deep dive,
loss classification, significance tests. Fixed the per-order-side
fair_value_cents averaging bug that made v1 show Brier 0.50.
- reports/BACKTEST_APR17.md: Phase 0 go/no-go report — five weather
families pass family-Brier gate by 4-8x; KXBTC/KXETH flagged for
directional block; market-mid leg deferred to Phase 1 logging.
Deploy
------
- deploy/kalshi-daemon.service + kalshi-weather-daemon.service units.
- deploy/05_deploy_weather_daemon.sh, updated deploy/04_redeploy.sh
with full daemon module import-check battery.
Tests
-----
- tests/daemon/: cycle_runner, scheduler, poller_base, smart_gates_trajectory
- tests/bot/: api_concurrency, db_wal
- tests/signals/: new source coverage
- tests/test_{weather_daemon,weather_quoter,smart_gates,money,fee_calc,
fedwatch_parser,positions,settlement_certainty,db_schema}.py
- Removed tests/test_{adverse_selection_defenses,mm_opportunity_log}.py
(covered legacy market_maker module)
Gitignore
---------
Expanded to block all forms of secrets (*.pem, *.key, .env*), DBs,
logs, local audit dumps (AUDIT_EXPORT*, REVIEW_V*, HEALTH_REPORT,
etc.), binary .docx, backup files (*.bak*, *.backup*, trade_v*_backup,
trade.py.bak*), and Claude tooling dirs.
What this commit does NOT do
----------------------------
- METARPoller.on_result is still None — event-driven requote not wired.
- Weather MM stays fully blocked (block list in config unchanged).
- Directional trading stays DRY_RUN.
- No alpha_backtest table yet, no Platt correction wired, no settlement-
driven learning population. All Phase 1 follow-up items.
CLAUDE.md is intentionally committed as-is and will be rewritten in
the next commit to reflect the new daemon architecture.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Rewrites the project overview to match the post-refactor reality: - Daemon supervisor (bot.daemon.main) with 60s cycle + event-driven pollers, replacing the systemd timer oneshot - WAL + DB_WRITE_LOCK / API_LOCK concurrency model documented - bot/market_maker/ removed from the file tree (deleted in 04ca78f); bot/daemon/ documented in full - Expanded ensemble table with new sources (NWS/NBM/HRRR/MADIS/AFD/ GDPNow/ADP-NFP/commodity futures) - Current phase section: Phase 0 passed, Phase 1 is the current work, nothing trades live, weather MM re-enable is shadow-first - Known Bug Patterns: added thirdlayerinc#13 (per-side fair_value normalization — the Apr 17 bug), thirdlayerinc#14 (DB_WRITE_LOCK), #15 (shared DB connection) - Current Performance updated from the Apr 17 backtest: 922 fills / 116 settlements / 11.2% WR / favorable +6.12¢ markout / per-family Brier showing weather alpha / catastrophic KXBTC/KXETH/KXHIGHDEN - Audit History: Apr 14/16/17 entries added - Phase 1 Work section: the 8-step plan now on record - Critical Conventions: added fair_value_cents + ensemble_prob per-side rules that were only in the backtest report before Preserves: Boil the ocean, Planning and qualifying questions, all YES-equivalent math, bracket vs threshold, synthetic sell, graduated exits, dynamic sizing. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Phase 1 needs an auditable decision journal to evaluate the Phase 0 gate's "ensemble beats market-mid by >=0.005" leg. This commit adds the table, logger, and two hooks in trade.py's directional path. - bot/db.py: alpha_backtest table (decision + raw market snapshot + settlement backfill fields) with 4 indexes including a partial pending-settle index. Raw yes_bid/ask/last/age/spread are stored alongside a canonical market_prob_yes + market_prob_source tag so analysis can re-evaluate the gate under multiple market-mid definitions without re-collecting data. - bot/learning/alpha_log.py: atomic log_decision() + fill_settlement() under DB_WRITE_LOCK. resolve_market_prob() implements the mid/last/wide_mid/ one_side/none fallback ladder. Never raises — logging must not break the trading loop. - trade.py: log_decision() called alongside existing log_opportunity() at the two directional callsites (Kelly skip + shadow trade). Safe Compounder sites intentionally omitted — SC isn't ensemble-validated and would pollute the gate's analysis slice. - tests/test_alpha_log.py: 40+ cases covering family extraction, Kalshi price coercion (incl. CLAUDE.md bug pattern #5), the full resolution ladder, log_decision round-trip, and fill_settlement idempotency. - tests/test_db_schema.py: alpha_backtest added to expected-tables set.
Phase 1 step 4. The legacy learning writers (calibration, timing_patterns, edge_convergence, loss_postmortems) read from `trades` + `mm_orders`. But directional is DRY_RUN (empty `trades`) and MM was deleted (frozen `mm_orders`), so today's cycle populates almost nothing — active_feedback has no data to act on. This commit adds alpha_backtest-driven writers that run alongside the legacy ones, so directional shadow decisions feed the same downstream analysis as live rows would. - bot/learning/alpha_log.py: new fill_settlement_for_ticker() settles all open rows for a ticker in one UPDATE, computing per-row won_yes and counterfactual realized_pnl_cents (contracts * (100 - price_cents) on wins, -contracts * price_cents on losses). - bot/db.py: add nullable alpha_id column + partial unique index (where alpha_id IS NOT NULL) to calibration, timing_patterns, edge_convergence, loss_postmortems. Legacy rows pass through as NULL. - bot/learning/populate_from_alpha.py: one function per target table plus a populate_all() orchestrator. Each writer is idempotent via NOT EXISTS subquery on alpha_id. Never raises — instrumentation must not break the trading loop. Provenance tagged via source='alpha:shadow' or source='alpha:<decision_type>'. - trade.py: record_settlements() now calls fill_settlement_for_ticker() per ticker; cycle body calls populate_all() right after. - tests/test_alpha_log.py: covers fill_settlement_for_ticker's per-side win logic, counterfactual P&L, idempotency. - tests/test_populate_from_alpha.py: 18 cases covering bucket assignment (YES uses p_yes, NO uses 1-p_yes), edge computation, convergence_pct math, loss classification (bad_source / efficient_market / adverse), provenance tags, and full populate_all idempotency. All 498 tests pass.
Collapse the three duplicate calibration implementations (trade.py,
ensemble.py, bot/learning/calibration.py) into one Platt-scaling module
with label-smoothed Newton-Raphson fit, L2 ridge, per-family overrides,
shadow isotonic PAV for future promotion, and kv_cache persistence.
Fixes the latent shape-mismatch bug where the old flat {bucket: offset}
dict would crash ensemble.py's dict-of-dicts expectation once the
calibration table accumulated settlement rows. Ensemble now passes
ticker through both callsites so family-specific curves apply. 46 new
tests cover fit/apply/persist end-to-end.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Closes the Phase 1 step-6 gap: the METAR poller now fans temperature changes into a shadow-by-default requote engine that persists proposed quotes to the new weather_mm_shadow table. The step-9 gate will read those rows to score event-driven MM on counterfactual P&L before the WEATHER_MM_LIVE flip. - New bot/daemon/forecast_cache.py extracts the Open-Meteo forecast cache from the legacy orchestrator with merge-on-failure semantics so one bad station doesn't wipe the others. - New bot/daemon/weather_handler.py owns per-series cooldown, forecast fallback (running_high + 5°F), and the shadow-vs-live gate. - WeatherQuoter gains shadow_requote_city / _shadow_requote_single + compute_quote_prices as a shared static to prevent live/shadow drift. - weather_mm_shadow table captures FV, proposed bid/ask, market snap, smart-gate decision, latency, and live_mode for later analysis. - bot/daemon/main.py now instantiates the handler, registers the forecast_refresh task, and rolls handler stats into health logs. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Phase 1 step 7. Pure evaluator at bot/learning/directional_shadow.py runs per candidate: family blocklist → kelly_zero → below_edge (vs YES-side market mid) → shadow_pass. Replaces the two inline _alpha_log_decision sites in trade.py with one call-site that maps outcomes to AlphaOutcome.DISCARDED / SHADOW_ONLY. Blocks KXBTC, KXETH, KXHIGHDEN by default (Phase 0 catastrophic- calibration findings), overridable via DIRECTIONAL_BLOCKLIST env. Per-family live flag lives in kv_cache under directional_live:<FAMILY> — primitive for step 9's shadow-to-live promotion job. should_go_live is stubbed False until step 9 writes the alpha_backtest SQL. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Adds a per-family promotion state machine on top of the step-7 shadow evaluator. Families start in SHADOW; a daily sweep auto-promotes to LIVE_CANARY (0.5× Kelly) after ≥50 settled shadow decisions clear edge_beat ≥ 0.005 on both the full window and the second-half OOS slice, and auto-graduates canary → LIVE_FULL after 30 settled canary decisions with non-negative P&L. A trifecta kill switch (P&L floor, Brier regime shift, single-trade hard stop) demotes FULL → CANARY → SHADOW; shadow demotion is terminal until an operator runs manual_re_enable under a ratcheted 0.010 edge_beat gate. All transitions are journaled to a new promotion_events table. trade.py scales directional contract sizing by the family's Kelly multiplier and only posts when the family is in a live state. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Phase 1 step 10: per-series promotion state machine (SHADOW → LIVE_CANARY → LIVE_FULL) gated on shadow spread-capture evidence, with paired shadow-row logging on the live path so the shadow-fill model can be continuously calibrated against realized fills. - bot/learning/mm_promotion.py: LiveState enum, evaluate_mm_promotion (N≥80 settled shadow fills, mean pnl/fill ≥ 2¢, OOS second-half slice must also pass), evaluate_canary_graduation, evaluate_mm_kill_switch (single-trade hard stop + rolling floor), match_shadow_fills (trade-conservative crossing heuristic), annotate_shadow_pnl, run_mm_promotion_sweep daily driver - bot/learning/threshold_tuner.py: T.8 weekly proposer — 3^4 grid search over the four promotion thresholds, objective = log-growth − λ·drawdown, writes to threshold_proposals only if best beats current by MIN_OBJECTIVE_DELTA_FOR_PROPOSAL - bot/daemon/weather_quoter.py: requote_city accepts order_size_multiplier + old/new temp for T.6 paired logging; _post_quotes returns (n, bid_oid, ask_oid, bid_price, ask_price) so the handler can stamp a live-mode weather_mm_shadow row alongside the live orders - bot/daemon/weather_handler.py: per-series gate reads mm_live:<SERIES> via is_mm_live / get_mm_order_size_multiplier; master WEATHER_MM_LIVE env still wins - bot/daemon/main.py: three new scheduler tasks — mm_fill_match (5 min), mm_promotion_sweep (daily), threshold_tuner (weekly) - trade.py record_settlements: on settle, call annotate_shadow_pnl so settled shadow rows become eligible for the promotion gate - bot/db.py: weather_mm_shadow.order_size column migration - tests/test_mm_promotion.py, test_threshold_tuner.py, test_mm_promotion_golden.py + tests/golden/mm_promotion_fixtures.json: T.7 CI regression harness that requires an explicit fixture update for any behavior change in the gate - 722 tests pass Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
The position_health_log schema has settlement_result + settlement_pnl_cents columns described as "filled post-settlement for learning" — but nothing ever filled them. Rows stayed NULL forever, starving the bandit that trains on which health-band decisions held winners vs losers. record_settlements now runs a scoped UPDATE per settled ticker so every prior per-cycle health snapshot carries the eventual outcome. NULL-guard on the WHERE clause keeps this idempotent across multiple settlements. Audit note: the other four Phase 1 step #3 learning sinks (calibration, timing_patterns, edge_convergence, loss_postmortems) are already fully populated from alpha_backtest via bot/learning/populate_from_alpha.py and from the legacy trade.py writers — no change needed there. Step #4 (Platt in get_independent_estimate) and step #6 (directional shadow evaluator with KXBTC/KXETH/KXHIGHDEN blocks) were likewise already wired. position_health was the one real gap. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Kalshi families like KXFED-26MAY / KXFED-26JUN / KXFED-26JUL are one rate-path bet, not three independent ones. Kelly-by-market sized each independently; the Apr 17 book ended up 95% KXFED — one leveraged Fed thesis, not a diversified book. This cap limits aggregate correlated exposure (default 25% of equity) without constraining per-market Kelly on genuinely independent bets. It runs AFTER the 50% global cap so it's the tighter constraint that binds for concentrated families. - bot/core/exposure.py: family_from_ticker, compute_family_exposures (buckets Kalshi position rows), family_headroom_cents, and size_trade_against_family_cap which returns (allowed_contracts, skip_reason) - bot/config.py: MAX_FAMILY_EXPOSURE_RATIO env var - trade.py: fetches positions once per cycle, computes family_exposures, applies the cap per-candidate AFTER the global cap, mutates the accumulator so within-cycle accepts count against the next candidate - tests/test_exposure.py: 22 tests — pass/reduce/reject paths, within-cycle accumulation, fallback ordering, cross-family isolation Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
- Code Structure tree: add bot/core/{exit_model,exposure,sizing}.py,
bot/daemon/{dispatcher,fills_writer,forecast_cache,requote_triggers,weather_handler,__main__}.py,
bot/learning/{alpha_log,bakeoff,directional_shadow,edge_convergence,mm_promotion,populate_from_alpha,self_modifier,shadow_promotion,shadow_testing}.py,
bot/signals/regime.py, bot/scoring/four_factor.py, bot/observability/cost_tracker.py,
bot/signals/sources/{_fomc_calendar,zq_futures}.py, expanded tests listing.
Consolidate weather sources (weather.py now holds Open-Meteo + Tomorrow.io +
NOAA) and economics sources (economics.py now holds FRED + BLS + Cleveland Fed).
Update trade.py line count ~4.8K → ~7K.
- Cycle Flow: rewrite for current trade.main() — phase system, alpha-populate
step, Platt fit per cycle, advanced learning loops, family/expiry exposure
caps, graduated per-family sizing, directional shadow evaluator (already live,
not "Phase 1 will log"). MM quoting step removed (legacy MM code deleted;
weather MM is event-driven on WeatherQuoter path).
- Database Schema: add sessions, learned_config, decision_log, weather_mm_shadow,
weather_source_weights, weather_forecast_snapshots, promotion_events,
threshold_proposals, fills_ledger. Re-group by purpose. Move calibration /
timing_patterns / edge_convergence out of "populated in Phase 1" — they're
populated each cycle now.
- Source weights table: fix drifted weights (NBM 0.77→0.80, HRRR 0.72→0.85,
MADIS 0.68→0.60, GDPNow 0.60→0.78, ADP/NFP 0.58→0.80). Add weather_ensemble
(0.95), zq_futures (0.85), AFD (0.50).
- Env vars: SC_ENABLED default true (not false). Add FORCE_PHASE,
DIRECTIONAL_BLOCKLIST, MAX_{PORTFOLIO,FAMILY,EXPIRY}_EXPOSURE_RATIO,
EXIT_{EDGE_DECAY_RATIO,TIME_BACKSTOP_HOURS,TIME_BACKSTOP_EDGE_ABS,STALE_HOLD_HOURS},
MM_SIZING_TARGET_EDGE_CENTS.
- Phase 1 Work: mark items 2–7 done (all have landed code paths); item 8
(shadow-to-live gate) still in flight as graduated promotion; add item 9
(T3 fills-ledger consumer migration, in flight).
- Current Phase: summarize landed vs. in-flight Phase 1 items.
The Apr-17 → Apr-21 data corruption (20,478 fake-filled rows on
fabricated zero-book data) took four days to surface because nothing
asserted that weather_mm_shadow.market_yes_bid had the shape Kalshi
actually returns. The B+D fix hardened _safe_cents and the MM promotion
gate, but a typo in any future parser would hit the same failure mode.
This adds three invariant checks that run every 10 min on a 1-hour
window — catches the Apr-17 class of bug within minutes of first
corrupt write:
- Zero-price invariant (critical → Telegram alert): any row with
market_yes_bid=0 or market_yes_ask=0. Kalshi never quotes below 1¢.
- Blind-quote watchdog (warning): ≥20 gated-post rows but zero
observed books — upstream parser is returning None for every
market.
- Stuck-book watchdog (info): ≥20 book observations with only 1
distinct bid value in an hour.
scripts/shadow_status.py is the operator dashboard: per-series state +
shadow P&L table, integrity findings (reuses check_shadow_data_integrity
so the CLI can never disagree with the daemon monitor), and explicit
next-action hints per series against the CANARY and LIVE_FULL gates.
Wiring into the daemon scheduler (bot/daemon/main.py) and deploy-time
import assertions (deploy/04_redeploy.sh) land in the broader Phase 1
commit that follows.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
- agent.py, agent-claude.py: pre-daemon orchestration scripts; the bot.daemon supervisor replaces both. Listed as deleted but never cleaned up. - trade_audit_export.py, trade_v3_audit.py: stale one-shot export dumps (~14K lines between them). The current audit process uses backtest_comprehensive.py + reports/ markdown. - bot/learning/threshold_tuner.py + test: never fired useful signal; proposed-thresholds table was read-only by design and the proposals were always ignored. Replaced by the shadow→canary→full graduated promotion gate which owns threshold evolution end-to-end. - bot/observability/opportunity_log.py: DB-write was moved into trade.main long ago; this helper was dead. - tests/golden/mm_promotion_fixtures.json + golden test: replaced by parameterised tests that drive the two-gate logic directly (tests/test_mm_promotion.py). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Before T1.1 there were five separate station registries (stations.py, metar_observations.py, weather.py, madis.py, and a derived copy in smart_gates.py). They disagreed on NYC resolution — the daemon polled KJFK while signal sources polled KNYC, a 2–5°F systematic gap depending on season. Kalshi's KXHIGHNY settles against the NWS climatological record for NYC, which has used Central Park (KNYC) since the 19th century. KJFK is coastal and runs 2–5°F cooler in summer. Phase 0 backtest brier scores (0.09–0.21 on weather families) were computed with signal sources reading KNYC — switching them to KJFK would have invalidated the validation. This commit makes stations.py the single source of truth: - KXHIGHNY primary station: KNYC (was KJFK) - KJFK, KLGA, KEWR remain as backups (poller still cross-references; MADIS basket still spatially averages) - ALL_STATION_IDS is the canonical URL driver for METARPoller - New STATION_BY_SERIES dict provides the O(1) series→station lookup used by WeatherQuoter and smart_gates Weather MM is currently blocked (WEATHER_MM_LIVE=false) so re-homing the daemon primary has zero trading impact — it just aligns shadow- mode readings with settlement for when we flip live. tests/daemon/test_station_registry.py locks the KNYC primary + KJFK backup invariant so no future refactor can silently demote KNYC. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Pre-T1.2 the weather MM quoter posted on METAR events only, and every requote blocked the METAR poller thread for the duration of a Kalshi cancel-replace round-trip (~500–1500 ms). A slow round-trip for one city stalled observations for all six — and time-decay effects (sigma shrink as we approach day-close) produced no requotes at all unless a METAR happened to fire. This commit ships three pieces: 1. AsyncEventDispatcher (dispatcher.py) — one worker thread per series. Same-series work is strictly serialised (invariant the quoter's cancel-replace logic depends on), but LAX's work never blocks NYC's. Stale pending events coalesce down to latest-state so a burst of METARs doesn't produce a queue of stale requotes. 2. TimeDecayDriver (requote_triggers.py) — ticks the cadence clock every 30 s. Fires synthetic requotes as sigma shrinks: 600 s cadence >8h out, tightening to 45 s in the final hour. Shares the same enqueue_synthetic path as METAR events so the quoter sees one event type, not three. 3. ForecastChangeDriver (requote_triggers.py) — captures pre/post Open-Meteo cache snapshots on every forecast_refresh. Fires a synthetic requote only when |Δfv| >= threshold AND the ticker is currently tradable — no-op refreshes produce no load. Handler.on_fire is wired to time_decay_driver.note_external_fire so a METAR event resets the cadence clock; otherwise a METAR at T+0 would be followed by a redundant time-decay fire at T+45s. VALID_REASONS frozenset locks the trigger taxonomy to exactly 3 labels (METAR_CHANGE, TIME_DECAY, FORECAST_CHANGE) — anything else is a typo. tests/daemon/test_integration_cadence.py exercises the end-to-end cadence shape (45 s → 600 s transition at the 8h boundary) so a future driver refactor can't silently regress the late-day tightening. orchestrator.py one-liner is a T1.1 follow-on (Station dataclass attribute access replaces the pre-T1.1 dict access). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Adds the fills_ledger table as the T3 canonical append-only record of every Kalshi fill, keyed by Kalshi's trade_id. Replaces the mm_processed_fills table's role as the fills source of truth (though mm_processed_fills stays writable during the T3.1→T3.3 transition). Pieces: - fills_ledger table + 4 indexes (ticker+ts, order_id, series+ts, family+ts) in bot/db.py. INSERT OR IGNORE on trade_id dedups so overlapping sync_since calls are free. - FillsWriter (bot/daemon/fills_writer.py) — single writer of every ledger row. Two methods: ingest_page (one /portfolio/fills response page) and sync_since (drives pagination forward from a timestamp). Per writer-ownership rules, this is the ONLY path into fills_ledger. - ValidationReport + compare_last_n_days / format_report (bot/learning/fills_validator.py) — dual-run divergence check comparing fills_ledger to mm_processed_fills over a 7-day window. is_meaningful gates alerting: one-sided (only one table populated) is the steady state during T3.1 bedding-in and logs info only; two-sided divergence is the signal T3.3 migration cares about. Also in bot/db.py: - db_write_ctx() context manager (T0.2 write discipline). Wraps SQLite writes in DB_WRITE_LOCK + BEGIN IMMEDIATE + commit/rollback so every writer respects the daemon's single-connection invariant. Scoping doc: reports/T3_FILLS_LEDGER_SCOPING.md (lands with the reports commit). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Two entangled changes that share mm_promotion.py and must land together: **B+D (two-gate shadow→canary→full promotion)** The Apr-17 data-corruption incident exposed a single-criterion promotion gate that auto-graduated two families on fabricated fills. Plan B+D from the post-mortem: - Step B: SHADOW → CANARY gate now requires sum(shadow_pnl) > 0 in addition to fill count (MM_CANARY_MIN_PNL_PER_FILL_CENTS = 1¢). Spurious 1¢-YES fills that always resolved NO can no longer pass. - Step D: new CANARY → FULL graduation gate requires MM_GRADUATION_MIN_PAIRED_N (20) paired live/shadow rows AND sum(live_pnl) / sum(shadow_pnl) >= MM_GRADUATION_MIN_PNL_RATIO (0.5). Live must capture at least half the P&L the shadow model predicted before we scale up. evaluate_mm_graduation(conn, series) is the new CANARY→FULL evaluator. evaluate_mm_kill_switch unchanged (stateless two-day drawdown rule on live_pnl alone). **T3.3 (reader migration)** _attribute_live_fills_to_shadow_rows populates weather_mm_shadow. live_pnl_cents from fills_ledger at settlement time. Without this the graduation gate's `live_pnl_cents IS NOT NULL` filter matches zero rows forever and CANARY is a terminal state. annotate_shadow_pnl now calls the attributor as part of its settlement pass — idempotent via WHERE ts_settle_unix IS NULL. Migrated readers: - bot/signals/regime.py: detect_regime reads fills from fills_ledger - backtest_comprehensive.py: per-fill aggregations join fills_ledger mm_processed_fills stays writable during T3.1→T3.3 transition; the dual-run validator (T3.1) watches for divergence. **bot/config.py** carries the B+D knobs plus a broader config wave: - MM_CANARY_MIN_PNL_PER_FILL_CENTS, MM_GRADUATION_MIN_PAIRED_N, MM_GRADUATION_MIN_PNL_RATIO (B+D) - MAX_EXPIRY_EXPOSURE_RATIO (per-settlement cap, consumed by the exposure refactor that follows) - EXIT_EDGE_DECAY_RATIO, EXIT_TIME_BACKSTOP_*, EXIT_STALE_HOLD_HOURS (consumed by bot/core/exit_model.py in the next commit) - MM_SIZING_* (consumed by bot/core/sizing.py in the next commit) All share the same bot/config.py file, so they land as a single config addition even though consumers land across multiple commits. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Pulls three distinct concerns out of trade.py / manage_positions
into testable bot/core/ modules:
- bot/core/sizing.py: Thompson-sampled MM sizing. Replaces the
3-step SHADOW/CANARY/FULL multiplier gate with a posterior draw
over realised per-fill P&L. Below MM_SIZING_MIN_N (5 fills),
multiplier = 0 (shadow-equivalent). Above the target edge
(MM_SIZING_TARGET_EDGE_CENTS = 2¢), multiplier = 1.0 (full
MM_ORDER_SIZE). Cached for MM_SIZING_CACHE_TTL_S (300s) so
within-cycle quote bursts see a stable multiplier.
- bot/core/exit_model.py: Directional exit evaluator. Three signals:
- edge_decay: remaining_edge < entry_edge × EXIT_EDGE_DECAY_RATIO
(default 0.33 — exit when ⅔ of entry edge has eroded)
- time_backstop: inside EXIT_TIME_BACKSTOP_HOURS (0.25h default)
of expiry with |remaining_edge| < EXIT_TIME_BACKSTOP_EDGE_ABS
(2c default) — catches frozen-ensemble positions
- stale_hold: held past EXIT_STALE_HOLD_HOURS (24h) flat or
deteriorating
- bot/core/exposure.py: per-expiry cap enforcement. New
check_expiry_exposure() caps concentration on any single
settlement date at MAX_EXPIRY_EXPOSURE_RATIO (7.5% equity). The
family cap alone pooled KXFED-27APR with KXFED-26OCT — the
expiry cap separates them so one surprise FOMC can't compound.
- bot/core/money.py: no functional change, minor docstring nits.
All three modules are called from trade.py (wiring lands in the
final commit of this series). Tests cover the edge cases:
- test_sizing: MIN_N gate, cap multiplier, cache TTL, single-
observation variance degeneracy.
- test_exit_model: each signal fires independently; combined-
signal priority; entry-metadata-missing graceful degrade.
- test_exposure: per-expiry cap applied after family cap,
stacks with portfolio cap, handles resting+filled correctly.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Batch of incremental signal and learning improvements that landed alongside the T1/T3/B+D work. Grouped because they're small per-file changes that share the same goal: tighten the settlement-driven learning loop so promotion decisions have cleaner inputs. Signal sources (bot/signals/): - sources/metar_observations.py, sources/weather.py, sources/madis.py: reads now defer to bot/daemon/stations.STATION_BY_SERIES instead of holding parallel station maps. Same code change as T1.1 on the daemon side, completed on the source side. - weather_ensemble.py: router accepts the new STATION_BY_SERIES shape; correlated-group weighting respects the canonical station list. - ensemble.py: pipeline-health counters safe under concurrent reads via PIPELINE_STATS_LOCK (daemon requirement). - scoring/four_factor.py: minor score-normalisation adjustment. Learning loop (bot/learning/): - alpha_log.py: settlement back-fill hardened against missing ts_settle_unix. Idempotent via WHERE settlement_unix IS NULL. - calibration.py: Platt persistence via kv_cache read on hot path rather than per-cycle refit (_cal_fit_and_persist still fits on every cycle, but consumers read cached curve). - edge_convergence.py: reads ensemble_prob with per-side normalisation (CASE WHEN side='yes' THEN ep ELSE 1-ep END) — the same convention flip the Apr-17 v2 backtest fix landed for mm_orders.fair_value_cents. - populate_from_alpha.py: cascades settled alpha_backtest into calibration / timing_patterns / edge_convergence / postmortems. Called each cycle via _alpha_populate_all. - postmortems.py: loss-classification tagger robust to None-valued avg_entry from legacy rows. - self_modifier.py: learned_config persistence gate now checks n_samples not just improvement delta (prevents overfit-to-noise). - shadow_promotion.py, shadow_testing.py: share the new mm_promotion.get_mm_live_state signature (returns LiveFlag dataclass with .state + .last_promotion_unix, not bare string). - timing_patterns.py: hour-of-day and hour-to-expiry buckets now keyed on LST-adjusted hour for weather series. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Provides compute_bakeoff() + render_bakeoff_report() for head-to-head evaluation of competing strategy variants against the same settlement universe. Uses the same settlement back-fill path as the learning loop, so a bakeoff is just an alternate aggregation over alpha_backtest rows — no extra shadow-mode wiring required. Will be called from the daemon's periodic sweep once we have two competing strategies to compare. For Phase 1 this lands as dormant infrastructure; first consumer is the post-Phase-1 directional-live cutover comparing ensemble-with-Platt vs ensemble-without. Tests cover the degenerate cases: empty universe, single-strategy input, tied scoring, and the edge where one strategy had zero fills (returns None for the comparison, not an error). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
…rift) A battery of boring-but-critical guard tests that catch the classes of mistake the Apr-17 incident and earlier audits identified: - test_writer_ownership (tests/ + tests/daemon/): scans every SQL-write callsite in bot/ and asserts each target table has exactly one writer module. Multi-writer tables are how Apr-17 snuck in — two paths touched weather_mm_shadow with different contracts. Registry is explicit so new tables must declare ownership or the test fails. - test_no_secrets_in_repo: walks tracked files for API key, RSA key, and Telegram token patterns. Fail-closed on match. Prevents the KALSHI_PRIVATE_KEY or .env leakage that gitignore alone can't guarantee. - test_db_discipline: every direct sqlite3 write outside of db_write_ctx() is flagged. Enforces the daemon's single-connection invariant (see bug thirdlayerinc#14 in CLAUDE.md regression watchlist). - test_config_no_drift: asserts bot/config.py constants referenced by assertions in deploy/04_redeploy.sh still exist with compatible types. Catches the class of failure where a config rename in a PR passes tests but breaks the deploy-time import gate. - test_client_order_id_coverage: every code path that emits a client_order_id is test-covered for the "no periods" invariant (Kalshi rejects dotted IDs — regression bug #1 in CLAUDE.md). - test_integration_row_shape (daemon): one-shot integration test that boots the daemon briefly, posts a fake METAR, and asserts the resulting weather_mm_shadow row has the exact post-B+D shape (market_yes_bid non-zero, gate_should_quote 0 or 1, no NULL fair_value, etc). Catches Apr-17-class row-shape regressions before they hit production. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Commits the five markdown reports generated during Phase 1 planning and incident response, plus the CLAUDE.md drift audit that reflects the post-incident architecture. Reports: - AUDIT_T1_2_2026-04-20.md: pre-ship code review of the event- driven requote drivers + dispatcher before the T1.2 commit. - GO_LIVE_REVIEW_2026-04-20.md: pre-live readiness checklist; source of the "human-in-the-loop on first LIVE_CANARY flip" gate that shadow_status.py now exposes. - POSTMORTEM_SHADOW_DATA_CORRUPTION_2026-04-21.md: the Apr-17 → Apr-21 data-corruption incident writeup. Source of the B+D plan and the post-mortem follow-on list (#2 = shadow integrity monitor, which landed as shadow_integrity.py in commit 0962096). - T3_FILLS_LEDGER_SCOPING.md: scoping doc for the canonical fills ledger (T3.1–T3.4). Current status noted in CLAUDE.md: T3.1 + T3.3 complete, T3.4 trade.py fills-write freeze pending. - T4_CANARY_GATES_DESIGN_2026-04-20.md: design of the two-gate shadow→canary→full promotion that B+D implements. CLAUDE.md: audits the codebase-vs-docs drift accumulated during Phase 1: - Replaces the deleted bot/market_maker/ section with the new bot/daemon/ structure. - Adds T3.1/T3.3/B+D status markers to Phase 1 Work. - Corrects mm_orders.fair_value_cents convention section (per-YES storage, not per-side — source of the Apr 17 v1 Brier 0.50 bug and now in the regression watchlist as thirdlayerinc#13). - Adds bug thirdlayerinc#14 (daemon pollers writing without DB_WRITE_LOCK) and #15 (process-local DB assumption) to the regression watchlist. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Final wiring commit that connects the Phase 1 modules landed in this series into the running system. **trade.py**: - Immutable initial-config snapshot: apply_phase_limits() and the active-feedback block now derive from _INITIAL_* rather than current mutated globals. Long-running daemon cycles no longer compound multiplications that drove KELLY_FRACTION → 0 and MIN_EDGE → ∞ over process lifetime. Guard test: tests/test_config_no_drift.py. - Consumes bot/core/sizing.py, bot/core/exit_model.py, and bot/core/exposure.py.check_expiry_exposure. manage_positions now routes through the extracted exit_model evaluator. - Graduated per-family sizing multiplier reads from mm_promotion.evaluate_mm_promotion which now returns the B+D two-gate state. - Directional shadow evaluator and block-list intact, no semantic change. **bot/daemon/main.py**: Wires every new scheduler task: - shadow_integrity @ 600s — Apr-17 data-corruption monitor - fills_sync @ 60s — FillsWriter.sync_since with 120s overlap - fills_validator @ 24h — dual-run divergence report - wx_time_decay @ 30s — TimeDecayDriver tick - forecast_refresh wraps with ForecastChangeDriver.on_refresh for material-change requotes - Handler.on_fire wired to time_decay_driver.note_external_fire so METAR events reset the cadence clock - AsyncEventDispatcher per-series worker pool constructed once, drained on shutdown alongside pollers - Removes the threshold_tuner registration (module deleted) - Health log now covers the new subsystems: wx_dispatch worker health, wx_time_decay cadence stats, wx_forecast_change fire counts, wx_handler synthetic-enqueue + rejection counts **deploy/04_redeploy.sh**: - rsync filter includes scripts/ (shadow_status.py is now shipped to the VPS) - Import-check battery expanded with assertions for every Phase 1 module: STATION_BY_SERIES, VALID_REASONS, FillsWriter, ValidationReport, MM_CANARY_MIN_PNL_PER_FILL_CENTS, MM_GRADUATION_MIN_PAIRED_N, _attribute_live_fills_to_shadow_rows, detect_regime (fills_ledger switch), shadow_integrity module. - Every assertion is tagged with its originating task (T1.1, T1.2, T3.1, T3.3, B+D, shadow_integrity) so a future failure points to the story it's guarding. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
…egression tests Latent bug in bot/signals/ensemble.py: a single source that sat in N correlated groups (e.g. `fred` is in cpi/fed/nfp/gdp) was counted N times toward n_effective, inflating the directional edge-threshold tier (5%/7%/10% scaling). Replaced with `claim by first matching group` semantics: a source contributes 1.0 to the first group that owns it and 0 to subsequent groups. Verified monotone — new n ≤ old n — so the fix can only tighten the threshold, never loosen it. Backtest replay against 521 sourced rows in opportunity_log on the VPS DB: every row was `ensemble(fred)` (economics families). OLD impl returned n=4 → 5% tier; NEW returns n=1 → 10% tier. Zero historical flips because all rows were MM (which doesn't gate on n_effective) and no directional decisions exist in the captured window — so the fix is forward-looking insurance for when directional goes live. Also pins the rest of the Known Bug Patterns watchlist (CLAUDE.md) with explicit regression tests: #5 fixed-point parsing — tests/test_fixed_point_parsing.py #4 inventory-zero-without-settlement — tests/test_inventory_zero_settlement_only.py thirdlayerinc#8 Tomorrow.io >7-day horizon — tests/signals/test_tomorrow_horizon.py + clamp at bot/signals/sources/weather.py thirdlayerinc#9 correlated double-count — tests/signals/test_correlated_double_count.py thirdlayerinc#10 MM spread fee floor — tests/test_mm_spread_fee_floor.py thirdlayerinc#12 cache bounded — tests/test_cache_bounded.py + TTLCache(maxsize=4096, ttl=3600) replacing unbounded {} in trade.py thirdlayerinc#13 fair_value_cents reader handling — tests/test_fair_value_cents_readers.py + `# fv-mixed-side-ok` ack markers in trade.py + backtest_comprehensive.py CLAUDE.md Known Bug Patterns updated with per-pattern test references. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Introduce a precision-weighted multi-source Gaussian combine (weather_ensemble_v2.predict_v2) gated behind WEATHER_ENSEMBLE_V2 env flag (default false, falls back to v1 on any error). Adds: - bot/signals/weather_sources.py — canonical source-name registry preventing recurrence of the open_meteo/"weather" drift bug. - bot/signals/weather_ensemble_v2.py — A1–A5 precision-weighted combine with per-source bias/sigma calibration and effective-N discount. - bot/signals/weather_forecast.py — abstraction layer that lets each source emit its internal Gaussian without re-fetching. - weather_gaussian_snapshots_backfill, weather_metar_hourly_backfill — retroactive archive tables (separate from live weather_forecast_snapshots because they carry observed_high_f and are populated out-of-band). - WeatherQuoter._compute_fair_value_v2 routing in weather_quoter.py, clamped to [2, 98] with v1 fallback on any v2 failure. Each weather source now exposes a Gaussian-emit contract used by v2. Writer-ownership registry updated to allow weather_ensemble_v2 to write to weather_forecast_snapshots (dual-write with v1 during shadow soak). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Refactor weather MOS bias correction to use 2-tuple (source, city) keys
with EWMA decay (H=14d half-life), persisted at kv_cache prefix
weather_mos_bias_{source}_{city}. Adds:
- bot/learning/weather_mos_materializer.py — hourly scheduler task that
walks settled weather tickers, fetches IEM ASOS observed daily-highs
once per (city, date), and writes one row per canonical Gaussian
source into weather_gaussian_snapshots_backfill. Covers nws_point and
tomorrow which have no historical archive. Uses morning-of snapshot
(closest to hours_out=12, recency tiebreak), idempotent via
UNIQUE(source, city, settlement_date, lead_hours).
- METARPoller.persist_running_highs — kv_cache-backed running-high
recovery so seed_running_high() rebuilds in-memory state across
daemon restarts without losing the day's peak observation.
- metar_observations.get_metar_gaussian — α_h + β_h·T(h) + RMSE per
(station, lst_hour) cell, fit from weather_metar_hourly_backfill
and persisted to kv_cache. Fixes the regression where MOS bias was
applied with the wrong key shape.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Fill the last Phase 1 gap: settle-then-learn for shadow-only weather markets (WEATHER_MM_LIVE=false), which never enter `settlements` or `mm_orders` and so were invisible to the existing settlement-cascade. - bot/learning/settlement_backfill.py — scheduler task that walks alpha_backtest tickers with ts_settle_unix IS NULL, resolves outcomes via the Kalshi /events archive, and back-fills both weather_mm_shadow.live_pnl_cents (via mm_promotion.annotate_shadow_pnl) and downstream learning tables. - bot/learning/shadow_calibration_bridge.py — watermarked walker (kv_cache key shadow_cal_bridge_watermark) that streams settled weather_mm_shadow rows into the calibration table so v2 Platt fits see shadow outcomes the same way live trades populate them. Bridge call is inline within the settlement_backfill task for transactional atomicity. - bot/daemon/main.py — wires settlement_backfill, shadow_cal_bridge, and mos_materializer scheduler tasks with staggered initial delays. - trade.py — annotate_shadow_pnl now runs BEFORE the dup-skip and bot-position gate in record_settlements (required because shadow-only tickers never enter mm_orders, so the old gate dropped every shadow row on the floor; idempotent via WHERE ts_settle_unix IS NULL). - bot/scoring/filters.py — partition prefix-avoidance by strategy so MM losses on KXHIGH* don't veto directional candidates that pass Phase 0 by 4–8× on the same family. - bot/learning/fills_validator.py — schema-guard for legacy mm_processed_fills rows lacking side/contracts/price_cents/recorded_at. - tools/, tests/tools/, analysis_laddering/ — markout, sigma, and laddering analysis scripts. Includes weather_markout_analysis.py exempted from row_factory discipline (CLI one-shot, conn never threaded — matches diagnose_sources.py / eval_bot.py exemption). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Bump SHADOW→CANARY n-floor 5→15 fills and per-fill P&L floor 1¢→2¢ so canary doesn't trigger on noise that fails to clear maker fees on a bad day. Bump CANARY→FULL paired-row floor 20→30 for the same reason. Add MM_BLOCKED_SERIES env-driven set, default cohort-2 holdback (KXHIGHCHI/NY correlated pair + KXHIGHDEN worse-Brier). Cohort 1 (MIA/AUS/LAX, distinct synoptic regimes) launches simultaneously when shadow data clears; CHI/NY released by shrinking env on next deploy. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
fit_and_persist_mos_bias is now called every mos_materializer tick (3600s) so warm-bias corrections are written to kv_cache and _apply_mos_bias in weather_ensemble_v2 can de-bias Gaussian forecasts at quote time. Previously the materializer populated the training table but never fitted or persisted corrections — kv_cache entries were never written, so the correction hook was always a no-op. Also fixes test_weather_handler.py TestLiveMode to use KXHIGHMIA instead of KXHIGHNY — KXHIGHNY is now in MM_BLOCKED_SERIES (cohort-staggering) and set_mm_live_state raises on blocked promotions. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
The unfiltered /markets?status=open response started returning ~99% KXMVE parlay legs (50K+ rows). The 10-page (5K-market) cursor walk hit zero non-parlay markets per cycle for days, silently starving the scanner. Switch to per-series fetch via /markets?series_ticker=<X> for the 12 series we have ensemble signal for (TRADE_SERIES_ALLOWLIST in bot/config.py). New routable series surface via bot/daemon/series_discovery.py — daily sweep over /events?status=open, alert-only with a discovered_series dedup table. Auto-add stays off because adding (e.g.) a new weather city without a station registered would mis-route the ensemble. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
_parse_threshold in bot/signals/sources/weather.py had a hardcoded is_above=True default for any T-suffix market the title regex didn't match. Kalshi T-suffix tickers are bi-directional — the same prefix encodes both >= and <= variants, with direction in yes_sub_title plus the API floor_strike/cap_strike fields. The default flipped every "or below" market into a "or above" probability, producing inverted edge across all 5 weather families that share this parser (Open-Meteo, HRRR, NBM, NWS-Point, MADIS, AFD, weather_ensemble_v2). METAR was unaffected — it has its own parser. New priority: API strikes (cap-only→below, floor-only→above) → yes_sub_title number-then-keyword → legacy keyword-then-number → bare <N/>N → bracket fallback → refuse to guess. Every internal caller updated to pass market_data instead of just title. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
VPS had drifted from local: dead modules (agent.py, agent-claude.py,
trade_v{1,2}_backup.py, trade_v3_audit.py, trade_audit_export.py,
bot/observability/opportunity_log.py, bot/learning/threshold_tuner.py),
stale tests (test_threshold_tuner.py, test_mm_promotion_golden.py),
an in-repo .kalshi_private_key.pem (canonical location is
~/.kalshi_private_key.pem outside the repo), a duplicated
Users/jlu/autoagent/ subtree from a botched rsync, and a .gitignore
missing *.pem/*.key patterns. Each surfaced as a test failure on the
VPS that didn't repro locally.
Add .gitignore to the rsync include list and extend the post-sync rm
list to cover all the above. After this run: VPS suite goes from
3 failures → 1724 passed.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Add 2s sleep between per-(city, date) IEM fetches in materialize_due so a backlog of city-dates doesn't burst the Iowa State mesonet endpoint. Single tick is unaffected (one fetch, no sleep); subsequent fetches within the same call sleep 2s before the request. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
BOT_EXPLAINED.md: plain-English walkthrough of the entire bot for onboarding and review. tools/backtest_v2_calibration.py: replays weather_ensemble_v2 against the 91-day OM+METAR backfill to measure calibration drift before/after parser fixes. Also gitignore .coverage / htmlcov so pytest-coverage runs don't leak artifacts into the working tree. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Multi-day audit + fix sweep on the v2 weather ensemble. Key findings: WEATHER_ENSEMBLE_V2 was dormant in production while we calibrated it; the Platt curve was a step function poisoning every prediction; the "model group" was one Open-Meteo source labeled three times; HRRR/NBM/weather shared identical hourly traces; AFD bias was cap-saturated; METAR collapsed to running_high during cold-start windows; late-day combined σ was too tight for bracket resolution. Production code changes: * WEATHER_ENSEMBLE_V2 + CALIBRATION_ENABLED feature flags in bot/config. v2 is on; Platt application is off (the persisted curve was fit on poisoned v1 outputs and is now a step function — bypass globally until per-category fits land). * Per-(source, city) skill σ + MOS bias fitter from weather_gaussian_snapshots_backfill, with winsorize=0.02 to absorb freak-day outliers. Per-city σ varies 0.96-1.96°F; pooled fit is wrong for everyone. * Per-(source, city) skill σ + MOS bias fitter from weather_forecast_snapshots — fills cells where the Open-Meteo backfill was thin (NWS Point, MADIS, METAR). Snapshots-based fitter writes hourly. Currently writes 15 keys/hour; thin cells fill in as data accumulates. * Per-(station, LST hour) METAR residual σ fit from hourly METAR backfill. NY hour 0: σ=6.7°F; NY hour 22: σ=0.31°F. Replaces a hardcoded schedule that said 5°F at hours_left=4. Real value 0.86°F. * Source staleness inflation. Each forecast source carries an issued_at; σ inflates by sqrt(1 + staleness_h / horizon_h), clamped to [1.0, 2.0]. Per-source schedules in bot/signals/sources/_freshness.py derive issued_at from each model's known publish cadence (HRRR every 1h, NBM at 01/07/13/19z, etc.). * Source σ ceiling at 2.0°F. NWS Point/MADIS/AFD inherited a wide pooled fallback (3+°F) that effectively excluded them from the precision pool. Ceiling caps σ so they still contribute meaningfully. * Truncated-Gaussian projection in weather_forecast.probability_for_market. Daily high cannot be below already-observed running max — left- truncate the combined distribution at METAR's μ before the bracket CDF. Verified vs 200K-sample Monte Carlo. * Combined σ floor at 0.5°F. Per-station-hour residual σ at LST hour 22 is 0.20°F — a real measurement of std(eventual_high − running_max), but doesn't capture bracket-resolution uncertainty (sensor lag, late-arriving observations, rounding). With σ=0.20 we put 99% on a single 1°F bracket; a 0.5°F μ error puts 99% on the wrong one and costs Brier 0.98 per row. Floor keeps meaningful probability in adjacent brackets. * METAR cold-start fix. _get_forecast_high used to return running_high+5°F when the kv was empty (post-restart, before forecast sources fired). On hot mornings that collapsed METAR's μ toward current temp, dragging combined μ below the actual peak. Now returns None and METAR widens σ to _COLD_START_SIGMA_F (10°F) to reflect ignorance instead of guessing low. * Materializer initial_delay reduced 1800s → 60s. The 30-min defensive delay made every redeploy cause a 30-min window of uncalibrated METAR σ. Dropped to 1 minute. * Directional weather → v2 short-circuit in trade.py and bot/signals/ensemble.py. Weather tickers bypass the per-source probability-space combine and Platt step entirely; predict_v2 runs directly. Verified zero v1-fallback warnings post-deploy. * Source coverage audit at every materializer tick. Logs WARNINGs when a (source, city) cell is missing skill σ or MOS bias. City list is the canonical 6-city set used by the materializer (not STATION_BY_CITY.keys() which includes aliases — that produced 30+ false-positive warnings that masked real gaps). * WeatherQuoter v1 fallback now logs WARNING + counter on every fire. Silent fallback to broken legacy code is the worst kind of bug. * AFD audit closed. Multi-signal extraction (Option 3) tested via tools/backtest_afd_signal — LLM bias direction is weakly right but magnitude is consistently 2-3× too large. Confidence is uncalibrated. AT THE BRACKET LEVEL however (replay test), AFD shift HELPS pooled Brier by 0.013. Keep AFD as-is; documented inline at _MAX_AFD_SHIFT_ABS_F so values aren't tweaked without re-running both tests. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
New tools to investigate/validate the weather ensemble v2 changes: - backtest_v2_replay.py — replay historical weather_forecast_snapshots through current predict_v2 to estimate bracket Brier without waiting for new settlements. Supports --include-ecmwf and --disable-afd flags. - backtest_production_path.py — reads weather_mm_shadow.fair_value_cents joined to settlements for ground-truth production-path Brier. - backtest_afd_signal.py — multi-signal LLM extraction validation across 90 days × 6 cities; computes AFD-only point error vs baseline. - audit_afd_stratified.py — per-city/confidence/agreement subset analysis of AFD signal quality. - audit_source_accuracy_by_horizon.py — per-source forecast accuracy binned by hours-out from settlement. - audit_source_residuals.py — per-(source, city, hours-out bucket) residual fits for skill-σ calibration sanity check. - backfill_directional_shadow.py — synthesize alpha_backtest rows from historical Kalshi trades for directional gate evaluation. - diagnose_nowcast.py / diagnose_methodology.py — multi-horizon Brier diagnostics excluding thin sources. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
- test_freshness.py — schedule-derived issued_at for HRRR/NBM/NWS/OpenMeteo - test_weather_ensemble_v2.py — σ ceiling (2.0°F), staleness inflation, combined σ floor (0.5°F), running-high truncation projection - test_weather_forecast.py — truncated bracket projection + Monte-Carlo sanity check; tightened clamp [0.005, 0.995] - test_weather_mos_materializer.py — per-(station, hour) METAR residual σ fit, snapshots-based skill σ + MOS bias fitter - test_calibration.py — CALIBRATION_ENABLED gate (default off) preserves legacy math when enabled - test_ensemble_family_routing.py / test_weather_sources_registry.py / test_mm_promotion.py — adjustments for v2 short-circuit + freshness Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
The 0.04 Brier gap chase converged on a single root cause: the entire
weather calibration stack was training against the wrong target.
Kalshi settles every weather market on the NWS Climatological Daily
Report (CF6 form) — confirmed by reading rules text directly from the
markets API for every series, then validated against the 4 catastrophic
Miami cases where CF6 TMAX landed inside Kalshi's settled bracket on
every one (4/22=81, 4/23=79, 4/24=84, 4/25=85). Our backfill was using
max-of-hourly-tmpf, which systematically undershoots TMAX by 1-3°F
because ASOS captures peaks between hourly observations. Every skill σ,
MOS bias, and METAR residual σ fit was learning from a cold-shifted
target → ensemble runs structurally cold → catastrophic losses on close
calls where the actual high crossed a bracket boundary we missed.
Production changes
------------------
* HOURLY_BACKFILL daily scheduler task (bot/daemon/main.py). Walks the
past 7 days of IEM hourly METAR for every primary station, then
fetches CF6 TMAX and overwrites daily_high_f. Fires at 06:00 UTC; the
7-day rolling window self-heals any single-day IEM hiccup. Replaces
the manual 'tools/backfill_weather_effective_n.py --hourly-metar'
invocation that nobody had run since 2026-04-22 — six days of
calibration training data missing entirely.
* CF6 fetcher + update path (tools/backfill_weather_effective_n.py).
fetch_cf6_tmax + update_daily_high_from_cf6 query IEM's AFOS archive
with a per-station PIL ('CF6MIA', 'CF6NYC', etc.), parse the daily
table, and UPDATE weather_metar_hourly_backfill.daily_high_f in place.
Idempotent (UPDATE matches by station+lst_date).
* H3 conditional truncation (bot/signals/weather_ensemble_v2.py). Step
4c (_apply_running_high_floor) already shifts combined.μ up to METAR.μ
whenever forecast disagrees with observation, so by step 5 combined.μ
≥ METAR.μ always — and the unconditional truncation_floor was
re-amplifying the residual upper-tail by 1/p_above_t ≈ 2× when
combined.μ ≈ METAR.μ, clamping to 0.995 on whichever bracket held the
centred μ. Pre-CF6 the amplification was accidentally helping cold
predictions; post-CF6 it became net-harmful. Sweep validates +0.0146
pooled improvement, 4 of 6 families improved (MIA −0.034, NY −0.026,
AUS −0.024, DEN −0.014).
* σ floor 0.5°F → 1.0°F (bot/signals/weather_ensemble_v2.py). Post-CF6
sweep optimum: 0.5 was tuned for the cold-biased era where
concentration on the bracket nearest truth helped; with corrected μ,
1.0°F gives meaningful probability in adjacent brackets without
over-spreading on clear cases.
* forecast_cache startup prime (bot/daemon/main.py). Synchronously
refreshes the Open-Meteo forecast cache before pollers start emitting
events. Eliminates the ~6-per-restart 'no forecast for K[STATION];
fallback X°F' warnings (counted exactly 40 per station across rotated
logs — uniformly restart-correlated, not station-specific).
* Replay calibration application (tools/backtest_v2_replay.py). The
monkey-patch of _collect_gaussians was bypassing _apply_learned_sigma,
_apply_staleness_inflation, _apply_mos_bias, and the σ ceiling — so
every prior sweep result measured raw-σ ensemble behavior, not
production. All historical knob-comparison conclusions remain
relative-correct (toggled vs baseline both bypassed) but absolute
numbers were uncalibrated.
* deploy/kalshi-daemon.service: TimeoutStopSec 30 → 360. The
mos_materializer task takes up to ~280s; the prior 30s cap was
causing redeploys to force-kill mid-task and leave systemd in a
failed state.
Test coverage
-------------
* tests/daemon/test_main_helpers.py — _seconds_until_utc_hour
alignment math, cross-month + cross-day cases.
* tests/signals/test_weather_ensemble_v2.py — H3 conditional fires
when forecast disagrees, skipped when forecast agrees; σ floor
pinned to 1.0°F.
* tests/tools/test_backfill_weather_effective_n.py — CF6 parser
against a real-world CF6MIA fixture; PIL-coverage drift-guard
ensures every primary station has a CF6 PIL mapping.
Verification
------------
End-to-end on n=143 settled tickers (post-deploy):
pre-fix v2_replay Brier 0.151 (gap −0.064 vs market)
post-fix v2_replay Brier 0.137 (gap −0.049 vs market)
KXHIGHMIA pooled 0.18 → 0.17, with the worst individual losses
dramatically improved:
4/24 B84.5 (won 84-85): rB 0.95 → 0.32 (μ 82.0 → 83.4)
4/25 B85.5 (won 85-86): rB 0.61 → 0.27 (μ 84.0 → 85.3)
Known follow-ups (not in this commit, both research-grade)
----------------------------------------------------------
1. Late-day residual peak σ conditional on weather regime (sea-breeze
detection, cloud-cover input). Current per-(station, lst_hour) fit
is the right shape but unconditional. Needs more data + regime
plumbing.
2. Forecast-side cold bias closure on the close-edge cases. With
accurate ground truth in place, MOS bias will absorb residual
forecast-side cold offsets as more days accumulate. No code change
today; expect gradual improvement.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
These six tools drove the investigation that landed in the prior commit. Keeping them in tree so the same pattern is reusable when the next hypothesis-tree exercise comes up. * sweep_v2_hypotheses.py — single-pass hypothesis sweep (σ floor, AFD on/off, truncation on/off, group ρ forced to 1.0). Reuses backtest_v2_replay's market cache so 9 experiments × 1500 tickers share the slow Kalshi fetch. * diagnose_v2_gap.py — three reports on one replay pass: Brier-by-horizon, Brier-by-bracket-edge-distance, Miami drill. Captures combined.μ + σ via redirected snapshot writes so per-case diagnostics know what predict_v2 actually computed. * investigate_miami_late_day.py — per-ticker drill on 4 specific catastrophic Miami cases: METAR snapshot freshness, shadow-row activity by horizon bucket, hourly METAR trajectory. * probe_kmia_data.py — direct IEM ASOS query for KMIA + Miami-area alternates (KFLL / KMFL / KOPF), comparing tmpf max vs our backfill vs Kalshi settlement bracket. The probe that surfaced the consistent 2-3°F gap between KMIA tmpf max and Kalshi's settled values, prompting the audit below. * audit_kalshi_settlement_sources.py — fetches one current market per weather series via the public Kalshi markets API, prints the rules_primary text alongside our STATION_BY_SERIES assumption. Output revealed 'NWS Climatological Daily Report' as the official settlement source for every weather series — the smoking gun. * validate_cf6_hypothesis.py — fetches CF6MIA from IEM's AFOS archive, parses the daily TMAX table, validates against the 4 catastrophic cases. Every CF6 TMAX landed inside Kalshi's settled bracket; hypothesis confirmed before any production code changed. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Self-contained summary of where the weather-Brier-gap work landed: what shipped, the two open research items (regime-conditional residual σ; forecast-side cold-bias closure), what's already been ruled out, and quick-start instructions for picking the work up cold. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This session covers two threads of work that landed together:
1. Weather ensemble v2 hardening
- Source state machine (shadow → probationary → active → demoted)
with daily evaluator. Probationary sources get σ × 1.3 (capped
weight while on trial). Demoted-→shadow re-trial after 7d.
- Three new sources: ICON (DWD), UKMO (Met Office), IEM 1-min ASOS.
ICON + UKMO live in the combine; IEM held back due to 24h
publication latency (state row + pre-seeded σ retained for future).
- Sanity gate excludes any source whose μ is >5°F from the
METAR/IEM_1MIN anchor (catches cold-cache or model blow-ups).
- Pre-seeded σ + bias from the multi-source eval pipeline so day-1
predictions use informed weights, not flat priors.
- Dynamic ensemble: σ ceiling now conditional on whether σ was
learned (so NWS Point's true ~5°F passes through unclipped) but
floored at 1.5°F to prevent pathological self-referential fits
from dominating combine. Discovered when METAR's σ-fit produced
0.3°F (n=18, observation correlated with its own contribution
to "actual high"), collapsing ensemble σ to <0.5°F and blowing
KXHIGHNY directional Brier from 0.16 → 0.46. Verified live:
post-fix combined σ 1.25-1.41°F, calibrated bracket spread.
2. Phase B.3 cross-bracket portfolio shadow
- bot/scoring/bracket_portfolio.py: per-leg decide() + portfolio
scorer with σ floor + price-band guards.
- bot/daemon/cross_bracket_shadow.py: scheduler task running every
5 min — fetches all open KXHIGH* markets, groups by settlement,
scores via combined Gaussian, logs each non-skip decision to
alpha_backtest with shared market_id for portfolio reconstruction.
- alpha_backtest schema: new market_id + portfolio_leg_count columns
+ partial index. Idempotent ALTER for existing DBs. log_decision
accepts the new fields as optional kwargs.
- tools/validate_cross_bracket.py: per-family Brier/PnL retro-replay
comparing cross-bracket vs single-side directional shadow cohorts.
Net PnL uses Kalshi maker fee (cross-bracket would post limit).
Persisted reports at reports/cross_bracket_validation.{md,csv}.
- Daily scheduler hook at 08:00 UTC = 01:00 PT (after all US weather
settlements finalize). Logs one line per (cohort, family).
- tools/backfill_cross_bracket_columns.py: one-shot regex-parse of
legacy notes-encoded market_id values into the new columns.
- 78 new tests covering bracket math, writer, validator (incl.
regression test for the won_yes-as-our-trade-won convention bug
that inverted Brier on every NO-side row).
- Documented won_yes column convention in alpha_log.py docstring.
3. Bug fixes shipped during the work
- URL doubling in cross_bracket_shadow's market fetch (`/trade-api/v2/`
was duplicated → 404 on every call, silently swallowed at DEBUG).
- f-string crash in bracket_portfolio's skip_reason path on one-sided
market quotes (one of edge_yes/edge_no was None → caught silently
at the per-settlement try/except → was dropping 67% of settlements).
- Both have regression tests so they can't reappear.
4. Diagnostic tooling (used to investigate the σ-collapse regression
and the won_yes inversion bug)
- tools/regime_*.py: regime stratification + feasibility analysis
- tools/replay_postfix_brier.py: replay settled rows with corrected
Brier formula
- tools/migrate_alpha_label_inversion.py: one-shot migration tool
- tools/audit_no_replay.py, audit_snapshot_timing.py: data integrity
- tools/evaluate_sources/: per-source eval pipeline with backfill
- tools/dashboard.py: HTML+Plotly dashboard for source health,
calibration, recent trading, system health
- tools/seed_source_priors_from_eval.py: pre-seed kv_cache from
eval data for day-1 informed weights
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Addresses the question: can we backtest cross-bracket on historical data
without waiting for shadow settlements? Yes — by replaying the σ-fixed
v2 ensemble against settled `weather_mm_shadow` cycles.
Tool: `tools/backtest_cross_bracket_historical.py`
* Reuses replay_postfix_results for σ-fixed (μ, σ) at any past T.
* Pulls per-bracket market quotes from weather_mm_shadow.
* Runs production score_market_portfolio() — no parallel impl drift.
* Sums per-portfolio gross + net (maker fee) PnL using the actual
ticker_settled_yes outcomes.
Headline finding (42 settlements, all 6 weather families):
* SHORT TTE (4-6h): 24 fires, 96% WR, +85.9¢/leg net
* MEDIUM TTE (8h): 19 fires, 53% WR, +29.6¢/leg net
* LONG TTE (10-12h): 75 fires, 33% WR, -4.4¢/leg net
Cross-bracket has clear, statistically-significant alpha at TTE ≤ 6h
(p ≈ 0.0001 vs H0=50%). Loses edge at TTE > 8h. Production
cross_bracket_shadow currently fires every 5 min across all TTE
windows — mixing the profitable short-TTE shots with money-losers.
A TTE gate (4 ≤ TTE ≤ 8h) preserves alpha and filters losses.
Per-family investigation:
* KXHIGHDEN: mostly statistical noise. 12 of 19 Denver fires came
from ONE settlement (KXHIGHDEN-26APR28). Excluding it, Denver WR
is comparable to other families. μ accuracy is best of all
families (mean error 1.34°F, SD 0.53°F). Re-evaluate Denver's
directional blocklist after σ-fix data accumulates.
* KXHIGHMIA: structurally biased at long TTE. Multiple sources have
persistent negative MOS bias (HRRR -1°F, NBM -1°F, UKMO -2.6°F,
weather -1.1°F). _apply_mos_bias corrects ~1°F but residual
under-prediction is 2-5°F. Likely coastal-airport / heat-island
artifact: KMIA is on the coast, daily highs happen inland.
* KXHIGHCHI: wide source σ priors (mean 3.9°F before floor), μ
accuracy mean 2.16°F. Genuinely harder to predict.
* KXHIGHAUS, NY, LAX: typical long-TTE failure pattern. AUS
actually wins money at long TTE (+13.9¢/leg, 64% WR) — the
only family that does.
Recommendation: don't blocklist any family. The TTE gate handles
everything. Hold promotion of cross-bracket to live until ≥100
post-σ-fix shadow fires accumulate (~7 days). Investigate Miami's
residual bias as separate workstream (per-TTE-bucket bias fit, or
higher Miami-specific σ floor).
Report: reports/CROSS_BRACKET_BACKTEST_2026-04-30.md (full data,
methodology, per-settlement detail, limitations).
No production code changed. This commit is investigation + report
only — let new shadow data accumulate before changing the runner.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
…fixes Core findings driving the changes (KXHIGHNY canary 2026-05-03 lost $1.45): 1. Forecast lat/lons grid-resolved to wrong stations - NYC at (40.71,-74.01) → "Hoboken, NJ" not KNYC Central Park - LAX at (34.05,-118.24) → "Vernon, CA" not KLAX coast (no marine layer) - Denver at (39.74,-104.99) → "Glendale, CO" not KDEN airport Fixed by aligning WEATHER_CITIES tradeable-city coords to the settlement-station coords in bot.daemon.stations. Test pin in tests/signals/test_weather_cities_alignment.py. 2. nws_5min for NYC was substituting KLGA which ran 3-5°F warmer than KNYC. Removed NYC from PRIMARY_5MIN_STATION_BY_CITY; both nws_5min and nws_5min_diurnal now return None for NYC. 3. Per-city source exclusions (EXCLUDED_SOURCES_BY_CITY) drop sources the regression flagged with persistent >3°F bias at the wrong station — nws_point at NYC/CHI/MIA, metno+gem at LAX (worst marine- layer outliers), nws_5min at CHI/MIA. 4. Per-city HRRR σ priors. Default bumped 1.2 → 2.0 after measured RMSE was 3× the prior. Cities where HRRR was already well- calibrated (DEN/MIA/AUS, RMSE < 2.5°F at settlement) keep the old 1.2°F prior so the bump doesn't down-weight HRRR uniformly. 5. σ inflation TTE-aware. Pre-peak (TTE >= 8h) full per-family factor applies. Post-peak (TTE <= 2h) factor decays to 1.0. Linear in between. Wide σ post-peak misallocates probability across brackets that observation has already ruled out. 6. Cross-bracket POST-only bug fix + slippage protection. post_only=True was hitting "post only cross" rejection because cross-bracket FVs are by design on the wrong side of the spread. Now post_only=False with two slippage layers: (a) limit price capped at best_ask + 2¢, (b) count capped at top-of-book size. Tests pin both layers + the post_only flag. 7. Diurnal fitter wired into the daemon's hourly_backfill task. fit_metar_diurnal + persist_diurnal_fit were previously only invoked from the CLI tool's --persist-diurnal flag; nothing in the daemon called them, so weather_metar_diurnal_* kv keys were never written on prod and nws_5min_diurnal silently returned None. Now refreshes daily after CF6 stage 2. 8. tomorrow.io dropped from v1 ensemble path. Last fired 2026-04-28; regression showed -5.49°F bias at KNYC. Source code retained. 9. nws_5min_analog demoted from GAUSSIAN_COMBINE_SOURCES to SHADOW. Feature-vintage bug + insufficient regime coverage; module retained for re-enable when both fix and 60+ days of history land. Backtest impact (60,200 settled rows over 14 days): POOLED Brier 0.1175 → 0.1097 (+6.6%) KXHIGHAUS +20%, KXHIGHMIA +16%, KXHIGHLAX +8%, KXHIGHNY +5.5%, KXHIGHCHI flat, KXHIGHDEN regression caveat: backtest doesn't replay full v2 pipeline (missing MOS bias + learned σ overrides), forward-test will tell us real DEN behavior. 2150 tests passing. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
…nts-int
The 2026-05-03 cross-bracket canary placed 18 live orders that Kalshi
filled successfully — but every fill was rejected by fills_writer as
"malformed" because Kalshi switched its /fills endpoint to a new
response shape we didn't know about:
Legacy: {"count": 1, "yes_price": 91, "no_price": 9}
New: {"count_fp": "1.00",
"yes_price_dollars": "0.9100",
"no_price_dollars": "0.0900"}
All 18 fills are real positions on Kalshi but never made it into
local fills_ledger. live_pnl_cents on weather_mm_shadow won't backfill
at settlement and mm_promotion's graduation logic can't see the fills.
Fix: read either shape, defensively normalizing to int cents. Two new
module-level helpers (_parse_count, _parse_price_cents) try the legacy
field first, fall through to the dollar-string field, return None on
genuine missing/garbage. The malformed-fill warning now includes
raw_keys so future Kalshi format drift is diagnosable from the log
alone without re-instrumenting code.
5 new tests in TestDualFormatPayloads pin both shapes against captured
production payloads, including the exact cross-bracket fill from
trade_id 76372d92-f9b7-78fc-fa05-f61f83575422.
2155 tests passing.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
reports/WEATHER_ENSEMBLE_STATE_2026-05-04.md is the single source of truth for "what does the weather ensemble look like right now." Drop this in front of any new session that needs to know the active sources, per-city architecture, σ inflation system, pipeline order, postmortem findings, known-issues backlog, and verification recipes. tools/verify_all_station_mappings.py — auditor that probes NWS /points for each tradeable city's lat/lon and dumps (source, city) bias at settlement. Re-run after any future lat/lon change to catch grid drift. tools/ensemble_backtest.py — backtest of the new pipeline (per-city exclusions + per-city HRRR σ + TTE-aware σ inflation) against the last 14 days of settled outcomes. Note: doesn't replay learned σ / MOS bias / AFD shift, so it underestimates real Brier improvement. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
systemd: - Move StartLimitIntervalSec / StartLimitBurst from [Service] to [Unit]. Modern systemd requires them in [Unit]; prior placement caused "Unknown key name" warnings AND silently fell back to defaults (5 starts / 10s instead of the intended 10 / 600s). - Restart=on-failure → Restart=always. SIGKILL-after-TimeoutStopSec is technically a "result=timeout" failure, but the May 3 outage showed cgroup teardown can fail in a way that breaks on-failure's recovery path. Restart=always is safer for an always-on daemon. - TimeoutStopSec 360 → 90. The original 360s was sized for mos_materializer's worst-case shutdown but hitting it during a routine deploy means SIGKILL + multi-hour auto-restart failure window. 90s lets a wedged daemon get recycled cleanly. Any on_stop hook that takes >90s is a bug to fix in code. Verified live (PID 633652, no restart needed): Restart=always TimeoutStopUSec=1min 30s StartLimitIntervalUSec=10min StartLimitBurst=10 tools/platt_fit_inspect.py: diagnostic for the persisted per-family Platt curves. Findings (don't ship): Every family fit has A in millions (KXHIGHDEN A=38.6M, KXHIGHLAX 14.4M, ...). That's Newton-Raphson collapsing to a step function on bimodal probability data. Even A-clipping to [0.5, 5.0] doesn't recover — the B coefficients (also in millions) amplify the shift catastrophically. Per-family Brier with clipped Platt is 22-73% WORSE than raw. Conclusion: re-enabling CALIBRATION_ENABLED today would degrade signal quality, not improve it. Three viable next steps logged in reports/WEATHER_ENSEMBLE_STATE_2026-05-04.md backlog: - bounded-Newton Platt (clamp A + B during iteration, not after) - per-family isotonic regression - Beta-distribution calibration Each ~1-3h. Defer until then. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
reports/CALIBRATION_INVESTIGATION_2026-05-04.md is the focused
entry point for the calibration deep-dive. Covers:
- Live evidence: every per-family Platt fit has A in millions
(collapsed to step function on bimodal probability data)
- Why naive A-clipping makes things worse (Brier 22-73% worse)
because B was co-optimized at million-scale
- Three viable fixes (bounded-Newton Platt, per-family isotonic,
Beta calibration) with concrete file paths + sketches
- Recommended order: Option A (bounded Newton, ~1h, 20-line diff)
first; isotonic as v2 if A doesn't capture enough Brier
- Test pins to add when shipping
- Schema reference for the calibration table + kv curve shape
- Pre-/post-fix data split (don't fit on pre-2026-04-27 v1-era rows)
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
ijlu
added a commit
that referenced
this pull request
May 6, 2026
Trailing commits on mm-calibration-timing that weren't pushed to origin when PR #2 was merged. Includes calibration investigation (bounded-Newton Platt + bake-off + raw-prob logging), full cross-bracket strategy work, and the Phase 1 ensemble eval spec. Production VPS already runs this code (rsync'd via deploy/04_redeploy.sh). This merge brings main into sync with what's deployed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What this is
This PR is the cumulative
mm-calibration-timingbranch sincemainwas last advanced on 2026-04-17. It started as the_compute_n_effectivefix (commitadf884d) but accumulated 63 commits across six workstreams. Rather than retroactively splitting, merging it whole and adopting a stricter "one branch per coherent change" rule going forward.Solo-author repo, no review gate — this PR's purpose is the audit trail, not approval.
Workstreams included
_compute_n_effectivedouble-count fix + Known Bug Pattern pinning tests (adf884d)Ground truth
Code on the VPS is already running this branch via
deploy/04_redeploy.sh— merging it tomainmatches reality, doesn't change deploy state.Going forward
One branch per coherent change. Merge within days. No more multi-week feature branches that grow off-topic.