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
 
f73e2d7
 
1ea1791
f73e2d7
 
 
 
4ea7a51
f73e2d7
 
 
 
 
 
 
 
 
 
4ea7a51
f73e2d7
 
 
 
 
 
 
 
 
 
 
4ea7a51
f73e2d7
 
 
 
 
 
 
 
 
 
4ea7a51
 
f73e2d7
 
 
 
 
 
 
 
 
 
4ea7a51
 
 
 
 
f73e2d7
4ea7a51
f73e2d7
 
 
 
 
4ea7a51
f73e2d7
 
 
 
 
 
 
 
4ea7a51
f73e2d7
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
#!/usr/bin/env python3
"""
Financial AI Predictor
======================

Sistema di predizione finanziaria basato su:
- Modello generalista pre-addestrato (scikit-learn)
- Layer finanziario specializzato
- Dati real-time da Yahoo Finance
- Feature engineering avanzato
- Validazione robusta

Author: Financial AI Research
License: Educational Use Only
"""

import warnings
import numpy as np
import pandas as pd
import yfinance as yf
import gradio as gr
import plotly.graph_objects as go
import plotly.express as px
from datetime import datetime, timedelta
import ta
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
from sklearn.linear_model import Ridge
from sklearn.preprocessing import StandardScaler, RobustScaler
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
from sklearn.model_selection import TimeSeriesSplit
import joblib
import json
from typing import Dict, List, Tuple, Optional

warnings.filterwarnings('ignore')

class FinancialFeatureExtractor:
    """Estrae feature finanziarie avanzate dai dati di mercato"""
    
    def __init__(self):
        self.feature_names = []
    
    def extract_technical_features(self, data: pd.DataFrame) -> pd.DataFrame:
        """Estrae indicatori tecnici avanzati"""
        features = pd.DataFrame(index=data.index)
        
        # Price-based features
        features['returns'] = data['Close'].pct_change()
        features['log_returns'] = np.log(data['Close'] / data['Close'].shift(1))
        features['price_momentum_5'] = data['Close'] / data['Close'].shift(5) - 1
        features['price_momentum_20'] = data['Close'] / data['Close'].shift(20) - 1
        
        # Moving averages and ratios
        for period in [5, 10, 20, 50]:
            ma = data['Close'].rolling(period).mean()
            features[f'ma_{period}_ratio'] = data['Close'] / ma
            features[f'ma_{period}_slope'] = ma.pct_change(5)
        
        # Volatility features
        features['volatility_5'] = features['returns'].rolling(5).std()
        features['volatility_20'] = features['returns'].rolling(20).std()
        features['volatility_ratio'] = features['volatility_5'] / features['volatility_20']
        
        # Volume features
        features['volume_sma'] = data['Volume'].rolling(20).mean()
        features['volume_ratio'] = data['Volume'] / features['volume_sma']
        features['volume_momentum'] = data['Volume'].pct_change(5)
        
        # Price-Volume features
        features['price_volume_trend'] = (data['Close'].pct_change() * 
                                        np.log(data['Volume'] + 1))
        
        return features
    
    def extract_ta_features(self, data: pd.DataFrame) -> pd.DataFrame:
        """Estrae indicatori tecnici usando la libreria TA"""
        features = pd.DataFrame(index=data.index)
        
        try:
            # Trend indicators
            features['sma_20'] = ta.trend.sma_indicator(data['Close'], window=20)
            features['ema_12'] = ta.trend.ema_indicator(data['Close'], window=12)
            features['ema_26'] = ta.trend.ema_indicator(data['Close'], window=26)
            features['macd'] = ta.trend.macd_diff(data['Close'])
            features['adx'] = ta.trend.adx(data['High'], data['Low'], data['Close'])
            
            # Momentum indicators
            features['rsi'] = ta.momentum.rsi(data['Close'])
            features['stoch'] = ta.momentum.stoch(data['High'], data['Low'], data['Close'])
            features['williams_r'] = ta.momentum.williams_r(data['High'], data['Low'], data['Close'])
            
            # Volatility indicators
            bb = ta.volatility.BollingerBands(data['Close'])
            features['bb_high'] = bb.bollinger_hband()
            features['bb_low'] = bb.bollinger_lband()
            features['bb_width'] = (features['bb_high'] - features['bb_low']) / data['Close']
            features['bb_position'] = (data['Close'] - features['bb_low']) / (features['bb_high'] - features['bb_low'])
            
            # Volume indicators
            features['obv'] = ta.volume.on_balance_volume(data['Close'], data['Volume'])
            features['cmf'] = ta.volume.chaikin_money_flow(data['High'], data['Low'], data['Close'], data['Volume'])
            features['vwap'] = ta.volume.volume_weighted_average_price(data['High'], data['Low'], data['Close'], data['Volume'])
            
        except Exception as e:
            print(f"Warning: Some TA features failed: {e}")
        
        return features
    
    def extract_market_regime_features(self, data: pd.DataFrame) -> pd.DataFrame:
        """Estrae feature di regime di mercato"""
        features = pd.DataFrame(index=data.index)
        
        # Trend strength
        returns = data['Close'].pct_change()
        features['trend_strength'] = returns.rolling(20).mean() / returns.rolling(20).std()
        
        # Market state indicators
        features['high_low_ratio'] = (data['High'] - data['Low']) / data['Close']
        features['close_position'] = (data['Close'] - data['Low']) / (data['High'] - data['Low'])
        
        # Volatility regime
        vol_20 = returns.rolling(20).std()
        vol_60 = returns.rolling(60).std()
        features['vol_regime'] = vol_20 / vol_60
        
        # Gap features
        features['gap'] = (data['Open'] - data['Close'].shift(1)) / data['Close'].shift(1)
        features['gap_filled'] = np.where(
            features['gap'] > 0,
            (data['Low'] <= data['Close'].shift(1)).astype(int),
            (data['High'] >= data['Close'].shift(1)).astype(int)
        )
        
        return features
    
    def extract_all_features(self, data: pd.DataFrame) -> pd.DataFrame:
        """Estrae tutte le feature"""
        print("๐Ÿ“Š Extracting technical features...")
        tech_features = self.extract_technical_features(data)
        
        print("๐Ÿ“ˆ Extracting TA indicators...")
        ta_features = self.extract_ta_features(data)
        
        print("๐ŸŒŠ Extracting market regime features...")
        regime_features = self.extract_market_regime_features(data)
        
        # Combina tutte le feature
        all_features = pd.concat([tech_features, ta_features, regime_features], axis=1)
        
        # Rimuovi feature con troppi NaN
        all_features = all_features.loc[:, all_features.isnull().mean() < 0.5]
        
        # Forward fill e backward fill
        all_features = all_features.fillna(method='ffill').fillna(method='bfill')
        
        # Rimuovi outliers estremi
        for col in all_features.columns:
            if all_features[col].dtype in ['float64', 'int64']:
                q99 = all_features[col].quantile(0.99)
                q01 = all_features[col].quantile(0.01)
                all_features[col] = all_features[col].clip(lower=q01, upper=q99)
        
        self.feature_names = all_features.columns.tolist()
        print(f"โœ… Extracted {len(self.feature_names)} features")
        
        return all_features

