-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_full_quant_system.py
More file actions
180 lines (137 loc) Β· 5.69 KB
/
test_full_quant_system.py
File metadata and controls
180 lines (137 loc) Β· 5.69 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
#!/usr/bin/env python3
"""
Test script to validate the complete quantitative trading system
This test verifies that the quantitative engine is properly integrated
into the Donchian strategy and produces meaningful results.
"""
import logging
import numpy as np
from brokers.mt5_connection_manager import MT5ConnectionManager
from core.quant_engine import QuantitativeEngine
# Configure logging
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)
def test_quantitative_integration():
"""Test the complete integration of quantitative analysis in the strategy"""
print("π Testing Complete Quantitative Trading System Integration...")
# Initialize components
mt5_manager = MT5ConnectionManager()
connection_ok = mt5_manager.connect()
if not connection_ok:
logger.error("Failed to connect to MT5")
return False
try:
# Initialize quantitative engine
quant_engine = QuantitativeEngine()
logger.info("β
All components initialized successfully")
# Test with sample data to simulate what happens in the strategy
# Generate sample price data (simulating what would come from MT5)
np.random.seed(42) # For reproducible results
sample_prices = 100 + np.cumsum(
np.random.normal(0, 0.1, 200),
) # 200 price points
logger.info(f"π Generated sample price data: {len(sample_prices)} points")
logger.info(
f"π Price range: {sample_prices.min():.5f} - {sample_prices.max():.5f}",
)
# Test quantitative analysis
adx_value = 25.0 # Simulated ADX value
di_plus = 20.0 # Simulated +DI value
di_minus = 15.0 # Simulated -DI value
logger.info(
f"π Simulated indicators - ADX: {adx_value}, +DI: {di_plus}, -DI: {di_minus}",
)
# Calculate entry score using quantitative engine
entry_result = quant_engine.calculate_entry_score(
prices=sample_prices,
adx_value=adx_value,
di_plus=di_plus,
di_minus=di_minus,
)
logger.info(f"π― Quantitative Entry Score: {entry_result['entry_score']:.3f}")
logger.info(f"π‘ Recommendation: {entry_result['recommendation']}")
logger.info(f"π Filters: {entry_result['filters']}")
# Test position sizing
optimal_size = quant_engine.calculate_optimal_position_size(
entry_score=entry_result["entry_score"],
account_balance=10000, # $10,000 account
)
logger.info(f"π° Optimal Position Size: {optimal_size:.3f} lots")
# Verify results make sense
assert 0 <= entry_result["entry_score"] <= 1, (
"Entry score should be between 0 and 1"
)
assert entry_result["recommendation"] in ["BUY", "SELL", "HOLD"], (
"Invalid recommendation"
)
assert optimal_size >= 0, "Position size should be non-negative"
logger.info("β
Quantitative analysis passed validation")
# Test optimizer
optimal_period = quant_engine.optimizer.optimize_donchian_period(sample_prices)
logger.info(f"βοΈ Optimal Donchian Period: {optimal_period}")
assert 5 <= optimal_period <= 50, "Optimal period should be in reasonable range"
logger.info("β
All quantitative system tests passed!")
return True
except Exception as e:
logger.error(f"β Error during quantitative system test: {e}")
import traceback
traceback.print_exc()
return False
finally:
# Clean up
mt5_manager.disconnect()
def test_edge_cases():
"""Test edge cases for the quantitative system"""
print("\nπ§ͺ Testing Edge Cases...")
quant_engine = QuantitativeEngine()
# Test with volatile data
volatile_prices = 100 + np.cumsum(np.random.normal(0, 0.5, 100)) # High volatility
result = quant_engine.calculate_entry_score(
prices=volatile_prices,
adx_value=15.0, # Low ADX
di_plus=10.0,
di_minus=30.0,
)
logger.info(
f"π Volatile market result - Score: {result['entry_score']:.3f}, Recommendation: {result['recommendation']}",
)
# Test with trending data
trending_prices = np.linspace(100, 120, 100) + np.random.normal(
0, 0.2, 100,
) # Upward trend
result = quant_engine.calculate_entry_score(
prices=trending_prices,
adx_value=40.0, # Strong trend
di_plus=35.0,
di_minus=10.0,
)
logger.info(
f"π Trending market result - Score: {result['entry_score']:.3f}, Recommendation: {result['recommendation']}",
)
logger.info("β
Edge case tests completed")
def main():
"""Main test function"""
print("π Starting Complete Quantitative Trading System Test")
print("=" * 60)
# Test main integration
success = test_quantitative_integration()
if success:
# Test edge cases
test_edge_cases()
print("\n" + "=" * 60)
print("π All tests completed successfully!")
print("π The quantitative trading system is working properly with:")
print(" β’ Mathematical formulas for decision making")
print(" β’ Statistical probability models")
print(" β’ Dynamic position sizing based on quantitative analysis")
print(" β’ Parameter optimization using quantitative methods")
print(" β’ Integration with existing Donchian strategy")
print("=" * 60)
else:
print("\nβ Tests failed - please check the implementation")
return 1
return 0
if __name__ == "__main__":
exit(main())