#!/usr/bin/env python3
"""
Final Optimized Strategy - Long Only, Simple and Robust
Based on previous successful tests: Conservative config had 100% win rate.
"""

import numpy as np
import pandas as pd
from pathlib import Path
from datetime import datetime
import json

DATA_FILE = Path('/var/www/html/bestrading.cuttalo.com/scripts/prices_BTC_EUR_2025_full.csv')
OUTPUT_DIR = Path('/var/www/html/bestrading.cuttalo.com/models/btc_v6')

# Best configuration - balanced between activity and quality
CONFIG = {
    'position_size': 0.15,      # 15% of capital per trade
    'stop_loss': 0.02,          # 2% stop loss
    'take_profit': 0.035,       # 3.5% take profit
    'fee_rate': 0.002,          # 0.2% per trade (Kraken taker)
    'slippage': 0.0003,         # 0.03%
    'bullish_ret20': 0.003,     # 0.3% 20-min return for bullish
    'bullish_ret60': 0.002,     # 0.2% 60-min return for bullish
    'bearish_ret20': -0.003,    # -0.3% for bearish
    'bearish_ret60': -0.002,    # -0.2% for bearish
    'min_confirm': 45,          # 45 min regime confirmation
    'min_hold': 45,             # 45 min minimum hold
    'cooldown': 90,             # 90 min between trades
}

def compute_features(prices, idx):
    if idx < 60:
        return None
    return {
        'ret20': (prices[idx] - prices[idx-20]) / prices[idx-20],
        'ret60': (prices[idx] - prices[idx-60]) / prices[idx-60],
        'vol30': np.std(np.diff(prices[max(0,idx-30):idx+1]) / prices[max(0,idx-30):idx])
    }

def detect_regime(features):
    if features is None:
        return 'neutral'
    if features['ret20'] > CONFIG['bullish_ret20'] and features['ret60'] > CONFIG['bullish_ret60']:
        return 'bullish'
    elif features['ret20'] < CONFIG['bearish_ret20'] and features['ret60'] < CONFIG['bearish_ret60']:
        return 'bearish'
    return 'neutral'

