forked from alphago2580/MESA
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_backtest.py
More file actions
94 lines (72 loc) · 2.84 KB
/
example_backtest.py
File metadata and controls
94 lines (72 loc) · 2.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
"""
Example script for running backtests on historical data.
"""
import asyncio
import json
import logging
import sys
from pathlib import Path
# Add src to path
sys.path.insert(0, str(Path(__file__).parent))
from src.exchange import ExchangeConnector
from src.backtesting import Backtester
from src.strategies.sma_strategy import SimpleMovingAverage
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
def load_config(config_path: str = 'config.json') -> dict:
"""Load configuration from JSON file."""
try:
with open(config_path, 'r') as f:
return json.load(f)
except FileNotFoundError:
logger.warning(f"Config file not found: {config_path}, using defaults")
return {
'exchange': {'name': 'binance', 'enableRateLimit': True},
'trading': {'symbol': 'BTC/USDT', 'timeframe': '1h'},
'backtesting': {'initial_balance': 10000}
}
async def run_backtest():
"""Run backtest on historical data."""
logger.info("="*60)
logger.info("MESA - Backtesting Example")
logger.info("="*60)
# Load configuration
config = load_config()
# Initialize exchange connector to fetch historical data
exchange = ExchangeConnector(config['exchange'])
try:
# Connect to exchange
await exchange.connect()
# Fetch historical data
symbol = config['trading']['symbol']
timeframe = config['trading']['timeframe']
logger.info(f"Fetching historical data for {symbol} ({timeframe})...")
# Fetch more data for better backtesting (500 candles)
ohlcv_data = await exchange.fetch_ohlcv(symbol, timeframe, limit=500)
logger.info(f"Fetched {len(ohlcv_data)} candles")
# Initialize strategy
strategy = SimpleMovingAverage(short_window=10, long_window=30)
logger.info(f"Strategy: {strategy.name}")
# Initialize backtester
initial_balance = config['backtesting']['initial_balance']
backtester = Backtester(initial_balance=initial_balance)
# Run backtest
logger.info("Running backtest...")
results = await backtester.run(strategy, ohlcv_data, trade_amount=0.5)
# Save results
with open('backtest_results.json', 'w') as f:
# Remove trades list for cleaner output
summary = {k: v for k, v in results.items() if k != 'trades'}
json.dump(summary, f, indent=2)
logger.info("Results saved to backtest_results.json")
except Exception as e:
logger.error(f"Error during backtest: {e}")
raise
finally:
await exchange.disconnect()
if __name__ == "__main__":
asyncio.run(run_backtest())