Commit Graph

120 Commits

Author SHA1 Message Date
OpenSquared
aeb5233deb feat: frise sub-lanes + event manager + MA indicators + absorption
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>
2026-06-24 20:31:57 +02:00
OpenSquared
43b4816596 refactor: Snapshot Externe — layout 3 lignes temporelles × 4 piliers
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>
2026-06-24 18:47:08 +02:00
OpenSquared
8afa06118c feat: frise chronologique + page Snapshot Externe 4 piliers
- TimelineFrise.tsx : visualisation horizontale scrollable COVID→aujourd'hui
  3 lanes (long/medium/short), événements cliquables, marqueur aujourd'hui/date, axe années
- ExternalSnapshot.tsx (/snapshot) : dashboard 4 piliers du contexte externe
  Pilier 1 Géopolitique : 3 badges L/M/C avec J+ depuis événement + lien /timeline?date=
  Pilier 2 Prix & Marchés : quotes SPY/QQQ/GLD/USO/TLT/UUP live + lien Specialist Desks
  Pilier 3 Régimes Macro : régime dominant + scores scénarios + jauges VIX/DXY/10Y
  Pilier 4 Calendrier Économique : prochains événements + récents, liens Calendar/Institutional
- Timeline.tsx : remplace mini-strip par TimelineFrise, lit ?date= query param
- Sidebar : Snapshot Externe (ScanEye) + Timeline (Layers)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-24 18:36:12 +02:00
OpenSquared
37f770a09a fix: Timeline — utiliser axios /api relatif au lieu de fetch localhost:8000
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>
2026-06-24 18:13:47 +02:00
OpenSquared
c6178c14d5 feat: Timeline Navigator — contexte historique 3 temporalités COVID → aujourd'hui
- 2 nouvelles tables SQLite : market_events + timeline_context
- 32 événements historiques seedés (long/medium/short de feb 2020 à juin 2026)
- timeline_service.py : bootstrap, get_events_for_date, génération commentaires GPT-4o-mini
- /api/timeline router : GET /day/{date}, GET /events, POST /generate/{date}, POST /bootstrap
- Timeline.tsx : navigateur date avec strip visuel, 3 panneaux contextuels, catalogue d'événements
- Sidebar : entrée Timeline avec icône Layers

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-24 17:45:35 +02:00
OpenSquared
281b7e30ba fix: forward curve — stop 40+ yfinance errors per cycle, batch downloads
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>
2026-06-24 08:30:15 +02:00
OpenSquared
a31f6e21b1 docs: v6.1 — Specialist Desks v2 (COT, Forward Curves, Surprise, Hawk/Dove)
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>
2026-06-23 18:59:24 +02:00
OpenSquared
c9f7757a86 fix: COT fetch returns 0 — CFTC exchange names changed since 2022
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>
2026-06-23 18:53:51 +02:00
OpenSquared
5005324653 fix: SQLite UNIQUE constraint on forward_curve_data — expressions not allowed
Replace UNIQUE(asset, DATE(fetched_at)) with dedicated fetch_date column
+ UNIQUE(asset, fetch_date). SQLite prohibits function calls in inline
UNIQUE/PRIMARY KEY constraints.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-23 18:07:29 +02:00
OpenSquared
3b7fa35456 feat: Specialist Desks v2 — COT, Forward Curves, Surprise Index, Hawk/Dove scorer
- COT Positioning: CFTC disaggregated + financial futures (19 markets) via Socrata free API
  net MM position % OI + weekly change stored in cot_data table
- Forward Curves: yfinance front-month vs +3M slope (8 commodities)
  contango/backwardation/flat stored in forward_curve_data table
- Surprise Index: consensus_estimate + actual_value on specialist_reports
  auto-computes surprise_score = actual - consensus on save
- Hawk/Dove Text Scorer: GPT-4o-mini endpoint for CB statements
  score -1..+1, label, summary, key_phrases (forex/bonds: hawk/dove; commodities: bull/bear)
- AI context injection: COT net positioning, forward curve structure,
  surprise scores, upcoming consensus estimates injected into all desk blocks
- Frontend: COT panel (net% bars), Forward Curves panel, SurpriseInput
  on report cards, Hawk/Dove scorer in forex/bonds config tab