class FinancialPredictor:
    """Sistema di predizione finanziaria con modelli generalisti"""
    
    def __init__(self):
        self.models = {}
        self.scalers = {}
        self.feature_extractor = FinancialFeatureExtractor()
        self.is_trained = False
        self.feature_importance = {}
        self.validation_scores = {}
        
    def create_models(self):
        """Crea i modelli generalisti"""
        self.models = {
            'random_forest': RandomForestRegressor(
                n_estimators=200,
                max_depth=15,
                min_samples_split=5,
                min_samples_leaf=2,
                random_state=42,
                n_jobs=-1
            ),
            'gradient_boost': GradientBoostingRegressor(
                n_estimators=150,
                max_depth=8,
                learning_rate=0.1,
                subsample=0.8,
                random_state=42
            ),
            'ridge': Ridge(
                alpha=1.0,
                random_state=42
            )
        }
        
        # Scaler robusto per gestire outliers
        self.scalers = {
            'robust': RobustScaler(),
            'standard': StandardScaler()
        }
    
    def prepare_data(self, symbol: str, period: str = "2y") -> Tuple[pd.DataFrame, pd.DataFrame]:
        """Prepara i dati per il training"""
        print(f"๐Ÿ“ฅ Fetching data for {symbol}...")
        
        # Fetch data
        ticker = yf.Ticker(symbol)
        data = ticker.history(period=period)
        
        if data is None or len(data) < 100:
            raise ValueError(f"Insufficient data for {symbol}")
        
        print(f"๐Ÿ“Š Data shape: {data.shape}")
        
        # Extract features
        features = self.feature_extractor.extract_all_features(data)
        
        # Create targets (predicting next day return)
        targets = pd.DataFrame(index=data.index)
        targets['next_return'] = data['Close'].pct_change().shift(-1)
        targets['next_direction'] = (targets['next_return'] > 0).astype(int)
        targets['next_volatility'] = targets['next_return'].rolling(5).std().shift(-1)
        
        # Align data
        common_index = features.index.intersection(targets.index)
        features = features.loc[common_index]
        targets = targets.loc[common_index]
        
        # Remove last row (no target)
        features = features.iloc[:-1]
        targets = targets.iloc[:-1]
        
        # Remove NaN
        mask = ~(features.isnull().any(axis=1) | targets.isnull().any(axis=1))
        features = features[mask]
        targets = targets[mask]
        
        print(f"โœ… Prepared data: {len(features)} samples, {len(features.columns)} features")
        
        return features, targets
    
    def train_models(self, symbol: str, period: str = "2y"):
        """Addestra i modelli con validazione temporale"""
        print(f"๐Ÿš€ Training models for {symbol}...")
        
        # Prepare data
        features, targets = self.prepare_data(symbol, period)
        
        if len(features) < 200:
            raise ValueError("Insufficient data for training")
        
        # Create models
        self.create_models()
        
        # Scale features
        features_scaled = features.copy()
        self.scalers['robust'].fit(features)
        features_scaled = pd.DataFrame(
            self.scalers['robust'].transform(features),
            index=features.index,
            columns=features.columns
        )
        
        # Time series split for validation
        tscv = TimeSeriesSplit(n_splits=5)
        
        # Train each model
        for name, model in self.models.items():
            print(f"  ๐Ÿ“ˆ Training {name}...")
            
            # Cross-validation scores
            cv_scores = []
            
            for train_idx, val_idx in tscv.split(features_scaled):
                X_train = features_scaled.iloc[train_idx]
                X_val = features_scaled.iloc[val_idx]
                y_train = targets['next_return'].iloc[train_idx]
                y_val = targets['next_return'].iloc[val_idx]
                
                # Train model
                model.fit(X_train, y_train)
                
                # Validate
                y_pred = model.predict(X_val)
                score = r2_score(y_val, y_pred)
                cv_scores.append(score)
            
            avg_score = np.mean(cv_scores)
            self.validation_scores[name] = {
                'r2_scores': cv_scores,
                'mean_r2': avg_score,
                'std_r2': np.std(cv_scores)
            }
            
            print(f"    โœ… {name}: Rยฒ = {avg_score:.4f} ยฑ {np.std(cv_scores):.4f}")
            
            # Final training on all data
            model.fit(features_scaled, targets['next_return'])
            
            # Feature importance (for tree-based models)
            if hasattr(model, 'feature_importances_'):
                importance_df = pd.DataFrame({
                    'feature': features.columns,
                    'importance': model.feature_importances_
                }).sort_values('importance', ascending=False)
                self.feature_importance[name] = importance_df
        
        self.is_trained = True
        print("๐ŸŽ‰ Training completed!")
        
        return self.validation_scores
    
    def predict(self, symbol: str, days: int = 10) -> Dict:
        """Genera predizioni"""
        if not self.is_trained:
            raise ValueError("Models not trained yet")
        
        print(f"๐Ÿ”ฎ Generating predictions for {symbol}...")
        
        # Get recent data
        ticker = yf.Ticker(symbol)
        data = ticker.history(period="1y")
        
        # Extract features
        features = self.feature_extractor.extract_all_features(data)
        features = features.iloc[-50:]  # Last 50 days for context
        
        # Scale features
        features_scaled = pd.DataFrame(
            self.scalers['robust'].transform(features),
            index=features.index,
            columns=features.columns
        )
        
        current_price = data['Close'].iloc[-1]
        predictions = {}
        
        # Get predictions from each model
        for name, model in self.models.items():
            # Predict next return
            latest_features = features_scaled.iloc[-1:].values
            pred_return = model.predict(latest_features)[0]
            pred_price = current_price * (1 + pred_return)
            
            predictions[name] = {
                'predicted_return': pred_return,
                'predicted_price': pred_price,
                'confidence': self.validation_scores[name]['mean_r2'] if name in self.validation_scores else 0.5
            }
        
        # Ensemble prediction (weighted by validation performance)
        weights = {}
        total_weight = 0
        
        for name in predictions.keys():
            if name in self.validation_scores:
                weight = max(0.1, self.validation_scores[name]['mean_r2'])
            else:
                weight = 0.3
            weights[name] = weight
            total_weight += weight
        
        # Normalize weights
        for name in weights:
            weights[name] /= total_weight
        
        # Calculate ensemble prediction
        ensemble_return = sum(predictions[name]['predicted_return'] * weights[name] 
                            for name in predictions.keys())
        ensemble_price = current_price * (1 + ensemble_return)
        
        # Generate multi-day predictions (simplified)
        multi_day_predictions = []
        confidence_intervals = []
        
        for day in range(1, days + 1):
            # Simple drift model for multi-day
            daily_return = ensemble_return * (0.8 ** (day - 1))  # Decay factor
            pred_price = current_price * (1 + daily_return * day)
            
            # Estimate uncertainty
            model_disagreement = np.std([pred['predicted_return'] for pred in predictions.values()])
            uncertainty = model_disagreement * np.sqrt(day) * current_price
            
            multi_day_predictions.append(pred_price)
            confidence_intervals.append((pred_price - uncertainty, pred_price + uncertainty))
        
        return {
            'current_price': current_price,
            'individual_predictions': predictions,
            'ensemble_prediction': {
                'return': ensemble_return,
                'price': ensemble_price,
                'weights': weights
            },
            'multi_day_predictions': multi_day_predictions,
            'confidence_intervals': confidence_intervals,
            'data_date': data.index[-1]
        }
    
    def get_feature_analysis(self) -> Dict:
        """Analisi delle feature piรน importanti"""
        if not self.feature_importance:
            return {}
        
        # Combina importanza da tutti i modelli
        all_features = set()
        for model_importance in self.feature_importance.values():
            all_features.update(model_importance['feature'].tolist())
        
        combined_importance = {}
        for feature in all_features:
            importances = []
            for model_name, model_importance in self.feature_importance.items():
                feature_row = model_importance[model_importance['feature'] == feature]
                if not feature_row.empty:
                    importances.append(feature_row['importance'].iloc[0])
            
            if importances:
                combined_importance[feature] = np.mean(importances)
        
        # Sort by importance
        sorted_features = sorted(combined_importance.items(), 
                               key=lambda x: x[1], reverse=True)
        
        return {
            'top_features': sorted_features[:15],
            'individual_model_importance': self.feature_importance
        }

