feat: Rapport de Cycle — auto-généré à chaque run avec contexte IA, delta, PnL/VaR snapshot
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -3,6 +3,7 @@ from fastapi.middleware.cors import CORSMiddleware
|
|||||||
from routers import market_data, geopolitical, options, backtest, ai, portfolio, config, patterns, journal, cycle as cycle_router, profiles as profiles_router, reasoning as reasoning_router, knowledge as knowledge_router, options_vol as options_vol_router, analytics as analytics_router, risk as risk_router
|
from routers import market_data, geopolitical, options, backtest, ai, portfolio, config, patterns, journal, cycle as cycle_router, profiles as profiles_router, reasoning as reasoning_router, knowledge as knowledge_router, options_vol as options_vol_router, analytics as analytics_router, risk as risk_router
|
||||||
from routers import logs as logs_router
|
from routers import logs as logs_router
|
||||||
from routers import var as var_router
|
from routers import var as var_router
|
||||||
|
from routers import reports as reports_router
|
||||||
from services.database import init_db, get_config, cleanup_stale_running_cycles
|
from services.database import init_db, get_config, cleanup_stale_running_cycles
|
||||||
import os
|
import os
|
||||||
import logging
|
import logging
|
||||||
@@ -108,6 +109,7 @@ app.include_router(analytics_router.router)
|
|||||||
app.include_router(risk_router.router)
|
app.include_router(risk_router.router)
|
||||||
app.include_router(logs_router.router)
|
app.include_router(logs_router.router)
|
||||||
app.include_router(var_router.router)
|
app.include_router(var_router.router)
|
||||||
|
app.include_router(reports_router.router)
|
||||||
|
|
||||||
|
|
||||||
@app.get("/")
|
@app.get("/")
|
||||||
|
|||||||
25
backend/routers/reports.py
Normal file
25
backend/routers/reports.py
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
from fastapi import APIRouter, HTTPException
|
||||||
|
from services.database import get_cycle_reports, get_cycle_report, get_latest_cycle_report
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/reports", tags=["reports"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/cycle/latest")
|
||||||
|
def cycle_report_latest():
|
||||||
|
"""Most recent generated cycle report."""
|
||||||
|
return {"report": get_latest_cycle_report()}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/cycle/list")
|
||||||
|
def cycle_report_list(limit: int = 20):
|
||||||
|
"""List of cycle report summaries (no full JSON)."""
|
||||||
|
return {"reports": get_cycle_reports(limit)}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/cycle/{run_id}")
|
||||||
|
def cycle_report_detail(run_id: str):
|
||||||
|
"""Full cycle report for a specific run_id."""
|
||||||
|
report = get_cycle_report(run_id)
|
||||||
|
if not report:
|
||||||
|
raise HTTPException(404, "Rapport de cycle introuvable")
|
||||||
|
return report
|
||||||
@@ -636,6 +636,29 @@ def run_cycle_once(trigger: str = "auto") -> Dict[str, Any]:
|
|||||||
_current_status["last_run_at"] = datetime.utcnow().isoformat()
|
_current_status["last_run_at"] = datetime.utcnow().isoformat()
|
||||||
logger.info(f"[Cycle {run_id[:16]}] Completed — {added_count} new patterns, {len(scored)} scored")
|
logger.info(f"[Cycle {run_id[:16]}] Completed — {added_count} new patterns, {len(scored)} scored")
|
||||||
|
|
||||||
|
# ── Step 6.5: Generate full cycle report ─────────────────────────────
|
||||||
|
try:
|
||||||
|
_cycle_report = _generate_cycle_report(
|
||||||
|
run_id=run_id,
|
||||||
|
scored=scored,
|
||||||
|
dominant=dominant,
|
||||||
|
scenarios=scenarios,
|
||||||
|
geo_score_val=geo_score_val,
|
||||||
|
news=news,
|
||||||
|
gauges=gauges,
|
||||||
|
ai_key=ai_key,
|
||||||
|
added_patterns=[s for s in suggestions if s.get("id")],
|
||||||
|
scoring_run_id=scoring_run_id,
|
||||||
|
portfolio_monitor=summary.get("portfolio_monitor"),
|
||||||
|
commentary=commentary,
|
||||||
|
)
|
||||||
|
if _cycle_report:
|
||||||
|
from services.database import save_cycle_report
|
||||||
|
save_cycle_report(run_id, _cycle_report)
|
||||||
|
logger.info(f"[Cycle {run_id[:16]}] Cycle report saved")
|
||||||
|
except Exception as _rpe:
|
||||||
|
logger.warning(f"[Cycle] Cycle report failed (non-blocking): {_rpe}")
|
||||||
|
|
||||||
# ── Step 7: Auto portfolio snapshot ──────────────────────────────────
|
# ── Step 7: Auto portfolio snapshot ──────────────────────────────────
|
||||||
# Generate (or refresh) the portfolio report so the NEXT cycle has
|
# Generate (or refresh) the portfolio report so the NEXT cycle has
|
||||||
# fresh performance lessons. Runs in background to not block the cycle.
|
# fresh performance lessons. Runs in background to not block the cycle.
|
||||||
@@ -742,6 +765,232 @@ Réponds UNIQUEMENT en JSON: {{"commentary": "<ton texte 4-6 phrases>", "key_ris
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
# ── Cycle report generation ───────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def _generate_cycle_report(
|
||||||
|
run_id: str,
|
||||||
|
scored: List[Dict],
|
||||||
|
dominant: str,
|
||||||
|
scenarios: Dict,
|
||||||
|
geo_score_val: int,
|
||||||
|
news: List[Dict],
|
||||||
|
gauges: Dict,
|
||||||
|
ai_key: str,
|
||||||
|
added_patterns: List[Dict],
|
||||||
|
scoring_run_id: str,
|
||||||
|
portfolio_monitor: Optional[Dict],
|
||||||
|
commentary: Optional[str],
|
||||||
|
) -> Optional[Dict]:
|
||||||
|
"""
|
||||||
|
Build the full cycle report dict:
|
||||||
|
- PnL + VaR snapshots (timestamped with this cycle)
|
||||||
|
- Delta vs previous cycle (patterns added, trades logged, trades closed)
|
||||||
|
- GPT-4o context narrative (what was in context, what it used, why)
|
||||||
|
- Risk summary
|
||||||
|
"""
|
||||||
|
import json as _json
|
||||||
|
|
||||||
|
try:
|
||||||
|
from services.database import get_cycle_runs, get_trade_entries_by_run
|
||||||
|
except ImportError:
|
||||||
|
from services.database import get_cycle_runs
|
||||||
|
get_trade_entries_by_run = None
|
||||||
|
|
||||||
|
# ── Get previous cycle timestamp ──────────────────────────────────────────
|
||||||
|
prev_cycle_at: Optional[str] = None
|
||||||
|
try:
|
||||||
|
history = get_cycle_runs(limit=5)
|
||||||
|
prev_cycles = [r for r in history if r["run_id"] != run_id and r.get("status") == "completed"]
|
||||||
|
if prev_cycles:
|
||||||
|
prev_cycle_at = prev_cycles[0].get("started_at")
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# ── PnL snapshot ──────────────────────────────────────────────────────────
|
||||||
|
pnl_snapshot_id: Optional[int] = None
|
||||||
|
pnl_summary: Dict = {}
|
||||||
|
try:
|
||||||
|
from services.var_service import save_pnl_snapshot, get_latest_pnl_snapshot
|
||||||
|
pnl_snapshot_id = save_pnl_snapshot()
|
||||||
|
snap = get_latest_pnl_snapshot()
|
||||||
|
if snap:
|
||||||
|
pnl_summary = {
|
||||||
|
"total_pnl_pct": snap.get("total_pnl_pct"),
|
||||||
|
"total_pnl_eur": snap.get("total_pnl_eur"),
|
||||||
|
"total_capital_eur": snap.get("total_capital_eur"),
|
||||||
|
"n_open": snap.get("n_open"),
|
||||||
|
"n_closed": snap.get("n_closed"),
|
||||||
|
}
|
||||||
|
logger.info(f"[CycleReport] PnL snapshot saved id={pnl_snapshot_id}")
|
||||||
|
except Exception as _e:
|
||||||
|
logger.warning(f"[CycleReport] PnL snapshot failed: {_e}")
|
||||||
|
|
||||||
|
# ── VaR snapshot ──────────────────────────────────────────────────────────
|
||||||
|
var_snapshot_id: Optional[int] = None
|
||||||
|
var_summary: Dict = {}
|
||||||
|
try:
|
||||||
|
from services.var_service import compute_var, save_var_snapshot
|
||||||
|
var_result = compute_var(confidence=0.95, horizon_days=1, lookback_days=252, default_iv=0.20)
|
||||||
|
if "error" not in var_result:
|
||||||
|
var_snapshot_id = save_var_snapshot(var_result, 0.95, 1, 252, 0.20)
|
||||||
|
var_summary = {
|
||||||
|
"hist_var_1d_pct": var_result.get("hist_var_1d_pct"),
|
||||||
|
"hist_cvar_pct": var_result.get("hist_cvar_pct"),
|
||||||
|
"mc_var_1d_pct": var_result.get("mc_var_1d_pct"),
|
||||||
|
"n_positions": var_result.get("n_positions"),
|
||||||
|
}
|
||||||
|
logger.info(f"[CycleReport] VaR snapshot saved id={var_snapshot_id}")
|
||||||
|
except Exception as _e:
|
||||||
|
logger.warning(f"[CycleReport] VaR snapshot failed: {_e}")
|
||||||
|
|
||||||
|
# ── Trades delta ──────────────────────────────────────────────────────────
|
||||||
|
trades_logged: List[Dict] = []
|
||||||
|
trades_closed: List[Dict] = []
|
||||||
|
try:
|
||||||
|
from services.database import get_conn
|
||||||
|
_conn = get_conn()
|
||||||
|
# Trades logged this cycle (by scoring_run_id)
|
||||||
|
_rows = _conn.execute(
|
||||||
|
"""SELECT underlying, strategy, entry_date, pnl_pct, score_at_entry, pattern_name
|
||||||
|
FROM trade_entry_prices WHERE run_id=? ORDER BY entry_date DESC""",
|
||||||
|
(scoring_run_id,),
|
||||||
|
).fetchall()
|
||||||
|
trades_logged = [dict(r) for r in _rows]
|
||||||
|
|
||||||
|
# Trades closed since previous cycle
|
||||||
|
if prev_cycle_at:
|
||||||
|
_closed = _conn.execute(
|
||||||
|
"""SELECT underlying, strategy, closed_at, pnl_pct, pattern_name
|
||||||
|
FROM trade_entry_prices
|
||||||
|
WHERE status='closed' AND closed_at >= ?
|
||||||
|
ORDER BY closed_at DESC""",
|
||||||
|
(prev_cycle_at,),
|
||||||
|
).fetchall()
|
||||||
|
trades_closed = [dict(r) for r in _closed]
|
||||||
|
_conn.close()
|
||||||
|
except Exception as _e:
|
||||||
|
logger.warning(f"[CycleReport] Delta trades query failed: {_e}")
|
||||||
|
|
||||||
|
# ── Context narrative (GPT-4o) ────────────────────────────────────────────
|
||||||
|
context_narrative: Dict = {}
|
||||||
|
try:
|
||||||
|
from services.ai_analyzer import _chat
|
||||||
|
|
||||||
|
top_news_ctx = [
|
||||||
|
{"title": n.get("title", "")[:100], "impact": round(float(n.get("impact_score") or 0), 2)}
|
||||||
|
for n in sorted(news, key=lambda x: -(float(x.get("impact_score") or 0)))[:8]
|
||||||
|
]
|
||||||
|
|
||||||
|
def _gv(k: str) -> str:
|
||||||
|
v = gauges.get(k, {}).get("value")
|
||||||
|
return str(round(v, 2)) if v is not None else "N/A"
|
||||||
|
|
||||||
|
def _gc(k: str) -> str:
|
||||||
|
v = gauges.get(k, {}).get("change_pct")
|
||||||
|
return f"{v:+.2f}%" if v is not None else "N/A"
|
||||||
|
|
||||||
|
new_pattern_names = [p.get("name", "") for p in added_patterns]
|
||||||
|
top_scored = sorted(scored, key=lambda x: -(x.get("score") or 0))[:5]
|
||||||
|
|
||||||
|
ctx_prompt = f"""Tu es un analyste stratégique qui documente le RAISONNEMENT d'un cycle d'analyse géo-macro.
|
||||||
|
|
||||||
|
CONTEXTE TRANSMIS À L'IA CE CYCLE:
|
||||||
|
- Régime macro dominant: {dominant.upper()} (score: {scenarios.get('scores', {}).get(dominant, 0)}%)
|
||||||
|
- Score risque géopolitique: {geo_score_val}/100
|
||||||
|
- VIX: {_gv('vix')} | Pente 10Y-3M: {_gv('slope_10y3m')} | S&P/200j: {_gv('spx_vs_200d')}%
|
||||||
|
- Cuivre: {_gc('copper')} | Or: {_gc('gold')} | DXY: {_gc('dxy')} | Brent: {_gc('brent')}
|
||||||
|
- Top 8 news géopolitiques transmises: {_json.dumps(top_news_ctx, ensure_ascii=False)}
|
||||||
|
|
||||||
|
NOUVELLES IDÉES GÉNÉRÉES CE CYCLE ({len(new_pattern_names)} patterns ajoutés):
|
||||||
|
{_json.dumps(new_pattern_names, ensure_ascii=False)}
|
||||||
|
|
||||||
|
TOP 5 PATTERNS LES MIEUX SCORÉS MAINTENANT:
|
||||||
|
{_json.dumps([{{"name": s.get("geo_trigger","?"), "score": s.get("score"), "catalyst": s.get("key_catalyst","")[:80]}} for s in top_scored], ensure_ascii=False)}
|
||||||
|
|
||||||
|
Ta tâche: Explique le RAISONNEMENT de ce cycle.
|
||||||
|
Pour chaque nouvelle idée générée:
|
||||||
|
1. Quels éléments SPÉCIFIQUES du contexte transmis (news, macro, gauges) l'ont motivée ?
|
||||||
|
2. Qu'est-ce qui vient de ta connaissance GÉNÉRALE des marchés (pas du contexte transmis) ?
|
||||||
|
3. Quels signaux étaient les plus déterminants ?
|
||||||
|
|
||||||
|
Réponds en JSON avec ce schéma EXACT:
|
||||||
|
{{
|
||||||
|
"narrative": "<texte narratif 6-10 phrases expliquant le raisonnement global du cycle>",
|
||||||
|
"context_driven": ["<signal du contexte qui a motivé une idée spécifique>", ...],
|
||||||
|
"general_knowledge": ["<connaissance générale utilisée>", ...],
|
||||||
|
"key_signals": ["<3-5 signaux les plus décisifs>"],
|
||||||
|
"context_log": {{
|
||||||
|
"macro_regime": "{dominant}",
|
||||||
|
"geo_score": {geo_score_val},
|
||||||
|
"dominant_news": ["<titre news 1>", "<titre news 2>", "<titre news 3>"],
|
||||||
|
"key_gauges": {{"vix": {_gv('vix')}, "slope": {_gv('slope_10y3m')}, "copper_chg": {_gc('copper')}, "gold_chg": {_gc('gold')}}}
|
||||||
|
}}
|
||||||
|
}}"""
|
||||||
|
|
||||||
|
result = _chat(
|
||||||
|
"Tu es un analyste macro-géopolitique. Documente le raisonnement du cycle en JSON.",
|
||||||
|
ctx_prompt,
|
||||||
|
model="gpt-4o",
|
||||||
|
json_mode=True,
|
||||||
|
max_tokens=800,
|
||||||
|
)
|
||||||
|
if result and result.get("narrative"):
|
||||||
|
context_narrative = result
|
||||||
|
logger.info(f"[CycleReport] Context narrative generated ({len(result.get('narrative',''))} chars)")
|
||||||
|
except Exception as _e:
|
||||||
|
logger.warning(f"[CycleReport] Context narrative failed: {_e}")
|
||||||
|
context_narrative = {"narrative": "", "context_driven": [], "general_knowledge": [], "key_signals": []}
|
||||||
|
|
||||||
|
# ── Parse existing commentary ─────────────────────────────────────────────
|
||||||
|
commentary_parsed: Dict = {}
|
||||||
|
if commentary:
|
||||||
|
try:
|
||||||
|
commentary_parsed = _json.loads(commentary) if isinstance(commentary, str) else commentary
|
||||||
|
except Exception:
|
||||||
|
commentary_parsed = {"commentary": str(commentary)}
|
||||||
|
|
||||||
|
# ── Assemble full report ──────────────────────────────────────────────────
|
||||||
|
report = {
|
||||||
|
"run_id": run_id,
|
||||||
|
"macro_dominant": dominant,
|
||||||
|
"geo_score": geo_score_val,
|
||||||
|
"macro_scores": scenarios.get("scores", {}),
|
||||||
|
"macro_reasons": scenarios.get("reasons", {}).get(dominant, []),
|
||||||
|
# Snapshots
|
||||||
|
"pnl_snapshot_id": pnl_snapshot_id,
|
||||||
|
"var_snapshot_id": var_snapshot_id,
|
||||||
|
"pnl_summary": pnl_summary,
|
||||||
|
"var_summary": var_summary,
|
||||||
|
# Delta
|
||||||
|
"patterns_added": len(added_patterns),
|
||||||
|
"patterns_added_list": [
|
||||||
|
{"name": p.get("name"), "description": (p.get("description") or "")[:150],
|
||||||
|
"asset_class": p.get("asset_class"), "macro_fit": p.get("macro_fit"),
|
||||||
|
"triggers": p.get("triggers", [])[:3]}
|
||||||
|
for p in added_patterns
|
||||||
|
],
|
||||||
|
"trades_logged": len(trades_logged),
|
||||||
|
"trades_logged_list": trades_logged[:10],
|
||||||
|
"trades_closed": len(trades_closed),
|
||||||
|
"trades_closed_list": trades_closed[:10],
|
||||||
|
"prev_cycle_at": prev_cycle_at,
|
||||||
|
# Context narrative
|
||||||
|
"context_narrative": context_narrative,
|
||||||
|
# Cycle commentary (existing)
|
||||||
|
"commentary": commentary_parsed,
|
||||||
|
# Risk
|
||||||
|
"portfolio_monitor": portfolio_monitor,
|
||||||
|
"risk_alerts": portfolio_monitor.get("alerts") if portfolio_monitor else None,
|
||||||
|
# Top scored patterns
|
||||||
|
"top_scored": [
|
||||||
|
{"name": s.get("geo_trigger"), "score": s.get("score"),
|
||||||
|
"summary": (s.get("summary") or "")[:120], "key_catalyst": s.get("key_catalyst", "")}
|
||||||
|
for s in sorted(scored, key=lambda x: -(x.get("score") or 0))[:5]
|
||||||
|
],
|
||||||
|
}
|
||||||
|
return report
|
||||||
|
|
||||||
|
|
||||||
# ── Auto portfolio snapshot ───────────────────────────────────────────────────
|
# ── Auto portfolio snapshot ───────────────────────────────────────────────────
|
||||||
|
|
||||||
def _auto_portfolio_snapshot(ai_key: str) -> None:
|
def _auto_portfolio_snapshot(ai_key: str) -> None:
|
||||||
|
|||||||
@@ -443,6 +443,24 @@ def init_db():
|
|||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
c.execute("""CREATE TABLE IF NOT EXISTS cycle_reports (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
run_id TEXT NOT NULL UNIQUE,
|
||||||
|
generated_at TEXT NOT NULL,
|
||||||
|
macro_dominant TEXT,
|
||||||
|
geo_score INTEGER,
|
||||||
|
patterns_added INTEGER DEFAULT 0,
|
||||||
|
trades_logged INTEGER DEFAULT 0,
|
||||||
|
trades_closed INTEGER DEFAULT 0,
|
||||||
|
pnl_snapshot_id INTEGER,
|
||||||
|
var_snapshot_id INTEGER,
|
||||||
|
full_report_json TEXT
|
||||||
|
)""")
|
||||||
|
try:
|
||||||
|
c.execute("CREATE INDEX IF NOT EXISTS idx_cycle_reports_ts ON cycle_reports(generated_at DESC)")
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
try:
|
try:
|
||||||
c.execute("CREATE INDEX IF NOT EXISTS idx_kb_category ON knowledge_base(category, status)")
|
c.execute("CREATE INDEX IF NOT EXISTS idx_kb_category ON knowledge_base(category, status)")
|
||||||
c.execute("CREATE INDEX IF NOT EXISTS idx_rs_version ON reasoning_state(version DESC)")
|
c.execute("CREATE INDEX IF NOT EXISTS idx_rs_version ON reasoning_state(version DESC)")
|
||||||
@@ -3163,3 +3181,77 @@ def _build_risk_recommendation(
|
|||||||
"messages": messages,
|
"messages": messages,
|
||||||
"summary": messages[0] if messages else "",
|
"summary": messages[0] if messages else "",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ── Cycle reports ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def save_cycle_report(run_id: str, report: Dict[str, Any]) -> None:
|
||||||
|
import json as _json
|
||||||
|
conn = get_conn()
|
||||||
|
conn.execute(
|
||||||
|
"""INSERT OR REPLACE INTO cycle_reports
|
||||||
|
(run_id, generated_at, macro_dominant, geo_score,
|
||||||
|
patterns_added, trades_logged, trades_closed,
|
||||||
|
pnl_snapshot_id, var_snapshot_id, full_report_json)
|
||||||
|
VALUES (?, datetime('now'), ?, ?, ?, ?, ?, ?, ?, ?)""",
|
||||||
|
(
|
||||||
|
run_id,
|
||||||
|
report.get("macro_dominant"),
|
||||||
|
report.get("geo_score"),
|
||||||
|
report.get("patterns_added", 0),
|
||||||
|
report.get("trades_logged", 0),
|
||||||
|
report.get("trades_closed", 0),
|
||||||
|
report.get("pnl_snapshot_id"),
|
||||||
|
report.get("var_snapshot_id"),
|
||||||
|
_json.dumps(report, ensure_ascii=False),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def get_cycle_reports(limit: int = 20) -> List[Dict[str, Any]]:
|
||||||
|
conn = get_conn()
|
||||||
|
rows = conn.execute(
|
||||||
|
"""SELECT run_id, generated_at, macro_dominant, geo_score,
|
||||||
|
patterns_added, trades_logged, trades_closed
|
||||||
|
FROM cycle_reports ORDER BY generated_at DESC LIMIT ?""",
|
||||||
|
(limit,),
|
||||||
|
).fetchall()
|
||||||
|
conn.close()
|
||||||
|
return [dict(r) for r in rows]
|
||||||
|
|
||||||
|
|
||||||
|
def get_cycle_report(run_id: str) -> Optional[Dict[str, Any]]:
|
||||||
|
import json as _json
|
||||||
|
conn = get_conn()
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT full_report_json, generated_at FROM cycle_reports WHERE run_id=?",
|
||||||
|
(run_id,),
|
||||||
|
).fetchone()
|
||||||
|
conn.close()
|
||||||
|
if not row or not row["full_report_json"]:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
report = _json.loads(row["full_report_json"])
|
||||||
|
report["generated_at"] = row["generated_at"]
|
||||||
|
return report
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def get_latest_cycle_report() -> Optional[Dict[str, Any]]:
|
||||||
|
import json as _json
|
||||||
|
conn = get_conn()
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT full_report_json, generated_at FROM cycle_reports ORDER BY generated_at DESC LIMIT 1"
|
||||||
|
).fetchone()
|
||||||
|
conn.close()
|
||||||
|
if not row or not row["full_report_json"]:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
report = _json.loads(row["full_report_json"])
|
||||||
|
report["generated_at"] = row["generated_at"]
|
||||||
|
return report
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ const nav = [
|
|||||||
{ to: '/patterns', icon: Zap, label: 'Patterns' },
|
{ to: '/patterns', icon: Zap, label: 'Patterns' },
|
||||||
{ to: '/portfolio', icon: DollarSign, label: 'Portefeuille' },
|
{ to: '/portfolio', icon: DollarSign, label: 'Portefeuille' },
|
||||||
{ to: '/journal', icon: BookOpen, label: 'Journal de Bord' },
|
{ to: '/journal', icon: BookOpen, label: 'Journal de Bord' },
|
||||||
{ to: '/rapport', icon: FileBarChart, label: 'Rapport IA' },
|
{ to: '/rapport', icon: FileBarChart, label: 'Rapport de Cycle' },
|
||||||
{ to: '/super-contexte', icon: Brain, label: 'Super Contexte' },
|
{ to: '/super-contexte', icon: Brain, label: 'Super Contexte' },
|
||||||
{ to: '/analytics', icon: FlaskConical, label: 'Analytics' },
|
{ to: '/analytics', icon: FlaskConical, label: 'Analytics' },
|
||||||
{ to: '/analytics-advanced', icon: Microscope, label: 'Analytics Avancées' },
|
{ to: '/analytics-advanced', icon: Microscope, label: 'Analytics Avancées' },
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { Brain, TrendingUp, TrendingDown, RefreshCw, Zap, AlertTriangle, BookOpen, Target, Eye, Clock, ChevronRight, Trash2 } from 'lucide-react'
|
import { useQuery } from '@tanstack/react-query'
|
||||||
import clsx from 'clsx'
|
import clsx from 'clsx'
|
||||||
import { usePortfolioReportData, useGeneratePortfolioReport, useAiReportsList, useAiReport, useDeleteAiReport } from '../hooks/useApi'
|
import {
|
||||||
import { useQueryClient } from '@tanstack/react-query'
|
Brain, TrendingUp, TrendingDown, RefreshCw, ShieldAlert,
|
||||||
|
GitCompare, Layers, Zap, BookOpen, Clock, ChevronRight,
|
||||||
|
} from 'lucide-react'
|
||||||
|
|
||||||
const SCENARIO_META: Record<string, { label: string; color: string; emoji: string }> = {
|
const SCENARIO_META: Record<string, { label: string; color: string; emoji: string }> = {
|
||||||
goldilocks: { label: 'Goldilocks', color: '#22c55e', emoji: '🌟' },
|
goldilocks: { label: 'Goldilocks', color: '#22c55e', emoji: '🌟' },
|
||||||
@@ -16,11 +18,12 @@ const SCENARIO_META: Record<string, { label: string; color: string; emoji: strin
|
|||||||
incertain: { label: 'Incertain', color: '#64748b', emoji: '❓' },
|
incertain: { label: 'Incertain', color: '#64748b', emoji: '❓' },
|
||||||
}
|
}
|
||||||
|
|
||||||
function ScenarioBadge({ dominant }: { dominant: string }) {
|
function RegimeBadge({ dominant }: { dominant?: string }) {
|
||||||
|
if (!dominant) return null
|
||||||
const m = SCENARIO_META[dominant] ?? SCENARIO_META.incertain
|
const m = SCENARIO_META[dominant] ?? SCENARIO_META.incertain
|
||||||
return (
|
return (
|
||||||
<span
|
<span
|
||||||
className="inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[11px] font-semibold"
|
className="inline-flex items-center gap-1 rounded px-2 py-0.5 text-xs font-semibold"
|
||||||
style={{ background: `${m.color}22`, color: m.color, border: `1px solid ${m.color}44` }}
|
style={{ background: `${m.color}22`, color: m.color, border: `1px solid ${m.color}44` }}
|
||||||
>
|
>
|
||||||
{m.emoji} {m.label}
|
{m.emoji} {m.label}
|
||||||
@@ -28,499 +31,415 @@ function ScenarioBadge({ dominant }: { dominant: string }) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function PnlBar({ pnl }: { pnl: number }) {
|
function Section({ icon, title, children }: { icon: React.ReactNode; title: string; children: React.ReactNode }) {
|
||||||
const pos = pnl >= 0
|
|
||||||
const width = Math.min(Math.abs(pnl), 200) / 2 // cap at 100% width
|
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center gap-2">
|
<div className="card mb-4">
|
||||||
<span className={clsx('font-bold font-mono text-sm w-16 text-right', pos ? 'text-emerald-400' : 'text-red-400')}>
|
<div className="flex items-center gap-2 mb-3 pb-2 border-b border-slate-700/40">
|
||||||
{pos ? '+' : ''}{pnl.toFixed(1)}%
|
<span className="text-slate-400">{icon}</span>
|
||||||
</span>
|
<span className="text-sm font-semibold text-slate-200">{title}</span>
|
||||||
<div className="flex-1 h-1.5 bg-dark-700 rounded-full overflow-hidden">
|
|
||||||
<div
|
|
||||||
className="h-full rounded-full"
|
|
||||||
style={{ width: `${width}%`, background: pos ? '#22c55e' : '#ef4444' }}
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
|
{children}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function ScoreTrend({ trend }: { trend: number[] }) {
|
function DeltaRow({ emoji, label, count, items, colorClass }: {
|
||||||
if (!trend || trend.length === 0) return <span className="text-slate-700 text-xs">—</span>
|
emoji: string; label: string; count: number;
|
||||||
return (
|
items: any[]; colorClass: string;
|
||||||
<div className="flex items-end gap-0.5 h-6">
|
|
||||||
{trend.map((s, i) => (
|
|
||||||
<div
|
|
||||||
key={i}
|
|
||||||
className="w-2 rounded-sm"
|
|
||||||
style={{
|
|
||||||
height: `${Math.max(3, (s ?? 0) / 100 * 24)}px`,
|
|
||||||
background: (s ?? 0) >= 60 ? '#22c55e' : (s ?? 0) >= 40 ? '#eab308' : '#64748b',
|
|
||||||
}}
|
|
||||||
title={`${s}/100`}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function MoverCard({ trade, rank, type }: { trade: any; rank: number; type: 'winner' | 'loser' }) {
|
|
||||||
const [expanded, setExpanded] = useState(false)
|
|
||||||
const pnl = trade.pnl_pct ?? 0
|
|
||||||
const sc = trade.scoring_context ?? {}
|
|
||||||
const scOut = sc.output ?? {}
|
|
||||||
const sg = trade.suggestion_context ?? {}
|
|
||||||
const sgOut = sg.output ?? {}
|
|
||||||
const buckets: any[] = scOut.buckets ?? []
|
|
||||||
const isWinner = type === 'winner'
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className={clsx(
|
|
||||||
'card border',
|
|
||||||
isWinner ? 'border-emerald-700/20' : 'border-red-700/20'
|
|
||||||
)}>
|
|
||||||
<div className="flex items-start gap-3">
|
|
||||||
{/* Rank */}
|
|
||||||
<div className={clsx(
|
|
||||||
'w-7 h-7 rounded-full flex items-center justify-center text-xs font-bold shrink-0',
|
|
||||||
isWinner ? 'bg-emerald-900/40 text-emerald-400' : 'bg-red-900/40 text-red-400'
|
|
||||||
)}>
|
|
||||||
{rank}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex-1 min-w-0">
|
|
||||||
<div className="flex items-center justify-between gap-2 mb-1">
|
|
||||||
<div className="flex items-center gap-2 min-w-0">
|
|
||||||
<span className="font-semibold text-slate-200 truncate">{trade.pattern_name || trade.pattern_id}</span>
|
|
||||||
<span className={clsx('text-[10px] font-semibold px-1.5 py-0.5 rounded',
|
|
||||||
trade.direction === 'bearish' ? 'bg-red-900/30 text-red-400' : 'bg-emerald-900/30 text-emerald-400')}>
|
|
||||||
{trade.direction === 'bearish' ? '🐻' : '🐂'} {trade.strategy}
|
|
||||||
</span>
|
|
||||||
<span className="font-mono text-slate-400 text-xs">{trade.underlying}</span>
|
|
||||||
</div>
|
|
||||||
<button
|
|
||||||
onClick={() => setExpanded(v => !v)}
|
|
||||||
className="text-slate-600 hover:text-slate-400 shrink-0"
|
|
||||||
>
|
|
||||||
<Eye className="w-3.5 h-3.5" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<PnlBar pnl={pnl} />
|
|
||||||
|
|
||||||
<div className="flex flex-wrap items-center gap-3 mt-2 text-[11px] text-slate-500">
|
|
||||||
<span>Score entrée : <span className="font-mono text-slate-300">{trade.score_at_entry ?? '?'}/100</span></span>
|
|
||||||
<span>EV : <span className={clsx('font-mono', (trade.ev_net ?? 0) > 0 ? 'text-emerald-400' : 'text-red-400')}>
|
|
||||||
{trade.ev_net != null ? `${(trade.ev_net * 100).toFixed(0)}%` : '—'}
|
|
||||||
</span></span>
|
|
||||||
{sc.macro_dominant && <ScenarioBadge dominant={sc.macro_dominant} />}
|
|
||||||
{sc.geo_score != null && <span>Géo <span className="font-mono text-slate-300">{sc.geo_score}/100</span></span>}
|
|
||||||
<span className="ml-auto text-slate-700">{trade.entry_date}</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{scOut.key_catalyst && (
|
|
||||||
<p className="mt-1.5 text-[11px] text-slate-500 italic">
|
|
||||||
Catalyseur : {scOut.key_catalyst}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{trade.score_trend?.length > 0 && (
|
|
||||||
<div className="flex items-center gap-2 mt-2">
|
|
||||||
<span className="text-[10px] text-slate-600">Score trend :</span>
|
|
||||||
<ScoreTrend trend={trade.score_trend} />
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{expanded && (
|
|
||||||
<div className="mt-3 space-y-2 border-t border-slate-800 pt-3 text-xs">
|
|
||||||
{/* Thèse d'origine */}
|
|
||||||
{(sgOut.macro_fit || sgOut.description) && (
|
|
||||||
<div>
|
|
||||||
<span className="text-slate-600 font-medium">Thèse initiale : </span>
|
|
||||||
<span className="text-slate-400">{sgOut.macro_fit || sgOut.description}</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{/* Piliers */}
|
|
||||||
{buckets.length > 0 && (
|
|
||||||
<div className="grid grid-cols-2 gap-1.5 mt-2">
|
|
||||||
{buckets.map((b: any, i: number) => {
|
|
||||||
const pct = b.max ? Math.round((b.score / b.max) * 100) : 0
|
|
||||||
const color = pct >= 66 ? '#22c55e' : pct >= 33 ? '#eab308' : '#ef4444'
|
|
||||||
return (
|
|
||||||
<div key={i} className="flex items-center gap-2 bg-dark-800 rounded px-2 py-1">
|
|
||||||
<div className="w-10 h-1 bg-dark-700 rounded-full overflow-hidden shrink-0">
|
|
||||||
<div className="h-full rounded-full" style={{ width: `${pct}%`, background: color }} />
|
|
||||||
</div>
|
|
||||||
<span className="text-slate-500 truncate">{b.label ?? b.id}</span>
|
|
||||||
<span className="font-mono ml-auto shrink-0" style={{ color }}>{b.score}/{b.max}</span>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{scOut.summary && (
|
|
||||||
<p className="text-slate-600 italic mt-1">{scOut.summary}</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function ReportSection({ icon: Icon, title, content, color = 'text-slate-300' }: {
|
|
||||||
icon: any; title: string; content: string | string[]; color?: string
|
|
||||||
}) {
|
}) {
|
||||||
|
const [expanded, setExpanded] = useState(false)
|
||||||
return (
|
return (
|
||||||
<div className="space-y-1.5">
|
<div className="mb-2">
|
||||||
<div className="flex items-center gap-2 text-sm font-semibold text-slate-400">
|
<button
|
||||||
<Icon className="w-4 h-4" />
|
onClick={() => setExpanded(e => !e)}
|
||||||
{title}
|
className="flex items-center gap-2 w-full text-left"
|
||||||
</div>
|
>
|
||||||
{Array.isArray(content) ? (
|
<span className="text-base">{emoji}</span>
|
||||||
<ul className="space-y-1 pl-4">
|
<span className={clsx('text-sm font-bold', colorClass)}>{count}</span>
|
||||||
{content.map((item, i) => (
|
<span className="text-xs text-slate-400">{label}</span>
|
||||||
<li key={i} className={clsx('text-sm', color)}>• {item}</li>
|
{items.length > 0 && (
|
||||||
))}
|
<ChevronRight className={clsx('w-3 h-3 text-slate-600 ml-auto transition-transform', expanded && 'rotate-90')} />
|
||||||
</ul>
|
)}
|
||||||
) : (
|
</button>
|
||||||
<p className={clsx('text-sm leading-relaxed', color)}>{content}</p>
|
{expanded && items.length > 0 && (
|
||||||
)}
|
<div className="mt-1.5 ml-6 space-y-1">
|
||||||
</div>
|
{items.map((item: any, i: number) => (
|
||||||
)
|
<div key={i} className="text-xs text-slate-400 flex items-start gap-2">
|
||||||
}
|
<span className="text-slate-600 shrink-0 mt-0.5">—</span>
|
||||||
|
<div>
|
||||||
export default function RapportIA() {
|
<span className="text-slate-200 font-medium">
|
||||||
const [days, setDays] = useState(30)
|
{item.name ?? item.underlying ?? '?'}
|
||||||
const [selectedHistoryId, setSelectedHistoryId] = useState<number | null>(null)
|
{item.underlying && item.strategy ? ` · ${item.strategy}` : ''}
|
||||||
const [showHistory, setShowHistory] = useState(false)
|
</span>
|
||||||
|
{item.description && (
|
||||||
const queryClient = useQueryClient()
|
<div className="text-slate-600 text-[10px] mt-0.5 line-clamp-2">{item.description}</div>
|
||||||
const { data: rawData, isLoading: loadingRaw, refetch } = usePortfolioReportData(days)
|
)}
|
||||||
const { mutate: generate, isPending: generating, data: freshReportData, reset: resetFresh } = useGeneratePortfolioReport()
|
{item.triggers?.length > 0 && (
|
||||||
const { data: historyList } = useAiReportsList()
|
<div className="text-slate-700 text-[10px]">Déclencheurs: {item.triggers.join(', ')}</div>
|
||||||
const { data: historicReport } = useAiReport(selectedHistoryId)
|
)}
|
||||||
const { mutate: deleteReport } = useDeleteAiReport()
|
{item.pnl_pct != null && (
|
||||||
|
<span className={clsx('font-mono text-[10px] ml-1', item.pnl_pct >= 0 ? 'text-emerald-400' : 'text-red-400')}>
|
||||||
const history: any[] = (historyList as any)?.reports ?? []
|
{item.pnl_pct >= 0 ? '+' : ''}{item.pnl_pct.toFixed(1)}%
|
||||||
|
|
||||||
// Active report: either a loaded historic one, or the freshly generated one
|
|
||||||
const activeHistoric = historicReport as any
|
|
||||||
const fresh = freshReportData as any
|
|
||||||
const raw = rawData as any
|
|
||||||
|
|
||||||
const rep = selectedHistoryId && activeHistoric ? activeHistoric : fresh
|
|
||||||
const report = rep?.report ?? null
|
|
||||||
const stats = rep?.stats ?? raw
|
|
||||||
const winners = rep?.winners ?? raw?.winners ?? []
|
|
||||||
const losers = rep?.losers ?? raw?.losers ?? []
|
|
||||||
const avgPnl = stats?.avg_pnl_pct ?? null
|
|
||||||
|
|
||||||
function handleGenerate() {
|
|
||||||
setSelectedHistoryId(null)
|
|
||||||
resetFresh()
|
|
||||||
generate(days, {
|
|
||||||
onSuccess: () => {
|
|
||||||
queryClient.invalidateQueries({ queryKey: ['ai-reports-list'] })
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="flex h-full">
|
|
||||||
{/* History sidebar */}
|
|
||||||
{showHistory && (
|
|
||||||
<aside className="w-64 shrink-0 border-r border-slate-700/40 bg-dark-800 flex flex-col h-screen sticky top-0 overflow-y-auto">
|
|
||||||
<div className="p-3 border-b border-slate-700/40 flex items-center justify-between">
|
|
||||||
<span className="text-xs font-semibold text-slate-400 uppercase tracking-wide">Rapports archivés</span>
|
|
||||||
<button onClick={() => setShowHistory(false)} className="text-slate-600 hover:text-slate-400 text-xs">✕</button>
|
|
||||||
</div>
|
|
||||||
{history.length === 0 ? (
|
|
||||||
<div className="p-4 text-xs text-slate-600 text-center mt-4">
|
|
||||||
Aucun rapport archivé.<br />Générez votre premier rapport.
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="flex flex-col divide-y divide-slate-800">
|
|
||||||
{history.map((r: any) => {
|
|
||||||
const avg = r.stats?.avg_pnl_pct
|
|
||||||
const date = r.created_at?.slice(0, 16).replace('T', ' ') ?? ''
|
|
||||||
const isActive = selectedHistoryId === r.id
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
key={r.id}
|
|
||||||
className={clsx(
|
|
||||||
'group relative text-left hover:bg-dark-700/50 transition-colors',
|
|
||||||
isActive && 'bg-blue-900/20 border-l-2 border-blue-500'
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<button
|
|
||||||
onClick={() => { setSelectedHistoryId(r.id) }}
|
|
||||||
className="w-full text-left px-3 py-2.5 pr-8"
|
|
||||||
>
|
|
||||||
<div className="flex items-center justify-between mb-0.5">
|
|
||||||
<span className="text-[11px] font-mono text-slate-500">{date}</span>
|
|
||||||
<span className="text-[10px] text-slate-600">{r.days}j</span>
|
|
||||||
</div>
|
|
||||||
{r.report?.headline && (
|
|
||||||
<p className="text-xs text-slate-400 line-clamp-2 leading-snug">{r.report.headline}</p>
|
|
||||||
)}
|
|
||||||
{avg != null && (
|
|
||||||
<span className={clsx('text-[11px] font-mono font-bold mt-1 block',
|
|
||||||
avg >= 0 ? 'text-emerald-400' : 'text-red-400')}>
|
|
||||||
{avg >= 0 ? '+' : ''}{avg.toFixed(1)}% moy.
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
{isActive && <ChevronRight className="w-3 h-3 text-blue-400 mt-1" />}
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
onClick={(e) => {
|
|
||||||
e.stopPropagation()
|
|
||||||
if (confirm('Supprimer ce rapport ?')) {
|
|
||||||
if (selectedHistoryId === r.id) setSelectedHistoryId(null)
|
|
||||||
deleteReport(r.id)
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
className="absolute top-2 right-2 p-1 rounded opacity-0 group-hover:opacity-100 text-slate-600 hover:text-red-400 hover:bg-red-400/10 transition-all"
|
|
||||||
title="Supprimer ce rapport"
|
|
||||||
>
|
|
||||||
<Trash2 className="w-3 h-3" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</aside>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="flex-1 p-6 space-y-6 max-w-5xl overflow-auto">
|
|
||||||
{/* Header */}
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
{!showHistory && (
|
|
||||||
<button
|
|
||||||
onClick={() => setShowHistory(true)}
|
|
||||||
className="flex items-center gap-1.5 px-2.5 py-1.5 rounded border border-slate-700/40 text-slate-500 hover:text-slate-300 text-xs"
|
|
||||||
title={`${history.length} rapport${history.length !== 1 ? 's' : ''} archivé${history.length !== 1 ? 's' : ''}`}
|
|
||||||
>
|
|
||||||
<Clock className="w-3.5 h-3.5" />
|
|
||||||
{history.length > 0 && <span className="font-mono">{history.length}</span>}
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
<div>
|
|
||||||
<h1 className="text-xl font-bold text-white flex items-center gap-2">
|
|
||||||
<Brain className="w-6 h-6 text-blue-400" />
|
|
||||||
Rapport IA — Performance & Analyse
|
|
||||||
{selectedHistoryId && activeHistoric && (
|
|
||||||
<span className="text-xs font-normal text-slate-500 ml-2">
|
|
||||||
archivé · {activeHistoric.created_at?.slice(0, 10)}
|
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</h1>
|
{item.macro_fit && (
|
||||||
<p className="text-sm text-slate-500 mt-0.5">
|
<div className="text-slate-600 text-[10px] italic">{item.macro_fit}</div>
|
||||||
Synthèse des top mouvements + explication GPT-4o basée sur les traces de raisonnement
|
)}
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
{selectedHistoryId && (
|
|
||||||
<button
|
|
||||||
onClick={() => setSelectedHistoryId(null)}
|
|
||||||
className="text-xs text-slate-500 hover:text-slate-300 px-2.5 py-1.5 rounded border border-slate-700/40"
|
|
||||||
>
|
|
||||||
← Nouveau
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
{/* Période — only relevant for new generation */}
|
|
||||||
{!selectedHistoryId && (
|
|
||||||
<div className="flex items-center gap-2 text-sm text-slate-400">
|
|
||||||
<span>Période :</span>
|
|
||||||
{[7, 14, 30, 90].map(d => (
|
|
||||||
<button
|
|
||||||
key={d}
|
|
||||||
onClick={() => setDays(d)}
|
|
||||||
className={clsx(
|
|
||||||
'px-2.5 py-1 rounded text-xs font-medium transition-colors',
|
|
||||||
days === d
|
|
||||||
? 'bg-blue-900/40 text-blue-300 border border-blue-700/40'
|
|
||||||
: 'bg-dark-700 text-slate-500 hover:text-slate-300'
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{d}j
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
|
||||||
|
|
||||||
{!selectedHistoryId && (
|
|
||||||
<button
|
|
||||||
onClick={() => refetch()}
|
|
||||||
disabled={loadingRaw}
|
|
||||||
className="text-slate-600 hover:text-slate-400 disabled:opacity-40"
|
|
||||||
>
|
|
||||||
<RefreshCw className={clsx('w-4 h-4', loadingRaw && 'animate-spin')} />
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<button
|
|
||||||
onClick={handleGenerate}
|
|
||||||
disabled={generating}
|
|
||||||
className="flex items-center gap-2 px-4 py-2 rounded bg-blue-600 hover:bg-blue-700 disabled:opacity-50 text-white text-sm font-medium transition-colors"
|
|
||||||
>
|
|
||||||
<Zap className={clsx('w-4 h-4', generating && 'animate-pulse')} />
|
|
||||||
{generating ? 'Génération GPT-4o…' : 'Générer rapport IA'}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Stats bar */}
|
|
||||||
{(loadingRaw || stats) && (
|
|
||||||
<div className="grid grid-cols-3 gap-4">
|
|
||||||
{[
|
|
||||||
{ label: 'Trades total', value: stats?.total_trades ?? '…' },
|
|
||||||
{ label: 'Trades pricés', value: stats?.priced_count ?? '…' },
|
|
||||||
{
|
|
||||||
label: 'P&L moyen',
|
|
||||||
value: avgPnl != null
|
|
||||||
? <span className={clsx('font-bold', avgPnl >= 0 ? 'text-emerald-400' : 'text-red-400')}>
|
|
||||||
{avgPnl >= 0 ? '+' : ''}{avgPnl.toFixed(1)}%
|
|
||||||
</span>
|
|
||||||
: '—'
|
|
||||||
},
|
|
||||||
].map(({ label, value }) => (
|
|
||||||
<div key={label} className="card text-center">
|
|
||||||
<div className="text-2xl font-bold text-white">{value}</div>
|
|
||||||
<div className="text-xs text-slate-500 mt-0.5">{label}</div>
|
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
{/* GPT-4o report */}
|
export default function RapportCycle() {
|
||||||
{report && (
|
const [selectedRunId, setSelectedRunId] = useState<string | null>(null)
|
||||||
<div className="card border border-blue-700/30 space-y-5">
|
|
||||||
<div className="flex items-center gap-2 text-blue-400 font-semibold">
|
const { data: listData, isLoading: listLoading } = useQuery({
|
||||||
<Brain className="w-4 h-4" />
|
queryKey: ['cycle-reports-list'],
|
||||||
Analyse GPT-4o
|
queryFn: () => fetch('/api/reports/cycle/list?limit=20').then(r => r.ok ? r.json() : { reports: [] }),
|
||||||
|
staleTime: 30_000,
|
||||||
|
})
|
||||||
|
|
||||||
|
const { data: latestReport, isLoading: latestLoading } = useQuery({
|
||||||
|
queryKey: ['cycle-report-latest'],
|
||||||
|
queryFn: () => fetch('/api/reports/cycle/latest').then(r => r.ok ? r.json() : { report: null }),
|
||||||
|
staleTime: 30_000,
|
||||||
|
})
|
||||||
|
|
||||||
|
const { data: selectedReport, isLoading: selectedLoading } = useQuery({
|
||||||
|
queryKey: ['cycle-report', selectedRunId],
|
||||||
|
queryFn: () => fetch(`/api/reports/cycle/${selectedRunId}`).then(r => r.ok ? r.json() : null),
|
||||||
|
enabled: !!selectedRunId,
|
||||||
|
staleTime: 60_000,
|
||||||
|
})
|
||||||
|
|
||||||
|
const reports: any[] = listData?.reports ?? []
|
||||||
|
const report: any = selectedRunId ? selectedReport : latestReport?.report
|
||||||
|
const isLoading = selectedRunId ? selectedLoading : latestLoading
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="p-6 flex gap-4 h-full min-h-screen">
|
||||||
|
{/* Left panel — history list */}
|
||||||
|
<div className="w-56 shrink-0">
|
||||||
|
<div className="section-title flex items-center gap-1 mb-3">
|
||||||
|
<BookOpen className="w-3.5 h-3.5" /> Historique
|
||||||
|
</div>
|
||||||
|
{listLoading ? (
|
||||||
|
<div className="text-xs text-slate-600">Chargement…</div>
|
||||||
|
) : reports.length === 0 ? (
|
||||||
|
<div className="text-xs text-slate-600">Aucun rapport. Le premier sera généré au prochain cycle.</div>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-1">
|
||||||
|
{reports.map((r: any) => {
|
||||||
|
const dt = r.generated_at ? new Date(r.generated_at.endsWith('Z') ? r.generated_at : r.generated_at + 'Z') : null
|
||||||
|
const dateStr = dt
|
||||||
|
? dt.toLocaleDateString('fr-FR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' })
|
||||||
|
: '—'
|
||||||
|
const isActive = selectedRunId === r.run_id || (!selectedRunId && r === reports[0])
|
||||||
|
const m = SCENARIO_META[r.macro_dominant] ?? SCENARIO_META.incertain
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={r.run_id}
|
||||||
|
onClick={() => setSelectedRunId(r.run_id)}
|
||||||
|
className={clsx(
|
||||||
|
'w-full text-left px-2.5 py-2 rounded border text-xs transition-all',
|
||||||
|
isActive
|
||||||
|
? 'border-blue-600/60 bg-blue-900/20 text-slate-200'
|
||||||
|
: 'border-slate-700/30 bg-dark-800 text-slate-500 hover:border-slate-600/40 hover:text-slate-300'
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<div className="font-mono text-[10px] text-slate-600 mb-0.5">{dateStr}</div>
|
||||||
|
<div className="flex items-center gap-1.5 mb-1">
|
||||||
|
<span>{m.emoji}</span>
|
||||||
|
<span className="font-medium truncate" style={{ color: isActive ? m.color : undefined }}>{m.label}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-2 text-[10px] text-slate-600">
|
||||||
|
<span className="text-blue-400">+{r.patterns_added ?? 0} pat.</span>
|
||||||
|
<span className="text-emerald-500">{r.trades_logged ?? 0} log.</span>
|
||||||
|
{(r.trades_closed ?? 0) > 0 && <span className="text-slate-400">{r.trades_closed} clos</span>}
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
})}
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
{report.headline && (
|
{/* Right panel — report */}
|
||||||
<p className="text-base font-medium text-white border-l-2 border-blue-500 pl-3">
|
<div className="flex-1 min-w-0">
|
||||||
{report.headline}
|
{isLoading ? (
|
||||||
</p>
|
<div className="flex items-center gap-2 text-slate-500 text-sm mt-12 justify-center">
|
||||||
)}
|
<RefreshCw className="w-4 h-4 animate-spin" /> Chargement…
|
||||||
|
</div>
|
||||||
|
) : !report ? (
|
||||||
|
<div className="card text-center py-12">
|
||||||
|
<Brain className="w-10 h-10 text-slate-700 mx-auto mb-3" />
|
||||||
|
<div className="text-slate-500 text-sm mb-1">Aucun rapport de cycle disponible</div>
|
||||||
|
<div className="text-xs text-slate-600">Les rapports sont générés automatiquement à la fin de chaque cycle.</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
{/* Header */}
|
||||||
|
<div className="card mb-4">
|
||||||
|
<div className="flex items-start justify-between mb-3">
|
||||||
|
<div>
|
||||||
|
<div className="flex items-center gap-2 mb-1">
|
||||||
|
<RegimeBadge dominant={report.macro_dominant} />
|
||||||
|
<span className="text-xs text-slate-500 font-mono">
|
||||||
|
Géo {report.geo_score ?? '—'}/100
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="text-[10px] text-slate-600 font-mono">
|
||||||
|
Cycle du {report.generated_at
|
||||||
|
? new Date(report.generated_at.endsWith('Z') ? report.generated_at : report.generated_at + 'Z')
|
||||||
|
.toLocaleString('fr-FR')
|
||||||
|
: '—'}
|
||||||
|
{report.prev_cycle_at && (
|
||||||
|
<span className="ml-2 text-slate-700">
|
||||||
|
· vs cycle du {new Date(report.prev_cycle_at.endsWith('Z') ? report.prev_cycle_at : report.prev_cycle_at + 'Z')
|
||||||
|
.toLocaleDateString('fr-FR')}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/* Macro scores mini */}
|
||||||
|
{report.macro_scores && (
|
||||||
|
<div className="flex gap-1.5 flex-wrap justify-end max-w-[220px]">
|
||||||
|
{Object.entries(report.macro_scores as Record<string, number>)
|
||||||
|
.sort(([, a], [, b]) => b - a)
|
||||||
|
.slice(0, 4)
|
||||||
|
.map(([k, v]: [string, number]) => {
|
||||||
|
const m = SCENARIO_META[k] ?? SCENARIO_META.incertain
|
||||||
|
return (
|
||||||
|
<span key={k}
|
||||||
|
className="text-[9px] px-1.5 py-0.5 rounded font-mono"
|
||||||
|
style={{ background: `${m.color}18`, color: m.color }}>
|
||||||
|
{m.label} {v}%
|
||||||
|
</span>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{/* PnL + VaR summary row */}
|
||||||
|
<div className="grid grid-cols-2 gap-3 mt-2">
|
||||||
|
{report.pnl_summary && Object.keys(report.pnl_summary).length > 0 && (
|
||||||
|
<div className="bg-dark-700/50 rounded px-3 py-2">
|
||||||
|
<div className="text-[9px] text-slate-600 mb-1 uppercase tracking-wide">PnL au moment du cycle</div>
|
||||||
|
<div className="flex items-baseline gap-2">
|
||||||
|
<span className={clsx('text-lg font-bold font-mono',
|
||||||
|
(report.pnl_summary.total_pnl_pct ?? 0) >= 0 ? 'text-emerald-400' : 'text-red-400')}>
|
||||||
|
{report.pnl_summary.total_pnl_pct != null
|
||||||
|
? `${report.pnl_summary.total_pnl_pct >= 0 ? '+' : ''}${report.pnl_summary.total_pnl_pct.toFixed(2)}%`
|
||||||
|
: '—'}
|
||||||
|
</span>
|
||||||
|
{report.pnl_summary.total_pnl_eur != null && (
|
||||||
|
<span className="text-xs text-slate-500 font-mono">
|
||||||
|
{report.pnl_summary.total_pnl_eur >= 0 ? '+' : ''}
|
||||||
|
{report.pnl_summary.total_pnl_eur.toFixed(0)}€
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="text-[9px] text-slate-600 mt-0.5">
|
||||||
|
{report.pnl_summary.n_open ?? 0} ouvertes · {report.pnl_summary.n_closed ?? 0} fermées
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{report.var_summary && Object.keys(report.var_summary).length > 0 && (
|
||||||
|
<div className="bg-dark-700/50 rounded px-3 py-2">
|
||||||
|
<div className="text-[9px] text-slate-600 mb-1 uppercase tracking-wide">VaR 95% au moment du cycle</div>
|
||||||
|
<div className="grid grid-cols-3 gap-1">
|
||||||
|
{[
|
||||||
|
{ label: 'Hist.', val: report.var_summary.hist_var_1d_pct, color: 'text-blue-400' },
|
||||||
|
{ label: 'CVaR', val: report.var_summary.hist_cvar_pct, color: 'text-orange-400' },
|
||||||
|
{ label: 'MC', val: report.var_summary.mc_var_1d_pct, color: 'text-red-400' },
|
||||||
|
].map(({ label, val, color }) => (
|
||||||
|
<div key={label} className="text-center">
|
||||||
|
<div className="text-[8px] text-slate-700">{label}</div>
|
||||||
|
<div className={clsx('text-xs font-mono font-bold', color)}>
|
||||||
|
{val != null ? `${val >= 0 ? '+' : ''}${val.toFixed(2)}%` : '—'}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="grid grid-cols-2 gap-5">
|
{/* Delta section */}
|
||||||
{report.winners_analysis && (
|
<Section icon={<GitCompare className="w-4 h-4" />} title="Changements du cycle">
|
||||||
<ReportSection
|
<DeltaRow
|
||||||
icon={TrendingUp}
|
emoji="⭐" label="patterns ajoutés"
|
||||||
title="Pourquoi les gains"
|
count={report.patterns_added ?? 0}
|
||||||
content={report.winners_analysis}
|
items={report.patterns_added_list ?? []}
|
||||||
color="text-emerald-300"
|
colorClass="text-blue-400"
|
||||||
/>
|
/>
|
||||||
)}
|
<DeltaRow
|
||||||
{report.losers_analysis && (
|
emoji="📥" label="trades loggés"
|
||||||
<ReportSection
|
count={report.trades_logged ?? 0}
|
||||||
icon={TrendingDown}
|
items={(report.trades_logged_list ?? []).map((t: any) => ({
|
||||||
title="Pourquoi les pertes"
|
underlying: t.underlying, strategy: t.strategy,
|
||||||
content={report.losers_analysis}
|
pnl_pct: t.pnl_pct, description: t.pattern_name
|
||||||
color="text-red-300"
|
}))}
|
||||||
|
colorClass="text-emerald-400"
|
||||||
/>
|
/>
|
||||||
|
<DeltaRow
|
||||||
|
emoji="✅" label="trades fermés depuis le cycle précédent"
|
||||||
|
count={report.trades_closed ?? 0}
|
||||||
|
items={(report.trades_closed_list ?? []).map((t: any) => ({
|
||||||
|
underlying: t.underlying, strategy: t.strategy,
|
||||||
|
pnl_pct: t.pnl_pct, description: t.pattern_name
|
||||||
|
}))}
|
||||||
|
colorClass={report.trades_closed > 0 ? 'text-slate-300' : 'text-slate-600'}
|
||||||
|
/>
|
||||||
|
{/* Top scored */}
|
||||||
|
{(report.top_scored ?? []).length > 0 && (
|
||||||
|
<div className="mt-3 pt-3 border-t border-slate-700/30">
|
||||||
|
<div className="text-xs text-slate-500 mb-2">Top patterns scorés ce cycle</div>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
{(report.top_scored as any[]).map((p: any, i: number) => (
|
||||||
|
<div key={i} className="flex items-start gap-2 text-xs">
|
||||||
|
<span className="text-slate-700 font-mono w-4 shrink-0">{i + 1}</span>
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<span className="text-slate-300">{p.name ?? '—'}</span>
|
||||||
|
{p.key_catalyst && (
|
||||||
|
<div className="text-[10px] text-slate-600 truncate">{p.key_catalyst}</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<span className={clsx('font-mono font-bold shrink-0',
|
||||||
|
(p.score ?? 0) >= 60 ? 'text-emerald-400' : (p.score ?? 0) >= 40 ? 'text-yellow-400' : 'text-slate-500')}>
|
||||||
|
{p.score ?? '—'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Section>
|
||||||
|
|
||||||
|
{/* Context narrative */}
|
||||||
|
{report.context_narrative?.narrative && (
|
||||||
|
<Section icon={<Brain className="w-4 h-4" />} title="Raisonnement IA — ce cycle">
|
||||||
|
<p className="text-sm text-slate-300 leading-relaxed mb-4">
|
||||||
|
{report.context_narrative.narrative}
|
||||||
|
</p>
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
{(report.context_narrative.context_driven ?? []).length > 0 && (
|
||||||
|
<div>
|
||||||
|
<div className="text-[10px] text-emerald-400 font-semibold uppercase tracking-wide mb-2">
|
||||||
|
📡 Du contexte transmis
|
||||||
|
</div>
|
||||||
|
<ul className="space-y-1">
|
||||||
|
{(report.context_narrative.context_driven as string[]).map((s, i) => (
|
||||||
|
<li key={i} className="text-xs text-slate-400 flex items-start gap-1.5">
|
||||||
|
<span className="text-emerald-600 shrink-0 mt-0.5">•</span> {s}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{(report.context_narrative.general_knowledge ?? []).length > 0 && (
|
||||||
|
<div>
|
||||||
|
<div className="text-[10px] text-blue-400 font-semibold uppercase tracking-wide mb-2">
|
||||||
|
🧠 Connaissance générale
|
||||||
|
</div>
|
||||||
|
<ul className="space-y-1">
|
||||||
|
{(report.context_narrative.general_knowledge as string[]).map((s, i) => (
|
||||||
|
<li key={i} className="text-xs text-slate-400 flex items-start gap-1.5">
|
||||||
|
<span className="text-blue-600 shrink-0 mt-0.5">•</span> {s}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{(report.context_narrative.key_signals ?? []).length > 0 && (
|
||||||
|
<div className="mt-3 pt-3 border-t border-slate-700/30">
|
||||||
|
<div className="text-[10px] text-slate-500 mb-2">Signaux déterminants</div>
|
||||||
|
<div className="flex flex-wrap gap-1.5">
|
||||||
|
{(report.context_narrative.key_signals as string[]).map((s, i) => (
|
||||||
|
<span key={i} className="text-[10px] bg-slate-800 text-slate-300 border border-slate-700/50 px-2 py-0.5 rounded">
|
||||||
|
<Zap className="w-2.5 h-2.5 inline mr-1 text-yellow-500" />{s}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{/* Context log */}
|
||||||
|
{report.context_narrative.context_log && (
|
||||||
|
<div className="mt-3 pt-3 border-t border-slate-700/30">
|
||||||
|
<div className="text-[10px] text-slate-500 mb-2">Log contexte — état transmis à l'IA</div>
|
||||||
|
<div className="grid grid-cols-2 gap-x-4 gap-y-1 text-[10px]">
|
||||||
|
{Object.entries(report.context_narrative.context_log.key_gauges ?? {}).map(([k, v]: [string, any]) => (
|
||||||
|
<div key={k} className="flex items-center gap-1.5">
|
||||||
|
<span className="text-slate-600 w-20">{k}</span>
|
||||||
|
<span className="font-mono text-slate-400">{v}</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
{(report.context_narrative.context_log.dominant_news ?? []).length > 0 && (
|
||||||
|
<div className="mt-2">
|
||||||
|
<div className="text-[9px] text-slate-700 mb-1">News transmises (top impact)</div>
|
||||||
|
{(report.context_narrative.context_log.dominant_news as string[]).map((n, i) => (
|
||||||
|
<div key={i} className="text-[9px] text-slate-600 truncate">· {n}</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Section>
|
||||||
)}
|
)}
|
||||||
</div>
|
|
||||||
|
|
||||||
{report.regime_assessment && (
|
{/* Cycle commentary */}
|
||||||
<ReportSection
|
{report.commentary?.commentary && (
|
||||||
icon={Eye}
|
<Section icon={<Layers className="w-4 h-4" />} title="Analyse macro du cycle">
|
||||||
title="Alignement régime macro"
|
<p className="text-sm text-slate-300 leading-relaxed mb-3">{report.commentary.commentary}</p>
|
||||||
content={report.regime_assessment}
|
{report.commentary.key_risk && (
|
||||||
/>
|
<div className="flex items-start gap-2 text-xs text-orange-400 bg-orange-900/10 border border-orange-800/20 rounded px-3 py-2">
|
||||||
)}
|
<ShieldAlert className="w-3.5 h-3.5 shrink-0 mt-0.5" />
|
||||||
|
<span>{report.commentary.key_risk}</span>
|
||||||
{report.key_lessons?.length > 0 && (
|
</div>
|
||||||
<ReportSection
|
)}
|
||||||
icon={BookOpen}
|
{report.commentary.top_pattern && (
|
||||||
title="Leçons clés"
|
<div className="mt-2 text-xs text-slate-500">
|
||||||
content={report.key_lessons}
|
Pattern le plus pertinent : <span className="text-blue-400 font-medium">{report.commentary.top_pattern}</span>
|
||||||
color="text-blue-300"
|
</div>
|
||||||
/>
|
)}
|
||||||
)}
|
</Section>
|
||||||
|
|
||||||
{report.blind_spots && (
|
|
||||||
<ReportSection
|
|
||||||
icon={AlertTriangle}
|
|
||||||
title="Angles morts du scoring"
|
|
||||||
content={report.blind_spots}
|
|
||||||
color="text-yellow-300"
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{report.next_cycle_priorities && (
|
|
||||||
<ReportSection
|
|
||||||
icon={Target}
|
|
||||||
title="Priorités prochain cycle"
|
|
||||||
content={report.next_cycle_priorities}
|
|
||||||
color="text-purple-300"
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{report.risk_watch && (
|
|
||||||
<ReportSection
|
|
||||||
icon={AlertTriangle}
|
|
||||||
title="Risques à surveiller"
|
|
||||||
content={report.risk_watch}
|
|
||||||
color="text-orange-300"
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Top movers */}
|
|
||||||
{(winners.length > 0 || losers.length > 0) && (
|
|
||||||
<div className="grid grid-cols-2 gap-6">
|
|
||||||
{/* Winners */}
|
|
||||||
<div className="space-y-3">
|
|
||||||
<h2 className="text-sm font-semibold text-emerald-400 uppercase tracking-wide flex items-center gap-2">
|
|
||||||
<TrendingUp className="w-4 h-4" /> Top Gains
|
|
||||||
</h2>
|
|
||||||
{winners.length === 0 ? (
|
|
||||||
<div className="card text-center py-8 text-slate-600 text-sm">Aucun trade pricé</div>
|
|
||||||
) : (
|
|
||||||
winners.map((t: any, i: number) => (
|
|
||||||
<MoverCard key={t.id ?? i} trade={t} rank={i + 1} type="winner" />
|
|
||||||
))
|
|
||||||
)}
|
)}
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Losers */}
|
{/* Risk / portfolio monitor */}
|
||||||
<div className="space-y-3">
|
{report.portfolio_monitor && (
|
||||||
<h2 className="text-sm font-semibold text-red-400 uppercase tracking-wide flex items-center gap-2">
|
<Section icon={<ShieldAlert className="w-4 h-4" />} title="Risque & Alertes portefeuille">
|
||||||
<TrendingDown className="w-4 h-4" /> Top Pertes
|
<p className="text-sm text-slate-400 mb-3">{report.portfolio_monitor.assessment}</p>
|
||||||
</h2>
|
{(report.portfolio_monitor.actions ?? []).length > 0 && (
|
||||||
{losers.length === 0 ? (
|
<div className="space-y-2">
|
||||||
<div className="card text-center py-8 text-slate-600 text-sm">Aucun trade pricé</div>
|
{(report.portfolio_monitor.actions as any[]).map((a: any, i: number) => (
|
||||||
) : (
|
<div key={i} className={clsx(
|
||||||
losers.map((t: any, i: number) => (
|
'flex items-start gap-2 text-xs px-2.5 py-2 rounded border',
|
||||||
<MoverCard key={t.id ?? i} trade={t} rank={i + 1} type="loser" />
|
a.priority === 'high'
|
||||||
))
|
? 'border-red-700/30 bg-red-900/10 text-red-300'
|
||||||
|
: 'border-yellow-700/30 bg-yellow-900/10 text-yellow-300'
|
||||||
|
)}>
|
||||||
|
<span className="shrink-0 font-mono font-bold">{a.priority === 'high' ? '⚠️' : '👁'}</span>
|
||||||
|
<span>{a.underlying && <strong>{a.underlying} </strong>}{a.reason}</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{report.portfolio_monitor.rebalance_suggestion && (
|
||||||
|
<div className="mt-2 text-[11px] text-slate-500 italic">
|
||||||
|
💡 {report.portfolio_monitor.rebalance_suggestion}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Section>
|
||||||
)}
|
)}
|
||||||
</div>
|
</>
|
||||||
</div>
|
)}
|
||||||
)}
|
|
||||||
|
|
||||||
{!loadingRaw && !raw && !report && (
|
|
||||||
<div className="card text-center py-16 text-slate-600">
|
|
||||||
<Brain className="w-12 h-12 mx-auto mb-3 opacity-20" />
|
|
||||||
<p className="text-sm">Cliquer "Générer rapport IA" pour lancer l'analyse GPT-4o</p>
|
|
||||||
<p className="text-xs mt-1 text-slate-700">
|
|
||||||
Le rapport compare les trades gagnants et perdants, identifie les patterns récurrents
|
|
||||||
et génère des recommandations pour le prochain cycle.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
|
|||||||
Reference in New Issue
Block a user