- auto_cycle.py: non-blocking COT + curve refresh before each cycle

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-23 18:00:46 +02:00
OpenSquared
70a9e2b569 fix: inject specialist desks context into pattern suggestion prompt
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>
2026-06-23 13:41:50 +02:00
OpenSquared
91f12e177f feat: pattern calibration — progressive AI→observed expected_move blending
DB (database.py):
- 3 new columns on custom_patterns: calibrated_expected_move, calibration_weight, observed_avg_win_pct
- update_bayesian_posteriors() now also computes credibility blend w=n/(n+5):
  calibrated = (1-w)*ai_estimate + w*observed_avg_win_pct (only when wins exist)
- log_trade_entries() prefers calibrated_expected_move when w>10%
- get_calibration_summary() returns per-pattern state (source: pure_ai/early/mixed/data_driven)

Backend (patterns.py, auto_cycle.py):
- GET /api/patterns/calibration endpoint
- calibration_report block in cycle report: counts by source, avg weight, per-pattern detail

Frontend (PatternExplorer.tsx, RapportIA.tsx, useApi.ts):
- MaturityBadge on each PatternCard: blend bar (AI→observed), win rate, AI estimate vs calibrated
- usePatternCalibration hook
- Cycle report: calibration section with global bar + per-pattern table (weight%, n_trades, WR, AI→calibrated)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-23 12:38:16 +02:00
OpenSquared
a630cdc708 feat: Find Similar + Merge in Pattern Library
Backend (patterns.py):
- POST /api/patterns/find-similar — GPT-4o-mini compares a library pattern
  against all others; returns merge_as_instance | counter_scenario | new_pattern
- POST /api/patterns/merge — full transactional merge: remaps pattern_id in
  pattern_score_history, trade_entry_prices, ai_reasoning_traces, ai_call_logs,
  skipped_trades; unions historical_instances (dedup); sums backtest counters;
  deletes the discarded pattern

Frontend (PatternExplorer.tsx + useApi.ts):
- ScanSearch button on each non-builtin card triggers find-similar
- Inline result panel: duplicate → merge CTA with confirmation + destructive warning
  counter_scenario → apply regime_tag CTA; new_pattern → green "unique" badge
- useFindSimilarPattern + useMergePatterns hooks invalidate all-patterns on success

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-23 12:13:33 +02:00
OpenSquared
8d257adf3d fix: scheduler next_run accounts for elapsed time since last cycle
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>
2026-06-23 10:52:54 +02:00
OpenSquared
2f9d067a94 fix: InstitutionalReports — signal-aware category filter + Agri/Crypto/Bonds/Indices pills + Specialist Desks link
- 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>
2026-06-23 10:13:40 +02:00
OpenSquared
2fb683eec5 feat: Specialist Desks — per asset-class fundamental configs + report catalogue
- 7 pre-seeded desks (Forex, Metals, Agri, Energy, Indices, Crypto, Bonds)
  each with default fundamental drivers, macro regime sensitivities and
  price delta thresholds
- Global report catalogue (specialist_reports) fully manual — add any report
  including non-calendar ones (e.g. Cocoa Grinding Report, ICCO)
- Many-to-many report ↔ desk linking (report_desk_links table)
- 12 default reports pre-seeded (COT, EIA, WASDE, FOMC, ECB, CPI, NFP…)
- AI scorer injects SPECIALIST DESK context block for asset classes present
  in each scoring batch (upcoming reports, key drivers, regime sensitivity)
