Repository navigation
Expand file tree
/
Copy pathcdf.py
More file actions
4554 lines (4003 loc) · 169 KB
/
Copy pathcdf.py
File metadata and controls
4554 lines (4003 loc) · 169 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
"""Consolidation Detection Framework.
CDF is a research-oriented Python framework by James Sawyer for detecting
consolidation regimes in OHLC time series, optimizing detector parameters with
rolling-origin validation, and exporting diagnostic dashboards for review.
The module keeps the full workflow in one reference implementation: data
loading, feature engineering, parameter search, consolidation scoring,
breakout estimation, probability calibration, and visualization.
Project notes and related research:
https://labs.jamessawyer.co.uk/
"""
import hashlib
import html
import inspect
import json
import logging
import random
import sys
from dataclasses import dataclass, replace
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any
import numpy as np
import optuna
import pandas as pd
from optuna.pruners import MedianPruner
from optuna.samplers import TPESampler
from sklearn.metrics import f1_score, precision_score, recall_score
try:
from backtest_loader import load_backtest_prices
except ImportError:
load_backtest_prices = None
# =============================================================================
# CONFIGURATION - ALL VARIABLES AT TOP OF FILE
# =============================================================================
# Data configuration
DATA_FILE_PATH = None
TIMESTAMP_COLUMN = "snapshotTime"
DATETIME_FORMAT = "%Y:%m:%d-%H:%M:%S"
OPEN_COLUMN = "open"
HIGH_COLUMN = "high"
LOW_COLUMN = "low"
CLOSE_COLUMN = "close"
REJECT_STALE_BACKTEST_DATA = False
MAX_BACKTEST_CSV_AGE_HOURS = 2.0
# Optimization configuration
OPTIMIZATION_TRIALS = 100
VALIDATION_SPLITS = 5
RANDOM_SEED = 42
OPTIMIZATION_DIRECTION = "maximize"
STABILITY_PENALTY_WEIGHT = 0.15
MIN_VALIDATION_FOLDS = 2
ROLLING_CV_TRAIN_WINDOW_MULTIPLIER = 3
PROBABILITY_CALIBRATION_ENABLED = True
PROBABILITY_CALIBRATION_BINS = 7
PROBABILITY_CALIBRATION_MIN_SAMPLES = 25
PROBABILITY_CALIBRATION_BLEND = 0.65
# Feature calculation periods
SHORT_PERIODS = [5, 10]
MEDIUM_PERIODS = [20, 50]
LONG_PERIODS = [100]
# Consolidation detection bounds
MIN_LOOKBACK = 5
MAX_LOOKBACK = 50
MIN_LOOKFORWARD = 5
MAX_LOOKFORWARD = 30
MIN_CONSOLIDATION_BARS = 3
MAX_CONSOLIDATION_BARS = 15
MIN_CONSOLIDATION_THRESHOLD = 0.10
MAX_CONSOLIDATION_THRESHOLD = 0.50
# Weight bounds for optimization
MIN_WEIGHT = 0.1
MAX_WEIGHT = 0.5
# Breakout prediction bounds
MIN_HOLD_PERIODS = 5
MAX_HOLD_PERIODS = 30
MIN_LOGISTIC_STEEPNESS = 1.0
MAX_LOGISTIC_STEEPNESS = 5.0
MIN_LOGISTIC_THRESHOLD = 0.3
MAX_LOGISTIC_THRESHOLD = 1.5
HOLD_DURATION_MULTIPLIER = 1.5
# Hurst feature configuration
HURST_DEFAULT = 0.5
HURST_MIN_POINTS = 20
HURST_MIN_LAG = 2
HURST_MAX_LAG = 20
HURST_NON_PERSISTENT_THRESHOLD = 0.50
HURST_PERSISTENCE_PENALTY_MAX = 0.70
# Probability uncertainty configuration
PROBABILITY_CI_BOOTSTRAP_SAMPLES = 500
PROBABILITY_CI_LOW = 5.0
PROBABILITY_CI_MEDIAN = 50.0
PROBABILITY_CI_HIGH = 95.0
# Regime diagnostics
REGIME_RECENT_WINDOW = 20
REGIME_BASELINE_WINDOW = 80
REGIME_SHIFT_HIGH_THRESHOLD = 1.5
REGIME_SHIFT_LOW_THRESHOLD = 0.67
REGIME_EW_HALF_LIFE = 20
# Dashboard configuration
DASHBOARD_ENABLED = True
# Set adaptive dashboard windows to None so each panel uses the full dataset span
# unless a caller explicitly overrides it.
DASHBOARD_DAYS_BACK = None
DASHBOARD_HEIGHT = 1225
DASHBOARD_HEATMAP_DAYS = None
DASHBOARD_FORECAST_BARS = None
DASHBOARD_MAX_ZONES = None
DASHBOARD_MAX_COMPONENT_POINTS = None
DASHBOARD_SIGNAL_PROBABILITY_THRESHOLD = 0.55
DASHBOARD_OUTPUT_DIR = "results"
DASHBOARD_OUTPUT_NAME = "consolidation_dashboard_latest.html"
# Logging configuration
LOG_LEVEL = "INFO"
LOG_FORMAT = "%(asctime)s | %(levelname)-8s | %(name)s | %(message)s"
LOG_DATE_FORMAT = "%Y-%m-%d %H:%M:%S"
# Numerical stability configuration
PRICE_EPSILON = 1e-10
# Robust context similarity configuration
CONTEXT_WEIGHT_DEFAULT = 1.0
CONTEXT_SCALE_CLIP = 5.0
CONTEXT_IQR_TO_STD = 1.349
CONTEXT_MAD_TO_STD = 1.4826
# Alpha-Sutte configuration
SUTTE_MA_PERIOD = 3
SUTTE_WEIGHT = 0.35
SUTTE_THRESHOLD = 0.02
SUTTE_MIN_HISTORY = 10
SUTTE_SCORE_TYPICAL_MIN = 0.30
SUTTE_SCORE_TYPICAL_MAX = 0.80
SUTTE_DIVERGENCE_WINDOW = 20
SUTTE_DIVERGENCE_SIGNAL_THRESHOLD = 0.10
SUTTE_CONFIDENCE_BOOST = 0.30
SUTTE_CONFIDENCE_PENALTY = 0.50
# LSTNet-inspired detector enhancements
ATTENTION_HISTORY_MULTIPLIER = 8
ATTENTION_MIN_HISTORY_BARS = 20
ATTENTION_TOP_K = 12
ATTENTION_TEMPERATURE = 0.35
PERIODIC_TOP_K = 8
PERIODIC_TEMPERATURE = 0.20
AUTOREGRESSIVE_MAX_LAGS = 3
AUTOREGRESSIVE_MIN_SAMPLES = 10
AUTOREGRESSIVE_TOLERANCE = 0.75
BREAKOUT_CONTEXT_BONUS = 0.35
AUTO_CALIBRATE_THRESHOLD_ON_EMPTY = True
AUTO_CALIBRATION_PERCENTILE = 70.0
THRESHOLD_DIAGNOSTIC_SAMPLE_SIZE = 500
THRESHOLD_DIAGNOSTIC_LEVELS = (0.10, 0.20, 0.30, 0.40, 0.50)
ATTENTION_SCORE_TYPICAL_MIN = 0.30
ATTENTION_SCORE_TYPICAL_MAX = 0.80
PERIODIC_SCORE_TYPICAL_MIN = 0.30
PERIODIC_SCORE_TYPICAL_MAX = 0.80
SCALE_SCORE_TYPICAL_MIN = 0.30
SCALE_SCORE_TYPICAL_MAX = 0.80
ATTENTION_CONTEXT_WEIGHTS = {
"hl_range_pct": 1.10,
"oc_range_pct": 0.90,
"vol_ratio_20": 1.30,
"trend_strength_5": 0.85,
"trend_strength_20": 1.10,
"hurst_20": 1.25,
"rsi_5": 0.70,
"rsi_20": 0.85,
"body_to_range_ratio": 1.10,
"wick_balance": 1.00,
"sutte_signal": 1.15,
"sutte_conviction": 1.05,
"minute_sin": 0.50,
"minute_cos": 0.50,
"dow_sin": 0.35,
"dow_cos": 0.35,
}
PERIODIC_CONTEXT_WEIGHTS = {
"minute_sin": 1.00,
"minute_cos": 1.00,
"dow_sin": 0.80,
"dow_cos": 0.80,
}
# Context vector definitions
ATTENTION_CONTEXT_COLUMNS = (
"hl_range_pct",
"oc_range_pct",
"vol_ratio_20",
"trend_strength_5",
"trend_strength_20",
"hurst_20",
"rsi_5",
"rsi_20",
"body_to_range_ratio",
"wick_balance",
"sutte_signal",
"sutte_conviction",
"minute_sin",
"minute_cos",
"dow_sin",
"dow_cos",
)
PERIODIC_CONTEXT_COLUMNS = (
"minute_sin",
"minute_cos",
"dow_sin",
"dow_cos",
)
# =============================================================================
# LOGGING SETUP
# =============================================================================
def configure_logging(name: str = __name__, level: str = LOG_LEVEL) -> logging.Logger:
"""Configure module-level logging."""
level_map = {
"DEBUG": logging.DEBUG,
"INFO": logging.INFO,
"WARNING": logging.WARNING,
"ERROR": logging.ERROR,
}
module_logger = logging.getLogger(name)
if not module_logger.handlers:
handler = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter(LOG_FORMAT, datefmt=LOG_DATE_FORMAT)
handler.setFormatter(formatter)
module_logger.addHandler(handler)
module_logger.setLevel(level_map.get(level.upper(), logging.INFO))
module_logger.propagate = False
logging.getLogger("optuna").setLevel(logging.WARNING)
return module_logger
logger = configure_logging()
def setup_random_seed(seed: int = RANDOM_SEED) -> None:
"""Seed deterministic generators used by optimization and diagnostics."""
random.seed(seed)
np.random.seed(seed)
logger.debug("Seeded random generators with seed=%d", seed)
def _build_rolling_origin_splits(
df_length: int,
n_splits: int,
train_window_multiplier: int = ROLLING_CV_TRAIN_WINDOW_MULTIPLIER,
) -> list[tuple[np.ndarray, np.ndarray]]:
"""Build contiguous rolling-origin splits with a fixed training window."""
safe_length = max(0, int(df_length))
safe_splits = max(1, int(n_splits))
safe_multiplier = max(1, int(train_window_multiplier))
total_buckets = safe_splits + safe_multiplier
if safe_length <= total_buckets:
raise ValueError(
f"Insufficient rows for rolling CV: rows={safe_length}, required>{total_buckets}."
)
validation_window = max(1, safe_length // total_buckets)
train_window = safe_length - validation_window * safe_splits
if train_window < validation_window:
raise ValueError(
"Rolling CV could not allocate a fixed training window: "
f"rows={safe_length}, splits={safe_splits}, "
f"train_window={train_window}, validation_window={validation_window}."
)
splits: list[tuple[np.ndarray, np.ndarray]] = []
for split_idx in range(safe_splits):
train_start = split_idx * validation_window
train_end = train_start + train_window
val_start = train_end
val_end = val_start + validation_window
if split_idx == safe_splits - 1:
val_end = safe_length
if train_end > safe_length or val_start >= safe_length:
break
train_idx = np.arange(train_start, train_end, dtype=np.int64)
val_idx = np.arange(val_start, min(val_end, safe_length), dtype=np.int64)
if train_idx.size == 0 or val_idx.size == 0:
continue
splits.append((train_idx, val_idx))
if len(splits) < safe_splits:
raise ValueError(
f"Rolling CV produced too few splits: requested={safe_splits}, produced={len(splits)}."
)
return splits
# =============================================================================
# DATA STRUCTURES
# =============================================================================
@dataclass
class ConsolidationFeatures:
"""Container for consolidation detection features."""
start_idx: int
end_idx: int
duration: int
range_width: float
range_width_pct: float
volatility_ratio: float
mean_reversion_strength: float
hurst_exponent: float
consolidation_score: float = 0.0
attention_context_score_raw: float = 0.5
periodic_context_score_raw: float = 0.5
scale_anchor_score_raw: float = 0.5
attention_context_score: float = 0.5
periodic_context_score: float = 0.5
scale_anchor_score: float = 0.5
sutte_score_raw: float = 0.5
sutte_score: float = 0.5
sutte_divergence: float = 0.0
sutte_divergence_confidence: float = 0.0
sutte_divergence_signal: str = "NEUTRAL"
interaction_score: float = 0.0
timestamp_start: datetime | None = None
timestamp_end: datetime | None = None
def to_dict(self) -> dict[str, Any]:
"""Convert to dictionary for serialization."""
return {
"start_idx": self.start_idx,
"end_idx": self.end_idx,
"duration": self.duration,
"range_width": self.range_width,
"range_width_pct": self.range_width_pct,
"volatility_ratio": self.volatility_ratio,
"hurst_exponent": self.hurst_exponent,
"consolidation_score": self.consolidation_score,
"attention_context_score_raw": self.attention_context_score_raw,
"periodic_context_score_raw": self.periodic_context_score_raw,
"scale_anchor_score_raw": self.scale_anchor_score_raw,
"attention_context_score": self.attention_context_score,
"periodic_context_score": self.periodic_context_score,
"scale_anchor_score": self.scale_anchor_score,
"sutte_score_raw": self.sutte_score_raw,
"sutte_score": self.sutte_score,
"sutte_divergence": self.sutte_divergence,
"sutte_divergence_confidence": self.sutte_divergence_confidence,
"sutte_divergence_signal": self.sutte_divergence_signal,
"interaction_score": self.interaction_score,
}
@dataclass
class OptimizationParams:
"""Container for optimized parameters."""
lookback_period: int
lookforward_period: int
min_bars: int
range_threshold: float
position_sensitivity: float
consolidation_threshold: float
min_expansion: float
weight_contraction: float
weight_range: float
weight_position: float
weight_hurst: float
max_hold: int
logistic_steepness: float
logistic_threshold: float
weight_periodic: float = 0.0
weight_attention: float = 0.0
weight_scale: float = 0.0
weight_sutte: float = SUTTE_WEIGHT
def to_dict(self) -> dict[str, Any]:
"""Convert to dictionary for serialization."""
return {k: v for k, v in self.__dict__.items()}
def get_hash(self) -> str:
"""Generate deterministic hash of parameters."""
param_string = json.dumps(self.to_dict(), sort_keys=True)
return hashlib.sha256(param_string.encode()).hexdigest()[:8]
# =============================================================================
# FEATURE ENGINEERING
# =============================================================================
class FeatureEngineer:
"""Calculate technical features from OHLC data."""
def __init__(self, df: pd.DataFrame):
"""
Initialize feature engineer with OHLC dataframe.
Args:
df: DataFrame with OHLC columns
"""
self.df = df.copy()
self.logger = logging.getLogger(__name__)
def calculate_all_features(self) -> pd.DataFrame:
"""Calculate complete feature set from OHLC data."""
self.logger.info("Calculating features from OHLC data")
self._calculate_price_features()
self._calculate_volatility_features()
self._calculate_momentum_features()
self._calculate_statistical_features()
self._calculate_sutte_features()
# Keep rows usable by downstream detector/predictor while tolerating
# partial NaNs in non-critical engineered features.
self.df.replace([np.inf, -np.inf], np.nan, inplace=True)
self.df.dropna(axis=1, how="all", inplace=True)
required = [OPEN_COLUMN, HIGH_COLUMN, LOW_COLUMN, CLOSE_COLUMN, "hl_range_pct"]
self.df = self.df.dropna(subset=required)
if self.df.empty:
raise ValueError(
"Feature engineering produced an empty dataset. "
"Increase input history or reduce feature windows."
)
self.logger.debug(f"Feature calculation complete. Shape: {self.df.shape}")
return self.df
def _calculate_price_features(self) -> None:
"""Calculate basic price-derived features."""
self.df["typical_price"] = (self.df["high"] + self.df["low"] + self.df["close"]) / 3
self.df["hl_range"] = self.df["high"] - self.df["low"]
self.df["hl_range_pct"] = (self.df["hl_range"] / self.df["close"]) * 100
self.df["oc_range"] = abs(self.df["open"] - self.df["close"])
self.df["oc_range_pct"] = (self.df["oc_range"] / self.df["close"]) * 100
self.df["volume_proxy"] = self.df["hl_range"] * self.df["hl_range_pct"]
self.df["body_size"] = self.df["oc_range"]
self.df["upper_wick"] = self.df["high"] - self.df[["open", "close"]].max(axis=1)
self.df["lower_wick"] = self.df[["open", "close"]].min(axis=1) - self.df["low"]
self.df["body_to_range_ratio"] = self.df["body_size"] / (
self.df["hl_range"] + PRICE_EPSILON
)
self.df["wick_balance"] = 1.0 - (
abs(self.df["upper_wick"] - self.df["lower_wick"])
/ (self.df["hl_range"] + PRICE_EPSILON)
)
self.df["wick_balance"] = self.df["wick_balance"].clip(0.0, 1.0)
self._calculate_temporal_context_features()
def _calculate_temporal_context_features(self) -> None:
"""Add intraday and weekly context features for regime diagnostics."""
if not isinstance(self.df.index, pd.DatetimeIndex):
return
self.df["hour_utc"] = self.df.index.hour.astype(np.float64)
self.df["day_of_week"] = self.df.index.dayofweek.astype(np.float64)
self.df["minute_of_day"] = (self.df.index.hour * 60 + self.df.index.minute).astype(
np.float64
)
hour_radians = 2.0 * np.pi * self.df["hour_utc"] / 24.0
self.df["hour_sin"] = np.sin(hour_radians)
self.df["hour_cos"] = np.cos(hour_radians)
minute_radians = 2.0 * np.pi * self.df["minute_of_day"] / (24.0 * 60.0)
self.df["minute_sin"] = np.sin(minute_radians)
self.df["minute_cos"] = np.cos(minute_radians)
day_radians = 2.0 * np.pi * self.df["day_of_week"] / 7.0
self.df["dow_sin"] = np.sin(day_radians)
self.df["dow_cos"] = np.cos(day_radians)
def _calculate_volatility_features(self) -> None:
"""Calculate volatility metrics across multiple periods."""
all_periods = SHORT_PERIODS + MEDIUM_PERIODS + LONG_PERIODS
self.df["log_return"] = np.log(self.df["close"] / self.df["close"].shift(1))
for period in all_periods:
self.df[f"high_{period}"] = self.df["high"].rolling(period).max()
self.df[f"low_{period}"] = self.df["low"].rolling(period).min()
self.df[f"range_width_{period}"] = self.df[f"high_{period}"] - self.df[f"low_{period}"]
self.df[f"range_width_pct_{period}"] = (
self.df[f"range_width_{period}"] / self.df["close"] * 100
)
self.df[f"vol_ratio_{period}"] = (
self.df["hl_range_pct"].rolling(period, min_periods=period).mean()
/ self.df["hl_range_pct"].rolling(period * 3, min_periods=period).mean()
)
self.df[f"price_position_{period}"] = (self.df["close"] - self.df[f"low_{period}"]) / (
self.df[f"range_width_{period}"] + PRICE_EPSILON
)
self.df[f"realized_vol_{period}"] = self.df["log_return"].rolling(
period
).std() * np.sqrt(252)
def _calculate_momentum_features(self) -> None:
"""Calculate momentum and trend features."""
for period in SHORT_PERIODS + MEDIUM_PERIODS:
self.df[f"roc_{period}"] = self.df["close"].pct_change(period) * 100
self.df[f"rsi_{period}"] = self._calculate_rsi(period)
self.df[f"momentum_{period}"] = self.df["close"] - self.df["close"].shift(period)
self.df[f"trend_strength_{period}"] = abs(
self.df[f"roc_{period}"].rolling(period).mean()
) / (self.df["hl_range_pct"].rolling(period).mean() + PRICE_EPSILON)
def _calculate_rsi(self, period: int) -> pd.Series:
"""Calculate Relative Strength Index."""
delta = self.df["close"].diff()
gain = (delta.where(delta > 0, 0)).rolling(period).mean()
loss = (-delta.where(delta < 0, 0)).rolling(period).mean()
rs = gain / loss
rsi = 100 - (100 / (1 + rs))
return rsi
def _calculate_statistical_features(self) -> None:
"""Calculate advanced statistical features."""
for period in MEDIUM_PERIODS:
rolling_mean = self.df["close"].rolling(period).mean()
rolling_std = self.df["close"].rolling(period).std()
self.df[f"zscore_{period}"] = (self.df["close"] - rolling_mean) / rolling_std
self.df[f"hurst_{period}"] = self._calculate_hurst(period)
def _calculate_sutte_features(self) -> None:
"""Calculate Alpha-Sutte candle structure features."""
self.df["sutte_low_ratio"] = self.df["close"] / (self.df["low"] + PRICE_EPSILON)
self.df["sutte_high_ratio"] = self.df["close"] / (self.df["high"] + PRICE_EPSILON)
self.df["sutte_low_ma"] = (
self.df["sutte_low_ratio"]
.rolling(
window=SUTTE_MA_PERIOD,
min_periods=2,
)
.mean()
)
self.df["sutte_high_ma"] = (
self.df["sutte_high_ratio"]
.rolling(
window=SUTTE_MA_PERIOD,
min_periods=2,
)
.mean()
)
self.df["sutte_signal"] = (self.df["sutte_low_ma"] - self.df["sutte_high_ma"]) / (
self.df["sutte_low_ma"] + self.df["sutte_high_ma"] + PRICE_EPSILON
)
self.df["sutte_conviction"] = self.df["sutte_signal"].abs().clip(0.0, 1.0)
self.df["sutte_direction"] = np.where(
self.df["sutte_signal"] > SUTTE_THRESHOLD,
1,
np.where(self.df["sutte_signal"] < -SUTTE_THRESHOLD, -1, 0),
)
# Exponential smoothing keeps a faster-reacting variant available for live diagnostics.
self.df["sutte_adaptive_low"] = (
self.df["sutte_low_ratio"]
.ewm(
span=SUTTE_MA_PERIOD,
adjust=False,
)
.mean()
)
self.df["sutte_adaptive_high"] = (
self.df["sutte_high_ratio"]
.ewm(
span=SUTTE_MA_PERIOD,
adjust=False,
)
.mean()
)
self.df["sutte_adaptive_signal"] = (
self.df["sutte_adaptive_low"] - self.df["sutte_adaptive_high"]
) / (self.df["sutte_adaptive_low"] + self.df["sutte_adaptive_high"] + PRICE_EPSILON)
def _calculate_hurst(self, period: int) -> pd.Series:
"""Calculate rolling Hurst exponent with bounded lag set."""
prices = self.df["close"].to_numpy(dtype=np.float64, copy=False)
hurst = np.full(len(prices), HURST_DEFAULT, dtype=np.float64)
for i in range(period, len(prices)):
window = prices[i - period : i]
if len(window) < HURST_MIN_POINTS:
continue
max_lag = min(HURST_MAX_LAG, len(window) // 2)
if max_lag <= HURST_MIN_LAG:
continue
lags: list[int] = []
tau_vals: list[float] = []
for lag in range(HURST_MIN_LAG, max_lag + 1):
diffs = window[lag:] - window[:-lag]
tau = np.float64(np.std(diffs))
if np.isfinite(tau) and tau > 0.0:
lags.append(lag)
tau_vals.append(tau)
if len(tau_vals) < 2:
continue
try:
slope, _ = np.polyfit(np.log(lags), np.log(tau_vals), 1)
except (np.linalg.LinAlgError, ValueError, FloatingPointError):
continue
if np.isfinite(slope):
hurst[i] = np.float64(slope)
return pd.Series(hurst, index=self.df.index, dtype=np.float64)
# =============================================================================
# CONSOLIDATION DETECTOR
# =============================================================================
class ConsolidationDetector:
"""Detect consolidation zones using statistical methods."""
def __init__(self, params: OptimizationParams):
"""
Initialize detector with optimized parameters.
Args:
params: Optimized parameters for detection
"""
self.params = params
self.logger = logging.getLogger(__name__)
def detect(self, df: pd.DataFrame) -> list[ConsolidationFeatures]:
"""
Identify consolidation zones in the data.
Args:
df: DataFrame with calculated features
Returns:
List of consolidation features
"""
self.logger.info(f"Detecting consolidations with parameters: {self.params.get_hash()}")
consolidations = []
for i in range(len(df)):
cons = self._evaluate_window(df, i)
if cons is not None:
consolidations.append(cons)
self.logger.info(f"Found {len(consolidations)} consolidation zones")
return consolidations
def _normalize_component_score(
self,
score: float,
typical_min: float,
typical_max: float,
) -> float:
"""Rescale a bounded component score to a more useful 0-1 range."""
if typical_max <= typical_min:
return np.float64(min(max(score, 0.0), 1.0))
if score <= typical_min:
return 0.0
if score >= typical_max:
return 1.0
return np.float64((score - typical_min) / (typical_max - typical_min))
def _get_history_bounds(self, start_idx: int, lookback: int) -> tuple[int, int]:
"""Return the non-overlapping history span used for context matching."""
history_end = max(0, start_idx)
history_span = max(ATTENTION_MIN_HISTORY_BARS, lookback * ATTENTION_HISTORY_MULTIPLIER)
history_start = max(0, history_end - history_span)
return history_start, history_end
def _build_context_vector(self, row: pd.Series, columns: tuple[str, ...]) -> np.ndarray:
"""Return a stable numeric feature vector for similarity matching."""
values: list[float] = []
for col in columns:
raw_value = row[col] if col in row.index else 0.0
value = np.float64(raw_value) if pd.notna(raw_value) else 0.0
if not np.isfinite(value):
value = 0.0
values.append(value)
return np.asarray(values, dtype=np.float64)
def _resolve_context_weights(self, columns: tuple[str, ...]) -> np.ndarray:
"""Return per-feature weights for a given context family."""
if columns == ATTENTION_CONTEXT_COLUMNS:
weight_map = ATTENTION_CONTEXT_WEIGHTS
elif columns == PERIODIC_CONTEXT_COLUMNS:
weight_map = PERIODIC_CONTEXT_WEIGHTS
else:
weight_map = {}
return np.asarray(
[np.float64(weight_map.get(col, CONTEXT_WEIGHT_DEFAULT)) for col in columns],
dtype=np.float64,
)
def _build_context_statistics(
self,
history_frame: pd.DataFrame,
columns: tuple[str, ...],
) -> tuple[np.ndarray, np.ndarray]:
"""Estimate robust per-feature centers and scales from the matching history."""
centers: list[float] = []
scales: list[float] = []
for col in columns:
if col not in history_frame.columns:
centers.append(0.0)
scales.append(1.0)
continue
series = pd.to_numeric(history_frame[col], errors="coerce")
values = (
series.replace([np.inf, -np.inf], np.nan)
.dropna()
.to_numpy(dtype=np.float64, copy=False)
)
if values.size == 0:
centers.append(0.0)
scales.append(1.0)
continue
median_value = np.float64(np.median(values))
q1_value, q3_value = np.percentile(values, [25.0, 75.0])
iqr_scale = np.float64((q3_value - q1_value) / CONTEXT_IQR_TO_STD)
mad_scale = np.float64(CONTEXT_MAD_TO_STD * np.median(np.abs(values - median_value)))
robust_scale = max(iqr_scale, mad_scale)
if not np.isfinite(robust_scale) or robust_scale <= PRICE_EPSILON:
std_scale = np.float64(np.std(values))
robust_scale = std_scale if std_scale > PRICE_EPSILON else 1.0
centers.append(median_value)
scales.append(robust_scale)
return np.asarray(centers, dtype=np.float64), np.asarray(scales, dtype=np.float64)
def _scale_context_vector(
self,
vector: np.ndarray,
centers: np.ndarray,
scales: np.ndarray,
) -> np.ndarray:
"""Robust-scale a context vector to reduce dominance from high-variance features."""
safe_scales = np.where(scales > PRICE_EPSILON, scales, 1.0)
scaled = (vector - centers) / safe_scales
return np.clip(scaled, -CONTEXT_SCALE_CLIP, CONTEXT_SCALE_CLIP)
def _normalized_distance(
self,
left: np.ndarray,
right: np.ndarray,
weights: np.ndarray,
) -> float:
"""Measure weighted L1 distance between already robust-scaled context vectors."""
total_weight = np.float64(np.sum(weights))
if total_weight <= PRICE_EPSILON:
return 0.0
return np.float64(np.sum(weights * np.abs(left - right)) / total_weight)
def _hurst_non_persistence_score(self, hurst_value: float) -> float:
"""Reward non-persistent regimes while penalizing persistence above 0.5."""
value = np.float64(hurst_value)
if not np.isfinite(value):
return 0.5
if value <= HURST_NON_PERSISTENT_THRESHOLD:
return 1.0
if value >= HURST_PERSISTENCE_PENALTY_MAX:
return 0.0
penalty_progress = (value - HURST_NON_PERSISTENT_THRESHOLD) / (
HURST_PERSISTENCE_PENALTY_MAX - HURST_NON_PERSISTENT_THRESHOLD
)
return np.float64(1.0 - penalty_progress)
def _row_compression_signature(self, row: pd.Series) -> float:
"""Approximate how consolidation-like a row looks using local features."""
components: list[float] = []
vol_ratio = row.get("vol_ratio_20")
if pd.notna(vol_ratio):
components.append(1.0 - min(max(np.float64(vol_ratio), 0.0), 2.0) / 2.0)
body_to_range = row.get("body_to_range_ratio")
if pd.notna(body_to_range):
components.append(1.0 - min(max(np.float64(body_to_range), 0.0), 1.0))
wick_balance = row.get("wick_balance")
if pd.notna(wick_balance):
components.append(min(max(np.float64(wick_balance), 0.0), 1.0))
trend_strength = row.get("trend_strength_20")
if pd.notna(trend_strength):
components.append(1.0 - min(abs(np.float64(trend_strength)) / 2.0, 1.0))
hurst_value = row.get("hurst_20")
if pd.notna(hurst_value):
components.append(self._hurst_non_persistence_score(np.float64(hurst_value)))
if not components:
return 0.5
return np.float64(np.mean(components))
def _similarity_weighted_history_score(
self,
df: pd.DataFrame,
reference_idx: int,
start_idx: int,
lookback: int,
columns: tuple[str, ...],
top_k: int,
temperature: float,
) -> float:
"""Aggregate compression signatures from similar historical contexts."""
history_start, history_end = self._get_history_bounds(start_idx, lookback)
if history_end - history_start < self.params.min_bars:
return 0.5
history_frame = df.iloc[history_start:history_end]
centers, scales = self._build_context_statistics(history_frame, columns)
weights = self._resolve_context_weights(columns)
reference_vector = self._scale_context_vector(
self._build_context_vector(df.iloc[reference_idx], columns),
centers,
scales,
)
weighted_signatures: list[tuple[float, float]] = []
for candidate_idx in range(history_start, history_end):
candidate_row = df.iloc[candidate_idx]
candidate_vector = self._scale_context_vector(
self._build_context_vector(candidate_row, columns),
centers,
scales,
)
distance = self._normalized_distance(reference_vector, candidate_vector, weights)
weight = np.float64(np.exp(-distance / max(temperature, PRICE_EPSILON)))
signature = self._row_compression_signature(candidate_row)
weighted_signatures.append((weight, signature))
if not weighted_signatures:
return 0.5
weighted_signatures.sort(key=lambda item: item[0], reverse=True)
top_matches = weighted_signatures[:top_k]
total_weight = sum(weight for weight, _ in top_matches)
if total_weight <= PRICE_EPSILON:
return 0.5
weighted_sum = sum(weight * signature for weight, signature in top_matches)
return np.float64(weighted_sum / total_weight)
def _calculate_attention_context_score(
self,
df: pd.DataFrame,
reference_idx: int,
start_idx: int,
lookback: int,
) -> float:
"""Approximate temporal attention using feature-space similarity."""
return self._similarity_weighted_history_score(
df=df,
reference_idx=reference_idx,
start_idx=start_idx,
lookback=lookback,
columns=ATTENTION_CONTEXT_COLUMNS,
top_k=ATTENTION_TOP_K,
temperature=ATTENTION_TEMPERATURE,
)
def _calculate_periodic_context_score(
self,
df: pd.DataFrame,
reference_idx: int,
start_idx: int,
lookback: int,
) -> float:
"""Approximate periodic skip-memory using time-phase similarity."""
if "minute_sin" not in df.columns or "dow_sin" not in df.columns:
return 0.5
return self._similarity_weighted_history_score(
df=df,
reference_idx=reference_idx,
start_idx=start_idx,
lookback=lookback,
columns=PERIODIC_CONTEXT_COLUMNS,
top_k=PERIODIC_TOP_K,
temperature=PERIODIC_TEMPERATURE,
)
def _calculate_price_positions(
self,
df: pd.DataFrame,
start_idx: int,
end_idx: int,
) -> list[float]:
"""Track how tightly price stays within the growing local range."""
positions: list[float] = []
for row_idx in range(start_idx, end_idx + 1):
pos_window = df.iloc[start_idx : row_idx + 1]
pos_range = pos_window["high"].max() - pos_window["low"].min()
if pos_range <= 0:
continue
pos = (df["close"].iloc[row_idx] - pos_window["low"].min()) / pos_range
positions.append(np.float64(pos))
return positions
def _calculate_interaction_score(self, window: pd.DataFrame) -> float:
"""Measure candle compression from joint OHLC interactions."""
if "body_to_range_ratio" not in window.columns or "wick_balance" not in window.columns:
return 0.5
body_compression = 1.0 - min(
max(np.float64(window["body_to_range_ratio"].mean()), 0.0), 1.0
)
wick_balance = min(max(np.float64(window["wick_balance"].mean()), 0.0), 1.0)
return np.float64((body_compression + wick_balance) / 2.0)
def _calculate_sutte_score(self, window: pd.DataFrame) -> float:
"""Score Sutte signal strength, stability, and recent acceleration."""
if (
len(window) < SUTTE_MIN_HISTORY
or "sutte_conviction" not in window.columns
or window["sutte_conviction"].dropna().empty
):
return 0.5
conviction = window["sutte_conviction"].dropna()
mean_conviction = np.float64(conviction.mean())
consistency = 0.5
if "sutte_direction" in window.columns:
directions = window["sutte_direction"].dropna()
if len(directions) > 1:
direction_std = np.float64(directions.std())
consistency = 1.0 - min(direction_std, 1.0)
elif len(directions) == 1:
consistency = 1.0 if int(directions.iloc[0]) != 0 else 0.5
if len(conviction) >= 6:
recent_conviction = np.float64(conviction.iloc[-3:].mean())
earlier_conviction = np.float64(conviction.iloc[:3].mean())
conviction_trend = (recent_conviction - earlier_conviction) / (
earlier_conviction + PRICE_EPSILON
)
trend_score = 0.5 + np.clip(conviction_trend, -0.5, 0.5)
else:
trend_score = 0.5
score = 0.4 * mean_conviction + 0.3 * consistency + 0.3 * trend_score
return np.float64(min(max(score, 0.0), 1.0))
def assess_sutte_directional_alignment(
self,
df: pd.DataFrame,
consolidation_score: float,
window_size: int = SUTTE_DIVERGENCE_WINDOW,
) -> dict[str, Any]:
"""Detect agreement or divergence between Sutte bias and recent price direction."""
if (
"sutte_signal" not in df.columns
or "close" not in df.columns
or len(df) < max(2, SUTTE_MIN_HISTORY)
):
return {
"divergence": 0.0,
"signal": "NEUTRAL",
"confidence": 0.0,
"sutte_value": 0.0,
"price_trend": 0.0,
}