#!/usr/bin/env python3
"""
ANALYSE DES TRADES - Identifier les opportunités d'optimisation

Analyse :
1. Pourquoi les trades perdent ?
2. Quels patterns dans les wins vs losses ?
3. Peut-on améliorer le win rate ?
4. Peut-on améliorer le profit factor ?
"""

import pandas as pd
import numpy as np
from hybrid_system import HybridSystem
from martingale_backtester import MartingaleBacktester
import json

class AnalyzingSystem(HybridSystem):
    """Système qui enregistre plus de détails pour analyse"""

    def __init__(self, initial_capital=1000):
        super().__init__(initial_capital)
        self.detailed_trades = []

    def close_trade(self, exit_price, exit_type):
        """Override pour capturer plus de détails"""

        if not self.position:
            return

        params = self.position['params']

        # PnL
        if self.position['side'] == 'LONG':
            pnl_pct = (exit_price - self.position['entry']) / self.position['entry']
        else:
            pnl_pct = (self.position['entry'] - exit_price) / self.position['entry']

        pnl_pct *= params['leverage']
        pnl_pct -= 0.001

        pnl_usd = params['position_size'] * pnl_pct
        self.capital += pnl_usd

        won = pnl_usd > 0

        # DETAILED RECORD
        self.detailed_trades.append({
            'entry': self.position['entry'],
            'exit': exit_price,
            'side': self.position['side'],
            'pnl_usd': pnl_usd,
            'pnl_pct': pnl_pct * 100,
            'won': won,
            'exit_type': exit_type,
            'confirmations': self.position['confirmations'],
            'leverage': params['leverage'],
            'tp_pct': params['tp_pct'],
            'sl_pct': params['sl_pct'],
            'position_size': params['position_size']
        })

        # Update streaks
        if won:
            self.consecutive_losses = 0
        else:
            self.consecutive_losses += 1

        self.trades.append({
            'entry': self.position['entry'],
            'exit': exit_price,
            'side': self.position['side'],
            'pnl_usd': pnl_usd,
            'pnl_pct': pnl_pct * 100,
            'won': won,
            'exit_type': exit_type,
            'confirmations': self.position['confirmations']
        })

        self.position = None

print("=" * 80)
print("🔬 ANALYSE DÉTAILLÉE DES TRADES")
print("=" * 80)

backtester = MartingaleBacktester(
    initial_capital=1000.0,
    trading_fee_pct=0.0005,
    timeout_minutes=60
)

print("\n📥 Téléchargement BTC 4h (1000 bougies)...")
df = backtester.fetch_binance_data('BTCUSDT', '4h', 1000)

if df is None:
    exit(1)

print(f"✅ {len(df)} bougies\n")

# Run avec système analysant
system = AnalyzingSystem(initial_capital=1000)
result = system.backtest(df)

trades = system.detailed_trades

if not trades:
    print("❌ Aucun trade")
    exit(1)

print(f"📊 {len(trades)} trades analysés\n")

# ============ ANALYSE WINS VS LOSSES ============

wins = [t for t in trades if t['won']]
losses = [t for t in trades if not t['won']]

print("=" * 80)
print("📈 WINS vs LOSSES")
print("=" * 80)

print(f"\n✅ WINS ({len(wins)} trades):")
print(f"   PnL moyen:           {np.mean([t['pnl_pct'] for t in wins]):.2f}%")
print(f"   PnL médian:          {np.median([t['pnl_pct'] for t in wins]):.2f}%")
print(f"   Leverage moyen:      {np.mean([t['leverage'] for t in wins]):.1f}x")
print(f"   Confirmations moy:   {np.mean([t['confirmations'] for t in wins]):.2f}")

# Exit types
exit_types_win = {}
for t in wins:
    et = t['exit_type']
    exit_types_win[et] = exit_types_win.get(et, 0) + 1
print(f"   Exit types:          {exit_types_win}")

# Side distribution
long_wins = len([t for t in wins if t['side'] == 'LONG'])
short_wins = len([t for t in wins if t['side'] == 'SHORT'])
print(f"   LONG wins:           {long_wins}/{len(wins)} ({long_wins/len(wins)*100:.1f}%)")
print(f"   SHORT wins:          {short_wins}/{len(wins)} ({short_wins/len(wins)*100:.1f}%)")

print(f"\n❌ LOSSES ({len(losses)} trades):")
print(f"   PnL moyen:           {np.mean([t['pnl_pct'] for t in losses]):.2f}%")
print(f"   PnL médian:          {np.median([t['pnl_pct'] for t in losses]):.2f}%")
print(f"   Leverage moyen:      {np.mean([t['leverage'] for t in losses]):.1f}x")
print(f"   Confirmations moy:   {np.mean([t['confirmations'] for t in losses]):.2f}")

exit_types_loss = {}
for t in losses:
    et = t['exit_type']
    exit_types_loss[et] = exit_types_loss.get(et, 0) + 1