- /specialist-desks page: desk sidebar + fundamentals editor + macro
  sensitivity tag editor + reports tab + global reports catalogue + modal
  to create/edit any report with desk assignment

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-23 09:57:18 +02:00
OpenSquared
f2dd859ba0 fix: PatternLab save UX — color-coded toasts + meaningful error feedback
- 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>
2026-06-22 22:30:47 +02:00
OpenSquared
33097e1812 fix: custom tickers now placed in their natural asset-class tab
- 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>
2026-06-22 22:11:31 +02:00
OpenSquared
c3ea0b7f8c feat: dynamic market ticker watchlist (Markets page)
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>
2026-06-22 21:54:58 +02:00
OpenSquared
78c60d5254 feat: Pattern Lab Discover + fix history run display
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>
2026-06-22 21:36:00 +02:00
OpenSquared
a2315c3b78 feat: inline edit for patterns in library (name, description, category, direction, regime)
- 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>
2026-06-22 21:13:34 +02:00
OpenSquared
d794ad68aa fix: define .input component class in CSS (dark-themed inputs/selects)
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>
2026-06-22 21:10:10 +02:00
OpenSquared
f98ac112a3 feat: replace tree with faceted search + delete pattern button
- PatternExplorer: replace rigid taxonomy tree with FacetedSearch — combinable chip filters on Direction, Asset class, Category, Horizon, Source + full-text search (name/description/regime) + sort. No fixed hierarchy, scales with library size.
- PatternCard: delete button (trash icon) for non-builtin patterns, two-step confirm/cancel to prevent accidental deletion. Shows #regime_tag chip inline.
- RegimeCard and RegimeView unchanged.
- Remove dead code: TaxonomyNode, TreeNodeRow, enrichTree, pathStartsWith, TreeView, usePatternTaxonomy import.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-22 21:01:16 +02:00
OpenSquared
a435c11246 feat: regime system — Find Matching + By Regime view
- Pattern Lab: "Find Matching" button per pattern uses GPT-4o-mini to classify against library (merge_as_instance / counter_scenario / new_pattern); shows match badge + confidence + suggested #regime_tag; conditional action buttons (Merge / Save counter / Save new)
- save_pattern_from_run handles action='instance' (appends to historical_instances + updates stats), action='counter' (new pattern with counter_of link, tags parent regime_tag), action='new' (unchanged + regime_tag support)
- useApi.ts: extended useSaveLabPattern type + new useFindMatchingPattern mutation + MatchResult export type
- DB migrations: regime_tag + counter_of columns on custom_patterns
- PatternExplorer: new "By Regime" view groups saved patterns by regime_tag; RegimeCard shows historical instances, hit rate, counter-of link (orange); untagged group at bottom

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-22 20:52:11 +02:00
OpenSquared
198341b0c2 fix: trade_budget_eur + preferred_horizon saved and reloaded in Config
Backend:
- CycleConfigRequest: add trade_budget_eur, preferred_horizon_min/max fields
  (were missing — Pydantic silently dropped them, so saves never reached set_config)
- update_cycle_config: handle + persist the 3 new fields via set_config
- get_status(): read + return trade_budget_eur/preferred_horizon_min/max from DB
  (were missing — frontend always fell back to React default values on page load)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-22 20:25:31 +02:00
OpenSquared
6cca7f66b6 feat: ticker validation + SLV/USO/WEAT/CORN/TUR added to ETFs watchlist
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>
2026-06-22 20:15:26 +02:00
OpenSquared
a92094e1f3 feat: add ETFs tab to Markets page (SPY, QQQ, TLT, GLD, EEM, IWM, HYG…)
- New 'etfs' asset class in WATCHLIST: 18 key ETFs used in Pattern Lab presets
  (SPY, QQQ, IWM, TLT, IEF, HYG, GLD, EEM, FXI, EWG, EWJ, EWU, EWZ,
   XLF, SMH, KWEB, UUP, BIL)
- Added 'etfs' tab between Indices and Equities in Markets page
- Extended AssetClass union type to include 'etfs'

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-22 20:09:01 +02:00
OpenSquared
5ff5006dec feat: add purge-all for Pattern Library + clarify Trade Ideas in Data Management
Backend: DELETE /api/patterns/purge-all — removes all custom + backtested patterns
(source != 'builtin'), leaves Pattern Lab run history intact.

Frontend Config > Data Management:
- New PurgeButton for Pattern Library (custom_patterns table)
- Updated note: Trade Ideas are computed live from the Pattern Library (no separate table),
  so purging patterns resets trade idea generation on next cycle.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-22 18:42:11 +02:00
OpenSquared
5ac7b8a088 feat: 3-tier outcome scoring + options P&L simulation in Pattern Lab
Backend (pattern_lab.py):
- Replace binary HIT/MISS with FULL / PARTIAL / MISS scoring
  FULL: right direction AND ≥ 50% of expected move
  PARTIAL: right direction AND ≥ 15% of expected move (was always MISS before)
  MISS: wrong direction or negligible move
