#!/usr/bin/env python3
"""
PERFORMANCE MENSUELLE - 12 derniers mois

Test du système baseline (hybrid_system.py) mois par mois
sur l'année passée pour voir la consistance.
"""

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

print("=" * 80)
print("📅 PERFORMANCE MENSUELLE - BTC 4h - 12 Derniers Mois")
print("=" * 80)

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

# Télécharger données (environ 2200 bougies = 12 mois en 4h)
# 24h / 4h = 6 bougies par jour
# 6 * 365 = 2190 bougies par an
print("\n📥 Téléchargement BTC 4h (2200 bougies ≈ 12 mois)...")
df_full = backtester.fetch_binance_data('BTCUSDT', '4h', 2200)

if df_full is None:
    print("❌ Erreur téléchargement")
    exit(1)

print(f"✅ {len(df_full)} bougies récupérées")

# Vérifier qu'on a le champ timestamp
if 'timestamp' not in df_full.columns:
    print("⚠️  Ajout colonne timestamp...")
    # Utiliser l'index ou créer des timestamps factices
    df_full['timestamp'] = pd.date_range(end=datetime.now(), periods=len(df_full), freq='4H')

# Grouper par mois
df_full['year_month'] = pd.to_datetime(df_full['timestamp']).dt.to_period('M')

# Obtenir les 12 derniers mois
months = df_full['year_month'].unique()[-12:]

print(f"\n📊 Test sur {len(months)} mois:\n")

monthly_results = []

for month in months:
    month_data = df_full[df_full['year_month'] == month].copy()

    # Skip si trop peu de données
    if len(month_data) < 100:
        continue

    month_str = str(month)
    print(f"🧪 {month_str}...", end=" ")

    system = HybridSystem(initial_capital=1000)
    result = system.backtest(month_data)

    if result:
        result['month'] = month_str
        monthly_results.append(result)

        status = "✅" if result['roi'] > 15 else "⚠️" if result['roi'] > 5 else "🔵" if result['roi'] > 0 else "❌"
        print(f"{status} ROI: {result['roi']:+7.2f}% | WR: {result['win_rate']*100:5.1f}% | Trades: {result['trades']:2d} | DD: {result['max_dd']:5.2f}%")
    else:
        print(f"⚠️  Aucun trade")

# ============ STATISTIQUES ============

print("\n" + "=" * 80)
print("📊 STATISTIQUES ANNUELLES")
print("=" * 80)

if not monthly_results:
    print("\n❌ Aucun résultat mensuel")
    exit(1)

rois = [r['roi'] for r in monthly_results]
wrs = [r['win_rate'] for r in monthly_results]
pfs = [r['profit_factor'] for r in monthly_results]
trades = [r['trades'] for r in monthly_results]

profitable_months = [r for r in monthly_results if r['roi'] > 0]
losing_months = [r for r in monthly_results if r['roi'] <= 0]

print(f"\n📈 PERFORMANCE GLOBALE:")
print(f"   Mois testés:           {len(monthly_results)}")
print(f"   Mois profitables:      {len(profitable_months)} ({len(profitable_months)/len(monthly_results)*100:.1f}%)")
print(f"   Mois perdants:         {len(losing_months)} ({len(losing_months)/len(monthly_results)*100:.1f}%)")

print(f"\n💰 ROI:")
print(f"   ROI moyen mensuel:     {np.mean(rois):+.2f}%")
print(f"   ROI médian:            {np.median(rois):+.2f}%")
print(f"   ROI écart-type:        {np.std(rois):.2f}%")
print(f"   ROI min:               {min(rois):+.2f}%")
print(f"   ROI max:               {max(rois):+.2f}%")

if profitable_months:
    avg_profit_months = np.mean([r['roi'] for r in profitable_months])
    print(f"   ROI moyen (mois+):     +{avg_profit_months:.2f}%")

if losing_months:
    avg_loss_months = np.mean([r['roi'] for r in losing_months])
    print(f"   ROI moyen (mois-):     {avg_loss_months:.2f}%")

print(f"\n🎯 QUALITÉ:")
print(f"   Win rate moyen:        {np.mean(wrs)*100:.1f}%")
print(f"   Profit factor moyen:   {np.mean(pfs):.2f}")
print(f"   Trades moyen/mois:     {np.mean(trades):.1f}")

# Sharpe annualisé
sharpe_monthly = np.mean(rois) / np.std(rois) if np.std(rois) > 0 else 0
sharpe_annualized = sharpe_monthly * np.sqrt(12)  # Annualisé

print(f"\n📊 RATIOS:")
print(f"   Sharpe mensuel:        {sharpe_monthly:.2f}")
print(f"   Sharpe annualisé:      {sharpe_annualized:.2f}")

# Win streak / Lose streak
current_streak = 0
max_win_streak = 0
max_lose_streak = 0
current_is_win = None

for r in monthly_results:
    is_win = r['roi'] > 0

    if current_is_win == is_win:
        current_streak += 1
    else:
        current_streak = 1
        current_is_win = is_win

    if is_win:
        max_win_streak = max(max_win_streak, current_streak)
    else:
        max_lose_streak = max(max_lose_streak, current_streak)

