Team Ai
Apppublic

diegobeyl/backtesting

sourceHugging Faceupdated 9mo agoView on Hugging Face
2likes
test_backtest.py79 linesDownload Raw Back to tests
1"""Test script for debugging backtesting"""
2import sys
3sys.path.insert(0, '.')
4
5import MetaTrader5 as mt5
6import pandas as pd
7from backtesting import Backtest, Strategy
8
9print("1. Initializing MT5...")
10mt5.initialize()
11mt5.symbol_select('BTCUSD', True)
12
13print("2. Getting data...")
14rates = mt5.copy_rates_from_pos('BTCUSD', mt5.TIMEFRAME_D1, 0, 100)
15print(f"   Got {len(rates)} bars")
16
17print("3. Converting to DataFrame...")
18df = pd.DataFrame(rates)
19df['time'] = pd.to_datetime(df['time'], unit='s')
20df.set_index('time', inplace=True)
21df.rename(columns={
22    'open': 'Open', 
23    'high': 'High', 
24    'low': 'Low', 
25    'close': 'Close', 
26    'tick_volume': 'Volume'
27}, inplace=True)
28df = df[['Open', 'High', 'Low', 'Close', 'Volume']]
29print(f"   DataFrame shape: {df.shape}")
30print(df.tail())
31
32print("4. Creating simple strategy...")
33class SimpleStrategy(Strategy):
34    def init(self):
35        pass
36    def next(self):
37        if len(self.data) > 5:
38            if not self.position:
39                self.buy(size=0.01)
40
41print("5. Running backtest...")
42try:
43    bt = Backtest(df, SimpleStrategy, cash=10000, commission=0.001)
44    stats = bt.run()
45    print("6. Backtest completed!")
46    print(f"   Return: {stats['Return [%]']}")
47    print(f"   Trades: {stats['# Trades']}")
48except Exception as e:
49    print(f"ERROR: {e}")
50    import traceback
51    traceback.print_exc()
52
53print("\n7. Now testing the actual strategy...")
54try:
55    from core.donchian_strategy import create_strategy
56    config = {
57        'donchian_period': 1,
58        'risk_percent': 1.0,
59        'break_margin': 0.4,
60        'trade_direction': 'BOTH',
61        'lookbehind': 0,
62        'stop_resets_support': True,
63        'trailing_mode': 'FAST',
64        'leverage': 30,
65    }
66    StrategyClass = create_strategy(config)
67    bt = Backtest(df, StrategyClass, cash=10000, commission=0.001)
68    stats = bt.run()
69    print("8. Donchian strategy completed!")
70    print(f"   Return: {stats['Return [%]']}")
71    print(f"   Trades: {stats['# Trades']}")
72except Exception as e:
73    print(f"ERROR in Donchian strategy: {e}")
74    import traceback
75    traceback.print_exc()
76
77mt5.shutdown()
78print("\nDone!")
79