- Add direction_correct, direction_ratio, hit_type fields to all outcomes
- Add Black-Scholes ATM options P&L simulation (_bs_price, _ncdf, _sigma_for)
  Normalised to S₀=K=100, per-asset-class vol heuristic (FX 8%, indices 16%, crypto 65%)
  Supports: long call/put, straddle, strangle, call spread, put spread
- estimated_options_pnl_pct shows what the strategy would have returned

Frontend (PatternLab.tsx):
- OutcomeRow component: FULL HIT (green) / PARTIAL (amber) / MISS (red)
- Shows direction tick/cross + ratio % of target achieved
- Shows estimated options P&L with DollarSign icon
- Hit rate header shows full hits + partial count separately
- Card border: emerald = full, amber = partial, red = miss

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-22 18:36:33 +02:00
OpenSquared
66f6607568 feat: Data Management tab — purge endpoints for all major data stores
Backend — new DELETE /purge-all endpoints:
  - /api/logs/purge-all          → truncate system_logs (immediate, no 30d wait)
  - /api/reports/purge-all       → cycle_reports + ai_reports
  - /api/portfolio/purge-all     → portfolio + trade_entry_prices
  - /api/analytics/purge-all     → pattern_score_history, regime_clusters,
                                    pattern_embeddings, cycle_runs,
                                    macro_regime_history, geo_alert_history
  - /api/var/purge-all           → var_snapshots + pnl_snapshots
  - /api/pattern-lab/purge-all   → backtest_lab_runs

Frontend — Config.tsx: new 'Data Management' tab
  - PurgeButton component with inline double-confirm (click Purge → confirm)
  - Shows table names affected + row count deleted
  - 6 purge actions: Logs, AI Reports, Portfolio, Analytics, VaR, Pattern Lab

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-22 18:25:01 +02:00
OpenSquared
303ecc2a3a feat: instrument picker + Pattern Lab instrument scan mode
- instruments.ts: 90 IB-options-tradable instruments in 12 categories
  (US Indices, Europe, Asia, EM, Sectors, Forex, Bonds, Metals, Energy,
   Agriculture, Crypto, Volatility) — EUR/CHF, Cotton, etc. all included

- PatternExplorer: replace text input in Instrument Lens with categorised
  grid picker (category pill filters + search + custom ticker fallback)

- PatternLab: add Instrument Scan tab alongside Event Presets
  - Pick any instrument from the shared categorised picker
  - Set period (start/end date) + horizon per pattern
  - AI scans the full period: identifies 4-6 key pattern instances each with
    their own entry date, expected move, strategy
  - 'Evaluate outcomes' fetches actual price at T+horizon per pattern
  - 'Save pattern' promotes any instance to the Pattern Library

- backend/services/pattern_lab.py: run_instrument_scan() + evaluate_instrument_outcomes()
  (per-pattern analysis_date vs shared date in event mode)
- backend/routers/pattern_lab.py: POST /instrument-scan + POST /evaluate-instrument/{id}
- useApi.ts: useInstrumentScan + useEvaluateInstrumentScan hooks

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-22 18:20:22 +02:00
OpenSquared
cbf989502c feat: Pattern Lab — historical backtest engine for pattern discovery
- Remove all built-in patterns (no proof of legitimacy); seed_builtin_patterns is now a no-op
- DB: add backtest_lab_runs table + backtest_hits/runs_count columns on patterns
- services/pattern_lab.py: build_historical_context (yfinance + RSI/MA200),
  run_ai_backtest (GPT-4o as historical analyst), evaluate_outcomes (actual moves at T+horizon)
- routers/pattern_lab.py: POST /run, POST /evaluate/{id}, GET /runs, DELETE /runs/{id},
  POST /save-pattern (promotes hit pattern to library with reliability counters)
- PatternLab.tsx: 34 preset events 2015-2025 (macro/geo/credit/fx/commodities/volatility/tech),
  3-panel layout — preset selector + wizard + run history, market data table,
  AI pattern cards with hit/miss outcome display, Save to Library button
