Team Ai
Apppublic

diegobeyl/backtesting

sourceHugging Faceupdated 9mo agoView on Hugging Face
2likes
debug_shorts.py87 linesDownload Raw Back to debug
1
2import sys
3from pathlib import Path
4import pandas as pd
5import numpy as np
6
7# Add parent directory for imports
8sys.path.insert(0, str(Path(__file__).parent))
9
10from core.mt5_data_provider import get_data_provider
11from core.donchian_strategy import create_strategy
12from backtesting import Backtest
13
14def debug_shorts():
15    config = {
16        'symbol': 'BTCUSD',
17        'timeframe': 'H1',
18        'donchian_period': 1,
19        'risk_percent': 1.0,
20        'initial_capital': 10000.0,
21        'break_margin': 0.4,
22        'trade_direction': 'SHORT_ONLY', # Focus on shorts
23        'lookbehind': 0,
24        'stop_resets_support': True,
25        'commission': 0.1,
26        'slippage': 2,
27        'trailing_mode': 'FAST',
28        'leverage': 30,
29        'bars': 200
30    }
31    
32    print("Fetching data...")
33    provider = get_data_provider()
34    data = provider.get_data(
35        symbol=config['symbol'],
36        timeframe=config['timeframe'],
37        bars=config['bars']
38    )
39    
40    if data is None or data.empty:
41        print("Failed to fetch data")
42        return
43        
44    print(f"Data fetched: {len(data)} bars")
45    
46    # Scale price
47    scaling_factor = 100000.0 # Updated to match routes.py
48    scaled_data = data.copy()
49    for col in ['Open', 'High', 'Low', 'Close']:
50        scaled_data[col] = data[col] / scaling_factor
51    
52    # Calculate commission + slippage (2 points = $2 for BTC)
53    first_price = data['Open'].iloc[0]
54    slippage_percent = (2.0 / first_price) if first_price > 0 else 0
55    total_comm = (0.1 / 100.0) + slippage_percent
56        
57    StrategyClass = create_strategy(config)
58    bt = Backtest(
59        scaled_data,
60        StrategyClass,
61        cash=10000.0,
62        commission=total_comm,
63        margin=1 / 30,
64        exclusive_orders=True
65    )
66    
67    stats = bt.run()
68    strat = stats['_strategy']
69    sl_line = strat.sl_indicator
70    
71    print("\nChecking Short Trades and SL:")
72    trades = stats['_trades']
73    for idx, trade in trades.iterrows():
74        entry_bar = int(trade['EntryBar'])
75        exit_bar = int(trade['ExitBar'])
76        print(f"\nTrade {idx} ({trade['Size']/scaling_factor:.4f} units): Bars {entry_bar} to {exit_bar}")
77        print(f"  PnL: {trade['PnL']:.2f}")
78        for b in range(max(0, entry_bar-2), min(len(sl_line), exit_bar+2)):
79            sl_val = sl_line[b] * scaling_factor
80            struct_val = strat.structure_level * scaling_factor if strat.structure_level else 0
81            price = scaled_data['Close'].iloc[b] * scaling_factor
82            marker = "<- ENTRY" if b == entry_bar else "<- EXIT" if b == exit_bar else ""
83            print(f"  Bar {b}: Price={price:.2f}, SL={sl_val:.2f}, Struct={struct_val:.2f} {marker}")
84
85if __name__ == "__main__":
86    debug_shorts()
87