The AI often returns 'Guerre - Moyen-Orient' (ASCII dash) instead of
'Guerre — Moyen-Orient' (em-dash), causing exact match to fail silently.
Fix: normalize unicode, collapse all dash variants, then try
exact → normalized → partial substring matching.
Also log the raw AI response for debugging, increase max_tokens 1200→2000.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Previously: heuristic text matching (sub_type in category.name) — failed
for semantic cases like 'Iran Ceasefire Talks' → 'Guerre — Moyen-Orient'.
Now: all EventCategories are sent in the prompt (name + type + description).
The AI picks matched_category by semantic understanding, returns it in JSON.
- Validates returned name against known categories (case-insensitive)
- Auto-sets event sub_type when AI finds a match and sub_type was empty
- Returns matched_category in evaluate response + shown in UI eval message
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
_find_cat() returned only default_impacts, never the category name.
Now returns (name, defaults) tuple; cat_name → matched_cat_name.
Fixes: 'name cat_name is not defined' on AI evaluate.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
The LEFT JOIN on instrument_impacts (added for the evaluated subquery)
generates N rows per event when the event has N impacts. GROUP BY was
only applied when the instrument filter was active — now it's always on.
Fixes: total=2 but list shows 6+ duplicates.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Backend: add evaluated subquery column to list SELECT so each event
returns evaluated=1/0 (was missing, causing all events to appear
as unevaluated regardless of filter)
- Frontend: AbortController cancels the previous in-flight fetch when
a new load fires, preventing stale results from overwriting current
filter state
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Always-visible 'Catégorie IA' block in EventDetail (view + edit mode)
- Dropdown lists all EventCategories; selecting one instantly saves sub_type
and updates category type via PUT (no need to enter full edit mode)
- Shows matched category description + default impacts preview (ticker chips
with direction arrows and sensitivity %)
- Edit mode: category dropdown also auto-sets the category type field
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- MarketEvents: date presets (7j/30j/3m/6m/1an/Tout/Perso), instrument
impact filter (ticker + min score + direction → auto-sort by inst score),
sort controls (date/score/nom + asc/desc), clear-all button, count bar
- Market events list endpoint: full SQL JOIN rewrite supporting instrument
filter, date range, origin, sort_by=instrument_score
- Disable auto-bootstrap on startup (macro/eco/categories) — manual only
- CycleActions: bootstrap group (Macro/Eco/Categories) with force checkbox,
grouped layout (detection / bootstrap / data / ai / portfolio)
- cycle_actions router: /bootstrap-macro, /bootstrap-eco, /bootstrap-categories
endpoints + group field on all action catalogue entries
- InstrumentChart: greedy row placement for star labels (4 rows × 20px)
to eliminate horizontal overlap; labels now inline (★ + text)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- DB: colonne origin (migration + UPDATE heuristique sur données legacy)
- save/update_market_event: persist origin
- Tous les points de création taguent leur origine:
bootstrap_macro/eco/ma/legacy | detector_news/eco/technical/report | manual
- UI MarketEvents: badge d'origine avec icône + description dans le panneau détail,
icône tooltip dans la liste gauche, message explicite si pas de source_refs
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- InstrumentChart: remove setMarkers arrowDown (level-colored)
Add DOM overlay div with ★ HTML characters positioned via timeToCoordinate +
priceToCoordinate(candle.high) - 52px; sized by impact_score; colored by category
Label (title, 22 chars) rendered above each star; redrawn on scroll/zoom via
subscribeVisibleLogicalRangeChange; cleaned up on unmount
ChartEvent interface: add category, impact_score, end_date, description
Header legend: replace ▼ LT/MT/CT with ★ category color legend
- InstrumentDashboard: remove EventStarsStrip (now internal to chart)
Remove unused dateToMs helper
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Both bootstrap_macro_events() and bootstrap_eco_events() are now called
in the FastAPI startup event. Idempotent — skips already-existing events.
Logs how many events were inserted on first run.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Add macro_regime (goldilocks/stagflation/recession/etc.) to every instrument snapshot via get_macro_gauges() + score_macro_scenarios()
- RegimeCard now shows global macro cycle section (emoji + label + top-3 scenarios) above technical signals
- Fix _detect_regime() confidence: capped at 85% max; add late-bull (dist_MA200 > 20%) and correction-in-bull (MA50 > MA200 but momentum < -3%) detection so regime no longer locks at 100%
- Add macro_events_bootstrap.py with 30 curated historical events (FOMC 2022-2025, CPI surprises, Ukraine/Hamas/Iran geopolitics, BOJ pivots, Bitcoin ETF, Liberation Day tariffs, SVB crisis, etc.)
- POST /api/timeline/bootstrap-macro endpoint (idempotent, deduplicates by name)
- Fix event date filter in _get_relevant_events(): overlap logic instead of start-only filter — events extending into the chart window are now included
- EventTimelineStrip: add "Signaux Techniques" fallback row for events not matched by any driver keyword (MA crossovers are now always visible)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- instruments.json: add keywords array to every driver across 20 instruments
(Fed, BCE, BOJ, OPEC, CPI, AI, EIA, etc.) for event-to-driver matching
- instrument_service.py: add update_instrument_drivers() persisting changes to JSON
and refreshing in-memory cache
- instruments.py: add PUT /api/instruments/{id}/drivers endpoint (DriverUpdate model)
- InstrumentDashboard:
* RegimeCard: replace regime score bars with 6-metric signal grid
(MA50/MA200 position, MA50 slope, MA200 slope, momentum 20j, dist MA200, ATR vol ratio)
with colour-coded values and contextual sub-labels (Golden cross, Surextension, etc.)
* EventTimelineStrip: rows now keyed by top-4 instrument drivers (by weight)
instead of LT/MT/CT; events matched via case-insensitive keyword scan against
title + description + category; fallback dashed line when no events match
* DriversPanel: inline edit panel (toggle via Drivers button in header);
edit label, weight, keywords (comma-separated) per driver; add/remove drivers;
saves via PUT /api/instruments/{id}/drivers; optimistic local state update
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- InstrumentChart: onDateHover callback via subscribeCrosshairMove (useRef pattern)
- EventTimelineStrip: 3 rows LT/MT/CT with CSS-% bars aligned to chart X axis
- Cards date-aware: crosshair drives selectedDate; dateTrend + dateSignals computed
client-side from lookup maps (priceMap/indMap/sortedDates) without extra API calls
- TrendCard: price, RSI, ATR, slopes, momentum, 52W range all at selected date
- RegimeCard: 5 signals recomputed at selected date; regime label from server
- Date badge above cards; blue tint when browsing history, grey on last date
- instrument_service.py: end_date in events; price_data built before events block
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
The docker-compose mounts db_data named volume at /app/data which hid the
instruments.json file baked into the image. Moving to /app/config which is
not volume-overlaid resolves the FileNotFoundError on startup.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- TimelineVertical: replace horizontal frise with Y=time vertical layout,
3 columns (Long/Medium/Short), auto-scroll to selected date, sub-columns
for overlapping events, today/selected-date horizontal lines
- ma_analyzer.py: detect MA50/MA200 crossovers + MA100 slope changes +
MA20 direction swings on EUR/USD, Brent, Gold, S&P500, US10Y (5y history)
with 5-bar confirmation, dedup, GPT-4o-mini enrichment, idempotent DB save
- POST /api/timeline/bootstrap-ma endpoint to trigger analysis
- Bootstrap MA button in Timeline page with loading state + result count
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Frise chronologique:
- Sub-lane stacking (assignSubLanes) — overlapping events se décalent verticalement
- Zone d'overlap semi-transparente sur la période commune entre 2 événements
- Hauteur dynamique selon nb de sub-lanes par niveau
- Événements en cours avec flèche ▶ à droite, gradient de fin
- Tri par start_date pour placement greedy
Event Manager (composant EventManager.tsx):
- Tableau filtrable par niveau (Long/Moyen/Court)
- Edit modal complet : tous les champs + absorption_pct éditable
- Bouton "IA — Enrichir" par événement → POST /api/timeline/events/{id}/ai-enrich
→ GPT-4o-mini suggère absorption_pct + indicateurs pertinents par niveau temporel
- Delete avec confirmation double-clic
- Expand row pour voir description + indicateurs
- Intégré Timeline page via bouton "Gérer événements"
Backend:
- Nouvelles colonnes market_events: absorption_pct + relevant_indicators (ALTER idempotent)
- DELETE /api/timeline/events/{id}
- POST /api/timeline/events/{id}/ai-enrich
Snapshot Externe:
- AbsorptionBar par événement dans cellule Géopolitique
- MA indicators : fetch 200j history, compute MA10/MA20/MA100 per level (short/med/long)
- Affichage prix vs MA + % écart dans CellMarkets
- Si relevant_indicators configurés sur l'event → utilise ces symbols au lieu des défauts
- Calendar : horizons exclusifs (short 0-7j, medium 8-30j, long 31-90j) — bug corrigé
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Remplace le 2×2 indépendant par une matrice cohérente avec le concept E1/E2/E3 :
- 3 lignes (Long/Moyen/Court), chacune ancrée sur l'événement actif de ce niveau
- 4 colonnes (Géopolitique / Prix & Marchés / Régimes Macro / Calendrier)
- Assets affichés dans la colonne Prix filtrés selon affected_assets de l'événement
- Barres macro normalisées sur max score (overflow corrigé, overflow-hidden)
- Calendrier filtré par horizon temporel (7j / 1M / 3M) selon le niveau
- En-têtes colonnes globaux pour lecture matricielle immédiate
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Les appels fetch vers http://localhost:8000 ne fonctionnent pas en déploiement
Docker — remplacé par axios avec baseURL='/api' comme le reste de l'app.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Two root causes in the logs:
1. fetch_forward_curves() tried 5 offsets × 8 commodities = 40 individual
yfinance requests for monthly contracts (CLN26, GCQ26, etc.) that Yahoo
Finance does not support — generating ERROR storm and triggering hard
rate limiting that cascades onto front-month CL=F/GC=F calls used by
the main cycle.
2. Ticker format lacked exchange suffix (.NYM/.CMX/.CBT).
Fix: replace the per-ticker loop with two batch yfinance.download() calls
(one for all 8 front-months, one for all deferred candidates). Failed
deferred lookups are logged at DEBUG level and reported as structure='unknown'
rather than ERROR, since Yahoo Finance does not expose monthly commodity
contracts reliably. Added 1s sleep between batches to avoid rate spiking.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Section 12 refonte complète : 4 nouvelles sous-sections documentant le
COT CFTC (19 marchés par codes contrat stables), les Forward Curves
yfinance (contango/backwardation), le Surprise Index (actual-consensus)
et le Hawk/Dove Text Scorer GPT-4o-mini. Architecture : +2 tables DB
(cot_data, forward_curve_data), +6 colonnes specialist_reports. Schéma
et étape 4b mis à jour avec les nouvelles sources injectées dans le
contexte IA.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Replace per-endpoint market name matching with unified contract code
lookup on the legacy Socrata endpoint (6dca-aqww.json). COMEX became
"COMMODITY EXCHANGE INC.", CBOT became "CHICAGO BOARD OF TRADE", and
the disaggregated endpoints stopped receiving Natural Gas / financial
instruments after Feb 2022. Contract codes (067651, 023651, etc.) are
stable across rebranding. Fetch now returns 19/19 markets dated
2026-06-16.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
suggest_patterns_from_market_context() was missing the specialist desk
block that score_patterns_with_context() already received. All 7 desks
(forex, metals, agri, energy, indices, crypto, bonds) with their
fundamentals, macro sensitivity, and upcoming reports are now injected
so the AI can generate targeted patterns per desk rather than generic ones.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
On restart the scheduler was counting interval_hours from now, ignoring
when the last cycle actually ran. It now reads last_run_at (in-memory or
DB) and deducts elapsed time so a restart doesn't silently push the next
fire by a full interval.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Backend: category filter now ORs signal column so multi-category reports (category='multi') appear when filtering by Forex/Energy/Metals/Indices — fixes blank results
- Frontend: category pills expanded to match desk taxonomy (agri, crypto, bonds, indices added; equities kept for compatibility)
- Frontend: banner pointing to /specialist-desks clarifies the split between auto-fetched reports and manual desk report scheduling
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- handleSave now shows a red toast "Lancez d'abord un backtest" instead of
silently returning when activeRun is null (was completely invisible to user)
- All toasts now color-coded: green (emerald) for success, red for errors
- list_runs now includes context_snapshot so market data table shows when
loading a historical run from the right panel
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Detect yfinance quote_type (CURRENCY→forex, FUTURE→energy, INDEX→indices,
ETF→etfs, EQUITY→equities) when adding a custom ticker and persist it in
market_watchlist.asset_class
- get_all_quotes() merges custom tickers into their proper group (e.g. EURUSD=X
appears under Forex) instead of always under a separate "Custom" group
- "Custom" tab only shows tickers whose type couldn't be detected
- Add market_watchlist.asset_class migration; ensure backtest_lab_runs and
market_watchlist are always created at init_db() time
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Add ability to add/remove custom tickers (e.g. EURCHF=X) on the
Markets & Prices page without editing config. Tickers are validated
via yfinance, persisted in market_watchlist SQLite table, merged into
the quotes feed as a 'custom' group, and shown in a dedicated tab
with per-card remove buttons.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Fix: history runs now always show results — create synthetic selected preset
from run data when no matching preset found (was broken for custom events).
Also force mode='events' and reset matchResults on history load.
Discover tab: new "Discover" panel in left sidebar (AI knowledge search).
- GPT-4o generates 6 matching events from a free-text query (date, assets, hint)
- Confidence score + category badge per event
- Click → pre-fills experiment form exactly like a preset → ready to Run
- Backend: POST /api/pattern-lab/discover (DiscoverRequest, sorted by confidence)
- Frontend: useDiscoverEvents hook + DiscoveredEvent type + Discover UI with
Enter-to-search, spinner, empty states
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Backend: PATCH /api/patterns/custom/{id} — partial update, only provided fields changed
- useApi.ts: usePatchPattern mutation hook
- PatternCard: pencil icon (non-builtin only) → edit mode with inline inputs for name, description, direction (select), category, and #regime; ✓/✗ buttons to save or cancel; card border highlights blue while editing
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Missing class caused native selects to render with OS default white background.
Added .input to @layer components with dark bg, border, color-scheme:dark.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Backend:
- GET /api/market/validate?symbol= — validates ticker against yfinance,
returns {valid, name, price} or {valid: false, reason: 'helpful message'}
- Added SLV, USO, WEAT, CORN, TUR to ETFs WATCHLIST category
Frontend:
- validateTicker() async helper exported from useApi.ts
- InstrumentPicker (PatternLab): custom ticker field now validates before selecting
Shows spinner while checking, red error message if not found on yfinance
- InstrumentLens (PatternExplorer): same validation on Go button + Enter key
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>