- useApi.ts: usePatternLabRuns, useRunPatternLab, useEvaluatePatternLab, useSaveLabPattern, useDeleteLabRun
- Sidebar + App.tsx: /pattern-lab route + FlaskConical nav link

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-22 17:55:48 +02:00
OpenSquared
a68a08d9af feat: trade mandate (budget + horizon) wired end-to-end
- database.py: add trade_budget_eur / preferred_horizon_min/max config
  defaults and include them in cycle config migrations
- auto_cycle.py: read trade params from config and inject into cycle_meta
- ai_analyzer.py: inject INVESTOR TRADE MANDATE block into scoring and
  suggestion prompts so GPT-4o penalises horizon mismatches and sizes
  within the capital cap
- Config.tsx: Trade Parameters card with budget + horizon sliders and live
  mandate summary
- TradeIdeas.tsx: horizon filter pills (< 1M / 1-3M / 3-6M / > 6M) and
  budget/horizon indicator pulled from saved config
- useApi.ts: extend useUpdateCycleConfig type with new config fields

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-22 17:24:38 +02:00
OpenSquared
9b98594c07 fix: 3 bugs from system logs — timedelta, scoring IndexError, lxml
- database.py: add timedelta to datetime import (used in
  get_recent_economic_surprises, was raising NameError)
- ai_analyzer.py: scoring split was searching French string
  'Retourne UNIQUEMENT ce JSON valide:' but prompt is now in English
  'Return ONLY this valid JSON:' — caused IndexError crashing every cycle
- requirements.txt: add lxml>=5.0.0 (yfinance earnings_dates dependency,
  was silently failing all 23 ticker fetches every hour)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-22 17:11:23 +02:00
OpenSquared
1cc192a221 feat: PatternExplorer — sort + category filter + category badge on cards
- Sort dropdown: AI Score / Probability / Expected Move / Date Added
- Category filter pills auto-populated from patterns in current node
- CategoryBadge component with colored pills (matches Trade Ideas palette)
- AI score shown top-right on each pattern card
- Changing taxonomy node resets category filter

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-22 17:08:24 +02:00
OpenSquared
7b2e333a9d fix: PatternExplorer — exclude root id from node paths so they match taxonomy_path
enrichTree was building paths starting with 'root', but patterns store paths
like ['geopolitical', 'armed_conflict', ...] — no root prefix. Fix: start
enriching root children with parentPath=[] instead of ['root'].

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-22 16:56:57 +02:00
OpenSquared
5d969d6fdb fix: PatternExplorer tree — extract .tree from API response and compute node paths
The taxonomy endpoint returns {tree, patterns} but the component was casting
the whole response as the root node. Also added enrichTree() to attach computed
path arrays to each node (backend PATTERN_TAXONOMY has no path field).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-22 16:53:54 +02:00
OpenSquared
10ffc345d6 feat: Pattern Explorer — taxonomy tree + 23 historical patterns + instrument lens
- PatternExplorer.tsx: new page with two views:
    • Tree View — 6-root taxonomy (geopolitical, monetary_policy, economic,
      commodity, risk_off, market_structure) with collapsible sub-nodes;
      pattern cards appear on node selection
    • Instrument Lens — search any ticker (e.g. GLD, FXE) to see every
      pattern + scenario that references it, with matching trades highlighted
- geo_analyzer.py: PATTERN_TAXONOMY tree constant + taxonomy_path on all
  patterns; 15 new documented patterns P009-P023 (BoJ YCC, SVB crisis,
  Taiwan semis, OPEC cuts, Fed pivot, Debt ceiling, Iran nuclear, DPRK,
  VIX backwardation, ECB surprise, Extreme Fear contrarian, S. China Sea,
  European energy, CPI hot print, Flash crash)
- patterns.py: GET /api/patterns/taxonomy, GET /api/patterns/by-instrument
- database.py: taxonomy_path migration + seed_builtin_patterns updates path
- App.tsx: /patterns → PatternExplorer, /patterns/edit → PatternEditor

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-22 16:42:45 +02:00
OpenSquared
acc8bef29d feat: 4 remaining institutional reports — Earnings, VX curve, Central Bank RSS, Sentiment
New fetchers (no API keys required):
- earnings_fetcher.py: yfinance EPS calendar + surprise tracking for 23 geo-relevant tickers
- vx_fetcher.py: VIX term structure (^VIX/^VXV/^VXMT) + CBOE delayed futures, regime detection
- central_bank_fetcher.py: Fed + ECB RSS feeds, keyword-based hawkish/dovish classification
- sentiment_fetcher.py: CNN Fear & Greed (primary) + NAAIM + AAII (optional fallbacks)