def analyze_stock(symbol: str) -> Tuple[str, object, object, object]:
    """Funzione principale di analisi"""
    try:
        if not symbol or len(symbol.strip()) == 0:
            return "Please enter a valid stock symbol", None, None, None
        
        symbol = symbol.upper().strip()
        
        # Initialize predictor
        predictor = FinancialPredictor()
        
        # Train models
        print(f"๐ŸŽฏ Starting analysis for {symbol}")
        validation_scores = predictor.train_models(symbol, period="2y")
        
        # Generate predictions
        predictions = predictor.predict(symbol, days=10)
        
        # Get feature analysis
        feature_analysis = predictor.get_feature_analysis()
        
        # Create report
        report = create_analysis_report(symbol, predictions, validation_scores, feature_analysis)
        
        # Create charts
        price_chart = create_price_chart(symbol, predictions)
        prediction_chart = create_prediction_chart(predictions)
        feature_chart = create_feature_importance_chart(feature_analysis)
        
        return report, price_chart, prediction_chart, feature_chart
        
    except Exception as e:
        error_msg = f"โŒ Error analyzing {symbol}: {str(e)}"
        print(error_msg)
        import traceback
        traceback.print_exc()
        return error_msg, None, None, None

def create_analysis_report(symbol: str, predictions: Dict, validation_scores: Dict, feature_analysis: Dict) -> str:
    """Crea il report di analisi"""
    
    current_price = predictions['current_price']
    ensemble_pred = predictions['ensemble_prediction']
    individual_preds = predictions['individual_predictions']
    
    # Determine recommendation
    pred_return = ensemble_pred['return']
    if pred_return > 0.02:
        recommendation = "๐ŸŸข STRONG BUY"
    elif pred_return > 0.01:
        recommendation = "๐ŸŸข BUY"
    elif pred_return > -0.01:
        recommendation = "๐ŸŸก HOLD"
    elif pred_return > -0.02:
        recommendation = "๐Ÿ”ด SELL"
    else:
        recommendation = "๐Ÿ”ด STRONG SELL"
    
    # Model performance summary
    best_model = max(validation_scores.items(), key=lambda x: x[1]['mean_r2'])
    
    report = f"""๐Ÿค– **FINANCIAL AI PREDICTOR - {symbol}**

**๐Ÿ“Š CURRENT STATUS**
โ€ข **Symbol:** {symbol}
โ€ข **Current Price:** ${current_price:.2f}
โ€ข **Analysis Date:** {predictions['data_date'].strftime('%Y-%m-%d %H:%M:%S')}
โ€ข **Data Quality:** โœ… High (2 years of data)

**๐ŸŽฏ ENSEMBLE PREDICTION**
โ€ข **Next Day Target:** ${ensemble_pred['price']:.2f}
โ€ข **Expected Return:** {pred_return*100:+.2f}%
โ€ข **Recommendation:** {recommendation}
โ€ข **Prediction Confidence:** {np.mean([p['confidence'] for p in individual_preds.values()])*100:.1f}%

**๐Ÿค– MODEL PERFORMANCE**
"""
    
    for name, scores in validation_scores.items():
        report += f"โ€ข **{name.title()}:** Rยฒ = {scores['mean_r2']:.4f} ยฑ {scores['std_r2']:.4f}\n"
    
    report += f"""
**๐Ÿ† Best Model:** {best_model[0].title()} (Rยฒ = {best_model[1]['mean_r2']:.4f})

**๐Ÿ“ˆ INDIVIDUAL MODEL PREDICTIONS**
"""
    
    for name, pred in individual_preds.items():
        weight = ensemble_pred['weights'][name]
        report += f"โ€ข **{name.title()}:** ${pred['predicted_price']:.2f} ({pred['predicted_return']*100:+.2f}%) - Weight: {weight*100:.1f}%\n"
    
    report += f"""
**๐Ÿ”ฎ MULTI-DAY FORECAST**
"""
    
    for i, (price, (low, high)) in enumerate(zip(predictions['multi_day_predictions'], 
                                                 predictions['confidence_intervals']), 1):
        report += f"โ€ข **Day {i}:** ${price:.2f} (Range: ${low:.2f} - ${high:.2f})\n"
    
    if feature_analysis and 'top_features' in feature_analysis:
        report += f"""
**๐Ÿง  TOP PREDICTIVE FEATURES**
"""
        for feature, importance in feature_analysis['top_features'][:10]:
            report += f"โ€ข **{feature}:** {importance:.4f}\n"
    
    report += f"""
**โš™๏ธ TECHNICAL DETAILS**
โ€ข **Feature Engineering:** {len(predictor.feature_extractor.feature_names) if hasattr(predictor, 'feature_extractor') else 'N/A'} technical indicators
โ€ข **Model Architecture:** Ensemble of Random Forest + Gradient Boosting + Ridge
โ€ข **Validation Method:** Time Series Cross-Validation (5 folds)
โ€ข **Scaling:** Robust Scaler (outlier-resistant)
โ€ข **Data Source:** Yahoo Finance (real-time)

**๐ŸŽฏ METHODOLOGY**
โ€ข **Feature Extraction:** Technical indicators, momentum, volatility, volume analysis
โ€ข **Model Training:** Time series aware validation with walk-forward analysis
โ€ข **Ensemble Weighting:** Performance-based weighted averaging
โ€ข **Risk Management:** Confidence intervals based on model disagreement

**โš ๏ธ DISCLAIMER**
This analysis uses machine learning models trained on historical data. Past performance does not guarantee future results. This is for educational purposes only and not financial advice. Always do your own research and consider consulting a financial advisor.

**๐Ÿ“Š CONFIDENCE METRICS**
โ€ข **Data Sufficiency:** โœ… 2+ years of training data
โ€ข **Model Validation:** โœ… Time series cross-validation
โ€ข **Feature Quality:** โœ… {len(predictor.feature_extractor.feature_names) if hasattr(predictor, 'feature_extractor') else 'N/A'} engineered features
โ€ข **Ensemble Robustness:** โœ… Multiple model consensus
"""
    
    return report