def run_backtest():
    print("=" * 70)
    print("FINAL REGIME STRATEGY - LONG ONLY")
    print("=" * 70)

    # Load data
    df = pd.read_csv(DATA_FILE)
    prices = df['close'].values.astype(np.float64)
    timestamps = df['timestamp'].values

    btc_return = (prices[-1] - prices[0]) / prices[0] * 100
    print(f"\nData: {len(prices):,} candles")
    print(f"Period: {datetime.fromtimestamp(timestamps[0])} - {datetime.fromtimestamp(timestamps[-1])}")
    print(f"BTC Buy & Hold: {btc_return:+.2f}%")

    # State
    initial_capital = 10000.0
    capital = initial_capital
    btc_held = 0.0
    entry_price = 0.0
    entry_idx = 0
    in_position = False

    current_regime = 'neutral'
    regime_start = 61
    last_trade_idx = 0

    trades = []
    equity_history = []

    for i in range(61, len(prices)):
        price = prices[i]
        features = compute_features(prices, i)
        regime = detect_regime(features)

        # Track regime changes
        if regime != current_regime:
            current_regime = regime
            regime_start = i

        time_in_regime = i - regime_start
        time_since_trade = i - last_trade_idx
        time_held = i - entry_idx if in_position else 0

        action = None

        # Entry: Go long when bullish confirmed
        if not in_position and time_since_trade >= CONFIG['cooldown']:
            if regime == 'bullish' and time_in_regime >= CONFIG['min_confirm']:
                action = 'BUY'

        # Exit logic
        elif in_position:
            pnl_pct = (price - entry_price) / entry_price

            # Stop loss
            if pnl_pct < -CONFIG['stop_loss']:
                action = 'STOP_LOSS'
            # Take profit
            elif pnl_pct > CONFIG['take_profit']:
                action = 'TAKE_PROFIT'
            # Regime exit (after minimum hold)
            elif time_held >= CONFIG['min_hold'] and regime == 'bearish' and time_in_regime >= 15:
                action = 'REGIME_EXIT'

        # Execute trades
        if action == 'BUY':
            trade_value = capital * CONFIG['position_size']
            fee = trade_value * CONFIG['fee_rate']
            exec_price = price * (1 + CONFIG['slippage'])
            btc_amount = (trade_value - fee) / exec_price

            capital -= trade_value
            btc_held = btc_amount
            entry_price = exec_price
            entry_idx = i
            in_position = True
            last_trade_idx = i

            trades.append({
                'time': int(timestamps[i]),
                'action': 'BUY',
                'price': float(price),
                'btc': float(btc_amount),
                'regime': regime
            })

        elif action in ['STOP_LOSS', 'TAKE_PROFIT', 'REGIME_EXIT']:
            exec_price = price * (1 - CONFIG['slippage'])
            proceeds = btc_held * exec_price
            fee = proceeds * CONFIG['fee_rate']
            net_proceeds = proceeds - fee

            pnl = net_proceeds - (btc_held * entry_price)
            capital += net_proceeds

            trades.append({
                'time': int(timestamps[i]),
                'action': action,
                'price': float(price),
                'pnl': float(pnl),
                'regime': regime
            })

            btc_held = 0
            entry_price = 0
            entry_idx = 0
            in_position = False
            last_trade_idx = i

        # Track equity
        equity = capital + btc_held * price
        equity_history.append((timestamps[i], equity))

        if i % 100000 == 0:
            print(f"  Progress: {i:,}/{len(prices):,} | Equity: €{equity:,.0f} | Trades: {len([t for t in trades if 'pnl' in t])}")

    # Close final position
    if in_position:
        exec_price = prices[-1] * (1 - CONFIG['slippage'])
        proceeds = btc_held * exec_price
        fee = proceeds * CONFIG['fee_rate']
        net_proceeds = proceeds - fee
        pnl = net_proceeds - (btc_held * entry_price)
        capital += net_proceeds

        trades.append({
            'time': int(timestamps[-1]),
            'action': 'FINAL_EXIT',
            'price': float(prices[-1]),
            'pnl': float(pnl)
        })
        in_position = False

    final_capital = capital

    # Calculate metrics
    total_return = (final_capital - initial_capital) / initial_capital * 100
    alpha = total_return - btc_return

    if equity_history:
        max_eq = max(e[1] for e in equity_history)
        max_dd = min((e[1] - max_eq) / max_eq for e in equity_history) * 100
    else:
        max_dd = 0

    closed_trades = [t for t in trades if 'pnl' in t]
    winning = [t for t in closed_trades if t['pnl'] > 0]
    losing = [t for t in closed_trades if t['pnl'] <= 0]
    win_rate = len(winning) / len(closed_trades) * 100 if closed_trades else 0

    avg_win = np.mean([t['pnl'] for t in winning]) if winning else 0
    avg_loss = np.mean([t['pnl'] for t in losing]) if losing else 0
    total_pnl = sum(t['pnl'] for t in closed_trades)

    # Print results
    print("\n" + "=" * 70)
    print("RESULTS")
    print("=" * 70)

    print(f"""
    Initial Capital:      €{initial_capital:,.0f}
    Final Capital:        €{final_capital:,.0f}
    ─────────────────────────────────────────
    Total Return:         {total_return:+.2f}%
    Max Drawdown:         {max_dd:.2f}%
    ─────────────────────────────────────────
    Total Trades:         {len(closed_trades)}
    Winning:              {len(winning)} ({win_rate:.1f}%)
    Losing:               {len(losing)}
    Avg Win:              €{avg_win:+.2f}
    Avg Loss:             €{avg_loss:+.2f}
    Total PnL:            €{total_pnl:+.2f}
    ─────────────────────────────────────────
    BTC Buy & Hold:       {btc_return:+.2f}%
    Strategy Alpha:       {alpha:+.2f}%
    ─────────────────────────────────────────
    """)

    # Trade history
    print("Trade History:")
    for t in trades:
        dt = datetime.fromtimestamp(t['time'])
        if 'pnl' in t:
            print(f"  {dt.strftime('%Y-%m-%d %H:%M')} | {t['action']:14s} | €{t['price']:,.0f} | PnL: €{t['pnl']:+.2f}")
        else:
            print(f"  {dt.strftime('%Y-%m-%d %H:%M')} | {t['action']:14s} | €{t['price']:,.0f} | BTC: {t['btc']:.4f}")

    # Save results
    results = {
        'config': CONFIG,
        'metrics': {
            'initial_capital': initial_capital,
            'final_capital': float(final_capital),
            'total_return_pct': float(total_return),
            'max_drawdown_pct': float(max_dd),
            'total_trades': len(closed_trades),
            'winning_trades': len(winning),
            'losing_trades': len(losing),
            'win_rate_pct': float(win_rate),
            'avg_win': float(avg_win),
            'avg_loss': float(avg_loss),
            'total_pnl': float(total_pnl),
            'btc_return_pct': float(btc_return),
            'alpha_pct': float(alpha)
        },
        'trades': trades,
        'timestamp': datetime.now().isoformat()
    }

    output_file = OUTPUT_DIR / 'backtest_results.json'
    with open(output_file, 'w') as f:
        json.dump(results, f, indent=2)
    print(f"\nSaved results to: {output_file}")

    # Save equity curve
    equity_file = OUTPUT_DIR / 'equity_curve.csv'
    with open(equity_file, 'w') as f:
        f.write('timestamp,equity\n')
        for ts, eq in equity_history[::100]:  # Sample every 100
            f.write(f"{ts},{eq:.2f}\n")
    print(f"Saved equity curve to: {equity_file}")

    return results

if __name__ == '__main__':
    run_backtest()