Wiring:
- institutional_scheduler.py: all 4 now scheduled daily (≥08:00 UTC), deduplicated per day
- institutional.py /refresh: all 6 types handled with _run() helper
- ai_analyzer.py build_institutional_block(): limit 6→12, generic header text
- InstitutionalReports.tsx: 6-type color map, individual refresh buttons, expanded filters

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-22 14:26:19 +02:00
OpenSquared
d178615c74 feat: Phase 2 — economic event surprise tracker (FRED actuals + z-score)
- economic_events table in DB (series_id, actual, forecast_baseline, surprise_pct, surprise_zscore, direction)
- DB helpers: save_economic_event(), get_recent_economic_surprises(), get_economic_events_for_calendar()
- fred_fetcher.py: _compute_zscore_surprise() computes 12-period MA as implied consensus + z-score deviation; save_fred_releases_to_db() persists releases per cycle; build_economic_surprise_block() formats significant surprises for AI prompt
- auto_cycle.py: saves FRED releases to economic_events each cycle, appends surprise block to fred_block for injection into both suggestion and scoring prompts
- data_fetcher.py: get_economic_calendar() now merges static upcoming events with past FRED actuals from DB (Prev/Fcst/Actual/z-score fields populated)
- CalendarPage.tsx: past events show colored z-score badge ( for |z|≥1.5, bullish/bearish colors)
- EconomicEvent type: added surprise_zscore, surprise_direction, source fields

Activates automatically once fred_api_key is set in Configuration.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-22 14:00:35 +02:00
OpenSquared
3edbd6b0b7 feat: institutional reports — CFTC COT + EIA petroleum weekly
- New institutional_reports table (DB) with importance, signals per asset class, key points, absorption tracking
- cot_fetcher.py: CFTC Socrata API (6dca-aqww), 7 instruments (Gold/Silver/Copper/WTI/NatGas/SP500/EURUSD), net positioning + 52-week z-score
- eia_fetcher.py: EIA API v2, 4 series (crude/Cushing/gasoline/distillates), WoW surprise detection
- institutional.py router: GET /reports, GET /reports/{id}, POST /refresh, GET /stats
- institutional_scheduler.py: weekly auto-fetch (COT Saturdays, EIA Wednesday afternoons)
- ai_analyzer.py: build_institutional_block() + institutional_block param injected into AI scoring prompt
- auto_cycle.py: inject institutional block into suggestion + scoring, absorption tracking via keyword overlap after each cycle commentary
- InstitutionalReports.tsx: full page with filter bar (type/category/importance/period), cards with key point bullets, EXTREME alerts highlighted, signal badges, absorption badge, trading implications, expandable detail

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-22 13:45:07 +02:00
OpenSquared
4423ad91db docs: update documentation to v5.0 — Phase 5, 19 pages, IV Gate, Pattern Convergence
Major additions since v4.4:
- Cover/version bump to v5.0 (5 phases, 19 pages)
- Section 1.4: pages table updated 15→19 (VaR Analysis, Position History, Backtest, Calendar, System Logs)
- Step 1 macro engine: 50 signals table (vol surface, sector rotation XLK/XLF/XLP/XLU, EM/carry EEM/EMB/USDJPY, silver, 5 derived metrics)
- New Section 2b: Cycle Context Engine (delta temporal, news decay, context snapshot, FRED, technical indicators by horizon, price discovery, replay, weekend-aware scheduler)
- Section 3: IV Gate (2-level threshold, formula, rationale) + dynamic IV Watchlist (3 types, bootstrap)
- New Section 5b: Pattern Convergence (8 categories, signal_direction, conviction_score, Trade Ideas tab, IBKR ticket auto-calc)
- Section 8: 6 new tables (system_logs, iv_watchlist, context_snapshots, iv_history, pnl_snapshots, var_snapshots) + new columns in existing tables
- Section 9: Journal updated to 7 tabs, guide pages 14–19 (VaR, Position History, Backtest, Calendar, System Logs, Config v5)
- Section 10: 5 new design decisions (IV Gate, watchlist DB, weekend scheduler, indicators by horizon, context snapshot)
- Section 11: 14 new glossary terms (cycle_meta, news decay, IV Gate, signal direction, conviction score, IBKR ticket, DTE, vol surface regime, watchlist dynamique, etc.)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-22 09:40:46 +02:00
OpenSquared
dcbc9f19fc feat: translate all UI strings to English for international release
Complete French→English translation across all frontend pages and backend
services — every label, button, header, empty state, toast, and nav item
is now in English. Build verified clean (tsc + vite). No i18n library
added; direct string replacement throughout.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-22 09:06:37 +02:00
OpenSquared
f8a0a6d023 feat: pattern convergence UI — thematic filter, signal direction, conviction score
TradeIdeas.tsx:
- THEMATIC_CATEGORIES const (8 catégories: géopolitique, macro_monétaire, technique,
  commodités_supply, risk_off, flux_saisonnier, géo_économique, crédit_stress)
