Team Ai
Apppublic

diegobeyl/backtesting

sourceHugging Faceupdated 9mo agoView on Hugging Face
2likes
debug_stop_issue.py76 linesDownload Raw Back to debug
1import sys2import pandas as pd3import yfinance as yf4 5sys.path.insert(0, 'backtesting_app/backtesting_app')6 7from algorithms.fast_ariascampos import FastAriasCampos8from core.backtester import Backtester9 10print("Descargando datos...")11df = yf.download('AAPL', start='2023-01-01', end='2024-12-31', interval='1mo', progress=False)12df = df[['Open', 'High', 'Low', 'Close', 'Volume']]13df.columns = ['open', 'high', 'low', 'close', 'volume']14 15algo = FastAriasCampos()16params = algo.get_default_params()17params['timeframe'] = '1mo'18 19# Ejecutar algoritmo para ver los soportes20algo_result = algo.run(df, params)21 22print("\n=== ANALISIS SOPORTE JUNIO 2023 - MAYO 2024 ===\n")23for i, state in enumerate(algo_result.states):24    if state.timestamp < pd.Timestamp('2023-06-01') or state.timestamp > pd.Timestamp('2024-05-31'):25        continue26    27    bar = df.iloc[i]28    soporte_str = f"{state.support:.2f}" if state.support else "None"29    tendencia_str = "BULL" if state.trend.value == 1 else "BEAR"30    print(f"{state.timestamp.strftime('%Y-%m-%d')} | Low: {bar['low']:.2f} | Soporte: {soporte_str:>8s} | Tendencia: {tendencia_str}")31    32    if state.signal:33        sl_str = f"{state.signal.stop_loss:.2f}" if state.signal.stop_loss else "None"34        print(f"  >>> SEÑAL {state.signal.signal_type} con SL: {sl_str}")35 36# Ejecutar backtester37backtester = Backtester(38    algorithm=algo,39    initial_capital=10000,40    commission_pct=0.1,41    position_sizing='risk',42    risk_percent=3.043)44 45result = backtester.run(df, params, symbol='AAPL', timeframe='1mo')46 47print("\n=== TRADE LONG JUNIO 2023 ===\n")48for trade in result.trades:49    if trade.entry_date >= pd.Timestamp('2023-06-01') and trade.entry_date <= pd.Timestamp('2023-07-01'):50        print(f"Entry: {trade.entry_date.strftime('%Y-%m-%d')} @ ${trade.entry_price:.2f}")51        print(f"Stop Loss Inicial: ${trade.initial_sl:.2f}")52        print(f"Exit: {trade.exit_date.strftime('%Y-%m-%d')} @ ${trade.exit_price:.2f}")53        print(f"Razon: {trade.exit_reason}")54        55        if trade.sl_updates:56            print(f"\nActualizaciones del SL: {len(trade.sl_updates)} veces")57            for idx, sl in enumerate(trade.sl_updates):58                print(f"  Update {idx+1}: ${sl:.2f}")59            print(f"SL Final: ${trade.sl_updates[-1]:.2f}")60        61        if hasattr(trade, '_debug_checks'):62            print(f"\nDebug checks: {trade._debug_checks}")63        if hasattr(trade, '_debug_none_count'):64            print(f"Support None count: {trade._debug_none_count}")65        66        # Ver que paso barra por barra67        print(f"\n=== BARRAS DURANTE EL TRADE ===")68        entry_idx = df.index.get_loc(trade.entry_date)69        exit_idx = df.index.get_loc(trade.exit_date)70        71        for i in range(entry_idx, min(exit_idx + 1, len(df))):72            bar = df.iloc[i]73            state = result.algorithm_result.states[i]74            soporte_str = f"{state.support:.2f}" if state.support else "None"75            print(f"{bar.name.strftime('%Y-%m-%d')} | Low: {bar['low']:.2f} | Soporte: {soporte_str:>8s}")76