-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenetic_indicator_engine.py
More file actions
1587 lines (1337 loc) · 62.7 KB
/
genetic_indicator_engine.py
File metadata and controls
1587 lines (1337 loc) · 62.7 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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Genetic Indicator Combination Engine
=====================================
Evolves trading strategies by combining well-known technical indicators
(RSI, SMA, MACD, Stochastic, ADX, CCI, etc.) using a genetic algorithm.
Each chromosome encodes a complete trading strategy:
- Which indicators to use for entry/exit
- Indicator parameters (periods, thresholds)
- Logical combination (AND conditions)
- Stop-loss and take-profit levels
Backtesting is done with vectorbt for speed.
Uses the 'ta' library for indicator computation.
"""
import copy
import random
import time
import math
import warnings
import json
from dataclasses import dataclass, field, asdict
from typing import List, Tuple, Dict, Optional
from pathlib import Path
import numpy as np
import pandas as pd
import ta as ta_lib
import vectorbt as vbt
import dill
warnings.filterwarnings("ignore")
# ---------------------------------------------------------------------------
# 0. Configuration
# ---------------------------------------------------------------------------
RNG_SEED = 42
random.seed(RNG_SEED)
np.random.seed(RNG_SEED)
INITIAL_CASH = 10_000
COMMISSION_PCT = 0.001 # 0.1% per trade (typical crypto)
# ---------------------------------------------------------------------------
# 1. Indicator Definitions (using 'ta' library)
# ---------------------------------------------------------------------------
INDICATOR_REGISTRY = {}
def register_indicator(name, param_options, compute_fn, description=""):
INDICATOR_REGISTRY[name] = {
"param_options": param_options,
"compute": compute_fn,
"description": description,
}
# Helper: ensure Series output
def _s(val, index):
if isinstance(val, pd.Series):
return val
return pd.Series(val, index=index)
# --- RSI ---
register_indicator(
"RSI",
{"period": [7, 9, 14, 21, 28]},
lambda df, p: {"RSI": ta_lib.momentum.RSIIndicator(df["Close"], window=p["period"]).rsi()},
"Relative Strength Index",
)
# --- SMA crossover ---
register_indicator(
"SMA",
{"fast": [5, 10, 20], "slow": [50, 100, 200]},
lambda df, p: {
"SMA_fast": ta_lib.trend.SMAIndicator(df["Close"], window=p["fast"]).sma_indicator(),
"SMA_slow": ta_lib.trend.SMAIndicator(df["Close"], window=p["slow"]).sma_indicator(),
},
"Simple Moving Average crossover",
)
# --- EMA crossover ---
register_indicator(
"EMA",
{"fast": [5, 8, 12, 21], "slow": [26, 50, 100, 200]},
lambda df, p: {
"EMA_fast": ta_lib.trend.EMAIndicator(df["Close"], window=p["fast"]).ema_indicator(),
"EMA_slow": ta_lib.trend.EMAIndicator(df["Close"], window=p["slow"]).ema_indicator(),
},
"Exponential Moving Average crossover",
)
# --- MACD ---
register_indicator(
"MACD",
{"fast": [8, 12], "slow": [21, 26], "signal": [7, 9]},
lambda df, p: {
"MACD_line": ta_lib.trend.MACD(df["Close"], window_fast=p["fast"], window_slow=p["slow"], window_sign=p["signal"]).macd(),
"MACD_signal": ta_lib.trend.MACD(df["Close"], window_fast=p["fast"], window_slow=p["slow"], window_sign=p["signal"]).macd_signal(),
"MACD_hist": ta_lib.trend.MACD(df["Close"], window_fast=p["fast"], window_slow=p["slow"], window_sign=p["signal"]).macd_diff(),
},
"MACD line, signal, histogram",
)
# --- Stochastic ---
register_indicator(
"Stochastic",
{"k": [5, 9, 14], "d": [3, 5], "smooth_k": [3, 5]},
lambda df, p: {
"STOCH_K": ta_lib.momentum.StochasticOscillator(df["High"], df["Low"], df["Close"], window=p["k"], smooth_window=p["d"]).stoch(),
"STOCH_D": ta_lib.momentum.StochasticOscillator(df["High"], df["Low"], df["Close"], window=p["k"], smooth_window=p["d"]).stoch_signal(),
},
"Stochastic Oscillator K and D",
)
# --- ADX ---
register_indicator(
"ADX",
{"period": [7, 14, 21]},
lambda df, p: {
"ADX": ta_lib.trend.ADXIndicator(df["High"], df["Low"], df["Close"], window=p["period"]).adx(),
"DI_plus": ta_lib.trend.ADXIndicator(df["High"], df["Low"], df["Close"], window=p["period"]).adx_pos(),
"DI_minus": ta_lib.trend.ADXIndicator(df["High"], df["Low"], df["Close"], window=p["period"]).adx_neg(),
},
"Average Directional Index",
)
# --- CCI ---
register_indicator(
"CCI",
{"period": [14, 20, 50]},
lambda df, p: {"CCI": ta_lib.trend.CCIIndicator(df["High"], df["Low"], df["Close"], window=p["period"]).cci()},
"Commodity Channel Index",
)
# --- ROC ---
register_indicator(
"ROC",
{"period": [9, 12, 14, 21]},
lambda df, p: {"ROC": ta_lib.momentum.ROCIndicator(df["Close"], window=p["period"]).roc()},
"Rate of Change",
)
# --- MFI ---
register_indicator(
"MFI",
{"period": [10, 14, 20]},
lambda df, p: {"MFI": ta_lib.volume.MFIIndicator(df["High"], df["Low"], df["Close"], df["Volume"], window=p["period"]).money_flow_index()},
"Money Flow Index",
)
# --- Bollinger Bands ---
register_indicator(
"BollingerBands",
{"period": [10, 20, 30], "std": [1.5, 2.0, 2.5]},
lambda df, p: {
"BB_upper": ta_lib.volatility.BollingerBands(df["Close"], window=p["period"], window_dev=p["std"]).bollinger_hband(),
"BB_mid": ta_lib.volatility.BollingerBands(df["Close"], window=p["period"], window_dev=p["std"]).bollinger_mavg(),
"BB_lower": ta_lib.volatility.BollingerBands(df["Close"], window=p["period"], window_dev=p["std"]).bollinger_lband(),
"BB_pctb": ta_lib.volatility.BollingerBands(df["Close"], window=p["period"], window_dev=p["std"]).bollinger_pband(),
},
"Bollinger Bands",
)
# --- Keltner Channel ---
register_indicator(
"KeltnerChannel",
{"period": [10, 20], "atr_mult": [1.0, 1.5, 2.0]},
lambda df, p: {
"KC_upper": ta_lib.volatility.KeltnerChannel(df["High"], df["Low"], df["Close"], window=p["period"], multiplier=p["atr_mult"]).keltner_channel_hband(),
"KC_basis": ta_lib.volatility.KeltnerChannel(df["High"], df["Low"], df["Close"], window=p["period"], multiplier=p["atr_mult"]).keltner_channel_mband(),
"KC_lower": ta_lib.volatility.KeltnerChannel(df["High"], df["Low"], df["Close"], window=p["period"], multiplier=p["atr_mult"]).keltner_channel_lband(),
},
"Keltner Channel",
)
# --- KAMA ---
register_indicator(
"KAMA",
{"period": [10, 20, 30]},
lambda df, p: {"KAMA": ta_lib.momentum.KAMAIndicator(df["Close"], window=p["period"]).kama()},
"Kaufman Adaptive Moving Average",
)
# --- Williams %R ---
register_indicator(
"WilliamsR",
{"period": [7, 14, 21]},
lambda df, p: {"WILLR": ta_lib.momentum.WilliamsRIndicator(df["High"], df["Low"], df["Close"], lbp=p["period"]).williams_r()},
"Williams %R",
)
# --- ATR ---
register_indicator(
"ATR",
{"period": [7, 14, 21]},
lambda df, p: {"ATR": ta_lib.volatility.AverageTrueRange(df["High"], df["Low"], df["Close"], window=p["period"]).average_true_range()},
"Average True Range",
)
# --- OBV ---
register_indicator(
"OBV",
{},
lambda df, p: {"OBV": ta_lib.volume.OnBalanceVolumeIndicator(df["Close"], df["Volume"]).on_balance_volume()},
"On Balance Volume",
)
# --- Aroon ---
register_indicator(
"Aroon",
{"period": [14, 25]},
lambda df, p: {
"AROON_up": ta_lib.trend.AroonIndicator(df["Close"], window=p["period"]).aroon_up(),
"AROON_down": ta_lib.trend.AroonIndicator(df["Close"], window=p["period"]).aroon_down(),
},
"Aroon Oscillator",
)
# --- CMF (Chaikin Money Flow) ---
register_indicator(
"CMF",
{"period": [10, 20, 21]},
lambda df, p: {"CMF": ta_lib.volume.ChaikinMoneyFlowIndicator(df["High"], df["Low"], df["Close"], df["Volume"], window=p["period"]).chaikin_money_flow()},
"Chaikin Money Flow",
)
# --- TSI (True Strength Index) ---
register_indicator(
"TSI",
{"fast": [13, 25], "slow": [7, 13]},
lambda df, p: {"TSI": ta_lib.momentum.TSIIndicator(df["Close"], window_slow=p["fast"], window_fast=p["slow"]).tsi()},
"True Strength Index",
)
# --- PPO ---
register_indicator(
"PPO",
{"fast": [12, 26], "slow": [26, 50]},
lambda df, p: {"PPO": ta_lib.momentum.PercentagePriceOscillator(df["Close"], window_fast=p["fast"], window_slow=p["slow"]).ppo()},
"Percentage Price Oscillator",
)
# --- Ultimate Oscillator ---
register_indicator(
"UltimateOscillator",
{"fast": [7], "medium": [14], "slow": [28]},
lambda df, p: {"UO": ta_lib.momentum.UltimateOscillator(df["High"], df["Low"], df["Close"], window1=p["fast"], window2=p["medium"], window3=p["slow"]).ultimate_oscillator()},
"Ultimate Oscillator",
)
# --- Ichimoku ---
register_indicator(
"Ichimoku",
{"tenkan": [9], "kijun": [26]},
lambda df, p: {
"ICH_conv": ta_lib.trend.IchimokuIndicator(df["High"], df["Low"], window1=p["tenkan"], window2=p["kijun"]).ichimoku_conversion_line(),
"ICH_base": ta_lib.trend.IchimokuIndicator(df["High"], df["Low"], window1=p["tenkan"], window2=p["kijun"]).ichimoku_base_line(),
},
"Ichimoku Cloud",
)
# --- DPO ---
register_indicator(
"DPO",
{"period": [14, 20, 30]},
lambda df, p: {"DPO": ta_lib.trend.DPOIndicator(df["Close"], window=p["period"]).dpo()},
"Detrended Price Oscillator",
)
# --- VWAP ---
register_indicator(
"VWAP",
{},
lambda df, p: {"VWAP": ta_lib.volume.VolumeWeightedAveragePrice(df["High"], df["Low"], df["Close"], df["Volume"]).volume_weighted_average_price()},
"Volume Weighted Average Price",
)
# --- Awesome Oscillator ---
register_indicator(
"AwesomeOscillator",
{"fast": [5], "slow": [34]},
lambda df, p: {"AO": ta_lib.momentum.AwesomeOscillatorIndicator(df["High"], df["Low"], window1=p["fast"], window2=p["slow"]).awesome_oscillator()},
"Awesome Oscillator",
)
INDICATOR_NAMES = list(INDICATOR_REGISTRY.keys())
# ---------------------------------------------------------------------------
# 2. Condition Types
# ---------------------------------------------------------------------------
CONDITION_TYPES = [
"crosses_above",
"crosses_below",
"is_above",
"is_below",
"rising",
"falling",
]
# ---------------------------------------------------------------------------
# 3. Strategy Gene Encoding
# ---------------------------------------------------------------------------
@dataclass
class IndicatorCondition:
indicator_name: str
params: Dict
output_key: str
condition_type: str
threshold: float
compare_indicator: Optional[str] = None
compare_output_key: Optional[str] = None
def to_dict(self):
return asdict(self)
@dataclass
class TradingStrategy:
entry_conditions: List[IndicatorCondition]
exit_conditions: List[IndicatorCondition]
stop_loss_pct: float
take_profit_pct: float
direction: str = "long"
fitness_sharpe: float = 0.0
fitness_return: float = 0.0
fitness_trades: int = 0
fitness_winrate: float = 0.0
fitness_max_dd: float = 0.0
fitness_profit_factor: float = 0.0
fitness_sortino: float = 0.0
fitness_calmar: float = 0.0
fitness_score: float = -999.0
def to_dict(self):
return {
"entry_conditions": [c.to_dict() for c in self.entry_conditions],
"exit_conditions": [c.to_dict() for c in self.exit_conditions],
"stop_loss_pct": self.stop_loss_pct,
"take_profit_pct": self.take_profit_pct,
"direction": self.direction,
"fitness_sharpe": self.fitness_sharpe,
"fitness_return": self.fitness_return,
"fitness_trades": self.fitness_trades,
"fitness_winrate": self.fitness_winrate,
"fitness_max_dd": self.fitness_max_dd,
"fitness_profit_factor": self.fitness_profit_factor,
"fitness_sortino": self.fitness_sortino,
"fitness_calmar": self.fitness_calmar,
"fitness_score": self.fitness_score,
}
# ---------------------------------------------------------------------------
# 4. Random Strategy Generation
# ---------------------------------------------------------------------------
def random_params(indicator_name: str) -> Dict:
info = INDICATOR_REGISTRY[indicator_name]
params = {}
for param_name, options in info["param_options"].items():
params[param_name] = random.choice(options)
return params
def random_output_key(indicator_name: str, params: Dict, df: pd.DataFrame = None) -> str:
info = INDICATOR_REGISTRY[indicator_name]
try:
if df is not None and len(df) > 250:
sample = df.iloc[:250].copy()
else:
sample = df
outputs = info["compute"](sample, params)
keys = [k for k, v in outputs.items() if v is not None and not v.isna().all()]
if keys:
return random.choice(keys)
except Exception:
pass
return indicator_name
def get_threshold_for_indicator(output_key: str) -> float:
key = output_key.upper()
if "RSI" in key or "MFI" in key or "WILLR" in key or "STOCH" in key:
return random.choice([20, 25, 30, 50, 70, 75, 80])
elif "CCI" in key:
return random.choice([-200, -100, -50, 0, 50, 100, 200])
elif "ADX" in key or "DI_" in key:
return random.choice([15, 20, 25, 30, 40])
elif "ROC" in key or "PPO" in key or "DPO" in key:
return random.choice([-5, -2, -1, 0, 1, 2, 5])
elif "CMF" in key or "TSI" in key:
return random.choice([-0.1, -0.05, 0, 0.05, 0.1])
elif "AROON" in key:
return random.choice([30, 50, 70, 80])
elif "BB_pctb" in key:
return random.choice([0.0, 0.2, 0.5, 0.8, 1.0])
elif "MACD_hist" in key:
return 0.0
elif "UO" in key:
return random.choice([30, 40, 50, 60, 70])
elif "AO" in key:
return 0.0
else:
return 0.0
def random_condition(df: pd.DataFrame) -> IndicatorCondition:
ind_name = random.choice(INDICATOR_NAMES)
params = random_params(ind_name)
output_key = random_output_key(ind_name, params, df)
cond_type = random.choice(CONDITION_TYPES)
threshold = get_threshold_for_indicator(output_key)
compare_ind = None
compare_key = None
if cond_type in ("crosses_above", "crosses_below") and random.random() < 0.3:
compare_ind = random.choice(INDICATOR_NAMES)
compare_params = random_params(compare_ind)
compare_key = random_output_key(compare_ind, compare_params, df)
return IndicatorCondition(
indicator_name=ind_name,
params=params,
output_key=output_key,
condition_type=cond_type,
threshold=threshold,
compare_indicator=compare_ind,
compare_output_key=compare_key,
)
def random_strategy(df: pd.DataFrame, min_entry: int = 2, max_entry: int = 4,
min_exit: int = 1, max_exit: int = 2) -> TradingStrategy:
n_entry = random.randint(min_entry, max_entry)
n_exit = random.randint(min_exit, max_exit)
return TradingStrategy(
entry_conditions=[random_condition(df) for _ in range(n_entry)],
exit_conditions=[random_condition(df) for _ in range(n_exit)],
stop_loss_pct=round(random.uniform(0.01, 0.10), 3),
take_profit_pct=round(random.uniform(0.02, 0.20), 3),
direction=random.choice(["long", "short", "both"]),
)
# ---------------------------------------------------------------------------
# 5. Indicator Computation Cache
# ---------------------------------------------------------------------------
class IndicatorCache:
def __init__(self, df: pd.DataFrame):
self.df = df
self._cache: Dict[str, pd.Series] = {}
def get(self, indicator_name: str, params: Dict, output_key: str) -> pd.Series:
cache_key = f"{indicator_name}_{json.dumps(params, sort_keys=True)}_{output_key}"
if cache_key not in self._cache:
try:
info = INDICATOR_REGISTRY[indicator_name]
outputs = info["compute"](self.df, params)
for k, v in outputs.items():
ck = f"{indicator_name}_{json.dumps(params, sort_keys=True)}_{k}"
if v is not None:
self._cache[ck] = v
except Exception:
self._cache[cache_key] = pd.Series(np.nan, index=self.df.index)
return self._cache.get(cache_key, pd.Series(np.nan, index=self.df.index))
def clear(self):
self._cache.clear()
# ---------------------------------------------------------------------------
# 6. Signal Generation from Strategy
# ---------------------------------------------------------------------------
def evaluate_condition(cond: IndicatorCondition, cache: IndicatorCache) -> pd.Series:
series = cache.get(cond.indicator_name, cond.params, cond.output_key)
if cond.condition_type == "is_above":
return series > cond.threshold
elif cond.condition_type == "is_below":
return series < cond.threshold
elif cond.condition_type == "rising":
return series > series.shift(1)
elif cond.condition_type == "falling":
return series < series.shift(1)
elif cond.condition_type == "crosses_above":
if cond.compare_indicator and cond.compare_output_key:
other = cache.get(cond.compare_indicator, cond.params, cond.compare_output_key)
else:
other = pd.Series(cond.threshold, index=series.index)
return (series > other) & (series.shift(1) <= other.shift(1))
elif cond.condition_type == "crosses_below":
if cond.compare_indicator and cond.compare_output_key:
other = cache.get(cond.compare_indicator, cond.params, cond.compare_output_key)
else:
other = pd.Series(cond.threshold, index=series.index)
return (series < other) & (series.shift(1) >= other.shift(1))
else:
return pd.Series(False, index=series.index)
def generate_signals(strategy: TradingStrategy, cache: IndicatorCache) -> Tuple[pd.Series, pd.Series]:
idx = cache.df.index
# Entry: AND of all entry conditions
entry_signals = pd.Series(True, index=idx)
for cond in strategy.entry_conditions:
sig = evaluate_condition(cond, cache)
entry_signals = entry_signals & sig.reindex(idx, fill_value=False)
# Exit: OR of any exit condition
exit_signals = pd.Series(False, index=idx)
for cond in strategy.exit_conditions:
sig = evaluate_condition(cond, cache)
exit_signals = exit_signals | sig.reindex(idx, fill_value=False)
entry_signals = entry_signals.fillna(False).astype(bool)
exit_signals = exit_signals.fillna(False).astype(bool)
return entry_signals, exit_signals
# ---------------------------------------------------------------------------
# 7. Backtesting with vectorbt
# ---------------------------------------------------------------------------
def backtest_strategy(
strategy: TradingStrategy,
df: pd.DataFrame,
cache: IndicatorCache = None,
initial_cash: float = INITIAL_CASH,
commission: float = COMMISSION_PCT,
) -> Dict:
if cache is None:
cache = IndicatorCache(df)
try:
entries, exits = generate_signals(strategy, cache)
if entries.sum() == 0:
return _empty_metrics()
price = df["Close"]
if strategy.direction == "long":
pf = vbt.Portfolio.from_signals(
price, entries=entries, exits=exits,
init_cash=initial_cash, fees=commission,
sl_stop=strategy.stop_loss_pct, tp_stop=strategy.take_profit_pct,
freq="1h",
)
elif strategy.direction == "short":
pf = vbt.Portfolio.from_signals(
price, short_entries=entries, short_exits=exits,
init_cash=initial_cash, fees=commission,
sl_stop=strategy.stop_loss_pct, tp_stop=strategy.take_profit_pct,
freq="1h",
)
else: # both
pf = vbt.Portfolio.from_signals(
price, entries=entries, exits=exits,
short_entries=exits, short_exits=entries,
init_cash=initial_cash, fees=commission,
sl_stop=strategy.stop_loss_pct, tp_stop=strategy.take_profit_pct,
freq="1h",
)
stats = pf.stats()
total_trades = int(stats.get("Total Trades", 0))
if total_trades < 5:
return _empty_metrics()
total_return = float(stats.get("Total Return [%]", 0))
sharpe = float(stats.get("Sharpe Ratio", 0))
sortino = float(stats.get("Sortino Ratio", 0))
calmar = float(stats.get("Calmar Ratio", 0))
max_dd = float(stats.get("Max Drawdown [%]", 0))
win_rate = float(stats.get("Win Rate [%]", 0))
profit_factor = float(stats.get("Profit Factor", 0))
for name in ["sharpe", "sortino", "calmar", "profit_factor"]:
val = locals()[name]
if not np.isfinite(val):
locals()[name] # can't reassign via locals, handle below
sharpe = 0.0 if not np.isfinite(sharpe) else sharpe
sortino = 0.0 if not np.isfinite(sortino) else sortino
calmar = 0.0 if not np.isfinite(calmar) else calmar
profit_factor = 0.0 if not np.isfinite(profit_factor) else profit_factor
equity_curve = pf.value()
try:
trades_records = pf.trades.records_readable
except Exception:
trades_records = pd.DataFrame()
# Extract per-trade stats for consistency scoring
avg_win = 0.0
avg_loss = 0.0
expectancy = 0.0
tail_ratio = 0.0
try:
trade_pnls = pf.trades.pnl.values
if len(trade_pnls) > 0:
winners = trade_pnls[trade_pnls > 0]
losers = trade_pnls[trade_pnls < 0]
avg_win = float(np.mean(winners)) if len(winners) > 0 else 0.0
avg_loss = float(np.mean(losers)) if len(losers) > 0 else 0.0
wr = len(winners) / len(trade_pnls)
lr = 1.0 - wr
expectancy = (wr * avg_win + lr * avg_loss) if avg_loss != 0 else avg_win * wr
# Tail ratio: are big moves in our favor? (95th pctl win / 5th pctl loss)
p95 = float(np.percentile(trade_pnls, 95)) if len(trade_pnls) > 5 else 0.0
p5 = float(np.percentile(trade_pnls, 5)) if len(trade_pnls) > 5 else -1.0
tail_ratio = abs(p95 / p5) if p5 != 0 else 0.0
except Exception:
pass
# Equity curve smoothness (lower = smoother = better)
equity_volatility = 0.0
try:
if equity_curve is not None and len(equity_curve) > 10:
eq_returns = equity_curve.pct_change().dropna()
equity_volatility = float(eq_returns.std()) if len(eq_returns) > 0 else 0.0
except Exception:
pass
return {
"total_return": total_return,
"sharpe": sharpe,
"sortino": sortino,
"calmar": calmar,
"max_drawdown": max_dd,
"win_rate": win_rate,
"profit_factor": profit_factor,
"total_trades": total_trades,
"equity_curve": equity_curve,
"trades": trades_records,
"portfolio": pf,
"stats": stats,
"avg_win": avg_win,
"avg_loss": avg_loss,
"expectancy": expectancy,
"tail_ratio": tail_ratio,
"equity_volatility": equity_volatility,
}
except Exception:
return _empty_metrics()
def _empty_metrics():
return {
"total_return": 0.0,
"sharpe": 0.0,
"sortino": 0.0,
"calmar": 0.0,
"max_drawdown": 0.0,
"win_rate": 0.0,
"profit_factor": 0.0,
"total_trades": 0,
"equity_curve": None,
"trades": pd.DataFrame(),
"portfolio": None,
"stats": None,
"avg_win": 0.0,
"avg_loss": 0.0,
"expectancy": 0.0,
"tail_ratio": 0.0,
"equity_volatility": 0.0,
}
def compute_fitness_score(metrics: Dict, val_metrics: Dict = None) -> float:
"""
Improved fitness function designed to find ROBUST strategies, not flashy ones.
Key principles:
- Profit Factor is king (PF > 1.5 = you make 50% more on winners than losers)
- Drawdown is heavily penalized (real traders can't stomach 40%+ DD)
- Trade count matters: more trades = more statistical confidence
- Consistency beats one big winner
- IS/OOS gap is penalized when validation data is available
"""
trades = metrics["total_trades"]
if trades < 5:
return -999.0
sharpe = metrics["sharpe"]
sortino = metrics["sortino"]
total_return = metrics["total_return"]
win_rate = metrics["win_rate"]
profit_factor = metrics["profit_factor"]
max_dd = abs(metrics["max_drawdown"])
calmar = metrics.get("calmar", 0.0)
expectancy = metrics.get("expectancy", 0.0)
tail_ratio = metrics.get("tail_ratio", 0.0)
# --- Core Score Components ---
# 1. Profit Factor (capped at 4.0 to avoid rewarding lucky outliers)
# PF = 1.0 is breakeven, 1.5+ is good, 2.0+ is excellent
pf_score = min(profit_factor, 4.0) * 2.0
# 2. Sharpe (capped at 3.0 - anything higher is suspicious)
sharpe_score = min(max(sharpe, -2.0), 3.0) * 1.5
# 3. Win Rate bonus (scaled: 50% = neutral, 60%+ = good)
wr_score = (win_rate - 50.0) / 10.0 # +1 per 10% above 50%
# 4. Return (logarithmic scaling - diminishing returns above 50%)
if total_return > 0:
ret_score = math.log1p(total_return) * 0.8
else:
ret_score = total_return / 50.0 # Negative returns penalized linearly
# 5. Calmar ratio (return / max drawdown - rewards risk-adjusted returns)
calmar_capped = min(max(calmar, -2.0), 5.0) if np.isfinite(calmar) else 0.0
calmar_score = calmar_capped * 0.8
# --- Penalty Components ---
# 6. Drawdown penalty (exponential - gets much worse above 25%)
if max_dd < 15:
dd_penalty = max_dd * 0.05 # Mild penalty under 15%
elif max_dd < 30:
dd_penalty = 0.75 + (max_dd - 15) * 0.10 # Moderate 15-30%
else:
dd_penalty = 2.25 + (max_dd - 30) * 0.20 # Severe above 30%
# 7. Trade count scaling (gradual, not binary)
# 10 trades = 0.4x, 20 = 0.6x, 30 = 0.75x, 50 = 0.9x, 80+ = 1.0x
trade_multiplier = min(1.0, 0.3 + 0.7 * (trades / 80.0))
# 8. Expectancy bonus (positive expectancy per trade is crucial)
exp_score = 0.0
if expectancy > 0:
exp_score = min(expectancy / 100.0, 1.0) * 1.0 # Cap at 1.0 bonus
# --- Combine ---
raw_score = (
pf_score
+ sharpe_score
+ wr_score
+ ret_score
+ calmar_score
+ exp_score
- dd_penalty
)
# Apply trade count multiplier
score = raw_score * trade_multiplier
# --- Validation Penalty (fight overfitting!) ---
if val_metrics is not None and val_metrics["total_trades"] >= 3:
val_return = val_metrics["total_return"]
val_sharpe = val_metrics["sharpe"]
# Penalize large IS/OOS gaps
if total_return > 0 and val_return > 0:
# Both positive - reward consistency
return_ratio = min(val_return, total_return) / max(val_return, total_return, 0.01)
score *= (0.5 + 0.5 * return_ratio) # Scale 0.5x to 1.0x
elif total_return > 0 and val_return <= 0:
# Positive IS but negative OOS = likely overfit
score *= 0.3
# If IS is negative, score is already low, no extra penalty needed
# Bonus for strategies that actually work OOS
if val_sharpe > 0.5 and val_return > 0:
score += min(val_sharpe, 2.0) * 0.5 # OOS Sharpe bonus
return score
# ---------------------------------------------------------------------------
# 8. Genetic Operators
# ---------------------------------------------------------------------------
def crossover(strat1: TradingStrategy, strat2: TradingStrategy) -> Tuple[TradingStrategy, TradingStrategy]:
child1 = copy.deepcopy(strat1)
child2 = copy.deepcopy(strat2)
if random.random() < 0.5 and child1.entry_conditions and child2.entry_conditions:
idx1 = random.randrange(len(child1.entry_conditions))
idx2 = random.randrange(len(child2.entry_conditions))
child1.entry_conditions[idx1], child2.entry_conditions[idx2] = \
child2.entry_conditions[idx2], child1.entry_conditions[idx1]
if random.random() < 0.5 and child1.exit_conditions and child2.exit_conditions:
idx1 = random.randrange(len(child1.exit_conditions))
idx2 = random.randrange(len(child2.exit_conditions))
child1.exit_conditions[idx1], child2.exit_conditions[idx2] = \
child2.exit_conditions[idx2], child1.exit_conditions[idx1]
if random.random() < 0.3:
child1.stop_loss_pct, child2.stop_loss_pct = child2.stop_loss_pct, child1.stop_loss_pct
if random.random() < 0.3:
child1.take_profit_pct, child2.take_profit_pct = child2.take_profit_pct, child1.take_profit_pct
return child1, child2
def mutate(strat: TradingStrategy, df: pd.DataFrame,
min_entry: int = 2, max_entry: int = 4,
min_exit: int = 1, max_exit: int = 2) -> TradingStrategy:
child = copy.deepcopy(strat)
mutation_type = random.choice([
"replace_entry_cond", "replace_exit_cond",
"tweak_threshold", "tweak_sl_tp",
"add_entry_condition", "remove_entry_condition",
"add_exit_condition", "remove_exit_condition",
"change_params", "flip_direction",
])
if mutation_type == "replace_entry_cond" and child.entry_conditions:
idx = random.randrange(len(child.entry_conditions))
child.entry_conditions[idx] = random_condition(df)
elif mutation_type == "replace_exit_cond" and child.exit_conditions:
idx = random.randrange(len(child.exit_conditions))
child.exit_conditions[idx] = random_condition(df)
elif mutation_type == "tweak_threshold":
all_conds = child.entry_conditions + child.exit_conditions
if all_conds:
cond = random.choice(all_conds)
cond.threshold *= random.uniform(0.8, 1.2)
elif mutation_type == "tweak_sl_tp":
child.stop_loss_pct = max(0.005, min(0.15, child.stop_loss_pct * random.uniform(0.7, 1.3)))
child.take_profit_pct = max(0.01, min(0.30, child.take_profit_pct * random.uniform(0.7, 1.3)))
elif mutation_type == "add_entry_condition":
if len(child.entry_conditions) < max_entry:
child.entry_conditions.append(random_condition(df))
elif mutation_type == "remove_entry_condition":
if len(child.entry_conditions) > min_entry:
child.entry_conditions.pop(random.randrange(len(child.entry_conditions)))
elif mutation_type == "add_exit_condition":
if len(child.exit_conditions) < max_exit:
child.exit_conditions.append(random_condition(df))
elif mutation_type == "remove_exit_condition":
if len(child.exit_conditions) > min_exit:
child.exit_conditions.pop(random.randrange(len(child.exit_conditions)))
elif mutation_type == "change_params":
all_conds = child.entry_conditions + child.exit_conditions
if all_conds:
cond = random.choice(all_conds)
cond.params = random_params(cond.indicator_name)
elif mutation_type == "flip_direction":
child.direction = random.choice(["long", "short", "both"])
return child
# ---------------------------------------------------------------------------
# 9. Genetic Algorithm Evolution
# ---------------------------------------------------------------------------
def run_evolution(
df_train: pd.DataFrame,
df_val: pd.DataFrame = None,
pop_size: int = 100,
n_generations: int = 20,
p_crossover: float = 0.7,
p_mutation: float = 0.3,
tournament_size: int = 3,
elite_size: int = 5,
progress_callback=None,
min_entry: int = 2,
max_entry: int = 4,
min_exit: int = 1,
max_exit: int = 2,
) -> Dict:
start_time = time.time()
cache_train = IndicatorCache(df_train)
cache_val = IndicatorCache(df_val) if df_val is not None else None
print(f"Creating initial population of {pop_size} strategies...")
population = [random_strategy(df_train, min_entry, max_entry, min_exit, max_exit)
for _ in range(pop_size)]
generation_stats = []
all_evaluated = []
best_score_ever = -999.0
best_strategy_ever = None
for gen in range(n_generations):
gen_start = time.time()
for i, strat in enumerate(population):
metrics = backtest_strategy(strat, df_train, cache_train)
# Validate on OOS data if available (key anti-overfit mechanism)
val_metrics = None
if cache_val is not None and metrics["total_trades"] >= 5:
val_metrics = backtest_strategy(strat, df_val, cache_val)
score = compute_fitness_score(metrics, val_metrics)
strat.fitness_score = score
strat.fitness_sharpe = metrics["sharpe"]
strat.fitness_return = metrics["total_return"]
strat.fitness_trades = metrics["total_trades"]
strat.fitness_winrate = metrics["win_rate"]
strat.fitness_max_dd = metrics["max_drawdown"]
strat.fitness_profit_factor = metrics["profit_factor"]
strat.fitness_sortino = metrics["sortino"]
strat.fitness_calmar = metrics["calmar"]
all_evaluated.append({
"generation": gen + 1,
"index": i,
"score": score,
"sharpe": metrics["sharpe"],
"total_return": metrics["total_return"],
"trades": metrics["total_trades"],
"win_rate": metrics["win_rate"],
"max_dd": metrics["max_drawdown"],
"profit_factor": metrics["profit_factor"],
"sortino": metrics["sortino"],
})
population.sort(key=lambda s: s.fitness_score, reverse=True)
if population[0].fitness_score > best_score_ever:
best_score_ever = population[0].fitness_score
best_strategy_ever = copy.deepcopy(population[0])
scores = [s.fitness_score for s in population]
valid_scores = [s for s in scores if s > -999]
gen_time = time.time() - gen_start
stat = {
"generation": gen + 1,
"best_score": max(scores),
"avg_score": np.mean(valid_scores) if valid_scores else 0,
"median_score": np.median(valid_scores) if valid_scores else 0,
"best_sharpe": population[0].fitness_sharpe,
"best_return": population[0].fitness_return,
"best_trades": population[0].fitness_trades,
"best_winrate": population[0].fitness_winrate,
"best_max_dd": population[0].fitness_max_dd,
"best_pf": population[0].fitness_profit_factor,
"gen_time": gen_time,
"total_time": time.time() - start_time,
}
generation_stats.append(stat)
print(f"Gen {gen+1:3d}/{n_generations} | Best: {stat['best_score']:.3f} | "
f"Sharpe: {stat['best_sharpe']:.3f} | Return: {stat['best_return']:.1f}% | "
f"Trades: {stat['best_trades']} | Time: {gen_time:.1f}s")
if progress_callback:
progress_callback(gen + 1, n_generations, stat)
# Selection + new generation
if gen < n_generations - 1:
new_population = list(map(copy.deepcopy, population[:elite_size]))
while len(new_population) < pop_size:
t1 = random.sample(population, min(tournament_size, len(population)))
parent1 = max(t1, key=lambda s: s.fitness_score)
t2 = random.sample(population, min(tournament_size, len(population)))
parent2 = max(t2, key=lambda s: s.fitness_score)
if random.random() < p_crossover:
child1, child2 = crossover(parent1, parent2)
else:
child1, child2 = copy.deepcopy(parent1), copy.deepcopy(parent2)
if random.random() < p_mutation:
child1 = mutate(child1, df_train, min_entry, max_entry, min_exit, max_exit)
if random.random() < p_mutation:
child2 = mutate(child2, df_train, min_entry, max_entry, min_exit, max_exit)
new_population.append(child1)
if len(new_population) < pop_size:
new_population.append(child2)
population = new_population
top_strategies = sorted(population, key=lambda s: s.fitness_score, reverse=True)[:20]
if df_val is not None:
print("\nValidating top strategies on out-of-sample data...")
for strat in top_strategies:
val_metrics = backtest_strategy(strat, df_val, cache_val)
strat.val_return = val_metrics["total_return"]
strat.val_sharpe = val_metrics["sharpe"]
strat.val_score = compute_fitness_score(val_metrics)