File size: 10,866 Bytes
c49b21b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Final Null Handler Integration Script
Integrates the final null value handler into the existing merge pipeline.
"""

import sys
import subprocess
from pathlib import Path
import numpy as np
import pandas as pd
from final_null_handler import FinalNullValueHandler, process_crypto_features_file, process_stock_features_file

def run_final_null_handling():
    """Run the final null value handling on all feature files"""
    
    print("="*60)
    print("STARTING FINAL NULL VALUE HANDLING")
    print("="*60)
    
    base_path = Path("data/merged/features")
    
    files_to_process = [
        ("crypto_features.parquet", "crypto"),
        ("stocks_features.parquet", "stock"),
        ("merged_features.parquet", "merged")
    ]
    
    results = {}
    
    for filename, file_type in files_to_process:
        file_path = base_path / filename
        
        if not file_path.exists():
            print(f"[WARNING]  {filename} not found, skipping...")
            continue
        
        print(f"\n[INFO] Processing {filename}...")
        
        try:
            if file_type == "crypto":
                df_processed, report = process_crypto_features_file(file_path)
            elif file_type == "stock":
                df_processed, report = process_stock_features_file(file_path)
            elif file_type == "merged":
                # For merged file, determine type by content
                df_processed, report = process_merged_features_file(file_path)
            
            results[file_type] = {
                'success': True,
                'file_path': file_path,
                'report': report,
                'rows': len(df_processed),
                'nulls_filled': report['total_nulls_filled']
            }
            
            print(f"[SUCCESS] {filename} processed successfully!")
            print(f"   - Rows: {len(df_processed):,}")
            print(f"   - Nulls filled: {report['total_nulls_filled']:,}")
            
        except Exception as e:
            print(f"[ERROR] Error processing {filename}: {str(e)}")
            results[file_type] = {
                'success': False,
                'error': str(e),
                'file_path': file_path
            }
    
    return results

def process_merged_features_file(file_path):
    """Process merged features file (contains both crypto and stock data)"""
    print(f"Loading merged features from {file_path}...")
    df = pd.read_parquet(file_path)
    
    print(f"Loaded {len(df)} rows with {len(df.columns)} columns")
    print(f"Null values before processing: {df.isnull().sum().sum()}")
    
    handler = FinalNullValueHandler()
    
    # Separate crypto and stock data if possible
    if 'symbol' in df.columns:
        # Detect crypto vs stock based on available columns
        crypto_indicators = ['rank', 'dominance', 'performance.day', 'exchangePrices.binance']
        stock_indicators = ['news_activity_score_x', 'strongBuy', 'marketCapitalization']
        
        has_crypto_cols = any(col in df.columns for col in crypto_indicators)
        has_stock_cols = any(col in df.columns for col in stock_indicators)
        
        if has_crypto_cols and has_stock_cols:
            # Mixed data - process intelligently
            print("Detected mixed crypto/stock data - processing intelligently...")
            
            # Try to separate by symbol patterns or available data
            crypto_mask = df['rank'].notna() | df['dominance'].notna()
            if crypto_mask.any():
                print(f"Processing {crypto_mask.sum()} rows as crypto data...")
                df_crypto = df[crypto_mask].copy()
                df_crypto_processed = handler.process_crypto_features(df_crypto)
                df.loc[crypto_mask] = df_crypto_processed
            
            stock_mask = ~crypto_mask
            if stock_mask.any():
                print(f"Processing {stock_mask.sum()} rows as stock data...")
                df_stock = df[stock_mask].copy()
                df_stock_processed = handler.process_stock_features(df_stock)
                df.loc[stock_mask] = df_stock_processed
            
            df_processed = df
            
        elif has_crypto_cols:
            print("Detected crypto-only data...")
            df_processed = handler.process_crypto_features(df)
        elif has_stock_cols:
            print("Detected stock-only data...")
            df_processed = handler.process_stock_features(df)
        else:
            print("Could not determine data type, applying generic processing...")
            df_processed = handler.process_stock_features(df)  # Default to stock processing
    else:
        print("No symbol column found, applying generic processing...")
        df_processed = handler.process_stock_features(df)
    
    print(f"Null values after processing: {df_processed.isnull().sum().sum()}")
    
    # Generate report
    report = handler.generate_report(df, df_processed, 'merged')
    
    # Save processed data
    df_processed.to_parquet(file_path, index=False)
    print(f"Saved processed merged features to {file_path}")
    
    return df_processed, report

def validate_data_quality(results):
    """Validate that the data quality is maintained after null handling"""
    print("\n" + "="*60)
    print("DATA QUALITY VALIDATION")
    print("="*60)
    
    validation_results = {}
    
    for file_type, result in results.items():
        if not result.get('success', False):
            continue
        
        file_path = result['file_path']
        
        try:
            df = pd.read_parquet(file_path)
            
            # Basic validation checks
            validation = {
                'total_rows': len(df),
                'total_columns': len(df.columns),
                'remaining_nulls': df.isnull().sum().sum(),
                'duplicate_rows': df.duplicated().sum(),
                'infinite_values': np.isinf(df.select_dtypes(include=[np.number])).sum().sum(),
                'data_types_consistent': True,  # Could add more sophisticated checks
            }
            
            # Check for unrealistic values
            numeric_cols = df.select_dtypes(include=[np.number]).columns
            extreme_values = {}
            
            for col in numeric_cols:
                if col in df.columns:
                    col_data = df[col].dropna()
                    if len(col_data) > 0:
                        q1, q99 = col_data.quantile([0.01, 0.99])
                        extreme_count = ((col_data < q1 - 10 * (q99 - q1)) | 
                                       (col_data > q99 + 10 * (q99 - q1))).sum()
                        if extreme_count > 0:
                            extreme_values[col] = extreme_count
            
            validation['extreme_values'] = extreme_values
            validation['quality_score'] = calculate_quality_score(validation)
            
            validation_results[file_type] = validation
            
            print(f"\n{file_type.upper()} VALIDATION:")
            print(f"  βœ“ Rows: {validation['total_rows']:,}")
            print(f"  βœ“ Columns: {validation['total_columns']}")
            print(f"  βœ“ Remaining nulls: {validation['remaining_nulls']}")
            print(f"  βœ“ Duplicate rows: {validation['duplicate_rows']}")
            print(f"  βœ“ Infinite values: {validation['infinite_values']}")
            print(f"  βœ“ Quality score: {validation['quality_score']:.2%}")
            
            if extreme_values:
                print(f"  [WARNING]  Extreme values detected in {len(extreme_values)} columns")
            
        except Exception as e:
            print(f"[ERROR] Validation failed for {file_type}: {str(e)}")
            validation_results[file_type] = {'error': str(e)}
    
    return validation_results

def calculate_quality_score(validation):
    """Calculate a simple quality score"""
    score = 1.0
    
    # Penalize remaining nulls
    if validation['total_rows'] > 0:
        null_ratio = validation['remaining_nulls'] / (validation['total_rows'] * validation['total_columns'])
        score -= null_ratio * 0.5
    
    # Penalize duplicates
    if validation['total_rows'] > 0:
        dup_ratio = validation['duplicate_rows'] / validation['total_rows']
        score -= dup_ratio * 0.3
    
    # Penalize infinite values
    if validation['infinite_values'] > 0:
        score -= 0.1
    
    # Penalize extreme values
    extreme_columns = len(validation.get('extreme_values', {}))
    if extreme_columns > 0:
        score -= (extreme_columns / validation['total_columns']) * 0.2
    
    return max(0.0, score)

def print_final_summary(results, validation_results):
    """Print final summary of the null handling process"""
    print("\n" + "="*60)
    print("FINAL NULL HANDLING SUMMARY")
    print("="*60)
    
    total_nulls_filled = sum(r.get('nulls_filled', 0) for r in results.values() if r.get('success'))
    successful_files = sum(1 for r in results.values() if r.get('success'))
    total_files = len(results)
    
    print(f"\n[INFO] PROCESSING RESULTS:")
    print(f"   Files processed: {successful_files}/{total_files}")
    print(f"   Total nulls filled: {total_nulls_filled:,}")
    
    print(f"\n[METRICS] QUALITY METRICS:")
    for file_type, validation in validation_results.items():
        if 'error' not in validation:
            print(f"   {file_type}: {validation['quality_score']:.1%} quality score")
    
    if successful_files == total_files:
        print(f"\n[SUCCESS] ALL FILES PROCESSED SUCCESSFULLY!")
    else:
        failed_files = total_files - successful_files
        print(f"\n[WARNING]  {failed_files} files failed to process")
    
    print("\n[TIPS] RECOMMENDATIONS:")
    print("   - Review any remaining null columns in the reports")
    print("   - Monitor data quality scores in production")
    print("   - Consider additional validation rules if needed")
    
    print("\n" + "="*60)

def main():
    """Main function"""
    try:
        # Import numpy for validation
        import numpy as np
        globals()['np'] = np
        
        # Run the null handling process
        results = run_final_null_handling()
        
        # Validate data quality
        validation_results = validate_data_quality(results)
        
        # Print final summary
        print_final_summary(results, validation_results)
        
        # Return success if all files processed successfully
        success_count = sum(1 for r in results.values() if r.get('success'))
        return 0 if success_count == len(results) else 1
        
    except Exception as e:
        print(f"[ERROR] Fatal error in null handling process: {str(e)}")
        return 1

if __name__ == "__main__":
    exit_code = main()
    sys.exit(exit_code)