diegobeyl/backtesting
2
1"""
2Test script to verify Errno 22 fix in API routes
3This tests the datetime formatting in chart data preparation
4"""
5
6import sys
7from pathlib import Path
8import pandas as pd
9import numpy as np
10from datetime import datetime, timedelta
11
12# Add parent directory for imports
13sys.path.insert(0, str(Path(__file__).parent))
14
15from api.routes import _prepare_chart_data
16from api.schemas import BacktestConfig
17
18def test_chart_data_formatting():
19 """Test that chart data preparation doesn't raise Errno 22 on Windows"""
20
21 # Create sample OHLCV data with datetime index
22 dates = pd.date_range(start='2024-01-01', periods=100, freq='D')
23 data = pd.DataFrame({
24 'Open': np.random.uniform(100, 110, 100),
25 'High': np.random.uniform(110, 120, 100),
26 'Low': np.random.uniform(90, 100, 100),
27 'Close': np.random.uniform(100, 110, 100),
28 'Volume': np.random.uniform(1000, 10000, 100)
29 }, index=dates)
30
31 # Create mock stats with trades
32 mock_trades = pd.DataFrame({
33 'EntryTime': [dates[10], dates[30], dates[50]],
34 'ExitTime': [dates[15], dates[35], dates[55]],
35 'EntryPrice': [105.0, 107.0, 103.0],
36 'ExitPrice': [108.0, 106.0, 105.0],
37 'Size': [1.0, -1.0, 1.0]
38 })
39
40 mock_equity = pd.DataFrame({
41 'Equity': np.linspace(10000, 12000, 100),
42 'DrawdownPct': np.random.uniform(0, 0.1, 100)
43 }, index=dates)
44
45 stats = {
46 '_trades': mock_trades,
47 '_equity_curve': mock_equity
48 }
49
50 # Create config
51 config = BacktestConfig(
52 symbol='BTCUSD',
53 timeframe='D1',
54 donchian_period=20,
55 risk_percent=1.0,
56 initial_capital=10000.0
57 )
58
59 try:
60 # This should not raise Errno 22
61 chart_data = _prepare_chart_data(data, stats, config)
62
63 print("[PASS] Chart data preparation successful!")
64 print(f" - OHLC points: {len(chart_data['ohlc'])}")
65 print(f" - Donchian points: {len(chart_data['donchian'])}")
66 print(f" - Signals: {len(chart_data['signals'])}")
67
68 # Verify time format
69 if chart_data['ohlc']:
70 sample_time = chart_data['ohlc'][0]['time']
71 print(f" - Sample time format: {sample_time}")
72 assert 'T' in sample_time, "Time should be in ISO format"
73
74 print("\n[PASS] All tests passed! Errno 22 fix is working correctly.")
75 return True
76
77 except OSError as e:
78 if e.errno == 22:
79 print(f"[FAIL] Errno 22 still occurring!")
80 print(f" Error: {e}")
81 return False
82 raise
83 except Exception as e:
84 print(f"[FAIL] Unexpected error: {e}")
85 import traceback
86 traceback.print_exc()
87 return False
88
89if __name__ == "__main__":
90 success = test_chart_data_formatting()
91 sys.exit(0 if success else 1)
92 