def create_price_chart(symbol: str, predictions: Dict) -> object:
    """Crea il grafico dei prezzi con predizioni"""
    
    # Get historical data
    ticker = yf.Ticker(symbol)
    data = ticker.history(period="6mo")
    
    fig = go.Figure()
    
    # Historical prices
    fig.add_trace(go.Scatter(
        x=data.index,
        y=data['Close'],
        mode='lines',
        name='Historical Price',
        line=dict(color='blue', width=2)
    ))
    
    # Current price marker
    fig.add_trace(go.Scatter(
        x=[data.index[-1]],
        y=[predictions['current_price']],
        mode='markers',
        name='Current Price',
        marker=dict(color='red', size=10, symbol='diamond')
    ))
    
    # Predictions
    if predictions['multi_day_predictions']:
        future_dates = pd.date_range(
            start=data.index[-1] + timedelta(days=1),
            periods=len(predictions['multi_day_predictions'])
        )
        
        fig.add_trace(go.Scatter(
            x=future_dates,
            y=predictions['multi_day_predictions'],
            mode='lines+markers',
            name='AI Predictions',
            line=dict(color='red', width=3, dash='dash')
        ))
        
        # Confidence intervals
        if predictions['confidence_intervals']:
            upper_ci = [ci[1] for ci in predictions['confidence_intervals']]
            lower_ci = [ci[0] for ci in predictions['confidence_intervals']]
            
            fig.add_trace(go.Scatter(
                x=future_dates,
                y=upper_ci,
                mode='lines',
                line=dict(color='rgba(255,0,0,0)'),
                showlegend=False
            ))
            
            fig.add_trace(go.Scatter(
                x=future_dates,
                y=lower_ci,
                mode='lines',
                fill='tonexty',
                fillcolor='rgba(255,0,0,0.2)',
                line=dict(color='rgba(255,0,0,0)'),
                name='Confidence Interval'
            ))
    
    fig.update_layout(
        title=f'{symbol} - AI Price Prediction',
        xaxis_title='Date',
        yaxis_title='Price ($)',
        template='plotly_white',
        height=500,
        showlegend=True
    )
    
    return fig

