-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathconfig.py
More file actions
329 lines (269 loc) · 10.1 KB
/
Copy pathconfig.py
File metadata and controls
329 lines (269 loc) · 10.1 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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
"""
Configuration for pairs trading strategies.
Supports stocks, ETFs, futures, forex, commodities, and crypto pairs.
"""
from dataclasses import dataclass, field
from typing import Optional, Literal
import os
from datetime import datetime
@dataclass
class PairConfig:
"""Asset pair configuration."""
asset1_ticker: str = 'SPY'
asset2_ticker: str = 'QQQ'
pair_name: Optional[str] = None
asset1_name: str = 'Asset 1'
asset2_name: str = 'Asset 2'
start_date: str = '2015-01-01'
end_date: str = datetime.now().strftime('%Y-%m-%d')
spread_method: Literal['log', 'simple', 'ratio'] = 'log'
def __post_init__(self):
if self.pair_name is None:
self.pair_name = f"{self.asset1_ticker}-{self.asset2_ticker}"
@dataclass
class DataConfig:
"""Data quality and preprocessing parameters."""
min_price_threshold: float = 0.1
outlier_std_threshold: float = 5.0
max_missing_days: int = 3
cointegration_pvalue: float = 0.05
stationarity_pvalue: float = 0.05
min_half_life: float = 5
max_half_life: float = 90
min_data_points: int = 252
require_cointegration: bool = True
@dataclass
class StrategyConfig:
"""Mean-reversion strategy parameters."""
window: int = 30
z_entry_long: float = -2.0
z_entry_short: float = 2.0
z_exit: float = 0.5
lookback_period: int = 252
half_life_max: int = 60
use_regime_filter: bool = True
trend_sma_fast: int = 50
trend_sma_slow: int = 200
use_dynamic_thresholds: bool = True
vol_lookback: int = 100
scale_in_enabled: bool = True
scale_in_threshold: float = 0.5
max_pyramid_levels: int = 2
hedge_ratio_method: Literal['ols', 'tls', 'kalman'] = 'ols'
rolling_hedge_ratio: bool = False
hedge_ratio_window: int = 252
@dataclass
class RiskConfig:
"""Risk management parameters."""
initial_capital: float = 500_000
risk_per_trade: float = 0.02
max_position_size: float = 0.30
use_atr_stops: bool = True
atr_period: int = 14
atr_stop_multiple: float = 2.5
atr_target_multiple: float = 4.0
max_portfolio_heat: float = 0.10
max_correlation_exposure: float = 0.50
max_drawdown_stop: float = 0.20
max_simultaneous_pairs: int = 5
min_time_between_trades: int = 1
@dataclass
class BacktestConfig:
"""Backtesting and simulation parameters."""
transaction_cost_pct: float = 0.0005
slippage_pct: float = 0.0002
# Set to non-zero for futures
commission_per_contract: float = 0.0
contract_multiplier: float = 1.0
initial_capital: float = 500_000
walk_forward_enabled: bool = False
train_window_days: int = 504
test_window_days: int = 126
monte_carlo_runs: int = 1000
monte_carlo_enabled: bool = False
market_impact_enabled: bool = False
use_bid_ask_spread: bool = False
@dataclass
class OutputConfig:
"""Output, reporting, and visualization settings."""
results_dir: str = 'results'
save_plots: bool = True
plot_format: str = 'png'
plot_dpi: int = 300
show_plots: bool = True
generate_html_report: bool = True
generate_trade_journal: bool = True
export_to_csv: bool = True
verbose: bool = True
log_level: Literal['DEBUG', 'INFO', 'WARNING', 'ERROR'] = 'INFO'
def __post_init__(self):
os.makedirs(self.results_dir, exist_ok=True)
os.makedirs(f"{self.results_dir}/plots", exist_ok=True)
os.makedirs(f"{self.results_dir}/reports", exist_ok=True)
os.makedirs(f"{self.results_dir}/data", exist_ok=True)
class Config:
"""
Master configuration container for the pairs trading system.
Usage:
config = Config() # defaults to SPY-QQQ
config = Config(asset1='GLD', asset2='GDX', pair_name='Gold-Miners')
config = Config(
asset1='CL=F',
asset2='HO=F',
pair_name='Oil-Crack-Spread',
start_date='2010-01-01'
)
"""
def __init__(self,
asset1: str = 'SPY',
asset2: str = 'QQQ',
pair_name: Optional[str] = None,
start_date: str = '2015-01-01',
end_date: Optional[str] = None,
initial_capital: float = 500_000):
self.pair = PairConfig(
asset1_ticker=asset1,
asset2_ticker=asset2,
pair_name=pair_name,
start_date=start_date,
end_date=end_date or datetime.now().strftime('%Y-%m-%d')
)
self.data = DataConfig()
self.strategy = StrategyConfig()
self.risk = RiskConfig(initial_capital=initial_capital)
self.backtest = BacktestConfig(initial_capital=initial_capital)
self.output = OutputConfig()
self.start_date = self.pair.start_date
self.end_date = self.pair.end_date
self.initial_capital = initial_capital
def to_dict(self) -> dict:
"""Convert entire config to dictionary."""
return {
'pair': self.pair.__dict__,
'data': self.data.__dict__,
'strategy': self.strategy.__dict__,
'risk': self.risk.__dict__,
'backtest': self.backtest.__dict__,
'output': self.output.__dict__
}
def summary(self) -> str:
"""Return a human-readable configuration summary."""
lines = [
f"\nConfiguration: {self.pair.pair_name}",
f" Asset 1: {self.pair.asset1_ticker}",
f" Asset 2: {self.pair.asset2_ticker}",
f" Period: {self.pair.start_date} to {self.pair.end_date}",
f" Spread method: {self.pair.spread_method}",
f" Window: {self.strategy.window} days",
f" Entry thresholds: {self.strategy.z_entry_short}s / {self.strategy.z_entry_long}s",
f" Exit threshold: +/-{self.strategy.z_exit}s",
f" Regime filter: {'on' if self.strategy.use_regime_filter else 'off'}",
f" Dynamic thresholds: {'on' if self.strategy.use_dynamic_thresholds else 'off'}",
f" Position scaling: {'on' if self.strategy.scale_in_enabled else 'off'}",
f" Initial capital: ${self.risk.initial_capital:,.0f}",
f" Risk per trade: {self.risk.risk_per_trade*100:.1f}%",
f" Max position: {self.risk.max_position_size*100:.0f}%",
f" ATR stops: {'on' if self.risk.use_atr_stops else 'off'}",
f" Commission: {self.backtest.transaction_cost_pct*10000:.1f} bps",
f" Slippage: {self.backtest.slippage_pct*10000:.1f} bps",
]
return "\n".join(lines) + "\n"
def update_from_dict(self, config_dict: dict):
"""Update configuration from dictionary."""
for section, params in config_dict.items():
if hasattr(self, section):
section_obj = getattr(self, section)
for key, value in params.items():
if hasattr(section_obj, key):
setattr(section_obj, key, value)
@classmethod
def from_preset(cls, preset: str) -> 'Config':
"""
Create configuration from a named preset.
Available presets: 'spy-qqq', 'oil-crack', 'gold-silver', 'gold-miners', 'eafe-usa'
"""
presets = {
'spy-qqq': {
'asset1': 'SPY',
'asset2': 'QQQ',
'pair_name': 'S&P-Nasdaq',
'start_date': '2015-01-01'
},
'oil-crack': {
'asset1': 'CL=F',
'asset2': 'HO=F',
'pair_name': 'Crude-Heating-Oil',
'start_date': '2010-01-01'
},
'gold-silver': {
'asset1': 'GLD',
'asset2': 'SLV',
'pair_name': 'Gold-Silver',
'start_date': '2015-01-01'
},
'gold-miners': {
'asset1': 'GLD',
'asset2': 'GDX',
'pair_name': 'Gold-Miners',
'start_date': '2015-01-01'
},
'eafe-usa': {
'asset1': 'SPY',
'asset2': 'EFA',
'pair_name': 'US-International',
'start_date': '2015-01-01'
}
}
if preset not in presets:
raise ValueError(f"Unknown preset: {preset}. Choose from {list(presets.keys())}")
return cls(**presets[preset])
def get_default_config() -> Config:
"""Default SPY-QQQ configuration."""
return Config()
def get_oil_crack_config() -> Config:
"""CL-HO crack spread configuration with futures settings."""
config = Config(
asset1='CL=F',
asset2='HO=F',
pair_name='Oil-Crack-Spread',
start_date='2010-01-01'
)
config.backtest.commission_per_contract = 2.50
config.backtest.contract_multiplier = 1000
return config
def get_gold_miners_config() -> Config:
"""Gold vs Gold Miners ETF."""
return Config(
asset1='GLD',
asset2='GDX',
pair_name='Gold-Miners',
start_date='2015-01-01'
)
def get_conservative_config() -> Config:
"""Conservative risk settings."""
config = Config()
config.risk.risk_per_trade = 0.01
config.risk.max_position_size = 0.20
config.strategy.z_entry_long = -2.5
config.strategy.z_entry_short = 2.5
config.strategy.scale_in_enabled = False
return config
def get_aggressive_config() -> Config:
"""Aggressive risk settings."""
config = Config()
config.risk.risk_per_trade = 0.03
config.risk.max_position_size = 0.40
config.strategy.z_entry_long = -1.5
config.strategy.z_entry_short = 1.5
config.strategy.scale_in_enabled = True
config.strategy.max_pyramid_levels = 3
return config
if __name__ == "__main__":
config1 = Config()
print(config1.summary())
config2 = Config(asset1='GLD', asset2='SLV', pair_name='Gold-Silver')
print(config2.summary())
config3 = Config.from_preset('oil-crack')
print(config3.summary())
config4 = get_conservative_config()
print(config4.summary())