print(f"   Exit types:          {exit_types_loss}")

long_losses = len([t for t in losses if t['side'] == 'LONG'])
short_losses = len([t for t in losses if t['side'] == 'SHORT'])
print(f"   LONG losses:         {long_losses}/{len(losses)} ({long_losses/len(losses)*100:.1f}%)")
print(f"   SHORT losses:        {short_losses}/{len(losses)} ({short_losses/len(losses)*100:.1f}%)")

# ============ ANALYSE PAR SIDE ============

print(f"\n{'=' * 80}")
print("📊 ANALYSE PAR DIRECTION")
print("=" * 80)

longs = [t for t in trades if t['side'] == 'LONG']
shorts = [t for t in trades if t['side'] == 'SHORT']

print(f"\n📈 LONG ({len(longs)} trades):")
long_wr = len([t for t in longs if t['won']]) / len(longs) if longs else 0
print(f"   Win Rate:            {long_wr*100:.1f}%")
print(f"   PnL moyen:           {np.mean([t['pnl_pct'] for t in longs]):.2f}%")
long_pf = abs(sum([t['pnl_usd'] for t in longs if t['won']]) / sum([t['pnl_usd'] for t in longs if not t['won']])) if [t for t in longs if not t['won']] else 999
print(f"   Profit Factor:       {long_pf:.2f}")

print(f"\n📉 SHORT ({len(shorts)} trades):")
short_wr = len([t for t in shorts if t['won']]) / len(shorts) if shorts else 0
print(f"   Win Rate:            {short_wr*100:.1f}%")
print(f"   PnL moyen:           {np.mean([t['pnl_pct'] for t in shorts]):.2f}%")
short_pf = abs(sum([t['pnl_usd'] for t in shorts if t['won']]) / sum([t['pnl_usd'] for t in shorts if not t['won']])) if [t for t in shorts if not t['won']] else 999
print(f"   Profit Factor:       {short_pf:.2f}")

# ============ ANALYSE PAR CONFIRMATIONS ============

print(f"\n{'=' * 80}")
print("🎯 ANALYSE PAR NOMBRE DE CONFIRMATIONS")
print("=" * 80)

for conf in [2.0, 2.5, 3.0, 3.5, 4.0]:
    conf_trades = [t for t in trades if abs(t['confirmations'] - conf) < 0.3]
    if conf_trades:
        conf_wins = len([t for t in conf_trades if t['won']])
        conf_wr = conf_wins / len(conf_trades)
        conf_pnl = np.mean([t['pnl_pct'] for t in conf_trades])
        status = "✅" if conf_wr > 0.6 else "⚠️" if conf_wr > 0.5 else "❌"
        print(f"   {conf:.1f} conf ({len(conf_trades):2d} trades): {status} WR: {conf_wr*100:4.1f}% | PnL moy: {conf_pnl:+6.2f}%")

# ============ ANALYSE PAR LEVERAGE ============

print(f"\n{'=' * 80}")
print("⚡ ANALYSE PAR LEVERAGE")
print("=" * 80)

leverage_buckets = [(10, 20), (20, 30), (30, 40), (40, 50)]
for low, high in leverage_buckets:
    lev_trades = [t for t in trades if low <= t['leverage'] < high]
    if lev_trades:
        lev_wins = len([t for t in lev_trades if t['won']])
        lev_wr = lev_wins / len(lev_trades)
        lev_pnl = np.mean([t['pnl_pct'] for t in lev_trades])
        status = "✅" if lev_wr > 0.6 else "⚠️" if lev_wr > 0.5 else "❌"
        print(f"   {low:2d}-{high:2d}x ({len(lev_trades):2d} trades): {status} WR: {lev_wr*100:4.1f}% | PnL moy: {lev_pnl:+6.2f}%")

# ============ OPPORTUNITÉS D'OPTIMISATION ============

print(f"\n{'=' * 80}")
print("💡 OPPORTUNITÉS D'OPTIMISATION")
print("=" * 80)

suggestions = []

# 1. Side bias
if long_wr > short_wr + 0.15:
    suggestions.append(f"✅ LONG bias détecté ({long_wr*100:.1f}% vs {short_wr*100:.1f}%) - Privilégier LONG")
elif short_wr > long_wr + 0.15:
    suggestions.append(f"✅ SHORT bias détecté ({short_wr*100:.1f}% vs {long_wr*100:.1f}%) - Privilégier SHORT")

# 2. Confirmations
high_conf_trades = [t for t in trades if t['confirmations'] >= 3.0]
if high_conf_trades:
    high_conf_wr = len([t for t in high_conf_trades if t['won']]) / len(high_conf_trades)
    if high_conf_wr > 0.65:
        suggestions.append(f"✅ 3+ confirmations très performant ({high_conf_wr*100:.1f}% WR) - Augmenter seuil à 3")

