Team Ai
Apppublic

diegobeyl/backtesting

sourceHugging Faceupdated 9mo agoView on Hugging Face
2likes
repro_errno22.py87 linesDownload Raw Back to utilities
1
2import sys
3from pathlib import Path
4import pandas as pd
5import traceback
6import time
7
8# Add parent directory for imports
9sys.path.insert(0, str(Path(__file__).parent))
10
11from core.mt5_data_provider import get_data_provider
12from core.donchian_strategy import create_strategy
13from backtesting import Backtest
14
15def run_repro():
16    config = {
17        'symbol': 'BTCUSD',
18        'timeframe': 'H1', # User timeframe from image
19        'donchian_period': 1,
20        'risk_percent': 1.0,
21        'initial_capital': 10000.0,
22        'break_margin': 0.4,
23        'trade_direction': 'BOTH',
24        'lookbehind': 0,
25        'stop_resets_support': True,
26        'commission': 0.1,
27        'slippage': 2,
28        'trailing_mode': 'FAST',
29        'leverage': 30,
30        'bars': 500 # User bars from image
31    }
32    
33    try:
34        print("Fetching data...")
35        provider = get_data_provider()
36        data = provider.get_data(
37            symbol=config['symbol'],
38            timeframe=config['timeframe'],
39            bars=config['bars']
40        )
41        
42        if data is None or data.empty:
43            print("Failed to fetch data")
44            return
45            
46        print(f"Data fetched: {len(data)} bars")
47        
48        print("Creating strategy...")
49        StrategyClass = create_strategy(config)
50        
51        # Scale price down to allow fractional unit precision in backtesting.py
52        price_scaling_factor = 100.0
53        scaled_data = data.copy()
54        for col in ['Open', 'High', 'Low', 'Close']:
55            scaled_data[col] = data[col] / price_scaling_factor
56            
57        print("Running backtest with scaling...")
58        bt = Backtest(
59            scaled_data,
60            StrategyClass,
61            cash=config['initial_capital'],
62            commission=config['commission'] / 100,
63            margin=1 / config['leverage'],
64            exclusive_orders=True
65        )
66        
67        stats = bt.run()
68        print("Backtest complete!")
69        
70        # Scale back prices in results
71        if '_trades' in stats is not None and len(stats['_trades']) > 0:
72            stats['_trades']['EntryPrice'] *= price_scaling_factor
73            stats['_trades']['ExitPrice'] *= price_scaling_factor
74            
75        print(stats)
76        
77        if len(stats['_trades']) > 0:
78            print("\nLatest Trades (Scaled Back):")
79            print(stats['_trades'].tail(10))
80        
81    except Exception as e:
82        print(f"\nERROR CAUGHT: {e}")
83        traceback.print_exc()
84
85if __name__ == "__main__":
86    run_repro()
87