print(f"\n🔥 STREAKS:")
print(f"   Max winning streak:    {max_win_streak} mois")
print(f"   Max losing streak:     {max_lose_streak} mois")

# ============ PROJECTION CAPITAL ============

print(f"\n💵 PROJECTION CAPITAL (Compound):")
print(f"   Capital initial:       $1,000")

capital = 1000
for r in monthly_results:
    capital *= (1 + r['roi']/100)

gain = capital - 1000
roi_total = ((capital - 1000) / 1000) * 100

print(f"   Capital après 12 mois: ${capital:,.2f}")
print(f"   Gain total:            ${gain:,.2f}")
print(f"   ROI total:             {roi_total:+.2f}%")

# Comparaison avec holding BTC
btc_start = df_full.iloc[0]['close']
btc_end = df_full.iloc[-1]['close']
btc_roi = ((btc_end - btc_start) / btc_start) * 100

print(f"\n📊 VS BTC HOLD:")
print(f"   BTC prix début:        ${btc_start:,.2f}")
print(f"   BTC prix fin:          ${btc_end:,.2f}")
print(f"   BTC ROI (hold):        {btc_roi:+.2f}%")
print(f"   Strategy ROI:          {roi_total:+.2f}%")

if roi_total > btc_roi:
    print(f"   ✅ Strategy bat hold: +{roi_total - btc_roi:.2f}%")
else:
    print(f"   ❌ Hold meilleur:     {btc_roi - roi_total:.2f}%")

# ============ DISTRIBUTION ============

print(f"\n📊 DISTRIBUTION ROI MENSUEL:")

bins = [
    (-100, -10, "Très négatif"),
    (-10, -5, "Négatif"),
    (-5, 0, "Légèrement négatif"),
    (0, 5, "Légèrement positif"),
    (5, 10, "Bon"),
    (10, 20, "Très bon"),
    (20, 100, "Excellent")
]

for low, high, label in bins:
    count = len([r for r in rois if low <= r < high])
    if count > 0:
        pct = (count / len(rois)) * 100
        bar = "█" * int(pct / 5)
        print(f"   {label:<20} ({low:+3.0f}% à {high:+3.0f}%): {bar} {count} mois ({pct:.1f}%)")

# ============ VERDICT ============

print(f"\n{'=' * 80}")
print("🎯 VERDICT ANNUEL")
print("=" * 80)

profitable_rate = len(profitable_months) / len(monthly_results)

if roi_total > 50 and profitable_rate > 0.7:
    print("\n🎉 SYSTÈME EXCELLENT!")
    print(f"   ✅ ROI annuel > 50% ({roi_total:+.2f}%)")
    print(f"   ✅ {profitable_rate*100:.0f}% mois profitables")
    print(f"   ✅ Sharpe annualisé: {sharpe_annualized:.2f}")
elif roi_total > 30 and profitable_rate > 0.6:
    print("\n✅ SYSTÈME TRÈS BON")
    print(f"   ✅ ROI annuel: {roi_total:+.2f}%")
    print(f"   ✅ {profitable_rate*100:.0f}% mois profitables")
elif roi_total > 15:
    print("\n✅ SYSTÈME BON")
    print(f"   ROI annuel: {roi_total:+.2f}%")
elif roi_total > 0:
    print("\n⚠️  SYSTÈME LÉGÈREMENT PROFITABLE")
    print(f"   ROI annuel: {roi_total:+.2f}%")
else:
    print("\n❌ SYSTÈME NON PROFITABLE SUR L'ANNÉE")
    print(f"   ROI annuel: {roi_total:+.2f}%")

print(f"\n{'=' * 80}")

# ============ MEILLEUR/PIRE MOIS ============

best_month = max(monthly_results, key=lambda x: x['roi'])
worst_month = min(monthly_results, key=lambda x: x['roi'])

print(f"\n🥇 MEILLEUR MOIS: {best_month['month']}")
print(f"   ROI:     {best_month['roi']:+.2f}%")
print(f"   WR:      {best_month['win_rate']*100:.1f}%")
print(f"   Trades:  {best_month['trades']}")

print(f"\n🥉 PIRE MOIS: {worst_month['month']}")
print(f"   ROI:     {worst_month['roi']:+.2f}%")
print(f"   WR:      {worst_month['win_rate']*100:.1f}%")
print(f"   Trades:  {worst_month['trades']}")

# Sauvegarder
with open('monthly_performance.json', 'w') as f:
    json.dump({
        'months': monthly_results,
        'summary': {
            'total_months': len(monthly_results),
            'profitable_months': len(profitable_months),
            'profitable_rate': profitable_rate,
            'avg_roi_monthly': np.mean(rois),
            'std_roi': np.std(rois),
            'total_roi': roi_total,
            'final_capital': capital,
            'sharpe_annualized': sharpe_annualized,
            'vs_btc_hold': roi_total - btc_roi,
            'best_month': best_month['month'],
            'worst_month': worst_month['month']
        }
    }, f, indent=2, default=str)

print(f"\n💾 Résultats: monthly_performance.json")
print("=" * 80)