- SIGNAL_DIR map (bullish ▲ vert / bearish ▼ rouge / volatility ⟷ violet / neutral ↔ gris)
- TradeItem interface: + category, signalDirection, convictionScore, convictionBonus,
  convergenceCount, convergencePartners
- useMemo: double filter (asset_class + thematic category); sort by conviction_score;
  populate new fields from pattern + scoreInfo
- Toolbar: thematic filter row (violet) séparé du filtre asset_class (bleu)
- TradeCard: category badge violet, signal direction arrow, conviction badge ⟳+N,
  convergence banner quand count > 0
- TradeRow: score column shows conviction_score + ⟳+N bonus; direction arrow;
  category chip abrégé dans le nom pattern

useApi.ts: useUpdateCycleConfig type extended with weekend_cycle_enabled + weekend_cycle_times

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-21 20:31:55 +02:00
OpenSquared
952e326590 feat: pattern convergence engine — categories, signal_direction, conviction scores
Phase 1 — Catégorisation:
- database.py: ADD COLUMN category + signal_direction on custom_patterns (migration);
  save_custom_pattern persists category/signal_direction; new helpers:
  get_unclassified_patterns(), update_pattern_classification(),
  get_patterns_with_last_score()
- ai_analyzer.py: PATTERN_CATEGORIES dict (8 categories: géopolitique, macro_monétaire,
  technique, commodités_supply, risk_off, flux_saisonnier, géo_économique, crédit_stress);
  classify_patterns_batch() → GPT-4o-mini batch classification
- suggest schema: added category + signal_direction fields so new patterns are
  classified from birth
- auto_cycle.py: Step 3.1 classifies all unclassified patterns after each suggestion

Phase 2 — Convergence layer (post-scoring, no extra AI call):
- ai_analyzer.py: _compute_convergence() groups scored patterns by (underlying, signal_direction);
  conviction_bonus = min(20, +5 per additional agreeing pattern); adds conviction_score,
  conviction_bonus, convergence_count, convergence_underlying, convergence_partners to each result;
  called at end of score_patterns_with_context(), re-sorts by conviction_score
- auto_cycle.py: logs convergence summary after scoring; propagates category/signal_direction
  to scored results for display

Phase optionnelle — Convergence in suggestion prompt:
- ai_analyzer.py: suggest_patterns_from_market_context() accepts convergence_block param;
  injected into prompt so AI knows which underlyings have multi-pattern agreement
- auto_cycle.py: before suggestion, loads last-cycle scores via get_patterns_with_last_score(),
  calls _compute_convergence() to build convergence block, passes to suggester

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-21 20:22:08 +02:00
OpenSquared
319ac35a26 feat: weekend-aware scheduler with configurable cycle times
- auto_cycle.py: _scheduler_loop now distinguishes weekday (interval_hours)
  from weekend (weekend_cycle_times UTC slots or sleep until Monday);
  _parse_weekend_times() and _next_weekend_slot() helpers;
  get_status() exposes weekend_cycle_enabled + weekend_cycle_times