def create_prediction_chart(predictions: Dict) -> object:
    """Crea il grafico delle predizioni individuali"""
    
    individual_preds = predictions['individual_predictions']
    ensemble_pred = predictions['ensemble_prediction']
    
    models = list(individual_preds.keys())
    predicted_prices = [individual_preds[model]['predicted_price'] for model in models]
    predicted_returns = [individual_preds[model]['predicted_return'] * 100 for model in models]
    weights = [ensemble_pred['weights'][model] * 100 for model in models]
    
    fig = go.Figure()
    
    # Predicted prices
    fig.add_trace(go.Bar(
        x=models,
        y=predicted_prices,
        name='Predicted Price ($)',
        marker_color='lightblue',
        yaxis='y'
    ))
    
    # Predicted returns
    fig.add_trace(go.Scatter(
        x=models,
        y=predicted_returns,
        mode='markers+lines',
        name='Predicted Return (%)',
        marker=dict(color='red', size=10),
        yaxis='y2'
    ))
    
    # Ensemble prediction line
    fig.add_hline(
        y=ensemble_pred['price'],
        line_dash="dash",
        line_color="green",
        annotation_text=f"Ensemble: ${ensemble_pred['price']:.2f}"
    )
    
    fig.update_layout(
        title='Individual Model Predictions',
        xaxis_title='Model',
        yaxis=dict(title='Predicted Price ($)', side='left'),
        yaxis2=dict(title='Predicted Return (%)', side='right', overlaying='y'),
        template='plotly_white',
        height=400
    )
    
    return fig