# 3. Leverage
low_lev_trades = [t for t in trades if t['leverage'] <= 25]
if low_lev_trades:
    low_lev_wr = len([t for t in low_lev_trades if t['won']]) / len(low_lev_trades)
    if low_lev_wr > 0.65:
        suggestions.append(f"✅ Leverage faible performant ({low_lev_wr*100:.1f}% WR) - Réduire leverage max")

# 4. Exit types
sl_losses = [t for t in losses if t['exit_type'] == 'SL']
if len(sl_losses) > len(losses) * 0.7:
    suggestions.append(f"⚠️ {len(sl_losses)/len(losses)*100:.0f}% des pertes sont SL - Ajuster SL ou filtres")

# 5. Trailing
trailing_wins = [t for t in wins if t['exit_type'] == 'TRAILING']
if len(trailing_wins) > len(wins) * 0.3:
    suggestions.append(f"✅ Trailing stop efficace ({len(trailing_wins)} wins) - Bon système")

if not suggestions:
    suggestions.append("✅ Système déjà bien équilibré")

for s in suggestions:
    print(f"   {s}")

# ============ RECOMMANDATIONS ============

print(f"\n{'=' * 80}")
print("🎯 RECOMMANDATIONS D'OPTIMISATION")
print("=" * 80)

print("\n1️⃣ Ajuster seuil de confirmations")
best_conf = None
best_conf_wr = 0
for conf in [2.0, 2.5, 3.0, 3.5, 4.0]:
    conf_trades = [t for t in trades if abs(t['confirmations'] - conf) < 0.3]
    if len(conf_trades) >= 5:  # Minimum 5 trades
        conf_wr = len([t for t in conf_trades if t['won']]) / len(conf_trades)
        if conf_wr > best_conf_wr:
            best_conf_wr = conf_wr
            best_conf = conf

if best_conf:
    print(f"   Optimal: {best_conf:.1f} confirmations (WR: {best_conf_wr*100:.1f}%)")
    print(f"   Actuel:  2.0 confirmations")
    if best_conf > 2.0:
        print(f"   ➡️  AUGMENTER à {best_conf:.1f} confirmations")
    else:
        print(f"   ✅ Seuil actuel optimal")

print("\n2️⃣ Side filtering")
if long_wr > 0.6 and short_wr < 0.5:
    print(f"   LONG: {long_wr*100:.1f}% WR (Bon)")
    print(f"   SHORT: {short_wr*100:.1f}% WR (Faible)")
    print(f"   ➡️  CONSIDÉRER: Éviter SHORT ou ajouter filtres SHORT")
elif short_wr > 0.6 and long_wr < 0.5:
    print(f"   SHORT: {short_wr*100:.1f}% WR (Bon)")
    print(f"   LONG: {long_wr*100:.1f}% WR (Faible)")
    print(f"   ➡️  CONSIDÉRER: Éviter LONG ou ajouter filtres LONG")
else:
    print(f"   LONG: {long_wr*100:.1f}% WR")
    print(f"   SHORT: {short_wr*100:.1f}% WR")
    print(f"   ✅ Équilibré")

print("\n3️⃣ Leverage optimization")
best_lev_bucket = None
best_lev_wr = 0
for low, high in leverage_buckets:
    lev_trades = [t for t in trades if low <= t['leverage'] < high]
    if len(lev_trades) >= 5:
        lev_wr = len([t for t in lev_trades if t['won']]) / len(lev_trades)
        if lev_wr > best_lev_wr:
            best_lev_wr = lev_wr
            best_lev_bucket = (low, high)

if best_lev_bucket:
    print(f"   Optimal: {best_lev_bucket[0]}-{best_lev_bucket[1]}x (WR: {best_lev_wr*100:.1f}%)")
    if best_lev_bucket[1] < 40:
        print(f"   ➡️  RÉDUIRE max_leverage à {best_lev_bucket[1]}x")
    else:
        print(f"   ✅ Leverage range actuel OK")

print("\n4️⃣ Stop-loss ajustement")
avg_sl_loss = np.mean([t['pnl_pct'] for t in sl_losses]) if sl_losses else 0
print(f"   Perte moyenne SL: {avg_sl_loss:.2f}%")
if avg_sl_loss < -2.5:
    print(f"   ➡️  RESSERRER SL (pertes trop grandes)")
elif avg_sl_loss > -1.5:
    print(f"   ➡️  ÉLARGIR SL (SL trop serré)")
else:
    print(f"   ✅ SL bien calibré")

# Sauvegarder analyse
with open('trade_analysis.json', 'w') as f:
    json.dump({
        'total_trades': len(trades),
        'wins': len(wins),
        'losses': len(losses),
        'long_wr': long_wr,
        'short_wr': short_wr,
        'suggestions': suggestions,
        'detailed_trades': trades
    }, f, indent=2, default=str)

print(f"\n💾 Analyse sauvegardée: trade_analysis.json")
print("=" * 80)