- cycle.py: CycleConfigRequest adds weekend_cycle_enabled + weekend_cycle_times;
  update_cycle_config validates HH:MM format and persists to config DB
- Config.tsx: weekend scheduling section with enable toggle + time picker
  (06:00/08:00/12:00/18:00/22:00/00:00 UTC presets, multi-select);
  weekendEnabled + weekendTimes state synced from cycle status

Default: enabled with 08:00 + 22:00 UTC (covers news scan + Globex open Sunday)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-21 20:00:06 +02:00
OpenSquared
d4bc4e6624 fix: JSON serialization crash on NaN floats in cycle context snapshot
- portfolio_context.py: add _safe_float() helper (converts NaN/Inf → None);
  use .squeeze().dropna() on yfinance closes before computing moves;
  guard division by checking closes.iloc[-2] != 0
- cycle.py: add _sanitize_floats() recursive sanitizer applied to the full
  snapshot before FastAPI serializes it — catches any remaining NaN from
  iv_rank, technical indicators, or other sources

Fixes 500 on GET /api/cycle/contexts/{run_id} when yfinance returns NaN
weekend data for portfolio positions.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-21 19:48:19 +02:00
OpenSquared
96327bec8f fix: weekend-aware cycle — IVGate, pandas MultiIndex, ticker aliases, day/session in AI prompt
- auto_cycle.py: detect weekend/market session, build cycle_meta with day_of_week/is_weekend/market_note;
  IVGate skips iv_rank>=99 on weekends to avoid artificial weekend option premium cascade;
  inject portfolio context (open trades + price moves + concentration) before AI scoring;
  pass portfolio_context_block + run_id to both AI scorer and suggester
- ai_analyzer.py: _build_temporal_news_block injects market session banner (WEEKEND warning,
  pre/after-market note, or open session label) so AI knows markets are closed and defers execution to Monday
- iv_engine.py: add WHEAT/EUR/USD ticker aliases; skip saving IV snapshots on weekends to protect history;
  resolve aliases before slash-format conversion in _resolve_ticker
- technical_indicators.py: fix pandas MultiIndex from yfinance>=0.2 (droplevel+squeeze);
  use period proportional to lookback instead of fixed period=1d
- database.py: asset_class ticker-based fallback (_asset_class_from_ticker); one-time backfill migration
  for all NULL asset_class rows; ai_call_logs table + save/get helpers; normalize_ticker public function

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-21 19:38:08 +02:00
OpenSquared
4ad3a9a782 feat: portfolio context injection + AI call log viewer
Portfolio context (portfolio_context.py):
- get_open_trades_with_moves(): fetches open trades + 1d/5d yfinance price moves
- get_portfolio_concentration(): counts by asset_class
- build_portfolio_context_block(): formatted prompt block with strict AI instructions
  (no double positions, flag contradictions, avoid overweight classes)

AI call logging:
- ai_call_logs table in DB (run_id, call_type, system/user prompt, response, tokens, ms)
- _chat() now accepts log_meta dict → saves call to DB non-blocking after each call
- suggest and score_batch calls pass run_id + call_type for full traceability

auto_cycle.py:
- Builds portfolio context before snapshot and both AI calls
- Context snapshot now includes portfolio_open_positions key

SystemLogs.tsx:
- "Contexte IA" tab gains sub-tabs: Contexte / Appels IA
- AiCallRow: expandable with 3 panes (user prompt / system prompt / response)
  shows model, tokens breakdown, duration, call type badge

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-21 10:36:05 +02:00
OpenSquared
5d3ff19393 fix: ticker-based asset_class fallback + backfill migration for NULL rows
- _normalize_asset_class() now accepts ticker param and infers class from
  a full ticker→class lookup table (energy/metals/agri/indices/equities/forex)
- init_db() runs one-time UPDATE to backfill all NULL asset_class rows in
  trade_entry_prices and skipped_trades using known ticker lists
- log_trade_entries and log_skipped_trade pass ticker to normalizer
- Frontend _normalizeAssetClass() gets same ticker lookup + pattern fallbacks
  for =F futures, NSE: prefixed equities, =X currency pairs
- All 3 filter calls now pass t.underlying as second argument

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-20 18:58:25 +02:00