def create_feature_importance_chart(feature_analysis: Dict) -> object:
    """Crea il grafico dell'importanza delle feature"""
    
    if not feature_analysis or 'top_features' not in feature_analysis:
        # Empty chart
        fig = go.Figure()
        fig.add_annotation(
            text="Feature importance not available",
            xref="paper", yref="paper",
            x=0.5, y=0.5, showarrow=False,
            font=dict(size=16)
        )
        fig.update_layout(title="Feature Importance", height=400)
        return fig
    
    top_features = feature_analysis['top_features'][:15]
    features = [f[0] for f in top_features]
    importance = [f[1] for f in top_features]
    
    fig = go.Figure(go.Bar(
        x=importance,
        y=features,
        orientation='h',
        marker_color='green'
    ))
    
    fig.update_layout(
        title='Top 15 Most Important Features',
        xaxis_title='Importance Score',
        yaxis_title='Feature',
        template='plotly_white',
        height=600,
        yaxis=dict(autorange="reversed")
    )
    
    return fig

def create_interface():
    """Crea l'interfaccia Gradio"""
    
    with gr.Blocks(title="๐Ÿค– Financial AI Predictor", theme=gr.themes.Soft()) as interface:
        
        gr.Markdown("""
        # ๐Ÿค– Financial AI Predictor
        
        **Advanced Machine Learning for Stock Prediction**
        
        This system uses state-of-the-art machine learning models to predict stock prices:
        
        - ๐Ÿง  **Pre-trained Generalista Models**: Random Forest + Gradient Boosting + Ridge Regression
        - ๐Ÿ“Š **Advanced Feature Engineering**: 50+ technical indicators and market features
        - โฐ **Real-time Data**: Live data from Yahoo Finance
        - ๐Ÿ”ฌ **Robust Validation**: Time series cross-validation
        - ๐ŸŽฏ **Ensemble Predictions**: Model consensus for better accuracy
        
        **Built with scikit-learn, yfinance, and advanced feature engineering**
        """)
        
        with gr.Row():
            with gr.Column(scale=1):
                symbol_input = gr.Textbox(
                    label="๐Ÿ“ˆ Stock Symbol",
                    placeholder="Enter symbol (e.g., AAPL, GOOGL, TSLA)",
                    value="AAPL"
                )
                
                analyze_btn = gr.Button(
                    "๐Ÿค– Run AI Analysis",
                    variant="primary",
                    size="lg"
                )
                
                gr.Markdown("""
                ### ๐ŸŽฏ How it works:
                
                **1. Data Collection**
                - Downloads 2 years of historical data
                - Real-time price and volume data
                - Technical indicators calculation
                
                **2. Feature Engineering**
                - 50+ technical indicators
                - Price momentum features
                - Volume analysis
                - Market regime detection
                
                **3. Model Training**
                - Random Forest (ensemble learning)
                - Gradient Boosting (sequential learning)
                - Ridge Regression (linear baseline)
                - Time series cross-validation
                
                **4. Ensemble Prediction**
                - Weighted model consensus
                - Confidence interval estimation
                - Multi-day forecasting
                """)
        
        with gr.Row():
            with gr.Column(scale=2):
                analysis_output = gr.Textbox(
                    label="๐Ÿค– AI Analysis Report",
                    lines=40,
                    show_copy_button=True
                )
        
        with gr.Row():
            with gr.Column():
                price_chart = gr.Plot(
                    label="๐Ÿ“ˆ Price Prediction Chart"
                )
            
            with gr.Column():
                prediction_chart = gr.Plot(
                    label="๐ŸŽฏ Model Predictions"
                )
        
        with gr.Row():
            feature_chart = gr.Plot(
                label="๐Ÿง  Feature Importance Analysis"
            )
        
        gr.Markdown("""
        ---
        ### ๐Ÿ”ฌ Technical Details
        
        **๐Ÿ“Š Feature Engineering Pipeline:**
        - **Price Features**: Returns, momentum, moving averages, ratios
        - **Volume Features**: Volume trends, price-volume relationships
        - **Technical Indicators**: RSI, MACD, Bollinger Bands, ADX, Stochastic
        - **Market Regime**: Volatility regimes, trend strength, gap analysis
        - **Risk Features**: Volatility ratios, drawdown indicators
        
        **๐Ÿค– Model Architecture:**
        - **Random Forest**: 200 trees, max depth 15, robust to overfitting
        - **Gradient Boosting**: 150 estimators, adaptive learning rate
        - **Ridge Regression**: L2 regularization, linear baseline model
        - **Ensemble**: Performance-weighted model averaging
        
        **๐Ÿ” Validation Strategy:**
        - **Time Series Split**: 5-fold chronological validation
        - **Walk-Forward**: Respects temporal structure of financial data
        - **Robust Scaling**: Handles outliers in financial data
        - **Feature Selection**: Automatic removal of low-quality features
        
        **๐Ÿ“ˆ Prediction Pipeline:**
        1. **Real-time Data**: Fetches latest market data via yfinance
        2. **Feature Extraction**: Calculates all technical indicators
        3. **Model Inference**: Each model generates independent prediction
        4. **Ensemble**: Weighted average based on validation performance
        5. **Uncertainty**: Confidence intervals from model disagreement
        
        **โš™๏ธ Key Advantages:**
        - **No API Keys Required**: Uses free Yahoo Finance data
        - **Real-time**: Fresh predictions on every request
        - **Robust**: Multiple models reduce overfitting risk
        - **Transparent**: Shows feature importance and model weights
        - **Educational**: Clear methodology and validation metrics
        
        **๐ŸŽฏ Performance Metrics:**
        - **Rยฒ Score**: Coefficient of determination (higher = better fit)
        - **Cross-Validation**: Time series aware validation
        - **Feature Importance**: Which indicators drive predictions
        - **Model Weights**: How much each model contributes
        - **Confidence Intervals**: Uncertainty quantification
        
        **๐Ÿ“Š Supported Assets:**
        - **US Stocks**: All major exchanges (NYSE, NASDAQ)
        - **International**: Many global markets via Yahoo Finance
        - **ETFs**: Index funds and sector ETFs
        - **Crypto**: Bitcoin, Ethereum (BTC-USD, ETH-USD)
        - **Indices**: S&P 500 (^GSPC), NASDAQ (^IXIC)
        
        ### โš ๏ธ Important Disclaimers
        
        **๐ŸŽ“ Educational Purpose:**
        - This tool is designed for learning about machine learning in finance
        - Demonstrates modern ML techniques applied to financial data
        - Shows how to build robust prediction systems
        
        **๐Ÿ“‰ Financial Risk Warning:**
        - **Not Financial Advice**: Predictions are for educational purposes only
        - **Past Performance**: Historical data doesn't guarantee future results
        - **Model Limitations**: ML models can fail during market regime changes
        - **Risk Management**: Always use proper position sizing and stop losses
        - **Professional Advice**: Consult qualified financial advisors for investment decisions
        
        **๐Ÿ”ฌ Technical Limitations:**
        - **Market Efficiency**: Markets may already price in predictable patterns
        - **Black Swan Events**: Models cannot predict unprecedented events
        - **Regime Changes**: Performance may degrade during market shifts
        - **Data Quality**: Predictions depend on data quality and availability
        - **Overfitting Risk**: Models may overfit to historical patterns
        
        **๐Ÿ›ก๏ธ Best Practices:**
        - Use predictions as one input among many in your analysis
        - Always validate predictions against fundamental analysis
        - Consider multiple timeframes and market conditions
        - Implement proper risk management strategies
        - Continuously monitor and retrain models
        
        ### ๐Ÿš€ Advanced Features
        
        **๐Ÿง  Machine Learning Pipeline:**
        ```python
        # Feature Engineering
        features = extract_technical_indicators(data)
        features = add_momentum_features(features)
        features = add_volatility_features(features)
        
        # Model Training
        models = [RandomForest(), GradientBoosting(), Ridge()]
        ensemble = train_ensemble(models, features, targets)
        
        # Prediction
        prediction = ensemble.predict(latest_features)
        confidence = calculate_uncertainty(models, prediction)
        ```
        
        **๐Ÿ“Š Real-time Data Processing:**
        - Automatic data fetching from Yahoo Finance
        - Real-time feature calculation
        - Dynamic model updates
        - Live prediction generation
        
        **๐Ÿ” Feature Analysis:**
        - Identifies most predictive technical indicators
        - Shows feature importance across models
        - Helps understand what drives predictions
        - Guides feature engineering improvements
        
        **๐ŸŽฏ Ensemble Intelligence:**
        - Combines strengths of different algorithms
        - Reduces single-model bias
        - Provides uncertainty quantification
        - Improves prediction robustness
        """)
        
        # Connect the interface
        analyze_btn.click(
            fn=analyze_stock,
            inputs=[symbol_input],
            outputs=[analysis_output, price_chart, prediction_chart, feature_chart]
        )
        
        # Example stocks
        gr.Examples(
            examples=[
                ["AAPL"],   # Apple - tech giant
                ["GOOGL"],  # Google - search/AI leader  
                ["MSFT"],   # Microsoft - cloud computing
                ["TSLA"],   # Tesla - EV/energy
                ["NVDA"],   # NVIDIA - AI/semiconductors
                ["AMZN"],   # Amazon - e-commerce/cloud
                ["META"],   # Meta - social media
                ["JPM"],    # JPMorgan - banking
                ["JNJ"],    # Johnson & Johnson - healthcare
                ["V"],      # Visa - payments
                ["SPY"],    # S&P 500 ETF
                ["QQQ"],    # NASDAQ 100 ETF
                ["BTC-USD"], # Bitcoin
                ["ETH-USD"], # Ethereum
                ["^GSPC"],  # S&P 500 Index
            ],
            inputs=[symbol_input],
            label="๐Ÿ“ˆ Popular Stocks & ETFs"
        )
    
    return interface

# Global predictor instance
predictor = FinancialPredictor()

def main():
    """Funzione principale"""
    print("๐Ÿค– Starting Financial AI Predictor...")
    print("๐Ÿ“Š Checking dependencies...")
    
    # Check dependencies
    try:
        import yfinance as yf
        import ta
        from sklearn.ensemble import RandomForestRegressor
        print("โœ… All dependencies available")
    except ImportError as e:
        print(f"โŒ Missing dependency: {e}")
        print("Install with: pip install yfinance ta scikit-learn plotly gradio pandas numpy")
        return
    
    # Test data fetch
    try:
        print("๐Ÿ” Testing data connection...")
        test_ticker = yf.Ticker("AAPL")
        test_data = test_ticker.history(period="5d")
        if len(test_data) > 0:
            print(f"โœ… Data connection OK: {len(test_data)} days of AAPL data")
        else:
            print("โš ๏ธ Data connection: No data returned")
    except Exception as e:
        print(f"โš ๏ธ Data connection test failed: {e}")
    
    print("=" * 60)
    print("๐ŸŽฏ Financial AI Predictor Features:")
    print("โœ… Real-time data from Yahoo Finance")
    print("โœ… Advanced feature engineering (50+ indicators)")
    print("โœ… Ensemble ML models (RF + GB + Ridge)")
    print("โœ… Time series cross-validation")
    print("โœ… Confidence interval estimation")
    print("โœ… Feature importance analysis")
    print("โœ… Multi-day forecasting")
    print("=" * 60)
    
    try:
        print("๐Ÿš€ Creating interface...")
        interface = create_interface()
        print("โœ… Interface created successfully")
        
        print("\n๐ŸŒ Launching Financial AI Predictor...")
        print("๐Ÿ“ฑ Local URL: http://localhost:7860")
        print("๐ŸŒ Public URL will be displayed below...")
        print("๐Ÿค– Ready for stock analysis!")
        print("=" * 60)
        
        interface.launch(
            server_name="0.0.0.0",
            server_port=7860,
            share=True,
            show_error=True,
            debug=False
        )
        
    except KeyboardInterrupt:
        print("\n\n๐Ÿ›‘ Financial AI Predictor stopped by user")
        print("๐Ÿ‘‹ Thanks for using the Financial AI Predictor!")
        
    except Exception as e:
        print(f"\nโŒ Failed to launch: {e}")
        print("\n๐Ÿ”ง Troubleshooting:")
        print("1. Check if port 7860 is available")
        print("2. Install dependencies:")
        print("   pip install gradio yfinance pandas numpy plotly scikit-learn ta")
        print("3. Check internet connection")
        print("4. Try a different port: interface.launch(server_port=7861)")
        
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    main()