-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtechnical_analyzer.py
More file actions
1338 lines (1174 loc) · 87.4 KB
/
technical_analyzer.py
File metadata and controls
1338 lines (1174 loc) · 87.4 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
# --- START OF FILE technical_analyzer.py ---
import pandas as pd
import numpy as np
import logging
import re
# Importa config SOLO per le costanti, non altri moduli
try:
import config # type: ignore
except ImportError:
# Fallback se config.py non esiste o causa errori
class ConfigFallback:
RSI_PERIOD = 14
MACD_FAST = 12
MACD_SLOW = 26
MACD_SIGNAL = 9
BBANDS_PERIOD = 20
BBANDS_STDDEV = 2.0
ATR_PERIOD = 14
ADX_PERIOD = 14
SMA_PERIODS = [20, 50, 200]
EMA_PERIODS = [12, 26, 50]
# Aggiungiamo fallback per i nuovi parametri se config non carica
TA_VOLUME_SMA_SHORT = 10
TA_VOLUME_ZSCORE_PERIOD = 20
TA_UPDOWN_VOL_PERIOD = 10
TA_VWAP_ROLLING_PERIOD = 20
TA_VOLATILITY_PERCENTILE_PERIOD = 100
TA_ATR_TARGET_MULTIPLIERS = [1.0, 1.5, 2.0] # Esempio
config = ConfigFallback()
logging.warning("config.py non trovato o errore import. Uso valori di default per parametri TA.")
# Assicura che i parametri abbiano un fallback anche se config esiste ma manca la chiave
TA_VOLUME_SMA_SHORT = getattr(config, 'TA_VOLUME_SMA_SHORT', 10)
TA_VOLUME_ZSCORE_PERIOD = getattr(config, 'TA_VOLUME_ZSCORE_PERIOD', 20)
TA_UPDOWN_VOL_PERIOD = getattr(config, 'TA_UPDOWN_VOL_PERIOD', 10)
TA_VWAP_ROLLING_PERIOD = getattr(config, 'TA_VWAP_ROLLING_PERIOD', 20)
TA_VOLATILITY_PERCENTILE_PERIOD = getattr(config, 'TA_VOLATILITY_PERCENTILE_PERIOD', 100)
TA_ATR_TARGET_MULTIPLIERS = getattr(config, 'TA_ATR_TARGET_MULTIPLIERS', [1.0, 1.5, 2.0])
from typing import Dict, Any, List, Optional, Union, Callable
import sys # Per controllo numba
import time
import math # Per isnan
import scipy.stats as stats # Importato per percentileofscore
# Importa helper SOLO da statistical_analyzer_helpers
try:
from statistical_analyzer_helpers import safe_get_last_value, safe_get_value_at_index, _safe_get, _safe_float
HELPERS_LOADED = True
except ImportError:
logger_fallback = logging.getLogger(__name__)
logger_fallback.critical(
"ERRORE CRITICO: statistical_analyzer_helpers non trovato! "
"L'analisi tecnica fallirà. Assicurati che il file esista e sia nel PYTHONPATH."
)
HELPERS_LOADED = False
# Definizioni fittizie
def _safe_get(*args, **kwargs): return None
def safe_get_value_at_index(*args, **kwargs): return None
def safe_get_last_value(*args, **kwargs): return None
def _safe_float(*args, **kwargs): return None
# Importa pandas_ta
try:
import pandas_ta as ta
except ImportError:
logging.critical("ERRORE CRITICO: Libreria pandas_ta non trovata. Installala con: pip install pandas-ta")
ta = None
# Setup logging
logger = logging.getLogger(__name__)
class TechnicalAnalyzer:
"""
Calcola indicatori tecnici, S/R, trend, Volume Profile (incluso giornaliero/settimanale),
e feature tecniche combinate. Utilizza pandas_ta per i calcoli degli indicatori.
Include analisi volume, VWAP rolling, percentili volatilità e target ATR.
"""
def __init__(self, data: pd.DataFrame):
"""
Inizializza l'analizzatore tecnico.
"""
if not HELPERS_LOADED:
raise ImportError("statistical_analyzer_helpers non caricato. Impossibile inizializzare TechnicalAnalyzer.")
if data is None or data.empty: raise ValueError("Dati non validi per TechnicalAnalyzer.")
# Validazione indice e timezone
if not isinstance(data.index, pd.DatetimeIndex):
try: data.index = pd.to_datetime(data.index, utc=True)
except Exception as e: raise TypeError(f"Indice non DatetimeIndex in TA: {e}")
if data.index.tz is None or str(data.index.tz).upper() != 'UTC':
logger.warning("Indice non UTC in TA. Forzo UTC.")
try: data.index = data.index.tz_localize('UTC', ambiguous='infer') if data.index.tz is None else data.index.tz_convert('UTC')
except Exception as tz_err: raise TypeError(f"Errore forzatura UTC in TA: {tz_err}")
self.data = data.copy() # Lavora su copia
# Determina timeframe input
self.input_timeframe_delta: Optional[pd.Timedelta] = None
if len(self.data.index) > 1:
time_diffs = self.data.index.to_series().diff().dropna()
# Use median to be robust against missing candles
if not time_diffs.empty:
self.input_timeframe_delta = time_diffs.median()
else: # Fallback for only two data points
self.input_timeframe_delta = self.data.index[1] - self.data.index[0]
# Final check if delta is valid
if not isinstance(self.input_timeframe_delta, pd.Timedelta) or self.input_timeframe_delta <= pd.Timedelta(0):
self.input_timeframe_delta = None
logger.warning("Impossibile determinare un delta timeframe valido.")
logger.debug(f"Delta timeframe input rilevato: {self.input_timeframe_delta}")
# Normalizza nomi colonne e verifica/prepara OHLCV
self.data.columns = [str(col).lower().replace(' ','_') for col in self.data.columns]
required = ['open', 'high', 'low', 'close']
missing = [col for col in required if col not in self.data.columns]
if missing: raise ValueError(f"Colonne OHLC mancanti in TA: {missing}")
if 'volume' not in self.data.columns:
logger.warning("Colonna 'volume' mancante in TA. Aggiungo colonna volume=0.")
self.data['volume'] = 0.0
# Conversione numerica e dropna
for col in required + ['volume']:
if col in self.data.columns:
self.data[col] = pd.to_numeric(self.data[col], errors='coerce').astype(float)
initial_len = len(self.data)
self.data.dropna(subset=required, inplace=True)
rows_dropped = initial_len - len(self.data)
if rows_dropped > 0: logger.debug(f"TA: Rimossi {rows_dropped} righe con NaN in OHLC.")
if self.data.empty: raise ValueError("TA: Dati vuoti dopo rimozione NaN OHLC.")
self.results: Dict[str, Any] = {}
self._ensure_results_structure()
def _ensure_results_structure(self):
"""Assicura la struttura base del dizionario results."""
self.results.setdefault('technical_indicators', {})
self.results.setdefault('trend_analysis', {})
self.results.setdefault('support_resistance', {})
self.results.setdefault('volume_analysis', {}) # NUOVA SEZIONE
self.results.setdefault('volatility_analysis', {}) # NUOVA SEZIONE (per percentili)
self.results.setdefault('price_level_targets', {}) # NUOVA SEZIONE (per target ATR)
self.results.setdefault('volume_profile', {})
self.results.setdefault('volume_profile_periodic', {'daily': {}, 'weekly': {}})
self.results.setdefault('combined_features', {})
# --- Calcolo Indicatori (Helper e Specifici) ---
def _calculate_indicator(self, indicator_func: Callable, name: str, result_key: str, default_value: Any = None, **kwargs):
"""
Helper generico per calcolare indicatori con pandas_ta, aggiornare self.data
e preparare la voce base nel dizionario results.
"""
# (Codice invariato)
ti_dict = self.results.setdefault('technical_indicators', {})
is_dict_output = isinstance(default_value, dict)
# Initialize or clean the result entry
if result_key not in ti_dict:
ti_dict[result_key] = default_value
elif is_dict_output:
if isinstance(ti_dict.get(result_key), dict):
if isinstance(default_value, dict):
for k, v in default_value.items(): ti_dict[result_key].setdefault(k, v)
ti_dict[result_key].pop('error', None) # Clean previous error
else: # Overwrite if type mismatch
ti_dict[result_key] = default_value
if isinstance(ti_dict[result_key], dict): ti_dict[result_key].pop('error', None)
else: # Scalar output
ti_dict[result_key] = default_value # Reset to default
ti_dict.pop(f'{result_key}_error', None) # Clean previous scalar error
if ta is None:
error_msg = 'pandas_ta missing'
if is_dict_output and isinstance(ti_dict.get(result_key), dict): ti_dict[result_key]['error'] = error_msg
else: ti_dict[result_key] = None; ti_dict[f'{result_key}_error'] = error_msg
return
if self.data.empty:
error_msg = 'No data'
if is_dict_output and isinstance(ti_dict.get(result_key), dict): ti_dict[result_key]['error'] = error_msg
else: ti_dict[result_key] = None; ti_dict[f'{result_key}_error'] = error_msg
return
logger.debug(f"Calcolo {name} con parametri: {list(kwargs.keys())}")
try:
# Prepare arguments for pandas_ta function
relevant_kwargs = {}
input_cols = ['open', 'high', 'low', 'close', 'volume'] # Standard inputs
for col in input_cols:
if col in self.data.columns:
relevant_kwargs[col] = self.data[col] # Pass the whole series
# Pass specific parameters defined in the call
param_keys = ['length', 'fast', 'slow', 'signal', 'std', 'k', 'd', 'smooth_k', 'af', 'max_af', 'period'] # Common TA params
for key in param_keys:
if key in kwargs:
relevant_kwargs[key] = kwargs[key]
# Determine minimum length needed based on parameters (best effort)
period_arg = 14 # Default reasonable period
relevant_periods = [v for k, v in relevant_kwargs.items() if k in ['length', 'slow', 'k', 'period'] and isinstance(v, int)]
if relevant_periods:
period_arg = max(relevant_periods)
min_len_needed = max(5, period_arg + 1) # General rule of thumb
# Specific indicator minimum lengths
if 'bbands' in name.lower(): min_len_needed = max(min_len_needed, relevant_kwargs.get('length', 20))
if 'macd' in name.lower(): min_len_needed = max(min_len_needed, relevant_kwargs.get('slow', 26) + relevant_kwargs.get('signal', 9))
if 'adx' in name.lower(): min_len_needed = max(min_len_needed, 2 * relevant_kwargs.get('length', 14)) # ADX needs more data
if 'stoch' in name.lower(): min_len_needed = max(min_len_needed, relevant_kwargs.get('k', 14) + relevant_kwargs.get('d', 3))
if 'psar' in name.lower(): min_len_needed = max(min_len_needed, 10) # PSAR needs some history
# Check available valid 'close' data points (or other primary series if needed)
primary_series_col = 'close' # Assume close is primary unless specified otherwise
if primary_series_col not in self.data.columns or len(self.data[primary_series_col].dropna()) < min_len_needed:
raise ValueError(f"Dati '{primary_series_col}' validi insufficienti ({len(self.data.get(primary_series_col, pd.Series()).dropna())} < {min_len_needed})")
# --- CALL PANDAS_TA INDICATOR FUNCTION ---
indicator_result = indicator_func(**relevant_kwargs)
# -----------------------------------------
if indicator_result is None:
raise ValueError(f"Funzione {name} ha restituito None.")
# --- APPEND RESULTS TO self.data (Robustly) ---
logger.debug(f"Tentativo append {name} a self.data...")
if isinstance(indicator_result, (pd.DataFrame, pd.Series)):
indicator_params = {k: v for k, v in kwargs.items() if k in param_keys}
indicator_method_name = indicator_func.__name__ # Get the function name (e.g., 'sma')
# Check if the method exists directly under df.ta
if hasattr(self.data.ta, indicator_method_name):
try:
# Try using the built-in append mechanism
getattr(self.data.ta, indicator_method_name)(**indicator_params, append=True)
logger.debug(f"Appended {indicator_method_name} using df.ta mechanism.")
except Exception as ta_append_err:
logger.warning(f"Errore append {indicator_method_name} con df.ta: {ta_append_err}. Tento aggiunta manuale.")
# Fallback to manual addition
if isinstance(indicator_result, pd.DataFrame):
for col in indicator_result.columns:
if col not in self.data.columns: self.data[col] = indicator_result[col]
else: self.data[col].fillna(indicator_result[col], inplace=True) # Update existing? Or overwrite? Use fillna for now.
elif isinstance(indicator_result, pd.Series):
col_name = indicator_result.name or result_key # Use series name or result_key as fallback
if col_name not in self.data.columns: self.data[col_name] = indicator_result
else: self.data[col_name].fillna(indicator_result, inplace=True)
else:
# Method not found under df.ta, add manually
logger.warning(f"Metodo 'ta.{indicator_method_name}' non trovato, aggiunta manuale colonne.")
if isinstance(indicator_result, pd.DataFrame):
for col in indicator_result.columns:
if col not in self.data.columns: self.data[col] = indicator_result[col]
else: self.data[col].fillna(indicator_result[col], inplace=True)
elif isinstance(indicator_result, pd.Series):
col_name = indicator_result.name or result_key
if col_name not in self.data.columns: self.data[col_name] = indicator_result
else: self.data[col_name].fillna(indicator_result, inplace=True)
logger.debug(f"Colonne DataFrame dopo {name}: {self.data.columns.tolist()}")
else:
# This case should ideally not happen if pandas_ta functions are used correctly
raise TypeError(f"Tipo risultato inatteso da {name}: {type(indicator_result)}")
# --- END APPEND ---
except ValueError as ve:
# Specific error, likely insufficient data or bad parameters
logger.warning(f"Calcolo {name} fallito (ValueError): {ve}"); error_msg = str(ve)
if is_dict_output and isinstance(ti_dict.get(result_key), dict):
# Set other keys to None on error for dictionary outputs
for k in ti_dict[result_key]:
if k != 'error': ti_dict[result_key][k] = None
ti_dict[result_key]['error'] = error_msg
else: # Scalar output
ti_dict[result_key] = None
ti_dict[f'{result_key}_error'] = error_msg
except Exception as e:
# General unexpected errors during calculation or appending
logger.error(f"Errore generico calcolo/append {name}: {e}", exc_info=False); error_msg = f"Calc failed: {e}"
if is_dict_output and isinstance(ti_dict.get(result_key), dict):
for k in ti_dict[result_key]:
if k != 'error': ti_dict[result_key][k] = None
ti_dict[result_key]['error'] = error_msg
else:
ti_dict[result_key] = None
ti_dict[f'{result_key}_error'] = error_msg
# --- Metodi Calcolo Indicatori Specifici (Aggiornati per usare _calculate_indicator) ---
# (La logica di estrazione e interpretazione rimane invariata, ma il calcolo è delegato)
def _calculate_moving_averages(self) -> None:
"""Calcola medie mobili SMA ed EMA e rileva crossover."""
# (Logica invariata)
if ta is None: logger.error("pandas_ta mancante per medie mobili."); return
ti_key = 'technical_indicators'; ma_key = 'moving_averages'; self.results[ti_key].setdefault(ma_key, {})
local_ma_results = {}
for period in config.SMA_PERIODS:
self._calculate_indicator(ta.sma, name=f"SMA_{period}", result_key=f"_temp_sma_{period}", length=period)
sma_col_name = next((col for col in self.data.columns if col.lower() == f"sma_{period}".lower()), None)
if sma_col_name:
local_ma_results[f'sma_{period}'] = _safe_float(safe_get_last_value(self.data[sma_col_name]))
else:
logger.warning(f"Colonna SMA_{period} (o simile) non trovata dopo calcolo."); local_ma_results[f'sma_{period}'] = None
self.results[ti_key].pop(f"_temp_sma_{period}", None)
self.results[ti_key].pop(f"_temp_sma_{period}_error", None)
for period in config.EMA_PERIODS:
self._calculate_indicator(ta.ema, name=f"EMA_{period}", result_key=f"_temp_ema_{period}", length=period)
ema_col_name = next((col for col in self.data.columns if col.lower() == f"ema_{period}".lower()), None)
if ema_col_name:
local_ma_results[f'ema_{period}'] = _safe_float(safe_get_last_value(self.data[ema_col_name]))
else:
logger.warning(f"Colonna EMA_{period} (o simile) non trovata dopo calcolo."); local_ma_results[f'ema_{period}'] = None
self.results[ti_key].pop(f"_temp_ema_{period}", None)
self.results[ti_key].pop(f"_temp_ema_{period}_error", None)
self.results[ti_key][ma_key] = local_ma_results
crossover_results = {'golden_cross_recent_5p': None, 'death_cross_recent_5p': None}
sma50_col_df = next((col for col in self.data.columns if col.lower() == "sma_50"), None)
sma200_col_df = next((col for col in self.data.columns if col.lower() == "sma_200"), None)
if sma50_col_df and sma200_col_df:
sma50_series = self.data[sma50_col_df]; sma200_series = self.data[sma200_col_df]
if sma50_series.dropna().size >= 2 and sma200_series.dropna().size >= 2:
golden = (sma50_series > sma200_series) & (sma50_series.shift(1) <= sma200_series.shift(1))
death = (sma50_series < sma200_series) & (sma50_series.shift(1) >= sma200_series.shift(1))
lookback = 5
if len(golden) >= lookback: crossover_results['golden_cross_recent_5p'] = bool(golden.iloc[-lookback:].any())
if len(death) >= lookback: crossover_results['death_cross_recent_5p'] = bool(death.iloc[-lookback:].any())
else: logger.debug("Serie SMA50/SMA200 non hanno abbastanza punti validi per crossover.")
else: logger.debug("Colonne SMA50/SMA200 standard non trovate per calcolo crossover.")
self.results[ti_key]['crossovers'] = crossover_results
def _calculate_rsi(self, period: int = config.RSI_PERIOD) -> None:
"""Calcola RSI e determina la condizione."""
# (Logica invariata)
result_key = 'rsi'; default_value = {'value': None, 'condition': 'Unknown', 'base_thresholds': {'ob': 70, 'os': 30}, 'error': None}
self._calculate_indicator(ta.rsi, name=f"RSI_{period}", result_key=result_key, length=period, default_value=default_value)
current_result = self.results['technical_indicators'].get(result_key, default_value)
rsi_col_name = next((col for col in self.data.columns if col.lower() == f"rsi_{period}".lower()), None)
latest_rsi = None
if rsi_col_name:
latest_rsi = safe_get_last_value(self.data[rsi_col_name]);
if isinstance(current_result, dict):
current_result['value'] = _safe_float(latest_rsi);
if latest_rsi is not None: current_result.pop('error', None)
elif isinstance(current_result, dict) and not current_result.get('error'):
current_result['error'] = f"Colonna RSI_{period} (o simile) non trovata"
if isinstance(current_result, dict) and not current_result.get('error'):
latest_rsi_val = current_result.get('value')
if latest_rsi_val is not None:
OB_BASE, OS_BASE = 70, 30; NEAR_OB_BASE, NEAR_OS_BASE = OB_BASE - 5, OS_BASE + 5
if latest_rsi_val > OB_BASE: current_result['condition'] = "Overbought"
elif latest_rsi_val < OS_BASE: current_result['condition'] = "Oversold"
elif latest_rsi_val > NEAR_OB_BASE: current_result['condition'] = "Near Overbought"
elif latest_rsi_val < NEAR_OS_BASE: current_result['condition'] = "Near Oversold"
else: current_result['condition'] = "Neutral"
else: current_result['condition'] = "Unknown (NaN Value)"
def _calculate_macd(self, fast: int = config.MACD_FAST, slow: int = config.MACD_SLOW, signal: int = config.MACD_SIGNAL) -> None:
"""Calcola MACD, linee e istogramma, e determina condizione."""
# (Logica invariata)
result_key = 'macd'; default_value = {'macd_line': None, 'signal_line': None, 'histogram': None, 'condition': 'Unknown', 'error': None}
self._calculate_indicator(ta.macd, name="MACD", result_key=result_key, fast=fast, slow=slow, signal=signal, default_value=default_value)
current_result = self.results['technical_indicators'].get(result_key, default_value)
macd_col = next((c for c in self.data.columns if c.lower() == f"macd_{fast}_{slow}_{signal}".lower()), None)
hist_col = next((c for c in self.data.columns if c.lower() == f"macdh_{fast}_{slow}_{signal}".lower()), None)
signal_col = next((c for c in self.data.columns if c.lower() == f"macds_{fast}_{slow}_{signal}".lower()), None)
values_found = False
if macd_col: current_result['macd_line'] = _safe_float(safe_get_last_value(self.data[macd_col])); values_found = True
if hist_col: current_result['histogram'] = _safe_float(safe_get_last_value(self.data[hist_col])); values_found = True
if signal_col: current_result['signal_line'] = _safe_float(safe_get_last_value(self.data[signal_col])); values_found = True
if values_found and isinstance(current_result, dict):
current_result.pop('error', None) # Remove helper error if values were found
elif not values_found and isinstance(current_result, dict) and not current_result.get('error'):
current_result['error'] = "Colonne MACD (o simili) non trovate"
if isinstance(current_result, dict) and not current_result.get('error'):
latest_histogram = current_result.get('histogram')
if latest_histogram is not None:
tolerance = 1e-9
prev_histogram = safe_get_value_at_index(self.data.get(hist_col), index=-2) if hist_col else None
if prev_histogram is not None:
is_strengthening = False
if latest_histogram > tolerance and prev_histogram > tolerance: is_strengthening = latest_histogram > prev_histogram
elif latest_histogram < -tolerance and prev_histogram < -tolerance: is_strengthening = latest_histogram < prev_histogram # Corrected logic for bearish strengthening
elif latest_histogram > tolerance and prev_histogram <= tolerance: is_strengthening = True # Crossed zero bullish
elif latest_histogram < -tolerance and prev_histogram >= -tolerance: is_strengthening = True # Crossed zero bearish
strength_label = " (Strengthening)" if is_strengthening else " (Weakening)"
if latest_histogram > tolerance: current_result['condition'] = f"Bullish{strength_label}"
elif latest_histogram < -tolerance: current_result['condition'] = f"Bearish{strength_label}"
else: current_result['condition'] = "Neutral (Zero Cross/Flat)"
else: # No history to compare with
if latest_histogram > tolerance: current_result['condition'] = "Bullish"
elif latest_histogram < -tolerance: current_result['condition'] = "Bearish"
else: current_result['condition'] = "Neutral (Zero Cross/Flat)"
else: current_result['condition'] = "Unknown (NaN Value)"
def _calculate_bollinger_bands(self, period: int = config.BBANDS_PERIOD, std_dev: float = config.BBANDS_STDDEV) -> None:
"""Calcola Bande di Bollinger e condizioni associate."""
# (Logica invariata)
result_key = 'bollinger_bands'; default_value = {'middle': None, 'upper': None, 'lower': None, 'bandwidth': None, 'percent_b': None, 'condition': 'Unknown', 'condition_pb': 'Unknown', 'error': None}
self._calculate_indicator(ta.bbands, name="BBANDS", result_key=result_key, length=period, std=std_dev, default_value=default_value)
current_result = self.results['technical_indicators'].get(result_key, default_value)
std_dev_str = f"{std_dev:.1f}"
upper_col = next((c for c in self.data.columns if c.lower() == f"bbu_{period}_{std_dev_str}".lower()), None)
middle_col = next((c for c in self.data.columns if c.lower() == f"bbm_{period}_{std_dev_str}".lower()), None)
lower_col = next((c for c in self.data.columns if c.lower() == f"bbl_{period}_{std_dev_str}".lower()), None)
bw_col = next((c for c in self.data.columns if c.lower() == f"bbb_{period}_{std_dev_str}".lower()), None)
perc_b_col = next((c for c in self.data.columns if c.lower() == f"bbp_{period}_{std_dev_str}".lower()), None)
values_found = False
if upper_col: current_result['upper'] = _safe_float(safe_get_last_value(self.data[upper_col])); values_found = True
if middle_col: current_result['middle'] = _safe_float(safe_get_last_value(self.data[middle_col])); values_found = True
if lower_col: current_result['lower'] = _safe_float(safe_get_last_value(self.data[lower_col])); values_found = True
if bw_col: current_result['bandwidth'] = _safe_float(safe_get_last_value(self.data[bw_col])); values_found = True
if perc_b_col: current_result['percent_b'] = _safe_float(safe_get_last_value(self.data[perc_b_col])); values_found = True
if values_found and isinstance(current_result, dict):
current_result.pop('error', None)
elif not values_found and isinstance(current_result, dict) and not current_result.get('error'):
current_result['error'] = f"Colonne BBANDS_{period}_{std_dev_str} (o simili) non trovate"
if isinstance(current_result, dict) and not current_result.get('error'):
latest_close = safe_get_last_value(self.data['close'])
latest_upper = current_result.get('upper'); latest_lower = current_result.get('lower'); latest_percent_b = current_result.get('percent_b')
if latest_close is not None and latest_upper is not None and latest_lower is not None:
band_width = latest_upper - latest_lower
tolerance = band_width * 0.02 if band_width > 0 else 1e-6
if latest_close > (latest_upper - tolerance): current_result['condition'] = "Price Above/Near Upper Band"
elif latest_close < (latest_lower + tolerance): current_result['condition'] = "Price Below/Near Lower Band"
else: current_result['condition'] = "Price Within Bands"
else: current_result['condition'] = "Unknown (NaN Value)"
if latest_percent_b is not None:
if latest_percent_b > 1.0: current_result['condition_pb'] = "Overbought (>1)"
elif latest_percent_b < 0.0: current_result['condition_pb'] = "Oversold (<0)"
elif latest_percent_b > 0.8: current_result['condition_pb'] = "Near Upper Band (>0.8)"
elif latest_percent_b < 0.2: current_result['condition_pb'] = "Near Lower Band (<0.2)"
else: current_result['condition_pb'] = "Mid-Range (0.2-0.8)"
else: current_result['condition_pb'] = "Unknown (NaN %B)"
def calculate_atr(self, period=config.ATR_PERIOD) -> Optional[float]:
"""Calcola ATR, lo salva nei results e lo restituisce."""
# (Logica invariata)
result_key = 'atr'; default_value = None
self._calculate_indicator(ta.atr, name=f"ATR_{period}", result_key=result_key, length=period, default_value=default_value)
ti_dict = self.results.setdefault('technical_indicators', {})
helper_error = ti_dict.get(f'{result_key}_error')
final_value = None
atr_col_name_found = None
if not helper_error:
potential_cols = [f'ATR_{period}', f'ATRr_{period}', f'ATRe_{period}']
for col_base in potential_cols:
atr_col_name_found = next((col for col in self.data.columns if col.lower() == col_base.lower()), None)
if atr_col_name_found:
logger.debug(f"Trovata colonna ATR: '{atr_col_name_found}'")
final_value = _safe_float(safe_get_last_value(self.data[atr_col_name_found]))
break
if atr_col_name_found is None:
logger.warning(f"Colonna ATR_{period} (o simile) non trovata nel DataFrame dopo calcolo.")
ti_dict[result_key] = final_value
if final_value is not None:
ti_dict.pop(f'{result_key}_error', None)
else:
if not helper_error:
error_msg = f"Colonna ATR_{period} non trovata o NaN"
ti_dict[f'{result_key}_error'] = error_msg
logger.warning(error_msg)
if final_value is not None and final_value > 0:
return final_value
else:
if final_value is not None:
logger.warning(f"ATR calcolato ({final_value}) non è positivo.")
return None
def _calculate_stochastic(self, k: int = 14, d: int = 3, smooth_k: int = 3) -> None:
"""Calcola Stocastico, estrae k e d correttamente, e determina condizione."""
# (Logica invariata)
result_key = 'stochastic'; default_value = {'k': None, 'd': None, 'condition': 'Unknown', 'error': None}
self._calculate_indicator(ta.stoch, name="Stochastic", result_key=result_key, k=k, d=d, smooth_k=smooth_k, default_value=default_value)
current_result = self.results['technical_indicators'].get(result_key, default_value)
if isinstance(current_result, dict) and current_result.get('error'):
logger.warning(f"Salto interpretazione Stocastico causa errore calcolo: {current_result['error']}")
current_result['k'] = None; current_result['d'] = None; current_result['condition'] = "Unknown (Calculation Error)"; return
k_col_name_generated = f'STOCHk_{k}_{d}_{smooth_k}'; d_col_name_generated = f'STOCHd_{k}_{d}_{smooth_k}'
k_col_df = next((c for c in self.data.columns if c.lower() == k_col_name_generated.lower()), None)
d_col_df = next((c for c in self.data.columns if c.lower() == d_col_name_generated.lower()), None)
latest_k = safe_get_last_value(self.data.get(k_col_df)) if k_col_df else None
latest_d = safe_get_last_value(self.data.get(d_col_df)) if d_col_df else None
current_result['k'] = _safe_float(latest_k); current_result['d'] = _safe_float(latest_d)
keys_to_remove = [key for key in list(current_result.keys()) if key not in ['k', 'd', 'condition', 'error'] and key.lower().startswith(('stochk','stochd'))]
for key in keys_to_remove: current_result.pop(key, None)
if current_result['k'] is not None and current_result['d'] is not None:
prev_k = safe_get_value_at_index(self.data.get(k_col_df), index=-2) if k_col_df else None
prev_d = safe_get_value_at_index(self.data.get(d_col_df), index=-2) if d_col_df else None
OB, OS = 80, 20; condition = 'Unknown'
if current_result['k'] > OB and current_result['d'] > OB: condition = "Overbought"
elif current_result['k'] < OS and current_result['d'] < OS: condition = "Oversold"
elif prev_k is not None and prev_d is not None:
tolerance = 1e-6
if (prev_k <= prev_d + tolerance) and (current_result['k'] > current_result['d'] + tolerance): condition = "Bullish Crossover"
elif (prev_k >= prev_d - tolerance) and (current_result['k'] < current_result['d'] - tolerance): condition = "Bearish Crossover"
if condition == 'Unknown':
if current_result['k'] > current_result['d']: condition = "K above D"
elif current_result['k'] < current_result['d']: condition = "K below D"
else: condition = "K equals D"
current_result['condition'] = condition
current_result.pop('error', None)
else:
current_result['condition'] = "Unknown (NaN Value)"
if not current_result.get('error'):
current_result['error'] = f"Colonne {k_col_name_generated}/{d_col_name_generated} (o simili) non trovate o NaN"
def _calculate_cci(self, period: int = 20) -> None:
"""Calcola CCI e determina condizione."""
# (Logica invariata)
result_key = 'cci'; default_value = {'value': None, 'condition': 'Unknown', 'error': None}
self._calculate_indicator(ta.cci, name=f"CCI_{period}", result_key=result_key, length=period, default_value=default_value)
current_result = self.results['technical_indicators'].get(result_key, default_value)
cci_col_name = next((c for c in self.data.columns if c.lower().startswith(f"cci_{period}")), None)
latest_cci = None
if cci_col_name:
latest_cci = safe_get_last_value(self.data[cci_col_name])
if isinstance(current_result, dict):
current_result['value'] = _safe_float(latest_cci);
if latest_cci is not None: current_result.pop('error', None)
elif isinstance(current_result, dict) and not current_result.get('error'):
current_result['error'] = f"Colonna CCI_{period} (o simile) non trovata"
if isinstance(current_result, dict) and not current_result.get('error'):
latest_cci_val = current_result.get('value')
if latest_cci_val is not None:
OB, OS, NearOB, NearOS, ExtremOB, ExtremOS = 100, -100, 90, -90, 150, -150
if latest_cci_val > ExtremOB: current_result['condition'] = "Extreme Overbought (>150)"
elif latest_cci_val < ExtremOS: current_result['condition'] = "Extreme Oversold (<-150)"
elif latest_cci_val > OB: current_result['condition'] = "Overbought (>100)"
elif latest_cci_val < OS: current_result['condition'] = "Oversold (<-100)"
elif latest_cci_val > NearOB: current_result['condition'] = "Near Overbought (>90)"
elif latest_cci_val < NearOS: current_result['condition'] = "Near Oversold (<-90)"
elif latest_cci_val > 0: current_result['condition'] = "Above Zero"
elif latest_cci_val < 0: current_result['condition'] = "Below Zero"
else: current_result['condition'] = "Neutral (Zero)"
else: current_result['condition'] = "Unknown (NaN Value)"
def _calculate_obv(self) -> None:
"""Calcola OBV e determina trend relativo."""
# (Logica invariata)
result_key = 'obv'; default_value = {'value': None, 'trend': 'Unknown', 'error': None}
self._calculate_indicator(ta.obv, name="OBV", result_key=result_key, default_value=default_value)
current_result = self.results['technical_indicators'].get(result_key, default_value)
obv_col_name = next((c for c in self.data.columns if c.lower() == "obv"), None)
latest_obv = None; trend_calculated = False
if obv_col_name:
obv_series = self.data[obv_col_name]; latest_obv = safe_get_last_value(obv_series)
if isinstance(current_result, dict): current_result['value'] = _safe_float(latest_obv)
min_p = 10
if obv_series.dropna().size >= min_p:
obv_sma = obv_series.rolling(window=min_p, min_periods=max(1, min_p//2)).mean();
last_obv_sma = safe_get_last_value(obv_sma);
prev_obv_sma = safe_get_value_at_index(obv_sma, index=-2)
if last_obv_sma is not None and prev_obv_sma is not None:
if last_obv_sma > prev_obv_sma: current_result['trend'] = "Rising"
elif last_obv_sma < prev_obv_sma: current_result['trend'] = "Falling"
else: current_result['trend'] = "Flat"
trend_calculated = True
else: current_result['trend'] = "Unknown (SMA Calc Issue)"
else: current_result['trend'] = "Unknown (Insufficient Data for Trend)"
if latest_obv is not None and isinstance(current_result, dict):
current_result.pop('error', None)
elif isinstance(current_result, dict) and not current_result.get('error'):
current_result['error'] = f"Colonna OBV (o simile) non trovata"
def _calculate_psar(self, af: float = 0.02, max_af: float = 0.2) -> None:
"""Calcola PSAR, estrae valore, direzione e flip correttamente."""
# (Logica invariata)
result_key = 'psar'; default_value = {'psar': None, 'direction': 'Unknown', 'flipped_last_candle': None, 'error': None}
self._calculate_indicator(ta.psar, name="PSAR", result_key=result_key, af=af, max_af=max_af, default_value=default_value)
current_result = self.results['technical_indicators'].get(result_key, default_value)
if isinstance(current_result, dict) and current_result.get('error'):
logger.warning(f"Salto interpretazione PSAR causa errore calcolo: {current_result['error']}")
current_result['psar'] = None; current_result['direction'] = 'Unknown'; current_result['flipped_last_candle'] = None; return
actual_long_col = next((col for col in self.data.columns if col.lower().startswith('psarl')), None)
actual_short_col = next((col for col in self.data.columns if col.lower().startswith('psars')), None)
current_psar_actual = None; current_direction = 'Unknown'; prev_direction = 'Unknown'; flipped = None
if actual_long_col and actual_short_col:
logger.debug(f"Trovate colonne PSAR: long='{actual_long_col}', short='{actual_short_col}'")
psar_long_series = self.data[actual_long_col]; psar_short_series = self.data[actual_short_col]
last_psar_long = safe_get_last_value(psar_long_series, default=np.nan)
last_psar_short = safe_get_last_value(psar_short_series, default=np.nan)
if pd.notna(last_psar_long):
current_psar_actual = last_psar_long; current_direction = "Long"
elif pd.notna(last_psar_short):
current_psar_actual = last_psar_short; current_direction = "Short"
else:
logger.debug(f"Ultimi valori PSARl/s ({actual_long_col}/{actual_short_col}) sono NaN.")
if len(psar_long_series.dropna()) > 1 and len(psar_short_series.dropna()) > 1:
prev_psar_long = safe_get_value_at_index(psar_long_series, index=-2, default=np.nan)
prev_psar_short = safe_get_value_at_index(psar_short_series, index=-2, default=np.nan)
if pd.notna(prev_psar_long): prev_direction = "Long"
elif pd.notna(prev_psar_short): prev_direction = "Short"
flipped = (prev_direction != 'Unknown' and current_direction != 'Unknown' and prev_direction != current_direction)
else:
logger.debug("Dati insufficienti per determinare flip PSAR."); flipped = None
current_result['psar'] = _safe_float(current_psar_actual)
current_result['direction'] = current_direction
current_result['flipped_last_candle'] = flipped
current_result.pop('error', None)
else:
logger.debug(f"Colonne PSAR (psarl*/psars*) non trovate nel DataFrame.")
if not current_result.get('error'):
current_result['error'] = f"PSAR columns not found"
current_result['psar'] = None; current_result['direction'] = 'Unknown'; current_result['flipped_last_candle'] = None
keys_to_remove = [key for key in list(current_result.keys()) if key not in ['psar', 'direction', 'flipped_last_candle', 'error'] and key.lower().startswith('psar')]
for key in keys_to_remove: current_result.pop(key, None)
def _calculate_adx_detailed(self, period=config.ADX_PERIOD) -> Dict[str, Optional[float]]:
"""Calcola ADX, +DI, -DI. Usato internamente da _analyze_trend."""
# (Logica invariata)
result_key = '_temp_adx_detailed'; default_value = {'adx': None, 'plus_di': None, 'minus_di': None, 'error': None}
self._calculate_indicator(ta.adx, name="ADX", result_key=result_key, length=period, default_value=default_value)
indicator_output = self.results['technical_indicators'].pop(result_key, default_value)
helper_error = indicator_output.get('error') if isinstance(indicator_output, dict) else None
adx_col = next((c for c in self.data.columns if c.lower() == f"adx_{period}".lower()), None)
dmp_col = next((c for c in self.data.columns if c.lower() == f"dmp_{period}".lower()), None)
dmn_col = next((c for c in self.data.columns if c.lower() == f"dmn_{period}".lower()), None)
final_results = {'adx': None, 'plus_di': None, 'minus_di': None, 'error': None}; values_found = False
if adx_col: final_results['adx'] = _safe_float(safe_get_last_value(self.data[adx_col])); values_found = True
if dmp_col: final_results['plus_di'] = _safe_float(safe_get_last_value(self.data[dmp_col])); values_found = True
if dmn_col: final_results['minus_di'] = _safe_float(safe_get_last_value(self.data[dmn_col])); values_found = True
if values_found:
final_results.pop('error', None)
elif helper_error:
final_results['error'] = helper_error
else:
final_results['error'] = f"Colonne ADX_{period}/DMP/DMN (o simili) non trovate"
return final_results
# --- NUOVI METODI ---
def _calculate_volume_analysis(self, sma_period: int = TA_VOLUME_SMA_SHORT, zscore_period: int = TA_VOLUME_ZSCORE_PERIOD, updown_period: int = TA_UPDOWN_VOL_PERIOD) -> None:
"""Calcola analisi volume: SMA, Z-score, VROC, Up/Down Ratio."""
vol_results = {
'current_volume': None,
f'volume_sma_{sma_period}': None,
'volume_vs_sma_ratio': None,
f'volume_zscore_{zscore_period}': None,
'volume_spike_zscore': None, # Boolean based on z-score > threshold (e.g., 2)
'vroc_1_period_pct': None,
'vroc_5_period_pct': None,
f'up_down_volume_ratio_{updown_period}p': None,
'error': None
}
self.results['volume_analysis'] = vol_results
if 'volume' not in self.data.columns or self.data['volume'].isnull().all():
vol_results['error'] = "Volume data missing"; return
volume_series = self.data['volume']
vol_results['current_volume'] = _safe_float(safe_get_last_value(volume_series))
try:
# Volume SMA & Ratio
if len(volume_series.dropna()) >= sma_period:
vol_sma = volume_series.rolling(window=sma_period, min_periods=max(1, sma_period//2)).mean()
last_sma = _safe_float(safe_get_last_value(vol_sma))
vol_results[f'volume_sma_{sma_period}'] = last_sma
if vol_results['current_volume'] is not None and last_sma is not None and last_sma > 1e-9:
vol_results['volume_vs_sma_ratio'] = _safe_float(vol_results['current_volume'] / last_sma)
else: logger.debug(f"Dati insuff. per Volume SMA {sma_period}")
# Volume Z-Score
if len(volume_series.dropna()) >= zscore_period:
vol_rolling_mean = volume_series.rolling(window=zscore_period, min_periods=max(1, zscore_period//2)).mean()
vol_rolling_std = volume_series.rolling(window=zscore_period, min_periods=max(1, zscore_period//2)).std()
last_mean = safe_get_last_value(vol_rolling_mean)
last_std = safe_get_last_value(vol_rolling_std)
if vol_results['current_volume'] is not None and last_mean is not None and last_std is not None and last_std > 1e-9:
z_score = (vol_results['current_volume'] - last_mean) / last_std
vol_results[f'volume_zscore_{zscore_period}'] = _safe_float(z_score)
vol_results['volume_spike_zscore'] = bool(z_score > 2.0) # Soglia esempio 2.0
else: logger.debug(f"Dati insuff. per Volume Z-Score {zscore_period}")
# VROC
if len(volume_series.dropna()) >= 2:
vroc1 = volume_series.pct_change(periods=1) * 100
vol_results['vroc_1_period_pct'] = _safe_float(safe_get_last_value(vroc1))
if len(volume_series.dropna()) >= 6: # Need 5 periods + current
vroc5 = volume_series.pct_change(periods=5) * 100
vol_results['vroc_5_period_pct'] = _safe_float(safe_get_last_value(vroc5))
# Up/Down Volume Ratio
if len(volume_series.dropna()) >= updown_period and 'close' in self.data.columns and 'open' in self.data.columns:
recent_data = self.data.iloc[-updown_period:]
close_gt_open = recent_data['close'] > recent_data['open']
close_lt_open = recent_data['close'] < recent_data['open']
up_volume = recent_data.loc[close_gt_open, 'volume'].sum()
down_volume = recent_data.loc[close_lt_open, 'volume'].sum()
if pd.notna(down_volume) and down_volume > 1e-9:
vol_results[f'up_down_volume_ratio_{updown_period}p'] = _safe_float(up_volume / down_volume)
elif pd.notna(up_volume) and up_volume > 1e-9:
vol_results[f'up_down_volume_ratio_{updown_period}p'] = float('inf') # Infinite if only up volume
else:
vol_results[f'up_down_volume_ratio_{updown_period}p'] = None
else: logger.debug(f"Dati insuff. per Up/Down Volume Ratio {updown_period}")
vol_results.pop('error', None)
except Exception as e:
logger.error(f"Errore calcolo analisi volume: {e}", exc_info=True)
vol_results['error'] = str(e)
def _calculate_vwap_rolling(self, period: int = TA_VWAP_ROLLING_PERIOD) -> None:
"""Calcola VWAP Rolling."""
vwap_results = {
f'vwap_rolling_{period}': None,
f'price_vs_vwap{period}_pct': None,
'error': None
}
# Store results in a specific sub-dictionary if needed, or directly in technical_indicators
self.results['technical_indicators'][f'vwap_rolling_{period}_analysis'] = vwap_results
required_cols = ['high', 'low', 'close', 'volume']
if not all(col in self.data.columns for col in required_cols):
vwap_results['error'] = "Dati HLCV mancanti"; return
if len(self.data.dropna(subset=required_cols)) < period:
vwap_results['error'] = f"Dati insuff. per VWAP rolling {period}"; return
try:
df_vwap = self.data.copy()
tp = (df_vwap['high'] + df_vwap['low'] + df_vwap['close']) / 3
tp_vol = tp * df_vwap['volume']
rolling_tp_vol = tp_vol.rolling(window=period, min_periods=max(1, period//2)).sum()
rolling_volume = df_vwap['volume'].rolling(window=period, min_periods=max(1, period//2)).sum()
# Calculate VWAP, handle division by zero
valid_volume = rolling_volume.replace(0, np.nan)
vwap_series = rolling_tp_vol / valid_volume
vwap_series = vwap_series.replace([np.inf, -np.inf], np.nan)
# Add VWAP series to main dataframe (optional, but can be useful)
vwap_col_name = f"VWAP_{period}"
self.data[vwap_col_name] = vwap_series
# Get last value and calculate distance
last_vwap = _safe_float(safe_get_last_value(vwap_series))
vwap_results[f'vwap_rolling_{period}'] = last_vwap
last_close = safe_get_last_value(self.data['close'])
if last_close is not None and last_vwap is not None and last_vwap != 0:
dist_pct = ((last_close - last_vwap) / last_vwap) * 100
vwap_results[f'price_vs_vwap{period}_pct'] = _safe_float(dist_pct)
vwap_results.pop('error', None)
except Exception as e:
logger.error(f"Errore calcolo VWAP rolling {period}: {e}", exc_info=True)
vwap_results['error'] = str(e)
def _calculate_volatility_percentiles(self, period: int = TA_VOLATILITY_PERCENTILE_PERIOD) -> None:
"""Calcola i percentili storici per ATR e BB Bandwidth."""
vol_perc_results = {
'atr_value': None,
f'atr_percentile_{period}p': None,
'bbw_value': None,
f'bbw_percentile_{period}p': None,
'error': None
}
self.results['volatility_analysis'] = vol_perc_results # Store in new section
# --- ATR Percentile ---
# 1. Ottieni il valore ATR corrente dai risultati (calcolato precedentemente)
atr_val = _safe_get(self.results, ['technical_indicators', 'atr'])
vol_perc_results['atr_value'] = atr_val # Salva comunque il valore trovato
# 2. Cerca la colonna ATR nel DataFrame (necessaria per la storia)
atr_col_name = None
# Usa il periodo ATR corretto da config
atr_base_period = config.ATR_PERIOD
potential_cols = [f'ATR_{atr_base_period}', f'ATRr_{atr_base_period}', f'ATRe_{atr_base_period}'] # Common names from pandas_ta
for col_base in potential_cols:
atr_col_name = next((col for col in self.data.columns if col.lower() == col_base.lower()), None)
if atr_col_name:
logger.debug(f"Trovata colonna ATR '{atr_col_name}' per calcolo percentile.")
break # Trovata, esci dal loop
# 3. Calcola il percentile se la colonna esiste e ci sono dati sufficienti
if atr_col_name and atr_col_name in self.data.columns:
atr_series = self.data[atr_col_name].dropna()
if len(atr_series) >= period:
try:
# Calcola il rank percentile dell'ultimo valore ATR valido
last_valid_atr_for_perc = atr_series.iloc[-1] # Valore da confrontare
if pd.notna(last_valid_atr_for_perc):
historical_atr_window = atr_series.iloc[-period:] # Ultimi N valori
# Calcola percentile usando scipy.stats.percentileofscore
# 'weak' include il valore stesso nel conteggio <=
percentile_score = stats.percentileofscore(historical_atr_window, last_valid_atr_for_perc, kind='weak')
vol_perc_results[f'atr_percentile_{period}p'] = _safe_float(percentile_score)
else:
logger.warning("Ultimo valore ATR è NaN, impossibile calcolare percentile.")
except ImportError:
logger.error("Modulo Scipy non trovato per percentileofscore.")
vol_perc_results['error'] = (vol_perc_results.get('error') or "") + " Scipy missing for ATR percentile."
except Exception as e:
logger.warning(f"Errore calcolo percentile ATR {period}: {e}")
if not vol_perc_results.get('error'): vol_perc_results['error'] = f"ATR percentile calc failed: {e}"
else:
logger.debug(f"Dati ATR insuff. ({len(atr_series)} < {period}) per percentile.")
if not vol_perc_results.get('error'): vol_perc_results['error'] = "Insufficient ATR data for percentile."
elif not vol_perc_results.get('error'): # Aggiungi errore solo se non già presente
logger.warning(f"Colonna ATR (es. ATR_{atr_base_period}) non trovata per calcolo percentile.")
vol_perc_results['error'] = "ATR column not found for percentile calc."
# --- Bollinger Bandwidth Percentile ---
# (Logica simile per BBW, assicurandosi che la colonna esista)
bbw_val = _safe_get(self.results, ['technical_indicators', 'bollinger_bands', 'bandwidth'])
vol_perc_results['bbw_value'] = bbw_val
# Find BBW column name (handles float std dev in name)
std_dev_str = f"{config.BBANDS_STDDEV:.1f}"
bbw_col_name = next((c for c in self.data.columns if c.lower() == f"bbb_{config.BBANDS_PERIOD}_{std_dev_str}".lower()), None)
if bbw_col_name and bbw_col_name in self.data.columns:
bbw_series = self.data[bbw_col_name].dropna()
if len(bbw_series) >= period:
try:
last_valid_bbw = bbw_series.iloc[-1]
if pd.notna(last_valid_bbw):
historical_bbw_window = bbw_series.iloc[-period:]
percentile_score_bbw = stats.percentileofscore(historical_bbw_window, last_valid_bbw, kind='weak')
vol_perc_results[f'bbw_percentile_{period}p'] = _safe_float(percentile_score_bbw)
else:
logger.warning("Ultimo valore BBW è NaN, impossibile calcolare percentile.")
except ImportError:
logger.error("Modulo Scipy non trovato per percentileofscore.")
vol_perc_results['error'] = (vol_perc_results.get('error') or "") + " Scipy missing for BBW percentile."
except Exception as e:
logger.warning(f"Errore calcolo percentile BBW {period}: {e}")
if not vol_perc_results.get('error'): vol_perc_results['error'] = (vol_perc_results.get('error') or "") + f" BBW percentile calc failed: {e}"
else:
logger.debug(f"Dati BBW insuff. ({len(bbw_series)} < {period}) per percentile.")
if not vol_perc_results.get('error'): vol_perc_results['error'] = (vol_perc_results.get('error') or "") + " Insufficient BBW data for percentile."
elif not vol_perc_results.get('error'):
logger.warning(f"Colonna BBW (es. BBB_{config.BBANDS_PERIOD}_{std_dev_str}) non trovata per calcolo percentile.")
vol_perc_results['error'] = (vol_perc_results.get('error') or "") + " BBW column not found for percentile calc."
# Clean final error if any percentile was calculated
if vol_perc_results.get(f'atr_percentile_{period}p') is not None or vol_perc_results.get(f'bbw_percentile_{period}p') is not None:
vol_perc_results.pop('error', None)
def _calculate_atr_targets(self, multipliers: List[float] = TA_ATR_TARGET_MULTIPLIERS) -> None:
"""Calcola potenziali target basati su multipli dell'ATR."""
target_results = {}
self.results['price_level_targets']['atr_based'] = target_results # Store in new section
current_close = safe_get_last_value(self.data['close'])
current_atr = _safe_get(self.results, ['technical_indicators', 'atr'])
if current_close is None or current_atr is None or current_atr <= 0:
logger.warning("Prezzo o ATR non validi per calcolo target ATR.")
target_results['error'] = "Invalid price or ATR"
return
try:
for mult in multipliers:
mult_str = str(mult).replace('.', '_') # e.g., 1.5 -> 1_5
target_up_key = f'target_{mult_str}x_atr_up'
target_down_key = f'target_{mult_str}x_atr_down'
target_results[target_up_key] = _safe_float(current_close + (mult * current_atr))
target_results[target_down_key] = _safe_float(current_close - (mult * current_atr))
target_results.pop('error', None)
except Exception as e:
logger.error(f"Errore calcolo target ATR: {e}", exc_info=True)
target_results['error'] = str(e)
# --- Metodi Esistenti Aggiornati ---
def _calculate_support_resistance(self, window: int = 20, atr_multiplier: float = 0.5) -> None:
"""
Calcola supporto e resistenza più vicini basati su minimi/massimi locali e ATR.
MODIFICATO: Aggiunge distanza in ATR.
"""
sr_results = {
'nearest_support': None, 'nearest_resistance': None,
'support_distance_pct': None, 'resistance_distance_pct': None,
'support_distance_atr': None, 'resistance_distance_atr': None, # NUOVI CAMPI
'error': None
}
self.results['support_resistance'] = sr_results
# Ottieni ATR corrente (fondamentale per questo metodo)
current_atr_val = _safe_get(self.results, ['technical_indicators', 'atr'])
if current_atr_val is None or current_atr_val <= 0:
# Tenta ricalcolo se mancante
logger.debug("ATR non trovato/valido, tento ricalcolo per S/R...")
current_atr_val = self.calculate_atr() # Chiama metodo che aggiorna anche results
if current_atr_val is None or current_atr_val <= 0:
logger.warning("Impossibile ottenere/calcolare ATR valido per S/R.")
# Non impostare errore qui, l'analisi può continuare senza distanza ATR
current_atr_val = 0 # Usa 0 per evitare errori sotto, ma le distanze ATR saranno None
required_cols, min_p = ['high', 'low', 'close'], window
if not all(c in self.data.columns for c in required_cols) or len(self.data.dropna(subset=required_cols)) < min_p:
sr_results['error'] = "Insufficient HLC data"; return
try:
data_valid_hlc = self.data.dropna(subset=required_cols);
data_window = data_valid_hlc.iloc[-max(window, min_p):] # Considera almeno 'min_p' punti
current_close = safe_get_last_value(data_window['close'])
if current_close is None or current_close <= 0:
sr_results['error'] = "Invalid current price"; return
# Usa l'ATR valido o 0
current_atr = current_atr_val
atr_filter_threshold = current_atr * atr_multiplier
# Calcolo Pivot
roll_window_pivot = max(3, window // 4); highs, lows = data_window['high'], data_window['low']
try:
# `center=True` might need adjustment depending on desired pivot behavior
local_max_indices = highs.index[highs >= highs.rolling(roll_window_pivot, center=True, min_periods=1).max()]
local_min_indices = lows.index[lows <= lows.rolling(roll_window_pivot, center=True, min_periods=1).min()]
except ValueError:
logger.warning("Dati insuff. per rolling pivot S/R. Uso min/max globali finestra.");
local_max_indices = highs.index[highs == highs.max()]
local_min_indices = lows.index[lows == lows.min()]
local_max_prices = data_window.loc[local_max_indices, 'high'].dropna().unique()
local_min_prices = data_window.loc[local_min_indices, 'low'].dropna().unique()
# Trova S/R più vicini (con filtro ATR)
nearest_resistance, min_dist_res = None, float('inf'); nearest_support, min_dist_sup = None, float('inf')
for res_price in local_max_prices:
if res_price > current_close:
dist_res_cand = res_price - current_close
# Applica filtro ATR
if dist_res_cand > atr_filter_threshold and dist_res_cand < min_dist_res:
min_dist_res = dist_res_cand; nearest_resistance = res_price
for sup_price in local_min_prices:
if sup_price < current_close:
dist_sup_cand = current_close - sup_price
# Applica filtro ATR
if dist_sup_cand > atr_filter_threshold and dist_sup_cand < min_dist_sup:
min_dist_sup = dist_sup_cand; nearest_support = sup_price
# Salva risultati
sr_results['nearest_support'] = _safe_float(nearest_support); sr_results['nearest_resistance'] = _safe_float(nearest_resistance)
if nearest_support is not None:
sr_results['support_distance_pct'] = _safe_float((min_dist_sup / current_close) * 100)
# NUOVO: Distanza in ATR
if current_atr > 1e-9: sr_results['support_distance_atr'] = _safe_float(min_dist_sup / current_atr)
if nearest_resistance is not None: