diff --git a/ai_ml_lotto_generator.py b/ai_ml_lotto_generator.py deleted file mode 100644 index f775827..0000000 --- a/ai_ml_lotto_generator.py +++ /dev/null @@ -1,1336 +0,0 @@ -#!/usr/bin/env python3 -""" -AI-ML ULTIMATE LOTTO GENERATOR -Real-Time AI + Machine Learning für maximale Trefferquote - -Features: -- LSTM Neural Networks für Zeitreihen-Vorhersage -- Random Forest + Gradient Boosting Ensemble -- Real-Time Learning nach jeder Ziehung -- Adaptive Algorithmen die sich selbst optimieren -- Multi-Model Ensemble mit Confidence Scoring -- Live Performance Tracking und Auto-Adjustment -""" - -import pandas as pd -import numpy as np -import random -from collections import Counter, defaultdict, deque -import datetime -import pickle -import os -import json -import time - -# Machine Learning Imports -try: - from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor - from sklearn.neural_network import MLPRegressor - from sklearn.preprocessing import StandardScaler, MinMaxScaler - from sklearn.model_selection import train_test_split, cross_val_score - from sklearn.metrics import mean_squared_error, r2_score - import joblib - ML_AVAILABLE = True -except ImportError: - print("⚠️ Installiere scikit-learn für ML-Features: pip install scikit-learn") - ML_AVAILABLE = False - -# Deep Learning (optional) -try: - import tensorflow as tf - from tensorflow.keras.models import Sequential, load_model - from tensorflow.keras.layers import LSTM, Dense, Dropout - from tensorflow.keras.optimizers import Adam - DEEP_LEARNING_AVAILABLE = True -except ImportError: - DEEP_LEARNING_AVAILABLE = False - -class AIMLLottoGenerator: - def __init__(self, data_path): - self.data_path = data_path - self.df = None - - # AI/ML Core Systems - self.ml_models = {} - self.deep_models = {} - self.trained_models = {} # Initialize trained_models - self.ensemble_weights = {} - self.performance_tracker = PerformanceTracker() - self.real_time_learner = RealTimeLearner() - self.model_cache_path = os.path.join(os.path.dirname(data_path), "ml_models_cache") - - # Feature Engineering Pipeline - self.feature_engineer = FeatureEngineer() - self.scaler = StandardScaler() - self.is_trained = False - - # Real-Time Data Structures - self.prediction_history = deque(maxlen=100) - self.accuracy_tracker = {} - self.adaptive_weights = {} - - print("🤖 AI-ML ULTIMATE LOTTO GENERATOR") - print("=" * 50) - print("🧠 Real-Time AI + Machine Learning System") - - # Initialize - self.load_data() - if ML_AVAILABLE: - self.setup_ml_pipeline() - else: - print("⚠️ ML nicht verfügbar - verwende Fallback-Modus") - - def load_data(self): - """Lädt und preprocessed Lotto-Daten für ML.""" - try: - self.df = pd.read_csv(self.data_path, sep=';') - - # Datum konvertieren - if 'datum' in self.df.columns: - self.df['datum'] = pd.to_datetime(self.df['datum'], format='%Y-%m-%d', errors='coerce') - self.df = self.df.sort_values('datum') - - print(f"📊 {len(self.df)} Ziehungen für AI-Training geladen") - print(f"📅 Zeitraum: {len(self.df)} Ziehungen analysiert") - - # Data Quality Check - self._validate_data_quality() - - except Exception as e: - print(f"❌ Fehler beim Laden: {e}") - return False - - return True - - def _validate_data_quality(self): - """Validiert Datenqualität für ML.""" - issues = [] - - # Check for missing values - if self.df.isnull().sum().sum() > 0: - issues.append("Missing values detected") - - # Check number ranges - number_cols = ['Z1', 'Z2', 'Z3', 'Z4', 'Z5', 'Z6'] - for col in number_cols: - if col in self.df.columns: - if (self.df[col] < 1).any() or (self.df[col] > 49).any(): - issues.append(f"Invalid range in {col}") - - if issues: - print(f"⚠️ Data Quality Issues: {', '.join(issues)}") - else: - print("✅ Data Quality: Excellent") - - def setup_ml_pipeline(self): - """Setup Machine Learning Pipeline.""" - print("\n🔧 SETTING UP AI-ML PIPELINE...") - - try: - # 1. Feature Engineering - print("🔍 Feature Engineering...") - self.features_df = self.feature_engineer.create_features(self.df) - print(f"✅ {len(self.features_df)} feature vectors created") - - # 2. Setup ML Models - print("🧠 Initializing ML Models...") - self._initialize_ml_models() - - # 3. Setup Deep Learning - if DEEP_LEARNING_AVAILABLE: - print("🚀 Initializing Deep Learning Models...") - self._initialize_deep_models() - - # 4. Load or Train Models - if self._models_exist(): - print("📂 Loading pre-trained models...") - self._load_trained_models() - else: - print("🎯 Training new AI models...") - # Only train if we have sufficient data - if len(self.df) >= 50: - self._train_all_models() - else: - print("⚠️ Insufficient data for training - using fallback mode") - self.trained_models = {} # Ensure it's initialized - - # 5. Initialize Real-Time Learning - print("⚡ Activating Real-Time Learning...") - self.real_time_learner.initialize(self.features_df) - - print("✅ AI-ML Pipeline ready!") - - except Exception as e: - print(f"⚠️ ML Pipeline setup failed: {e}") - print("🔄 Falling back to basic mode...") - self.trained_models = {} # Ensure it's initialized - self.is_trained = False - - def _initialize_ml_models(self): - """Initialisiert ML-Modelle mit optimierten Hyperparametern.""" - if not ML_AVAILABLE: - return - - self.ml_models = { - 'random_forest': RandomForestRegressor( - n_estimators=200, - max_depth=10, - min_samples_split=5, - min_samples_leaf=2, - random_state=42, - n_jobs=-1 - ), - 'gradient_boost': GradientBoostingRegressor( - n_estimators=150, - learning_rate=0.1, - max_depth=6, - random_state=42 - ), - 'neural_network': MLPRegressor( - hidden_layer_sizes=(100, 50, 25), - activation='relu', - solver='adam', - learning_rate='adaptive', - random_state=42, - max_iter=1000 - ) - } - - # Initial equal weights - self.ensemble_weights = {name: 1/len(self.ml_models) for name in self.ml_models.keys()} - - def _initialize_deep_models(self): - """Initialisiert Deep Learning Modelle.""" - if not DEEP_LEARNING_AVAILABLE: - return - - # LSTM für Zeitreihen-Vorhersage - self.deep_models['lstm'] = self._create_lstm_model() - - # CNN für Pattern-Erkennung - self.deep_models['cnn'] = self._create_cnn_model() - - def _create_lstm_model(self): - """Erstellt LSTM-Modell für Zeitreihen.""" - model = Sequential([ - LSTM(50, return_sequences=True, input_shape=(10, 6)), # 10 timesteps, 6 features - Dropout(0.2), - LSTM(50, return_sequences=False), - Dropout(0.2), - Dense(25, activation='relu'), - Dense(1, activation='sigmoid') # Wahrscheinlichkeit für jede Zahl - ]) - - model.compile( - optimizer=Adam(learning_rate=0.001), - loss='mse', - metrics=['mae'] - ) - - return model - - def _create_cnn_model(self): - """Erstellt CNN für Pattern-Erkennung.""" - model = Sequential([ - tf.keras.layers.Conv1D(64, 3, activation='relu', input_shape=(49, 1)), - tf.keras.layers.MaxPooling1D(2), - tf.keras.layers.Conv1D(32, 3, activation='relu'), - tf.keras.layers.Flatten(), - tf.keras.layers.Dense(50, activation='relu'), - tf.keras.layers.Dropout(0.3), - Dense(1, activation='sigmoid') - ]) - - model.compile( - optimizer=Adam(learning_rate=0.001), - loss='mse', - metrics=['mae'] - ) - - return model - - def _models_exist(self): - """Prüft ob trainierte Modelle existieren.""" - return os.path.exists(self.model_cache_path) - - def _train_all_models(self): - """Trainiert alle AI-Modelle.""" - print("\n🎯 TRAINING AI MODELS...") - - if not ML_AVAILABLE or len(self.features_df) < 50: - print("❌ Insufficient data for training") - return - - # Prepare training data für jede Zahl - training_results = {} - - for number in range(1, 50): - print(f"Training models for number {number}...") - - # Features und Labels für diese Zahl - X, y = self._prepare_training_data_for_number(number) - - if len(X) < 20: # Minimum training samples - continue - - # Train/Test Split - X_train, X_test, y_train, y_test = train_test_split( - X, y, test_size=0.2, random_state=42 - ) - - # Scale features - scaler = StandardScaler() - X_train_scaled = scaler.fit_transform(X_train) - X_test_scaled = scaler.transform(X_test) - - number_models = {} - number_scores = {} - - # Train each ML model - for model_name, model in self.ml_models.items(): - try: - model.fit(X_train_scaled, y_train) - - # Evaluate - y_pred = model.predict(X_test_scaled) - score = r2_score(y_test, y_pred) - - number_models[model_name] = { - 'model': model, - 'scaler': scaler, - 'score': score - } - number_scores[model_name] = score - - print(f" {model_name}: R² = {score:.3f}") - - except Exception as e: - print(f" ❌ {model_name} failed: {e}") - - training_results[number] = { - 'models': number_models, - 'scores': number_scores - } - - # Save trained models - self._save_trained_models(training_results) - self.is_trained = True - - print("✅ All models trained successfully!") - - def _prepare_training_data_for_number(self, number): - """Bereitet Trainingsdaten für spezifische Zahl vor.""" - X = [] - y = [] - - # Sliding window approach - window_size = 10 - - for i in range(window_size, len(self.features_df)): - # Features: letzte 10 Ziehungen - features_window = [] - - for j in range(i - window_size, i): - row_features = [ - self.features_df.iloc[j]['freq_last_10'], - self.features_df.iloc[j]['trend_score'], - self.features_df.iloc[j]['position_bias'], - self.features_df.iloc[j]['gap_since_last'], - self.features_df.iloc[j]['seasonal_factor'], - self.features_df.iloc[j]['day_of_week'] - ] - features_window.extend(row_features) - - X.append(features_window) - - # Label: Wurde diese Zahl in der aktuellen Ziehung gezogen? - current_numbers = [ - self.df.iloc[i]['Z1'], self.df.iloc[i]['Z2'], self.df.iloc[i]['Z3'], - self.df.iloc[i]['Z4'], self.df.iloc[i]['Z5'], self.df.iloc[i]['Z6'] - ] - y.append(1 if number in current_numbers else 0) - - return np.array(X), np.array(y) - - def _save_trained_models(self, training_results): - """Speichert trainierte Modelle.""" - os.makedirs(self.model_cache_path, exist_ok=True) - - # Save with joblib for sklearn models - cache_file = os.path.join(self.model_cache_path, "trained_models.pkl") - with open(cache_file, 'wb') as f: - pickle.dump(training_results, f) - - print(f"💾 Models saved to {cache_file}") - - def _load_trained_models(self): - """Lädt vortrainierte Modelle.""" - cache_file = os.path.join(self.model_cache_path, "trained_models.pkl") - - try: - with open(cache_file, 'rb') as f: - self.trained_models = pickle.load(f) - - self.is_trained = True - print("✅ Pre-trained models loaded") - - except Exception as e: - print(f"❌ Failed to load models: {e}") - self._train_all_models() - - def predict_with_ai_ensemble(self): - """Vorhersage mit AI-Ensemble für alle Zahlen.""" - if not self.is_trained or not self.trained_models: - print("❌ Models not trained yet - using fallback predictions") - return self._generate_fallback_predictions() - - predictions = {} - - # Current features für Vorhersage - try: - current_features = self.feature_engineer.get_current_features(self.df) - except: - print("⚠️ Feature extraction failed - using fallback") - return self._generate_fallback_predictions() - - for number in range(1, 50): - if number not in self.trained_models: - predictions[number] = 0.1 + (number % 10) * 0.05 # Varied default - continue - - number_models = self.trained_models[number]['models'] - ensemble_pred = 0 - total_weight = 0 - - # Ensemble prediction - for model_name, model_data in number_models.items(): - try: - model = model_data['model'] - scaler = model_data['scaler'] - score = model_data['score'] - - # Prepare features - features_scaled = scaler.transform([current_features]) - pred = model.predict(features_scaled)[0] - - # Weight by model performance - weight = max(score, 0.1) # Minimum weight - ensemble_pred += pred * weight - total_weight += weight - - except Exception as e: - continue - - if total_weight > 0: - predictions[number] = min(max(ensemble_pred / total_weight, 0), 1) - else: - predictions[number] = 0.1 + (number % 10) * 0.02 - - return predictions - - def _generate_fallback_predictions(self): - """Generiert Fallback-Predictions ohne ML.""" - predictions = {} - - if len(self.df) == 0: - # Completely random if no data - for number in range(1, 50): - predictions[number] = 0.1 + random.random() * 0.4 - return predictions - - # Simple frequency-based predictions - number_freq = Counter() - recent_data = self.df.tail(20) # Last 20 drawings - - for _, row in recent_data.iterrows(): - numbers = [row.get('Z1', 0), row.get('Z2', 0), row.get('Z3', 0), - row.get('Z4', 0), row.get('Z5', 0), row.get('Z6', 0)] - for num in numbers: - if 1 <= num <= 49: - number_freq[num] += 1 - - # Convert to predictions - max_freq = max(number_freq.values()) if number_freq else 1 - - for number in range(1, 50): - freq = number_freq.get(number, 0) - base_prediction = 0.1 + (freq / max_freq) * 0.4 - # Add some randomness - predictions[number] = base_prediction + random.random() * 0.1 - - return predictions - - def generate_ai_tips(self, num_tips=10): - """Generiert AI-optimierte Tipps.""" - print("\n🤖 GENERATING AI-OPTIMIZED TIPS...") - - if not ML_AVAILABLE: - print("❌ ML not available - using enhanced fallback method") - return self._generate_enhanced_fallback_tips(num_tips) - - # AI Predictions - try: - ai_predictions = self.predict_with_ai_ensemble() - except Exception as e: - print(f"⚠️ AI prediction failed: {e} - using fallback") - ai_predictions = self._generate_fallback_predictions() - - # Real-Time Learning Update - try: - self.real_time_learner.update_predictions(ai_predictions) - except: - pass # Continue without real-time learning if it fails - - tips = [] - - print("🎯 AI-PREDICTION SCORES (Top 20):") - sorted_predictions = sorted(ai_predictions.items(), key=lambda x: x[1], reverse=True)[:20] - for i, (num, score) in enumerate(sorted_predictions): - status = "🔥" if score > 0.6 else "🌡️" if score > 0.4 else "😐" - print(f" {i+1:2}. Zahl {num:2}: {score:.3f} {status}") - - print(f"\n🎲 GENERATING {num_tips} AI-OPTIMIZED TIPS:") - print("=" * 70) - print("Nr 6 AI-Optimized Numbers SZ AI-Score Confidence Method") - print("-" * 70) - - for i in range(1, num_tips + 1): - tip = self._generate_single_ai_tip(ai_predictions, i) - tips.append(tip) - - # Output - zahlen_str = '-'.join([f"{n:2}" for n in tip['numbers']]) - print(f"{i:2} {zahlen_str} {tip['superzahl']} {tip['ai_score']:.3f} {tip['confidence']:.3f} {tip['method']}") - - # Update Performance Tracker - try: - self.performance_tracker.log_generated_tips(tips) - except: - pass - - # Real-Time Learning - try: - self.real_time_learner.learn_from_generation(tips, ai_predictions) - except: - pass - - return tips - - def _generate_enhanced_fallback_tips(self, num_tips): - """Enhanced Fallback wenn ML nicht verfügbar.""" - print("🔄 Using enhanced fallback method with frequency analysis...") - - tips = [] - - # Frequency analysis from data - if len(self.df) > 0: - number_freq = Counter() - superzahl_freq = Counter() - - # Analyze recent data - recent_data = self.df.tail(50) # Last 50 drawings - - for _, row in recent_data.iterrows(): - numbers = [] - for col in ['Z1', 'Z2', 'Z3', 'Z4', 'Z5', 'Z6']: - if col in row and pd.notna(row[col]): - num = int(row[col]) - if 1 <= num <= 49: - numbers.append(num) - number_freq[num] += 1 - - if 'SZ' in row and pd.notna(row['SZ']): - sz = int(row['SZ']) - if 0 <= sz <= 9: - superzahl_freq[sz] += 1 - - # Get hot numbers - hot_numbers = [num for num, freq in number_freq.most_common(20)] - top_superzahlen = [sz for sz, freq in superzahl_freq.most_common(5)] - else: - hot_numbers = list(range(1, 50)) - top_superzahlen = list(range(10)) - - for i in range(1, num_tips + 1): - # Mix of hot numbers and random selection - hot_selection = random.sample(hot_numbers[:15], min(4, len(hot_numbers))) - remaining_needed = 6 - len(hot_selection) - - if remaining_needed > 0: - available_numbers = [n for n in range(1, 50) if n not in hot_selection] - random_selection = random.sample(available_numbers, remaining_needed) - numbers = sorted(hot_selection + random_selection) - else: - numbers = sorted(hot_selection[:6]) - - superzahl = random.choice(top_superzahlen) if top_superzahlen else random.randint(0, 9) - - tip = { - 'tip_number': i, - 'numbers': numbers, - 'superzahl': superzahl, - 'ai_score': 0.4 + random.random() * 0.2, # Mock AI score - 'confidence': 0.3 + random.random() * 0.2, # Mock confidence - 'method': 'ENHANCED-FALLBACK' - } - tips.append(tip) - - return tips - - def _generate_single_ai_tip(self, ai_predictions, tip_number): - """Generiert einzelnen AI-Tipp mit verbesserter Diversität.""" - - # Top candidates basierend auf AI-Predictions - sorted_numbers = sorted(ai_predictions.items(), key=lambda x: x[1], reverse=True) - - # Intelligent selection mit echter Diversität - selected = [] - - # Strategy: Top AI predictions mit smart diversification - top_candidates = [num for num, score in sorted_numbers[:25]] - - # Seed für unterschiedliche Tipps - random.seed(42 + tip_number) # Unterschiedlicher Seed pro Tipp! - - # Erste Zahl: Top AI Prediction mit etwas Variation - first_candidates = sorted_numbers[:5] # Top 5 - selected.append(random.choice([num for num, score in first_candidates])) - - # Restliche 5 Zahlen mit intelligenter Auswahl - for position in range(2, 7): # Positionen 2-6 - best_candidate = None - best_combined_score = -1 - - # Kandidaten für diese Position - position_candidates = [] - - if position <= 2: # Frühe Positionen: Top Candidates - position_candidates = top_candidates[:15] - elif position <= 4: # Mittlere Positionen: Erweitert - position_candidates = top_candidates[:20] - else: # Späte Positionen: Noch breiter - position_candidates = top_candidates - - for candidate in position_candidates: - if candidate not in selected: - ai_score = ai_predictions[candidate] - diversity_bonus = self._calculate_enhanced_diversity_bonus(candidate, selected, tip_number) - - # Position-spezifische Gewichtung - position_weight = 1.0 + (random.random() - 0.5) * 0.3 # ±15% Variation - - combined_score = (ai_score * 0.6 + diversity_bonus * 0.4) * position_weight - - if combined_score > best_combined_score: - best_combined_score = combined_score - best_candidate = candidate - - if best_candidate: - selected.append(best_candidate) - else: - # Fallback: Zufällige verfügbare Zahl - available = [n for n in range(1, 50) if n not in selected] - if available: - selected.append(random.choice(available)) - - # Ensure exactly 6 unique numbers - selected = list(set(selected)) - while len(selected) < 6: - available = [n for n in range(1, 50) if n not in selected] - if available: - selected.append(random.choice(available)) - else: - break - - selected = sorted(selected[:6]) - - # Tip-spezifische Superzahl - saubere Version - superzahl = self._get_varied_superzahl(tip_number) - - # Stelle sicher dass superzahl ein Integer ist - if not isinstance(superzahl, int): - superzahl = int(superzahl) if superzahl is not None else 7 - - # Berechne Scores - ai_score = np.mean([ai_predictions.get(num, 0.1) for num in selected]) - confidence = self._calculate_tip_confidence(selected, ai_predictions) - - return { - 'tip_number': tip_number, - 'numbers': selected, - 'superzahl': superzahl, # DEBUG: Stelle sicher dass es gesetzt wird - 'ai_score': ai_score, - 'confidence': confidence, - 'method': 'AI-ENSEMBLE-V2', - 'timestamp': datetime.datetime.now() - } - - def _calculate_enhanced_diversity_bonus(self, candidate, selected, tip_number): - """Verbesserte Diversitäts-Berechnung mit Tip-spezifischen Faktoren.""" - if not selected: - return 1.0 - - bonus = 0.0 - - # 1. Abstands-Diversität (verbessert) - distances = [abs(candidate - sel) for sel in selected] - min_distance = min(distances) - avg_distance = np.mean(distances) - - # Belohne größere Abstände, aber nicht zu extrem - distance_bonus = min(min_distance / 8.0, 0.4) + min(avg_distance / 12.0, 0.3) - bonus += distance_bonus - - # 2. Bereichs-Diversität (N/M/H) - verbessert - def get_range(num): - if num <= 16: return 'N' - elif num <= 32: return 'M' - else: return 'H' - - candidate_range = get_range(candidate) - selected_ranges = [get_range(s) for s in selected] - range_counts = Counter(selected_ranges) - - # Bevorzuge ausgewogene Verteilung - current_count = range_counts.get(candidate_range, 0) - if current_count < 2: # Max 2 pro Bereich für Ausgeglichenheit - bonus += 0.25 - elif current_count >= 3: - bonus -= 0.15 # Penalty für Überrepräsentation - - # 3. Tip-spezifische Variation - tip_factor = (tip_number * 17) % 49 # Pseudo-random basierend auf Tip-Nummer - if candidate % 7 == tip_factor % 7: - bonus += 0.1 # Kleine Tip-spezifische Präferenz - - # 4. Gerade/Ungerade Balance - even_count = sum(1 for s in selected if s % 2 == 0) - candidate_is_even = candidate % 2 == 0 - - if len(selected) < 3: # Frühe Auswahl - bonus += 0.1 # Wenig Penalty - elif even_count < 2 and candidate_is_even: - bonus += 0.2 # Brauchen mehr gerade Zahlen - elif even_count > 3 and not candidate_is_even: - bonus += 0.2 # Brauchen mehr ungerade Zahlen - elif even_count >= 4 and candidate_is_even: - bonus -= 0.1 # Zu viele gerade Zahlen - - return max(0, min(bonus, 1.0)) # Clamp zwischen 0 und 1 - - def _get_varied_superzahl(self, tip_number): - """Generiert variierte Superzahl basierend auf Tip-Nummer.""" - - # Einfache, robuste Superzahl-Generierung - base_superzahlen = [7, 6, 3, 2, 0, 1, 4, 5, 8, 9] - - # Versuche historische Daten zu nutzen - try: - if hasattr(self, 'df') and self.df is not None and 'SZ' in self.df.columns and len(self.df) > 10: - recent_sz = self.df['SZ'].tail(20).dropna() - if len(recent_sz) > 0: - sz_freq = Counter(recent_sz) - if sz_freq: - # Top 5 häufigste als base nehmen - frequent_sz = [int(sz) for sz, _ in sz_freq.most_common(5) if 0 <= sz <= 9] - if frequent_sz: - base_superzahlen = frequent_sz + [7, 6, 3, 2, 0] # Mit Fallback - except Exception as e: - pass # Fallback zu default base_superzahlen - - # Tip-spezifische Auswahl - try: - if tip_number <= 3: - # Top Tipps: Häufigste SZ - result = base_superzahlen[0] - elif tip_number <= 6: - # Mittlere Tipps: Aus Top 3 wählen - available = base_superzahlen[:3] - result = available[tip_number % len(available)] - else: - # Späte Tipps: Breitere Variation - result = base_superzahlen[tip_number % len(base_superzahlen)] - - # Sicherstellen dass es ein Integer zwischen 0-9 ist - result = int(result) - if not (0 <= result <= 9): - result = 7 - - return result - - except Exception as e: - return 7 - - def _calculate_ai_diversity_bonus(self, candidate, selected): - """Berechnet AI-Diversitäts-Bonus.""" - if not selected: - return 1.0 - - # Abstands-Diversität - distances = [abs(candidate - sel) for sel in selected] - min_distance = min(distances) - distance_bonus = min(min_distance / 8.0, 0.5) - - # Bereichs-Diversität (N/M/H) - def get_range(num): - if num <= 16: return 0 - elif num <= 32: return 1 - else: return 2 - - candidate_range = get_range(candidate) - selected_ranges = [get_range(s) for s in selected] - range_counts = Counter(selected_ranges) - - if range_counts[candidate_range] < 2: - range_bonus = 0.3 - else: - range_bonus = 0.1 - - return distance_bonus + range_bonus - - def _get_ai_superzahl(self): - """AI-optimierte Superzahl-Auswahl.""" - # Vereinfacht: basierend auf aktuellen Trends - if 'SZ' in self.df.columns: - recent_sz = self.df['SZ'].tail(10) - sz_freq = Counter(recent_sz) - # Wähle häufigste aus letzten Ziehungen - if sz_freq: - return sz_freq.most_common(1)[0][0] - - return random.randint(0, 9) - - def _calculate_tip_confidence(self, numbers, ai_predictions): - """Berechnet Confidence-Score für Tipp.""" - individual_scores = [ai_predictions[num] for num in numbers] - - # Kombination aus Durchschnitt und Mindest-Score - avg_score = np.mean(individual_scores) - min_score = min(individual_scores) - - confidence = avg_score * 0.7 + min_score * 0.3 - return confidence - - def update_with_new_drawing(self, new_drawing): - """Real-Time Update mit neuer Ziehung.""" - print(f"\n⚡ REAL-TIME UPDATE mit neuer Ziehung...") - - # Validate drawing format - if not self._validate_drawing_format(new_drawing): - print("❌ Invalid drawing format") - return - - # Add to dataframe - self._add_drawing_to_data(new_drawing) - - # Update Performance Tracker - self.performance_tracker.evaluate_predictions(new_drawing) - - # Real-Time Learning - self.real_time_learner.learn_from_result(new_drawing) - - # Adaptive Model Updates - self._adaptive_model_update() - - print("✅ Real-Time Update completed") - - def _validate_drawing_format(self, drawing): - """Validiert Format der neuen Ziehung.""" - required_keys = ['Z1', 'Z2', 'Z3', 'Z4', 'Z5', 'Z6'] - - for key in required_keys: - if key not in drawing: - return False - if not (1 <= drawing[key] <= 49): - return False - - return True - - def _add_drawing_to_data(self, new_drawing): - """Fügt neue Ziehung zu Daten hinzu.""" - # Convert to dataframe row - new_row = pd.DataFrame([new_drawing]) - self.df = pd.concat([self.df, new_row], ignore_index=True) - - # Update features - self.features_df = self.feature_engineer.create_features(self.df) - - def _adaptive_model_update(self): - """Adaptive Modell-Updates basierend auf Performance.""" - if not self.is_trained: - return - - # Update ensemble weights basierend auf recent performance - model_performance = self.performance_tracker.get_model_performance() - - if model_performance: - total_performance = sum(model_performance.values()) - if total_performance > 0: - # Update weights - for model_name in self.ensemble_weights: - if model_name in model_performance: - self.ensemble_weights[model_name] = model_performance[model_name] / total_performance - - print("🔄 Adaptive weights updated") - - def _generate_fallback_tips(self, num_tips): - """Fallback wenn ML nicht verfügbar.""" - print("🔄 Using fallback method...") - - tips = [] - for i in range(1, num_tips + 1): - numbers = sorted(random.sample(range(1, 50), 6)) - tip = { - 'tip_number': i, - 'numbers': numbers, - 'superzahl': random.randint(0, 9), - 'ai_score': 0.5, - 'confidence': 0.3, - 'method': 'FALLBACK' - } - tips.append(tip) - - return tips - - def get_ai_insights(self): - """Liefert AI-Insights und Performance-Statistiken.""" - insights = { - 'model_status': 'Trained' if self.is_trained else 'Not Trained', - 'ml_available': ML_AVAILABLE, - 'deep_learning_available': DEEP_LEARNING_AVAILABLE, - 'data_size': len(self.df), - 'performance_stats': self.performance_tracker.get_statistics(), - 'adaptive_weights': self.ensemble_weights, - 'learning_stats': self.real_time_learner.get_learning_stats() - } - - return insights - -# Support Classes - -class FeatureEngineer: - def create_features(self, df): - """Erstellt Features für ML-Training.""" - features_list = [] - - for i in range(len(df)): - row_features = self._extract_row_features(df, i) - features_list.append(row_features) - - features_df = pd.DataFrame(features_list) - return features_df - - def _extract_row_features(self, df, row_idx): - """Extrahiert Features für eine Zeile.""" - features = {} - - # Historical frequency features - window_sizes = [5, 10, 20] - for window in window_sizes: - start_idx = max(0, row_idx - window) - historical_data = df.iloc[start_idx:row_idx] - - if len(historical_data) > 0: - all_numbers = [] - for _, row in historical_data.iterrows(): - numbers = [row['Z1'], row['Z2'], row['Z3'], row['Z4'], row['Z5'], row['Z6']] - all_numbers.extend(numbers) - - features[f'freq_last_{window}'] = len(set(all_numbers)) / (window * 6) if window > 0 else 0 - else: - features[f'freq_last_{window}'] = 0 - - # Trend features - features['trend_score'] = self._calculate_trend_score(df, row_idx) - features['position_bias'] = self._calculate_position_bias(df, row_idx) - features['gap_since_last'] = self._calculate_gap_since_last(df, row_idx) - - # Temporal features - if 'datum' in df.columns and pd.notna(df.iloc[row_idx]['datum']): - date = df.iloc[row_idx]['datum'] - features['day_of_week'] = date.dayofweek - features['month'] = date.month - features['seasonal_factor'] = np.sin(2 * np.pi * date.dayofyear / 365) - else: - features['day_of_week'] = 0 - features['month'] = 1 - features['seasonal_factor'] = 0 - - return features - - def _calculate_trend_score(self, df, row_idx): - """Berechnet Trend-Score.""" - if row_idx < 5: - return 0 - - recent_data = df.iloc[max(0, row_idx-5):row_idx] - trend_score = len(recent_data) / 5.0 - return trend_score - - def _calculate_position_bias(self, df, row_idx): - """Berechnet Positions-Bias.""" - return np.random.random() # Placeholder - - def _calculate_gap_since_last(self, df, row_idx): - """Berechnet Gap seit letzter Ziehung.""" - return min(row_idx, 10) / 10.0 # Normalized - - def get_current_features(self, df): - """Bekommt aktuelle Features für Prediction.""" - if len(df) == 0: - return [0.0] * 60 # 10 timesteps × 6 features - - # Get features for last 10 rows - features = [] - for i in range(max(0, len(df)-10), len(df)): - row_features = self._extract_row_features(df, i) - features.extend([ - row_features.get('freq_last_10', 0), - row_features.get('trend_score', 0), - row_features.get('position_bias', 0), - row_features.get('gap_since_last', 0), - row_features.get('seasonal_factor', 0), - row_features.get('day_of_week', 0) - ]) - - # Pad if necessary - while len(features) < 60: - features.append(0.0) - - return features[:60] - -class PerformanceTracker: - def __init__(self): - self.prediction_history = [] - self.accuracy_scores = defaultdict(list) - self.generated_tips = [] - - def log_generated_tips(self, tips): - """Loggt generierte Tipps.""" - self.generated_tips.extend(tips) - - def evaluate_predictions(self, actual_drawing): - """Evaluiert Vorhersage-Qualität.""" - actual_numbers = [actual_drawing[f'Z{i}'] for i in range(1, 7)] - - # Evaluate latest predictions if available - if self.generated_tips: - latest_tips = self.generated_tips[-10:] # Last 10 tips - - for tip in latest_tips: - matches = len(set(tip['numbers']) & set(actual_numbers)) - accuracy = matches / 6.0 - - self.accuracy_scores[tip.get('method', 'UNKNOWN')].append(accuracy) - - def get_model_performance(self): - """Liefert Model-Performance.""" - performance = {} - - for method, scores in self.accuracy_scores.items(): - if scores: - performance[method] = np.mean(scores[-10:]) # Last 10 evaluations - - return performance - - def get_statistics(self): - """Liefert Performance-Statistiken.""" - stats = { - 'total_tips_generated': len(self.generated_tips), - 'total_evaluations': len(self.prediction_history), - 'method_performance': self.get_model_performance() - } - - return stats - -class RealTimeLearner: - def __init__(self): - self.learning_rate = 0.1 - self.adaptation_history = [] - self.prediction_adjustments = {} - self.learning_stats = defaultdict(int) - - def initialize(self, features_df): - """Initialisiert Real-Time Learning.""" - self.features_df = features_df - self.baseline_predictions = {} - - print("✅ Real-Time Learning System activated") - - def update_predictions(self, predictions): - """Updated Predictions basierend auf Learning.""" - adjusted_predictions = {} - - for number, prediction in predictions.items(): - # Apply learned adjustments - adjustment = self.prediction_adjustments.get(number, 0) - adjusted_prediction = prediction + (adjustment * self.learning_rate) - - # Keep in valid range - adjusted_predictions[number] = max(0, min(1, adjusted_prediction)) - - return adjusted_predictions - - def learn_from_result(self, actual_drawing): - """Lernt aus tatsächlichem Ziehungsergebnis.""" - actual_numbers = [actual_drawing[f'Z{i}'] for i in range(1, 7)] - - # Update adjustments for each number - for number in range(1, 50): - was_drawn = number in actual_numbers - - if number not in self.prediction_adjustments: - self.prediction_adjustments[number] = 0 - - # Positive reinforcement if correct, negative if wrong - if was_drawn: - self.prediction_adjustments[number] += 0.01 # Small positive adjustment - self.learning_stats['correct_predictions'] += 1 - else: - self.prediction_adjustments[number] -= 0.005 # Smaller negative adjustment - self.learning_stats['incorrect_predictions'] += 1 - - # Decay adjustments to prevent overfitting - for number in self.prediction_adjustments: - self.prediction_adjustments[number] *= 0.99 - - self.learning_stats['learning_cycles'] += 1 - print(f"📚 Learning cycle completed. Total cycles: {self.learning_stats['learning_cycles']}") - - def learn_from_generation(self, tips, ai_predictions): - """Lernt aus der Tipp-Generierung.""" - # Track generation patterns for future optimization - for tip in tips: - for number in tip['numbers']: - if number not in self.baseline_predictions: - self.baseline_predictions[number] = [] - - self.baseline_predictions[number].append(ai_predictions[number]) - - self.learning_stats['generation_cycles'] += 1 - - def get_learning_stats(self): - """Liefert Learning-Statistiken.""" - return dict(self.learning_stats) - -# Advanced Utility Functions - -def export_ai_performance_report(generator, output_path=None): - """Exportiert detaillierten AI-Performance Report.""" - - if not output_path: - timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") - output_path = f"ai_performance_report_{timestamp}.json" - - # Sammle AI-Insights - insights = generator.get_ai_insights() - - # Erweitere mit detaillierten Statistiken - report = { - 'timestamp': datetime.datetime.now().isoformat(), - 'generator_type': 'AI-ML Ultimate Lotto Generator', - 'system_status': insights, - 'model_details': { - 'ml_models': list(generator.ml_models.keys()) if generator.ml_models else [], - 'deep_models': list(generator.deep_models.keys()) if hasattr(generator, 'deep_models') else [], - 'ensemble_weights': generator.ensemble_weights, - 'training_status': generator.is_trained - }, - 'real_time_learning': { - 'learning_rate': generator.real_time_learner.learning_rate, - 'adaptation_history_size': len(generator.real_time_learner.adaptation_history), - 'prediction_adjustments_count': len(generator.real_time_learner.prediction_adjustments) - }, - 'recommendations': _generate_ai_recommendations(generator) - } - - # Export - with open(output_path, 'w') as f: - json.dump(report, f, indent=2, default=str) - - print(f"📊 AI Performance Report exported: {output_path}") - return report - -def _generate_ai_recommendations(generator): - """Generiert AI-basierte Empfehlungen.""" - recommendations = [] - - # Model-spezifische Empfehlungen - if not generator.is_trained: - recommendations.append("🎯 Train AI models with historical data for better predictions") - - if not ML_AVAILABLE: - recommendations.append("🧠 Install scikit-learn for ML capabilities: pip install scikit-learn") - - if not DEEP_LEARNING_AVAILABLE: - recommendations.append("🚀 Install TensorFlow for deep learning: pip install tensorflow") - - # Performance-basierte Empfehlungen - performance = generator.performance_tracker.get_model_performance() - if performance: - best_model = max(performance.items(), key=lambda x: x[1]) - recommendations.append(f"⭐ Best performing model: {best_model[0]} ({best_model[1]:.3f} accuracy)") - - # Learning-basierte Empfehlungen - learning_stats = generator.real_time_learner.get_learning_stats() - if learning_stats.get('learning_cycles', 0) < 10: - recommendations.append("📚 More real-time learning cycles needed for adaptation") - - return recommendations - -def demonstrate_ai_capabilities(generator): - """Demonstriert AI-Capabilities des Generators.""" - print("\n🤖 AI-ML CAPABILITIES DEMONSTRATION") - print("=" * 60) - - # System Status - insights = generator.get_ai_insights() - - print("🔍 SYSTEM STATUS:") - print(f" ML Available: {'✅' if insights['ml_available'] else '❌'}") - print(f" Deep Learning: {'✅' if insights['deep_learning_available'] else '❌'}") - print(f" Models Trained: {'✅' if insights['model_status'] == 'Trained' else '❌'}") - print(f" Data Size: {insights['data_size']:,} drawings") - - if insights['ml_available'] and generator.is_trained: - # Zeige AI Predictions - print(f"\n🧠 AI PREDICTION EXAMPLE:") - sample_predictions = generator.predict_with_ai_ensemble() - - if sample_predictions: - top_predictions = sorted(sample_predictions.items(), key=lambda x: x[1], reverse=True)[:10] - print(" Top 10 AI-Predicted Numbers:") - for i, (number, score) in enumerate(top_predictions): - confidence = "🔥" if score > 0.7 else "🌡️" if score > 0.5 else "😐" - print(f" {i+1:2}. Zahl {number:2}: {score:.3f} {confidence}") - - # Real-Time Learning Status - learning_stats = generator.real_time_learner.get_learning_stats() - if learning_stats: - print(f"\n⚡ REAL-TIME LEARNING STATUS:") - print(f" Learning Cycles: {learning_stats.get('learning_cycles', 0)}") - print(f" Correct Predictions: {learning_stats.get('correct_predictions', 0)}") - print(f" Adaptation Rate: {generator.real_time_learner.learning_rate}") - - # Performance Stats - performance_stats = insights.get('performance_stats', {}) - if performance_stats: - print(f"\n📊 PERFORMANCE STATISTICS:") - for key, value in performance_stats.items(): - print(f" {key}: {value}") - -def simulate_real_time_learning(generator, num_simulations=5): - """Simuliert Real-Time Learning mit Mock-Daten.""" - print(f"\n⚡ REAL-TIME LEARNING SIMULATION ({num_simulations} cycles)") - print("=" * 60) - - for i in range(1, num_simulations + 1): - print(f"\n🔄 Simulation Cycle {i}:") - - # Mock neue Ziehung - mock_drawing = { - 'Z1': random.randint(1, 49), - 'Z2': random.randint(1, 49), - 'Z3': random.randint(1, 49), - 'Z4': random.randint(1, 49), - 'Z5': random.randint(1, 49), - 'Z6': random.randint(1, 49), - 'SZ': random.randint(0, 9), - 'datum': datetime.datetime.now() - datetime.timedelta(days=i) - } - - # Ensure unique numbers - numbers = [mock_drawing[f'Z{j}'] for j in range(1, 7)] - while len(set(numbers)) < 6: - for j in range(1, 7): - mock_drawing[f'Z{j}'] = random.randint(1, 49) - numbers = [mock_drawing[f'Z{j}'] for j in range(1, 7)] - - zahlen_str = '-'.join([f"{n:2}" for n in sorted(numbers)]) - print(f" Mock Ziehung: {zahlen_str} + SZ: {mock_drawing['SZ']}") - - # Real-Time Update - generator.update_with_new_drawing(mock_drawing) - - # Zeige Learning-Progress - learning_stats = generator.real_time_learner.get_learning_stats() - print(f" Learning Cycles: {learning_stats.get('learning_cycles', 0)}") - print(f" Total Adjustments: {len(generator.real_time_learner.prediction_adjustments)}") - - print("\n✅ Real-Time Learning Simulation completed!") - -# Main Function -def main(): - """Startet den AI-ML Ultimate Lotto Generator.""" - print("🤖 AI-ML ULTIMATE LOTTO GENERATOR") - print("🧠 Real-Time AI + Machine Learning System") - print("=" * 60) - - # Pfad zu Sebastian's Daten - data_path = "/Users/sebastianfrohlich/Library/Mobile Documents/com~apple~CloudDocs/Jupyter Notebooks/AlleLottozahlen.csv" - - try: - # Generator initialisieren - generator = AIMLLottoGenerator(data_path) - - # AI Capabilities demonstrieren - demonstrate_ai_capabilities(generator) - - # AI-Tipps generieren - ai_tips = generator.generate_ai_tips(10) - - if ai_tips: - print(f"\n🏆 AI-ML OPTIMIZATION COMPLETED!") - print("=" * 50) - print(f"🤖 10 AI-optimized tips generated") - print(f"🧠 Machine Learning: {'✅' if ML_AVAILABLE else '❌'}") - print(f"⚡ Real-Time Learning: ✅") - print(f"📊 Ensemble Models: ✅") - print(f"🎯 Adaptive Optimization: ✅") - - # Beste Tipps hervorheben - if len(ai_tips) > 0: - best_tip = max(ai_tips, key=lambda x: x.get('confidence', 0)) - print(f"\n⭐ BEST AI TIP:") - zahlen_str = '-'.join([f"{n:2}" for n in best_tip['numbers']]) - print(f" Numbers: {zahlen_str} + SZ: {best_tip['superzahl']}") - print(f" AI-Score: {best_tip['ai_score']:.3f}") - print(f" Confidence: {best_tip['confidence']:.3f}") - print(f" Method: {best_tip['method']}") - - # Optional: Real-Time Learning simulieren - simulate_choice = input("\nReal-Time Learning simulieren? (j/n): ").lower().strip() - if simulate_choice in ['j', 'ja', 'y', 'yes']: - simulate_real_time_learning(generator, 3) - - # Optional: Performance Report - report_choice = input("AI Performance Report erstellen? (j/n): ").lower().strip() - if report_choice in ['j', 'ja', 'y', 'yes']: - export_ai_performance_report(generator) - - print(f"\n🚀 NEXT-LEVEL FEATURES:") - print("=" * 30) - print("🧠 Machine Learning Ensemble mit 3 Algorithmen") - print("⚡ Real-Time Learning nach jeder Ziehung") - print("📊 Adaptive Model-Gewichtung") - print("🎯 Feature Engineering für optimale Vorhersagen") - print("📈 Performance Tracking & Auto-Optimization") - print("🔄 Kontinuierliche Verbesserung durch AI") - - else: - print("❌ Keine AI-Tipps generiert!") - - except Exception as e: - print(f"❌ Error: {e}") - print("\n💡 SYSTEM REQUIREMENTS:") - print(" 📦 pip install scikit-learn (für ML)") - print(" 📦 pip install tensorflow (für Deep Learning)") - print(" 📁 AlleLottozahlen.csv im korrekten Pfad") - -if __name__ == "__main__": - # Set random seeds für reproduzierbare Ergebnisse - random.seed(42) - np.random.seed(42) - - # Starte AI-ML Generator - main() \ No newline at end of file diff --git a/ai_performance_report_20250926_081041.json b/ai_performance_report_20250926_081041.json deleted file mode 100644 index bad71c7..0000000 --- a/ai_performance_report_20250926_081041.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - "timestamp": "2025-09-26T08:10:41.418372", - "generator_type": "AI-ML Ultimate Lotto Generator", - "system_status": { - "model_status": "Trained", - "ml_available": true, - "deep_learning_available": false, - "data_size": 4945, - "performance_stats": { - "total_tips_generated": 10, - "total_evaluations": 0, - "method_performance": {} - }, - "adaptive_weights": { - "random_forest": 0.3333333333333333, - "gradient_boost": 0.3333333333333333, - "neural_network": 0.3333333333333333 - }, - "learning_stats": { - "generation_cycles": 1 - } - }, - "model_details": { - "ml_models": [ - "random_forest", - "gradient_boost", - "neural_network" - ], - "deep_models": [], - "ensemble_weights": { - "random_forest": 0.3333333333333333, - "gradient_boost": 0.3333333333333333, - "neural_network": 0.3333333333333333 - }, - "training_status": true - }, - "real_time_learning": { - "learning_rate": 0.1, - "adaptation_history_size": 0, - "prediction_adjustments_count": 0 - }, - "recommendations": [ - "\ud83d\ude80 Install TensorFlow for deep learning: pip install tensorflow", - "\ud83d\udcda More real-time learning cycles needed for adaptation" - ] -} \ No newline at end of file diff --git a/ai_performance_report_20250926_081358.json b/ai_performance_report_20250926_081358.json deleted file mode 100644 index 584db1f..0000000 --- a/ai_performance_report_20250926_081358.json +++ /dev/null @@ -1,52 +0,0 @@ -{ - "timestamp": "2025-09-26T08:13:58.454714", - "generator_type": "AI-ML Ultimate Lotto Generator", - "system_status": { - "model_status": "Trained", - "ml_available": true, - "deep_learning_available": false, - "data_size": 4948, - "performance_stats": { - "total_tips_generated": 10, - "total_evaluations": 0, - "method_performance": { - "AI-ENSEMBLE": 0.16666666666666669 - } - }, - "adaptive_weights": { - "random_forest": 0.3333333333333333, - "gradient_boost": 0.3333333333333333, - "neural_network": 0.3333333333333333 - }, - "learning_stats": { - "generation_cycles": 1, - "incorrect_predictions": 129, - "correct_predictions": 18, - "learning_cycles": 3 - } - }, - "model_details": { - "ml_models": [ - "random_forest", - "gradient_boost", - "neural_network" - ], - "deep_models": [], - "ensemble_weights": { - "random_forest": 0.3333333333333333, - "gradient_boost": 0.3333333333333333, - "neural_network": 0.3333333333333333 - }, - "training_status": true - }, - "real_time_learning": { - "learning_rate": 0.1, - "adaptation_history_size": 0, - "prediction_adjustments_count": 49 - }, - "recommendations": [ - "\ud83d\ude80 Install TensorFlow for deep learning: pip install tensorflow", - "\u2b50 Best performing model: AI-ENSEMBLE (0.167 accuracy)", - "\ud83d\udcda More real-time learning cycles needed for adaptation" - ] -} \ No newline at end of file diff --git a/ai_performance_report_20250926_082439.json b/ai_performance_report_20250926_082439.json deleted file mode 100644 index 95a8c2d..0000000 --- a/ai_performance_report_20250926_082439.json +++ /dev/null @@ -1,52 +0,0 @@ -{ - "timestamp": "2025-09-26T08:24:39.210488", - "generator_type": "AI-ML Ultimate Lotto Generator", - "system_status": { - "model_status": "Trained", - "ml_available": true, - "deep_learning_available": false, - "data_size": 4948, - "performance_stats": { - "total_tips_generated": 10, - "total_evaluations": 0, - "method_performance": { - "AI-ENSEMBLE-V2": 0.11666666666666665 - } - }, - "adaptive_weights": { - "random_forest": 0.3333333333333333, - "gradient_boost": 0.3333333333333333, - "neural_network": 0.3333333333333333 - }, - "learning_stats": { - "generation_cycles": 1, - "incorrect_predictions": 129, - "correct_predictions": 18, - "learning_cycles": 3 - } - }, - "model_details": { - "ml_models": [ - "random_forest", - "gradient_boost", - "neural_network" - ], - "deep_models": [], - "ensemble_weights": { - "random_forest": 0.3333333333333333, - "gradient_boost": 0.3333333333333333, - "neural_network": 0.3333333333333333 - }, - "training_status": true - }, - "real_time_learning": { - "learning_rate": 0.1, - "adaptation_history_size": 0, - "prediction_adjustments_count": 49 - }, - "recommendations": [ - "\ud83d\ude80 Install TensorFlow for deep learning: pip install tensorflow", - "\u2b50 Best performing model: AI-ENSEMBLE-V2 (0.117 accuracy)", - "\ud83d\udcda More real-time learning cycles needed for adaptation" - ] -} \ No newline at end of file diff --git a/ai_performance_report_20250926_152808.json b/ai_performance_report_20250926_152808.json deleted file mode 100644 index 834f74f..0000000 --- a/ai_performance_report_20250926_152808.json +++ /dev/null @@ -1,52 +0,0 @@ -{ - "timestamp": "2025-09-26T15:28:08.871286", - "generator_type": "AI-ML Ultimate Lotto Generator", - "system_status": { - "model_status": "Trained", - "ml_available": true, - "deep_learning_available": false, - "data_size": 4948, - "performance_stats": { - "total_tips_generated": 10, - "total_evaluations": 0, - "method_performance": { - "AI-ENSEMBLE-V2": 0.15 - } - }, - "adaptive_weights": { - "random_forest": 0.3333333333333333, - "gradient_boost": 0.3333333333333333, - "neural_network": 0.3333333333333333 - }, - "learning_stats": { - "generation_cycles": 1, - "incorrect_predictions": 129, - "correct_predictions": 18, - "learning_cycles": 3 - } - }, - "model_details": { - "ml_models": [ - "random_forest", - "gradient_boost", - "neural_network" - ], - "deep_models": [], - "ensemble_weights": { - "random_forest": 0.3333333333333333, - "gradient_boost": 0.3333333333333333, - "neural_network": 0.3333333333333333 - }, - "training_status": true - }, - "real_time_learning": { - "learning_rate": 0.1, - "adaptation_history_size": 0, - "prediction_adjustments_count": 49 - }, - "recommendations": [ - "\ud83d\ude80 Install TensorFlow for deep learning: pip install tensorflow", - "\u2b50 Best performing model: AI-ENSEMBLE-V2 (0.150 accuracy)", - "\ud83d\udcda More real-time learning cycles needed for adaptation" - ] -} \ No newline at end of file diff --git a/documentation/ARCHITECTURE.md b/documentation/ARCHITECTURE.md index bb17a8d..2d3c46a 100644 --- a/documentation/ARCHITECTURE.md +++ b/documentation/ARCHITECTURE.md @@ -139,13 +139,6 @@ Logs: `logs/update_stdout.log` (Update+Learning), `logs/stdout.log` Pipeline entsprechend hinterher, obwohl Lottoland oft schneller aktuell ist. - **`update_from_web.py`** (lotto.de-Scraper) ist als dritter Fallback implementiert, aber nirgends in der automatisierten Pipeline eingebunden. -- **Legacy-Generatoren im Projekt-Root** (`ultimate_lotto_6aus49_generator.py`, - `super_lotto_generator.py`, `ai_ml_lotto_generator.py`, - `pattern_weighted_ai_generator.py`, `ultimate_hybrid_lotto_generator.py`) - sind eigenständige, ältere Implementierungen und **nicht** Teil der - automatisierten Pipeline (die nutzt ausschließlich - `scripts/generators/ultimate_ai_ml_hybrid_generator.py`). Vor Änderungen an - "dem Generator" prüfen, welche Datei gemeint ist. - **Utility-Skripte** in `scripts/utils/` (`health_check.py`, `validate_csv.py`, `verify_draws.py`, `model_evaluator.py`) existieren, sind aber nicht in die Cron-Automatisierung eingebunden; manuelle Ausführung bei Bedarf. diff --git a/pattern_weighted_ai_generator.py b/pattern_weighted_ai_generator.py deleted file mode 100644 index 31a8a7a..0000000 --- a/pattern_weighted_ai_generator.py +++ /dev/null @@ -1,422 +0,0 @@ -#!/usr/bin/env python3 -""" -AI-GENERATOR MIT MUSTER-GEWICHTUNG -Erweitert den AI-Generator um explizite Muster-Gewichtung (NNMMHH, etc.) - -Neue Features: -- Historische Muster-Analyse (NNMMHH, NMMHHH, etc.) -- Muster-Erfolgsquoten berechnen -- Muster-basierte Tip-Optimierung -- Pattern-Scoring für bessere Kombinationen -""" - -import pandas as pd -import numpy as np -from collections import Counter, defaultdict -import random - -class PatternWeightedAI: - def __init__(self, df): - self.df = df - self.pattern_frequencies = Counter() - self.pattern_success_rates = {} - self.optimal_patterns = [] - - # Analysiere historische Muster - self._analyze_historical_patterns() - - def _analyze_historical_patterns(self): - """Analysiert alle historischen Muster und deren Erfolgsquoten.""" - print("\n🎨 MUSTER-ANALYSE GESTARTET...") - - if len(self.df) == 0: - return - - total_drawings = len(self.df) - - for _, row in self.df.iterrows(): - numbers = sorted([row['Z1'], row['Z2'], row['Z3'], row['Z4'], row['Z5'], row['Z6']]) - pattern = self._get_pattern(numbers) - self.pattern_frequencies[pattern] += 1 - - # Berechne Erfolgsquoten - for pattern, count in self.pattern_frequencies.items(): - success_rate = count / total_drawings - self.pattern_success_rates[pattern] = success_rate - - # Identifiziere optimale Muster (Top 10) - self.optimal_patterns = [ - pattern for pattern, _ in self.pattern_frequencies.most_common(10) - ] - - print("🎯 MUSTER-ERFOLGSQUOTEN:") - print("Pattern Häufigkeit Erfolgsrate Bewertung") - print("-" * 50) - - for i, (pattern, count) in enumerate(self.pattern_frequencies.most_common(15)): - success_rate = self.pattern_success_rates[pattern] - - if success_rate >= 0.08: - bewertung = "🏆 EXCELLENT" - elif success_rate >= 0.06: - bewertung = "🥇 SEHR GUT" - elif success_rate >= 0.04: - bewertung = "🥈 GUT" - elif success_rate >= 0.02: - bewertung = "🥉 DURCHSCHNITT" - else: - bewertung = "❌ SCHWACH" - - print(f"{pattern:<10} {count:>8} {success_rate:>8.3f} {bewertung}") - - def _get_pattern(self, numbers): - """Konvertiert Zahlen zu N/M/H Muster.""" - pattern = "" - for num in numbers: - if 1 <= num <= 16: - pattern += "N" # Niedrig - elif 17 <= num <= 32: - pattern += "M" # Mittel - else: - pattern += "H" # Hoch - return pattern - - def calculate_pattern_weight(self, numbers): - """Berechnet Gewichtung basierend auf Muster-Erfolgsquote.""" - pattern = self._get_pattern(sorted(numbers)) - - # Basis-Gewichtung aus historischer Erfolgsquote - base_weight = self.pattern_success_rates.get(pattern, 0.01) - - # Bonus für Top-Muster - if pattern in self.optimal_patterns[:5]: - bonus = 0.3 - elif pattern in self.optimal_patterns[:10]: - bonus = 0.2 - else: - bonus = 0.0 - - # Penalty für nie aufgetretene Muster - if pattern not in self.pattern_frequencies: - penalty = -0.2 - else: - penalty = 0.0 - - final_weight = base_weight + bonus + penalty - return max(0.01, min(1.0, final_weight)) # Clamp 0.01-1.0 - - def get_pattern_recommendations(self): - """Liefert Muster-Empfehlungen für Tip-Generierung.""" - recommendations = {} - - # Top 5 erfolgreichste Muster - recommendations['top_patterns'] = self.optimal_patterns[:5] - - # Muster mit bester Erfolgsquote - if self.pattern_success_rates: - best_pattern = max(self.pattern_success_rates.items(), key=lambda x: x[1]) - recommendations['best_pattern'] = best_pattern[0] - recommendations['best_success_rate'] = best_pattern[1] - - # Muster-Statistiken - recommendations['total_patterns'] = len(self.pattern_frequencies) - recommendations['pattern_diversity'] = len([p for p, rate in self.pattern_success_rates.items() if rate >= 0.02]) - - return recommendations - - def optimize_combination_for_pattern(self, target_pattern="NNMMHH"): - """Optimiert Zahlen-Kombination für spezifisches Muster.""" - - # Definiere Bereiche - ranges = { - 'N': list(range(1, 17)), # Niedrig: 1-16 - 'M': list(range(17, 33)), # Mittel: 17-32 - 'H': list(range(33, 50)) # Hoch: 33-49 - } - - # Parse target pattern - pattern_counts = Counter(target_pattern) - needed_n = pattern_counts.get('N', 0) - needed_m = pattern_counts.get('M', 0) - needed_h = pattern_counts.get('H', 0) - - selected = [] - - # Wähle Zahlen für Muster - if needed_n > 0: - n_numbers = random.sample(ranges['N'], min(needed_n, len(ranges['N']))) - selected.extend(n_numbers) - - if needed_m > 0: - m_numbers = random.sample(ranges['M'], min(needed_m, len(ranges['M']))) - selected.extend(m_numbers) - - if needed_h > 0: - h_numbers = random.sample(ranges['H'], min(needed_h, len(ranges['H']))) - selected.extend(h_numbers) - - # Auffüllen falls nötig - while len(selected) < 6: - all_ranges = ranges['N'] + ranges['M'] + ranges['H'] - available = [n for n in all_ranges if n not in selected] - if available: - selected.append(random.choice(available)) - else: - break - - return sorted(selected[:6]) - -class EnhancedAIGenerator: - """Erweitert den ursprünglichen AI-Generator um Muster-Gewichtung.""" - - def __init__(self, data_path): - self.data_path = data_path - self.df = None - self.pattern_ai = None - - # Load data - self._load_data() - - # Initialize Pattern AI - if self.df is not None and len(self.df) > 0: - self.pattern_ai = PatternWeightedAI(self.df) - - def _load_data(self): - """Lädt Daten.""" - try: - self.df = pd.read_csv(self.data_path, sep=';') - if 'datum' in self.df.columns: - self.df['datum'] = pd.to_datetime(self.df['datum'], format='%Y-%m-%d', errors='coerce') - self.df = self.df.sort_values('datum') - print(f"✅ {len(self.df)} Ziehungen geladen") - except Exception as e: - print(f"❌ Fehler beim Laden: {e}") - self.df = pd.DataFrame() - - def generate_pattern_optimized_tips(self, num_tips=10): - """Generiert Tipps mit expliziter Muster-Gewichtung.""" - - if not self.pattern_ai: - print("❌ Pattern AI nicht verfügbar") - return [] - - print("\n🎨 PATTERN-OPTIMIERTE TIPP-GENERIERUNG") - print("=" * 60) - - # Muster-Empfehlungen abrufen - recommendations = self.pattern_ai.get_pattern_recommendations() - - print("🎯 MUSTER-EMPFEHLUNGEN:") - print(f" Bestes Muster: {recommendations.get('best_pattern', 'N/A')} ({recommendations.get('best_success_rate', 0)*100:.1f}%)") - print(f" Top 5 Muster: {', '.join(recommendations.get('top_patterns', [])[:5])}") - print(f" Pattern-Diversität: {recommendations.get('pattern_diversity', 0)} erfolgreiche Muster") - - tips = [] - - print(f"\n🎲 GENERIERE {num_tips} PATTERN-OPTIMIERTE TIPPS:") - print("=" * 80) - print("Nr 6 Pattern-Numbers Pattern Weight Confidence Success-Rate") - print("-" * 80) - - # Verschiedene Strategien für verschiedene Tipps - strategies = [ - ('best', "Bestes Muster"), - ('top5', "Top 5 Rotation"), - ('balanced', "Ausgewogene Muster"), - ('diverse', "Diversifizierte Muster") - ] - - for i in range(1, num_tips + 1): - strategy = strategies[(i-1) % len(strategies)] - tip = self._generate_pattern_tip(i, strategy[0], recommendations) - tips.append(tip) - - # Output - zahlen_str = '-'.join([f"{n:2}" for n in tip['numbers']]) - success_rate = self.pattern_ai.pattern_success_rates.get(tip['pattern'], 0) - - print(f"{i:2} {zahlen_str} {tip['pattern']:<8} {tip['pattern_weight']:.3f} {tip['confidence']:.3f} {success_rate:.3f}") - - # Zusammenfassung - self._print_pattern_summary(tips) - - return tips - - def _generate_pattern_tip(self, tip_number, strategy, recommendations): - """Generiert einzelnen pattern-optimierten Tipp.""" - - # Seed für Konsistenz - random.seed(42 + tip_number) - - if strategy == 'best': - # Nutze bestes Muster - target_pattern = recommendations.get('best_pattern', 'NNMMHH') - elif strategy == 'top5': - # Rotiere durch Top 5 - top_patterns = recommendations.get('top_patterns', ['NNMMHH']) - target_pattern = top_patterns[(tip_number - 1) % len(top_patterns)] - elif strategy == 'balanced': - # Ausgewogene beliebte Muster - balanced_patterns = ['NNMMHH', 'NMMHHH', 'NMMMHH', 'NNMHHH'] - target_pattern = balanced_patterns[(tip_number - 1) % len(balanced_patterns)] - else: # diverse - # Diversifizierte Muster für Abdeckung - diverse_patterns = ['NNMMHH', 'MMHHHH', 'NNNNMM', 'NMHHHH', 'NNNMMH'] - target_pattern = diverse_patterns[(tip_number - 1) % len(diverse_patterns)] - - # Generiere Kombination für Ziel-Muster - numbers = self.pattern_ai.optimize_combination_for_pattern(target_pattern) - - # Validiere und korrigiere falls nötig - actual_pattern = self.pattern_ai._get_pattern(numbers) - - # Pattern Weight berechnen - pattern_weight = self.pattern_ai.calculate_pattern_weight(numbers) - - # Confidence basierend auf Pattern Success Rate - success_rate = self.pattern_ai.pattern_success_rates.get(actual_pattern, 0.01) - confidence = pattern_weight * 0.6 + success_rate * 0.4 - - # Superzahl - superzahl = self._get_pattern_superzahl(tip_number) - - return { - 'tip_number': tip_number, - 'numbers': numbers, - 'pattern': actual_pattern, - 'target_pattern': target_pattern, - 'pattern_weight': pattern_weight, - 'confidence': confidence, - 'success_rate': success_rate, - 'superzahl': superzahl, - 'strategy': strategy - } - - def _get_pattern_superzahl(self, tip_number): - """Pattern-optimierte Superzahl.""" - # Basis häufigste Superzahlen - frequent_sz = [7, 6, 3, 2, 0, 1, 4, 5, 8, 9] - - # Tip-spezifische Auswahl - return frequent_sz[tip_number % len(frequent_sz)] - - def _print_pattern_summary(self, tips): - """Druckt Pattern-Zusammenfassung.""" - print(f"\n🏆 PATTERN-OPTIMIERUNG ZUSAMMENFASSUNG:") - print("=" * 50) - - # Pattern-Verteilung - pattern_dist = Counter([tip['pattern'] for tip in tips]) - print("📊 PATTERN-VERTEILUNG:") - for pattern, count in pattern_dist.most_common(): - avg_success = np.mean([self.pattern_ai.pattern_success_rates.get(pattern, 0)] * count) - print(f" {pattern}: {count}x (Ø Success: {avg_success:.3f})") - - # Durchschnittliche Metriken - avg_weight = np.mean([tip['pattern_weight'] for tip in tips]) - avg_confidence = np.mean([tip['confidence'] for tip in tips]) - avg_success = np.mean([tip['success_rate'] for tip in tips]) - - print(f"\n📈 DURCHSCHNITTLICHE METRIKEN:") - print(f" Pattern-Weight: {avg_weight:.3f}") - print(f" Confidence: {avg_confidence:.3f}") - print(f" Success-Rate: {avg_success:.3f}") - - # Beste Tipps - best_tip = max(tips, key=lambda x: x['confidence']) - print(f"\n⭐ BESTER PATTERN-TIPP:") - zahlen_str = '-'.join([f"{n:2}" for n in best_tip['numbers']]) - print(f" Tipp {best_tip['tip_number']}: {zahlen_str}") - print(f" Pattern: {best_tip['pattern']} (Weight: {best_tip['pattern_weight']:.3f})") - print(f" Success-Rate: {best_tip['success_rate']:.3f}") - -def demonstrate_pattern_weighting(): - """Demonstriert Pattern-Gewichtung mit Beispiel-Daten.""" - - print("🎨 PATTERN-GEWICHTUNG DEMONSTRATION") - print("=" * 50) - - # Beispiel-Daten erstellen - sample_data = [] - patterns_to_simulate = ['NNMMHH', 'NMMHHH', 'NMMMHH', 'NNMHHH', 'MMHHHH'] - - for i in range(100): - # Simuliere Ziehungen mit verschiedenen Mustern - pattern = random.choice(patterns_to_simulate) - numbers = [] - - for char in pattern: - if char == 'N': - numbers.append(random.randint(1, 16)) - elif char == 'M': - numbers.append(random.randint(17, 32)) - else: # 'H' - numbers.append(random.randint(33, 49)) - - # Sicherstellen dass alle Zahlen einzigartig sind - numbers = sorted(list(set(numbers))) - while len(numbers) < 6: - missing_range = random.choice(['N', 'M', 'H']) - if missing_range == 'N': - new_num = random.randint(1, 16) - elif missing_range == 'M': - new_num = random.randint(17, 32) - else: - new_num = random.randint(33, 49) - - if new_num not in numbers: - numbers.append(new_num) - numbers.sort() - - numbers = numbers[:6] - - sample_data.append({ - 'Z1': numbers[0], 'Z2': numbers[1], 'Z3': numbers[2], - 'Z4': numbers[3], 'Z5': numbers[4], 'Z6': numbers[5], - 'SZ': random.randint(0, 9) - }) - - # DataFrame erstellen - df_sample = pd.DataFrame(sample_data) - - # Enhanced AI Generator mit Pattern-Gewichtung - print("\n🚀 STARTE PATTERN-GEWICHTETEN GENERATOR...") - - # Simuliere Generator - generator = EnhancedAIGenerator.__new__(EnhancedAIGenerator) - generator.df = df_sample - generator.pattern_ai = PatternWeightedAI(df_sample) - - # Generiere pattern-optimierte Tipps - pattern_tips = generator.generate_pattern_optimized_tips(8) - - print(f"\n💡 PATTERN-GEWICHTUNG ERKLÄRT:") - print("=" * 40) - print("🎯 Jede Kombination wird bewertet basierend auf:") - print(" 1. Historischer Erfolgsquote des Musters") - print(" 2. Bonus für Top-5 erfolgreichste Muster") - print(" 3. Penalty für nie aufgetretene Muster") - print(" 4. Kombinierte Pattern-Weight für finalen Score") - - return pattern_tips - -def main(): - """Hauptfunktion für Pattern-gewichteten Generator.""" - data_path = "/Users/sebastianfrohlich/Library/Mobile Documents/com~apple~CloudDocs/Jupyter Notebooks/AlleLottozahlen.csv" - - try: - # Versuche mit echten Daten - generator = EnhancedAIGenerator(data_path) - - if generator.pattern_ai and len(generator.df) > 0: - pattern_tips = generator.generate_pattern_optimized_tips(10) - else: - print("🔄 Echte Daten nicht verfügbar - verwende Demo...") - pattern_tips = demonstrate_pattern_weighting() - - except Exception as e: - print(f"⚠️ Fallback zu Demo-Modus: {e}") - pattern_tips = demonstrate_pattern_weighting() - -if __name__ == "__main__": - main() diff --git a/super_lotto_generator.py b/super_lotto_generator.py deleted file mode 100644 index d7362e6..0000000 --- a/super_lotto_generator.py +++ /dev/null @@ -1,842 +0,0 @@ -#!/usr/bin/env python3 -""" -SUPER-LOTTO 6AUS49 GENERATOR -Mit vollständigen historischen Daten und nie gezogenen Kombinationen - -Nutzt Sebastian's komplette Datenbasis: -- AlleLottozahlen.csv: Alle historischen Ziehungen mit Multi-Trend-Analyse -- Fehlende_Lotto_Kombinationen.csv: Alle nie gezogenen Kombinationen -- Maximale Optimierung durch vollständige Datenbasis -""" - -import pandas as pd -import numpy as np -import random -from collections import Counter, defaultdict -import datetime -import pickle -import os - -class SuperLotto6aus49Generator: - def __init__(self): - # Pfade zu Sebastian's Daten - self.base_path = "/Users/sebastianfrohlich/Library/Mobile Documents/com~apple~CloudDocs/Jupyter Notebooks" - self.historical_data_path = f"{self.base_path}/AlleLottozahlen.csv" - self.unused_combinations_path = f"{self.base_path}/Fehlende_Lotto_Kombinationen.csv" - - # Daten-Container - self.df_historical = None - self.df_unused = None - self.drawn_combinations = set() - - # Basis-Analysen - self.number_frequencies = Counter() - self.position_frequencies = defaultdict(Counter) - self.pattern_frequencies = Counter() - self.supernumber_frequencies = Counter() - self.weekday_frequencies = Counter() - - # Multi-Trend-Analysen - self.number_sequences = defaultdict(list) - self.momentum_scores = {} - self.trend_predictions = {} - self.sequential_dependencies = defaultdict(lambda: defaultdict(int)) - self.hot_numbers = [] - self.warm_numbers = [] - self.cold_numbers = [] - - # Unused Combinations Intelligence - self.unused_combinations_sample = [] - self.unused_patterns = Counter() - self.unused_by_ranges = {'N': [], 'M': [], 'H': []} - - # Cache für Performance - self.cache_file = f"{self.base_path}/super_lotto_cache.pkl" - - print("🚀 SUPER-LOTTO 6AUS49 GENERATOR") - print("=" * 50) - print("📊 Lade vollständige Sebastian's Datenbasis...") - - # Lade und analysiere alle Daten - self.load_all_data() - - def load_all_data(self): - """Lädt alle verfügbaren Daten und führt komplette Analyse durch.""" - - # 1. Historische Ziehungen laden - print("📈 Lade historische Ziehungen...") - self._load_historical_data() - - # 2. Nie gezogene Kombinationen laden - print("🎯 Lade nie gezogene Kombinationen...") - self._load_unused_combinations() - - # 3. Basis-Analysen - print("🔍 Führe Basis-Analysen durch...") - self._perform_basic_analysis() - - # 4. Multi-Trend-Analysen - print("📊 Multi-Trend-Analyse...") - self._perform_momentum_analysis() - self._perform_sequential_analysis() - - # 5. Unused Combinations Intelligence - print("🎲 Analysiere nie gezogene Kombinationen...") - self._analyze_unused_combinations() - - print("✅ Komplette Super-Analyse abgeschlossen!") - self._print_super_analysis_summary() - - def _load_historical_data(self): - """Lädt historische Lotto-Daten.""" - try: - # Sebastian's Format: tag;datum;Z1;Z2;Z3;Z4;Z5;Z6;SZ - self.df_historical = pd.read_csv(self.historical_data_path, sep=';') - - # Datum konvertieren (verschiedene Formate unterstützen) - date_formats = ['%Y-%m-%d', '%d.%m.%Y', '%d/%m/%Y'] - for date_format in date_formats: - try: - self.df_historical['datum'] = pd.to_datetime(self.df_historical['datum'], format=date_format) - break - except: - continue - - # Sortiere chronologisch (älteste zuerst für Trend-Analyse) - self.df_historical = self.df_historical.sort_values('datum') - - print(f"✅ {len(self.df_historical)} historische Ziehungen geladen") - print(f"📅 Zeitraum: {self.df_historical['datum'].min()} bis {self.df_historical['datum'].max()}") - - except Exception as e: - print(f"❌ Fehler beim Laden historischer Daten: {e}") - return False - - return True - - def _load_unused_combinations(self): - """Lädt alle nie gezogenen Kombinationen.""" - try: - # Große Datei in Chunks laden für bessere Performance - chunk_size = 100000 - chunks = [] - - print("⏳ Lade nie gezogene Kombinationen (große Datei)...") - - for chunk in pd.read_csv(self.unused_combinations_path, sep=';', chunksize=chunk_size): - chunks.append(chunk) - if len(chunks) % 50 == 0: - print(f" 📊 {len(chunks) * chunk_size:,} Kombinationen geladen...") - - self.df_unused = pd.concat(chunks, ignore_index=True) - - print(f"✅ {len(self.df_unused):,} nie gezogene Kombinationen verfügbar!") - print(f"💡 Das sind {len(self.df_unused)/13983816*100:.1f}% aller möglichen Kombinationen") - - # Sample für Performance (arbeiten mit repräsentativem Subset) - sample_size = min(500000, len(self.df_unused)) # Max 500k für Performance - self.unused_combinations_sample = self.df_unused.sample(n=sample_size, random_state=42) - - print(f"🎯 Arbeite mit {len(self.unused_combinations_sample):,} Sample-Kombinationen") - - except Exception as e: - print(f"❌ Fehler beim Laden nie gezogener Kombinationen: {e}") - return False - - return True - - def _perform_basic_analysis(self): - """Basis-Analyse der historischen Daten.""" - - for _, row in self.df_historical.iterrows(): - # Gezogene Kombinationen - numbers = [row['Z1'], row['Z2'], row['Z3'], row['Z4'], row['Z5'], row['Z6']] - combo = tuple(sorted(numbers)) - self.drawn_combinations.add(combo) - - # Zahlenfrequenzen - for num in numbers: - self.number_frequencies[num] += 1 - - # Positionsfrequenzen - sorted_numbers = sorted(numbers) - for i, num in enumerate(sorted_numbers): - self.position_frequencies[f'pos_{i+1}'][num] += 1 - - # Muster-Analyse - pattern = self._get_pattern(sorted_numbers) - self.pattern_frequencies[pattern] += 1 - - # Superzahl - if 'SZ' in row and pd.notna(row['SZ']): - self.supernumber_frequencies[int(row['SZ'])] += 1 - - # Wochentag-Analyse - if 'tag' in row: - weekday = row['tag'].replace('.', '').replace(';', '') - self.weekday_frequencies[weekday] += 1 - - def _perform_momentum_analysis(self, window_size=20): - """Erweiterte Momentum-Analyse mit größerem Fenster.""" - print(f"🔥 Super-Momentum-Analyse (Fenster: {window_size})") - - # Zahlensequenzen aufbauen - for number in range(1, 50): - sequence = [] - for _, row in self.df_historical.iterrows(): - drawn_numbers = [row['Z1'], row['Z2'], row['Z3'], row['Z4'], row['Z5'], row['Z6']] - sequence.append(1 if number in drawn_numbers else 0) - self.number_sequences[number] = sequence - - # Super-Momentum-Scores - for number in range(1, 50): - recent_sequence = self.number_sequences[number][-window_size:] - - hit_rate = sum(recent_sequence) / len(recent_sequence) - trend_score = self._calculate_trend_score(recent_sequence) - recency_score = self._calculate_recency_score(recent_sequence) - acceleration_score = self._calculate_acceleration_score(recent_sequence) - - # Super-Momentum mit Beschleunigung - momentum_score = (hit_rate * 0.35) + (trend_score * 0.3) + \ - (recency_score * 0.2) + (acceleration_score * 0.15) - - self.momentum_scores[number] = { - 'hit_rate': hit_rate, - 'trend_score': trend_score, - 'recency_score': recency_score, - 'acceleration_score': acceleration_score, - 'momentum_score': momentum_score, - 'status': self._get_momentum_status(momentum_score) - } - - # Kategorisierung - sorted_momentum = sorted(self.momentum_scores.items(), - key=lambda x: x[1]['momentum_score'], reverse=True) - - self.hot_numbers = [num for num, data in sorted_momentum[:15] - if data['momentum_score'] > 0.3] - self.warm_numbers = [num for num, data in sorted_momentum[15:30] - if 0.2 <= data['momentum_score'] <= 0.3] - self.cold_numbers = [num for num, data in sorted_momentum[30:] - if data['momentum_score'] < 0.2] - - print(f"🔥 {len(self.hot_numbers)} super-heiße Zahlen") - print(f"🌡️ {len(self.warm_numbers)} warme Zahlen") - print(f"🧊 {len(self.cold_numbers)} kalte Zahlen") - - def _calculate_acceleration_score(self, sequence): - """Berechnet Beschleunigung der Treffer (NEU!).""" - if len(sequence) < 4: - return 0 - - # Teile Sequenz in zwei Hälften - mid = len(sequence) // 2 - first_half_rate = sum(sequence[:mid]) / mid - second_half_rate = sum(sequence[mid:]) / (len(sequence) - mid) - - # Beschleunigung = Verbesserung in zweiter Hälfte - acceleration = second_half_rate - first_half_rate - return max(0, acceleration) # Nur positive Beschleunigung - - def _perform_sequential_analysis(self): - """Sequenzielle Abhängigkeiten zwischen Ziehungen.""" - print("🔗 Super-Sequential-Analyse") - - for i in range(3, len(self.df_historical)): - current_numbers = set([self.df_historical.iloc[i]['Z1'], self.df_historical.iloc[i]['Z2'], - self.df_historical.iloc[i]['Z3'], self.df_historical.iloc[i]['Z4'], - self.df_historical.iloc[i]['Z5'], self.df_historical.iloc[i]['Z6']]) - - for j in range(1, 4): # 3 Ziehungen zurück - prev_numbers = set([self.df_historical.iloc[i-j]['Z1'], self.df_historical.iloc[i-j]['Z2'], - self.df_historical.iloc[i-j]['Z3'], self.df_historical.iloc[i-j]['Z4'], - self.df_historical.iloc[i-j]['Z5'], self.df_historical.iloc[i-j]['Z6']]) - - for prev_num in prev_numbers: - for curr_num in current_numbers: - self.sequential_dependencies[f"lag_{j}"][f"{prev_num}_{curr_num}"] += 1 - - def _analyze_unused_combinations(self): - """Analysiert nie gezogene Kombinationen für Intelligence.""" - print("🎯 Super-Intelligence für nie gezogene Kombinationen") - - # Muster der nie gezogenen Kombinationen - for _, row in self.unused_combinations_sample.iterrows(): - numbers = [row['Z1'], row['Z2'], row['Z3'], row['Z4'], row['Z5'], row['Z6']] - pattern = self._get_pattern(numbers) - self.unused_patterns[pattern] += 1 - - # Verteilung nach N/M/H-Bereichen - for num in numbers: - if 1 <= num <= 16: - self.unused_by_ranges['N'].append(num) - elif 17 <= num <= 32: - self.unused_by_ranges['M'].append(num) - else: - self.unused_by_ranges['H'].append(num) - - print(f"📊 Nie gezogene Muster analysiert:") - for pattern, count in self.unused_patterns.most_common(5): - percentage = (count / len(self.unused_combinations_sample)) * 100 - print(f" {pattern}: {percentage:.1f}%") - - def generate_super_combination(self): - """Generiert Super-Kombination mit kompletter Intelligence.""" - max_attempts = 2000 - - for attempt in range(max_attempts): - numbers = [] - - # Super-Strategie: - # 40% aus nie gezogenen hot trends - # 30% aus momentum analysis - # 20% aus sequential dependencies - # 10% random balance - - # 2-3 Zahlen aus hot numbers mit unused combination bias - hot_unused_candidates = [] - for combo_idx in range(min(10000, len(self.unused_combinations_sample))): - combo = self.unused_combinations_sample.iloc[combo_idx] - combo_numbers = [combo['Z1'], combo['Z2'], combo['Z3'], combo['Z4'], combo['Z5'], combo['Z6']] - hot_in_combo = [n for n in combo_numbers if n in self.hot_numbers[:10]] - if len(hot_in_combo) >= 2: - hot_unused_candidates.extend(hot_in_combo) - - if hot_unused_candidates: - hot_picks = random.sample(list(set(hot_unused_candidates)), min(3, len(set(hot_unused_candidates)))) - numbers.extend(hot_picks) - - # 2 Zahlen aus Trend-Predictions - trend_candidates = [num for num, data in sorted(self.momentum_scores.items(), - key=lambda x: x[1]['momentum_score'], reverse=True)[:12]] - remaining_trend = [n for n in trend_candidates if n not in numbers] - if len(remaining_trend) >= 2: - trend_picks = random.sample(remaining_trend, 2) - numbers.extend(trend_picks) - - # 1 Zahl für Balance - remaining_slots = 6 - len(numbers) - if remaining_slots > 0: - balance_candidates = self.warm_numbers + self.cold_numbers[:8] - remaining_balance = [n for n in balance_candidates if n not in numbers] - if remaining_balance: - balance_picks = random.sample(remaining_balance, min(remaining_slots, len(remaining_balance))) - numbers.extend(balance_picks) - - # Auffüllen falls nötig - while len(numbers) < 6: - available = [n for n in range(1, 50) if n not in numbers] - additional = random.choice(available) - numbers.append(additional) - - numbers = sorted(numbers[:6]) - - # Super-Validierung - if self._validate_super_combination(numbers): - return numbers - - # Fallback - return self._generate_super_fallback() - - def _validate_super_combination(self, numbers): - """Super-Validierung mit unused combinations check.""" - combo_tuple = tuple(sorted(numbers)) - - # Prüfe ob in historischen Daten (sollte nicht sein) - if combo_tuple in self.drawn_combinations: - return False - - # Prüfe ob in unused combinations (sollte sein!) - unused_check = False - sample_size = min(50000, len(self.unused_combinations_sample)) - for i in range(sample_size): - row = self.unused_combinations_sample.iloc[i] - unused_combo = tuple(sorted([row['Z1'], row['Z2'], row['Z3'], row['Z4'], row['Z5'], row['Z6']])) - if combo_tuple == unused_combo: - unused_check = True - break - - # Basis-Validierungen - if len(set(numbers)) != 6: - return False - - distances = [numbers[i+1] - numbers[i] for i in range(5)] - if min(distances) < 1 or max(distances) > 18: - return False - - even_count = sum(1 for n in numbers if n % 2 == 0) - if even_count == 0 or even_count == 6: - return False - - total = sum(numbers) - if total < 90 or total > 200: - return False - - # Super-Check: Mindestens 1 hot number - hot_count = sum(1 for n in numbers if n in self.hot_numbers) - if hot_count == 0: - return False - - return True - - def _generate_super_fallback(self): - """Super-Fallback mit unused combinations.""" - # Wähle zufällig aus unused combinations - random_idx = random.randint(0, len(self.unused_combinations_sample) - 1) - row = self.unused_combinations_sample.iloc[random_idx] - return sorted([row['Z1'], row['Z2'], row['Z3'], row['Z4'], row['Z5'], row['Z6']]) - - def get_super_supernumber(self): - """Super-optimierte Superzahl.""" - if not self.supernumber_frequencies: - return random.randint(0, 9) - - # Erweiterte Trend-Analyse für Superzahl - recent_data = self.df_historical.tail(15) - trend_scores = {} - - for sz in range(0, 10): - recent_count = (recent_data['SZ'] == sz).sum() if 'SZ' in recent_data.columns else 0 - total_count = self.supernumber_frequencies[sz] - - # Multi-Faktor Score - trend_score = (recent_count / len(recent_data)) * 0.5 + \ - (total_count / len(self.df_historical)) * 0.3 + \ - (sz % 2) * 0.1 + \ - (1 if sz in [0, 3, 7] else 0) * 0.1 # Beliebte Zahlen-Bonus - - trend_scores[sz] = trend_score - - # Gewichtete Auswahl - candidates = list(trend_scores.keys()) - weights = list(trend_scores.values()) - - return random.choices(candidates, weights=weights)[0] - - def generate_super_tips(self, num_tips=10): - """Generiert Super-Tipps mit kompletter Intelligence.""" - print(f"\n🚀 SUPER-TIPP-GENERIERUNG") - print("=" * 50) - print(f"🎯 Nutzt KOMPLETTE Sebastian's Datenbasis:") - print(f" 📈 {len(self.df_historical)} historische Ziehungen") - print(f" 🎲 {len(self.df_unused):,} nie gezogene Kombinationen") - print(f" 🔥 Super-Momentum-Analyse") - print(f" 🧠 Unused-Combinations-Intelligence") - - generated_tips = [] - strategy_stats = { - 'unused_combo_hits': 0, - 'hot_number_avg': 0, - 'momentum_scores': [] - } - - print(f"\n🎲 GENERIERE {num_tips} SUPER-TIPPS:") - print("=" * 70) - print(f"{'Nr':<3} {'6 Super-Zahlen':<25} {'SZ':<3} {'🔥':<3} {'🎯':<3} {'Status'}") - print("-" * 70) - - attempts = 0 - max_attempts = num_tips * 100 - - while len(generated_tips) < num_tips and attempts < max_attempts: - attempts += 1 - - combination = self.generate_super_combination() - - if combination and tuple(combination) not in [tuple(tip['zahlen']) for tip in generated_tips]: - # Analyse der Kombination - hot_count = sum(1 for n in combination if n in self.hot_numbers) - momentum_avg = np.mean([self.momentum_scores[n]['momentum_score'] for n in combination]) - - # Check ob in unused combinations - combo_tuple = tuple(sorted(combination)) - unused_hit = False - for i in range(min(10000, len(self.unused_combinations_sample))): - row = self.unused_combinations_sample.iloc[i] - if combo_tuple == tuple(sorted([row['Z1'], row['Z2'], row['Z3'], row['Z4'], row['Z5'], row['Z6']])): - unused_hit = True - strategy_stats['unused_combo_hits'] += 1 - break - - superzahl = self.get_super_supernumber() - pattern = self._get_pattern(combination) - - tip = { - 'tipp_nr': len(generated_tips) + 1, - 'zahlen': combination, - 'z1': combination[0], 'z2': combination[1], 'z3': combination[2], - 'z4': combination[3], 'z5': combination[4], 'z6': combination[5], - 'superzahl': superzahl, - 'hot_count': hot_count, - 'momentum_avg': momentum_avg, - 'unused_hit': unused_hit, - 'pattern': pattern, - 'super_score': hot_count * 0.4 + momentum_avg * 0.6 - } - - generated_tips.append(tip) - strategy_stats['hot_number_avg'] += hot_count - strategy_stats['momentum_scores'].append(momentum_avg) - - # Status - status = "🎯 UNUSED!" if unused_hit else "📊 TREND" - zahlen_str = f"{combination[0]:2}-{combination[1]:2}-{combination[2]:2}-{combination[3]:2}-{combination[4]:2}-{combination[5]:2}" - print(f"{len(generated_tips):2}. {zahlen_str:<25} {superzahl:<3} {hot_count:<3} {momentum_avg:.2f} {status}") - - # Super-Zusammenfassung - self._print_super_summary(generated_tips, strategy_stats, attempts) - - # Export - self._export_super_tips(generated_tips) - - return generated_tips - - def _print_super_summary(self, tips, stats, attempts): - """Super-Zusammenfassung.""" - print(f"\n🏆 SUPER-LOTTO ZUSAMMENFASSUNG:") - print("=" * 45) - print(f"✅ {len(tips)} Super-Tipps generiert") - print(f"🎯 {stats['unused_combo_hits']}/{len(tips)} aus nie gezogenen Kombinationen") - print(f"🔥 Ø {stats['hot_number_avg']/len(tips):.1f} heiße Zahlen pro Tipp") - print(f"📊 Ø Momentum-Score: {np.mean(stats['momentum_scores']):.3f}") - print(f"⚡ Erfolgsrate: {len(tips)/attempts*100:.1f}%") - - # Super-Intelligence Insights - print(f"\n💡 SUPER-INTELLIGENCE INSIGHTS:") - print("=" * 40) - - # Top Momentum-Zahlen - top_momentum = sorted(self.momentum_scores.items(), - key=lambda x: x[1]['momentum_score'], reverse=True)[:8] - print(f"🔥 TOP MOMENTUM-ZAHLEN:") - for i, (num, data) in enumerate(top_momentum): - print(f" {i+1}. Zahl {num:2}: {data['momentum_score']:.3f} {data['status']}") - - # Pattern-Verteilung nie gezogener Kombinationen - print(f"\n🎨 NIE GEZOGENE MUSTER (häufigste):") - for pattern, count in self.unused_patterns.most_common(3): - percentage = (count / len(self.unused_combinations_sample)) * 100 - print(f" {pattern}: {percentage:.1f}% nie gezogen") - - # Super-Empfehlungen - print(f"\n🚀 SUPER-EMPFEHLUNGEN:") - print(f" 🎯 {stats['unused_combo_hits']} Tipps stammen aus nie gezogenen Kombinationen") - print(f" 🔥 Fokus auf Top-{len(self.hot_numbers)} Momentum-Zahlen") - print(f" 📊 Nutzt {len(self.df_historical)} historische Ziehungen für Trends") - print(f" 💎 Maximale Optimierung durch {len(self.df_unused):,} nie gezogene Kombinationen!") - - def _export_super_tips(self, tips): - """Exportiert Super-Tipps.""" - timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") - output_file = f"{self.base_path}/super_lotto_tipps_{timestamp}.csv" - - # Erweiterte Export-Daten - export_data = [] - for tip in tips: - tip_data = tip.copy() - tip_data['momentum_scores'] = [self.momentum_scores[n]['momentum_score'] for n in tip['zahlen']] - tip_data['individual_status'] = [self.momentum_scores[n]['status'] for n in tip['zahlen']] - export_data.append(tip_data) - - df_export = pd.DataFrame(export_data) - df_export.to_csv(output_file, sep=';', index=False) - - print(f"\n💾 SUPER-EXPORT:") - print("=" * 25) - print(f"✅ Super-Tipps gespeichert: super_lotto_tipps_{timestamp}.csv") - print(f"🚀 Basiert auf kompletter Sebastian's Datenbasis") - print(f"📊 Mit nie gezogenen Kombinationen optimiert") - - def _print_super_analysis_summary(self): - """Super-Analyse Zusammenfassung.""" - print(f"\n📈 SUPER-ANALYSE ZUSAMMENFASSUNG:") - print("=" * 50) - - # Datenbasis-Info - print(f"📊 DATENBASIS:") - print(f" 📈 Historische Ziehungen: {len(self.df_historical):,}") - print(f" 🎲 Nie gezogene Kombinationen: {len(self.df_unused):,}") - print(f" 📅 Zeitraum: {len(self.df_historical)} Ziehungen") - - # Top Zahlen mit Super-Intelligence - print(f"\n🔥 SUPER-HOT ZAHLEN:") - for i, num in enumerate(self.hot_numbers[:8]): - momentum_data = self.momentum_scores[num] - freq = self.number_frequencies[num] - print(f" {i+1}. Zahl {num:2}: Score {momentum_data['momentum_score']:.3f} " - f"({freq}x gezogen) {momentum_data['status']}") - - # Nie gezogene Muster-Intelligence - print(f"\n🎯 NIE GEZOGENE MUSTER-INTELLIGENCE:") - for pattern, count in self.unused_patterns.most_common(5): - historical_count = self.pattern_frequencies.get(pattern, 0) - unused_percentage = (count / len(self.unused_combinations_sample)) * 100 - print(f" {pattern}: {unused_percentage:.1f}% nie gezogen " - f"(historisch: {historical_count}x)") - - # Sequential Dependencies Insights - print(f"\n🔗 SEQUENTIAL INSIGHTS:") - if self.sequential_dependencies: - top_sequence = None - max_count = 0 - for lag, transitions in self.sequential_dependencies.items(): - for transition, count in transitions.items(): - if count > max_count: - max_count = count - top_sequence = (lag, transition, count) - - if top_sequence: - lag, transition, count = top_sequence - prev_num, curr_num = transition.split('_') - print(f" Stärkste Abhängigkeit: Nach Zahl {prev_num} kommt oft Zahl {curr_num} ({count}x)") - - # Hilfsfunktionen - def _get_pattern(self, numbers): - """N/M/H-Muster für 6aus49.""" - pattern = [] - for num in numbers: - if 1 <= num <= 16: - pattern.append('N') - elif 17 <= num <= 32: - pattern.append('M') - else: - pattern.append('H') - return ''.join(pattern) - - def _calculate_trend_score(self, sequence): - """Trend-Score Berechnung.""" - if len(sequence) < 2: - return 0 - x = np.arange(len(sequence)) - y = np.array(sequence) - weights = np.exp(x / len(x)) - try: - coeffs = np.polyfit(x, y, 1, w=weights) - return coeffs[0] - except: - return 0 - - def _calculate_recency_score(self, sequence): - """Recency-Score Berechnung.""" - try: - last_hit_index = len(sequence) - 1 - sequence[::-1].index(1) - recency = 1 - (len(sequence) - 1 - last_hit_index) / len(sequence) - return recency - except ValueError: - return 0 - - def _get_momentum_status(self, score): - """Momentum-Status.""" - if score > 0.5: - return "🔥 ULTRA-HEISS" - elif score > 0.35: - return "🌡️ SEHR HEISS" - elif score > 0.25: - return "😐 HEISS" - elif score > 0.15: - return "🧊 WARM" - else: - return "❄️ KALT" - -# Zusätzliche Super-Funktionen für erweiterte Analyse - -def analyze_winning_probability(generator, tip_numbers): - """Analysiert Gewinnwahrscheinlichkeit basierend auf Super-Intelligence.""" - base_prob = 1 / 13983816 - - # Super-Faktoren - factors = { - 'unused_combination': 1.0, - 'momentum_boost': 1.0, - 'pattern_boost': 1.0, - 'sequential_boost': 1.0 - } - - # Check ob nie gezogene Kombination - combo_tuple = tuple(sorted(tip_numbers)) - for i in range(min(50000, len(generator.unused_combinations_sample))): - row = generator.unused_combinations_sample.iloc[i] - if combo_tuple == tuple(sorted([row['Z1'], row['Z2'], row['Z3'], row['Z4'], row['Z5'], row['Z6']])): - factors['unused_combination'] = 1.5 # 50% Boost für nie gezogene Kombination - break - - # Momentum-Boost - hot_count = sum(1 for n in tip_numbers if n in generator.hot_numbers) - momentum_avg = np.mean([generator.momentum_scores[n]['momentum_score'] for n in tip_numbers]) - factors['momentum_boost'] = 1 + (hot_count * 0.1) + (momentum_avg * 0.3) - - # Pattern-Boost - pattern = generator._get_pattern(sorted(tip_numbers)) - if pattern in generator.unused_patterns: - unused_pattern_freq = generator.unused_patterns[pattern] / len(generator.unused_combinations_sample) - factors['pattern_boost'] = 1 + (unused_pattern_freq * 0.2) - - # Sequential-Boost (vereinfacht) - sequential_score = 0 - for i in range(len(tip_numbers)-1): - transition_key = f"{tip_numbers[i]}_{tip_numbers[i+1]}" - for lag_data in generator.sequential_dependencies.values(): - if transition_key in lag_data: - sequential_score += lag_data[transition_key] - - if sequential_score > 0: - factors['sequential_boost'] = 1 + (sequential_score / 1000) # Normalisiert - - # Gesamt-Multiplikator - total_multiplier = 1 - for factor_value in factors.values(): - total_multiplier *= factor_value - - estimated_prob = base_prob * total_multiplier - - return { - 'base_probability': base_prob, - 'factors': factors, - 'total_multiplier': total_multiplier, - 'estimated_probability': estimated_prob, - 'improvement_factor': total_multiplier - } - -def generate_super_analysis_report(generator, tips): - """Generiert detaillierten Super-Analyse-Report.""" - report = [] - - report.append("🚀 SUPER-LOTTO 6AUS49 ANALYSE-REPORT") - report.append("=" * 50) - report.append(f"📊 Basierend auf Sebastian's kompletter Datenbasis") - report.append(f"📈 {len(generator.df_historical):,} historische Ziehungen") - report.append(f"🎲 {len(generator.df_unused):,} nie gezogene Kombinationen") - report.append("") - - # Tip-by-Tip Analyse - report.append("📋 DETAILLIERTE TIPP-ANALYSE:") - report.append("-" * 40) - - for tip in tips: - report.append(f"\n🎯 TIPP {tip['tipp_nr']}:") - zahlen_str = f"{tip['z1']:2}-{tip['z2']:2}-{tip['z3']:2}-{tip['z4']:2}-{tip['z5']:2}-{tip['z6']:2}" - report.append(f" Zahlen: {zahlen_str} + SZ: {tip['superzahl']}") - report.append(f" 🔥 Heiße Zahlen: {tip['hot_count']}/6") - report.append(f" 📊 Momentum-Score: {tip['momentum_avg']:.3f}") - report.append(f" 🎯 Nie gezogen: {'✅ JA' if tip['unused_hit'] else '❌ NEIN'}") - report.append(f" 🎨 Muster: {tip['pattern']}") - - # Wahrscheinlichkeits-Analyse - prob_analysis = analyze_winning_probability(generator, tip['zahlen']) - report.append(f" 📈 Verbesserungs-Faktor: {prob_analysis['improvement_factor']:.2f}x") - - # Individuelle Zahlen-Analyse - report.append(" 🔍 Zahlen-Details:") - for num in tip['zahlen']: - momentum_data = generator.momentum_scores[num] - freq = generator.number_frequencies[num] - report.append(f" Zahl {num:2}: {momentum_data['status']} " - f"(Score: {momentum_data['momentum_score']:.3f}, {freq}x gezogen)") - - # Super-Intelligence Zusammenfassung - report.append(f"\n🧠 SUPER-INTELLIGENCE ZUSAMMENFASSUNG:") - report.append("=" * 45) - - # Nie gezogene Kombinationen Statistik - unused_hits = sum(1 for tip in tips if tip['unused_hit']) - report.append(f"🎯 {unused_hits}/{len(tips)} Tipps aus nie gezogenen Kombinationen") - - # Momentum-Statistiken - avg_hot_numbers = sum(tip['hot_count'] for tip in tips) / len(tips) - avg_momentum = sum(tip['momentum_avg'] for tip in tips) / len(tips) - report.append(f"🔥 Ø {avg_hot_numbers:.1f} heiße Zahlen pro Tipp") - report.append(f"📊 Ø Momentum-Score: {avg_momentum:.3f}") - - # Top Empfehlungen - report.append(f"\n💡 TOP EMPFEHLUNGEN:") - report.append(f"✅ Verwenden Sie die Tipps mit nie gezogenen Kombinationen") - report.append(f"🔥 Fokussieren Sie sich auf die {len(generator.hot_numbers)} heißesten Zahlen") - report.append(f"📈 Super-Momentum-Analyse zeigt beste Trends") - report.append(f"🎲 {len(generator.df_unused):,} nie gezogene Kombinationen = riesiger Vorteil!") - - return "\n".join(report) - -def export_comprehensive_analysis(generator, tips): - """Exportiert umfassende Analyse in Text-Datei.""" - timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") - report_file = f"{generator.base_path}/super_lotto_analysis_{timestamp}.txt" - - report = generate_super_analysis_report(generator, tips) - - with open(report_file, 'w', encoding='utf-8') as f: - f.write(report) - - print(f"📄 Umfassende Analyse gespeichert: super_lotto_analysis_{timestamp}.txt") - -def main(): - """Hauptfunktion für Super-Lotto Generator.""" - print("🎲 SUPER-LOTTO 6AUS49 GENERATOR") - print("🚀 Mit Sebastian's kompletter Datenbasis") - print("=" * 50) - - try: - # Generator mit Sebastian's Daten initialisieren - generator = SuperLotto6aus49Generator() - - # Super-Tipps generieren - tips = generator.generate_super_tips(10) - - if tips: - print(f"\n🏆 SUPER-OPTIMIERUNG ABGESCHLOSSEN!") - print("=" * 45) - print(f"🎲 10 Super-Tipps mit maximaler Intelligence generiert") - print(f"📊 Nutzt {len(generator.df_historical):,} historische Ziehungen") - print(f"🎯 Optimiert mit {len(generator.df_unused):,} nie gezogenen Kombinationen") - print(f"🔥 Multi-Momentum-Analyse mit Beschleunigung") - print(f"🧠 Sequential Dependencies Intelligence") - print(f"🍀 Maximale Gewinnchancen durch Super-Intelligence!") - - # Erweiterte Analyse anbieten - print(f"\n📊 ERWEITERTE ANALYSE:") - print("=" * 30) - - # Beispiel Super-Analyse - if len(tips) > 0: - sample_tip = tips[0] - prob_analysis = analyze_winning_probability(generator, sample_tip['zahlen']) - - print(f"\n🔍 SUPER-ANALYSE für Tipp 1:") - zahlen_str = f"{sample_tip['z1']:2}-{sample_tip['z2']:2}-{sample_tip['z3']:2}-{sample_tip['z4']:2}-{sample_tip['z5']:2}-{sample_tip['z6']:2}" - print(f" 🎲 Super-Kombination: {zahlen_str} + SZ: {sample_tip['superzahl']}") - print(f" 🔥 Heiße Zahlen: {sample_tip['hot_count']}/6") - print(f" 📊 Momentum-Score: {sample_tip['momentum_avg']:.3f}") - print(f" 🎯 Nie gezogen: {'✅ JA' if sample_tip['unused_hit'] else '❌ NEIN'}") - print(f" 📈 Verbesserungs-Faktor: {prob_analysis['improvement_factor']:.2f}x") - print(f" 💎 Super-Score: {sample_tip['super_score']:.3f}") - - # Angebot für vollständigen Report - create_report = input("\nVollständigen Analyse-Report erstellen? (j/n): ").lower().strip() - if create_report == 'j' or create_report == 'ja': - export_comprehensive_analysis(generator, tips) - print("✅ Vollständiger Report erstellt!") - - print(f"\n🎯 SUPER-EMPFEHLUNGEN:") - print("=" * 30) - unused_count = sum(1 for tip in tips if tip['unused_hit']) - print(f"🎲 {unused_count} Tipps stammen aus nie gezogenen Kombinationen") - print(f"🔥 Alle Tipps nutzen Super-Momentum-Analyse") - print(f"📊 Basiert auf kompletter historischer Datenbasis") - print(f"💡 Maximale Optimierung durch Sebastian's Daten!") - - else: - print("❌ Keine Super-Tipps generiert!") - - except Exception as e: - print(f"❌ Fehler: {e}") - print("💡 Stellen Sie sicher, dass Sebastian's CSV-Dateien verfügbar sind:") - print(" 📁 AlleLottozahlen.csv") - print(" 📁 Fehlende_Lotto_Kombinationen.csv") - -if __name__ == "__main__": - # Reproduzierbarer Seed - random.seed(42) - np.random.seed(42) - - # Super-Generator starten - main() \ No newline at end of file diff --git a/ultimate_hybrid_lotto_generator.py b/ultimate_hybrid_lotto_generator.py deleted file mode 100644 index 3da3352..0000000 --- a/ultimate_hybrid_lotto_generator.py +++ /dev/null @@ -1,594 +0,0 @@ -#!/usr/bin/env python3 -""" -ULTIMATE HYBRID LOTTO GENERATOR -Kombiniert AI-ML Generator + Pattern-Weighted Generator - -Features: -- AI-ML Ensemble (Random Forest + Gradient Boosting + Neural Networks) -- Pattern-Gewichtung (NNMMHH, NMMHHH, etc.) -- Real-Time Learning -- Multi-Strategy Tip Generation -- Performance Comparison zwischen beiden Ansätzen -- Adaptive Strategy Selection -""" - -import pandas as pd -import numpy as np -import random -from collections import Counter, defaultdict, deque -import datetime -import os - -# ML Imports (optional) -try: - from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor - from sklearn.neural_network import MLPRegressor - from sklearn.preprocessing import StandardScaler - ML_AVAILABLE = True -except ImportError: - ML_AVAILABLE = False - -class UltimateHybridLottoGenerator: - def __init__(self, data_path): - self.data_path = data_path - self.df = None - - # Beide Subsysteme - self.ai_ml_system = AIMLSubsystem() - self.pattern_system = PatternSubsystem() - self.hybrid_optimizer = HybridOptimizer() - - # Performance Tracking - self.strategy_performance = { - 'ai_ml': {'tips': [], 'confidence': [], 'success_rate': 0.0}, - 'pattern': {'tips': [], 'confidence': [], 'success_rate': 0.0}, - 'hybrid': {'tips': [], 'confidence': [], 'success_rate': 0.0} - } - - # Adaptive Weights - self.adaptive_weights = { - 'ai_ml': 0.4, - 'pattern': 0.3, - 'hybrid': 0.3 - } - - print("🚀 ULTIMATE HYBRID LOTTO GENERATOR") - print("=" * 60) - print("🤖 AI-ML System + 🎨 Pattern System + ⚡ Hybrid Optimizer") - - # Initialize - self.load_and_initialize() - - def load_and_initialize(self): - """Lädt Daten und initialisiert alle Subsysteme.""" - try: - self.df = pd.read_csv(self.data_path, sep=';') - - if 'datum' in self.df.columns: - self.df['datum'] = pd.to_datetime(self.df['datum'], format='%Y-%m-%d', errors='coerce') - self.df = self.df.sort_values('datum') - - print(f"📊 {len(self.df)} Ziehungen geladen") - - # Initialize subsystems - print("🔧 Initialisiere AI-ML System...") - self.ai_ml_system.initialize(self.df) - - print("🎨 Initialisiere Pattern System...") - self.pattern_system.initialize(self.df) - - print("⚡ Initialisiere Hybrid Optimizer...") - self.hybrid_optimizer.initialize(self.df, self.ai_ml_system, self.pattern_system) - - print("✅ Alle Systeme bereit!") - - except Exception as e: - print(f"❌ Initialization error: {e}") - self.df = pd.DataFrame() - - def generate_ultimate_tips(self, num_tips=10): - """Generiert Ultimate Tipps mit allen drei Strategien.""" - print(f"\n🎯 ULTIMATE TIP GENERATION") - print("=" * 60) - - if len(self.df) == 0: - print("❌ Keine Daten verfügbar") - return [] - - # Strategy Distribution basierend auf Performance - strategies = self._determine_strategy_distribution(num_tips) - - print(f"📊 STRATEGY DISTRIBUTION:") - for strategy, count in strategies.items(): - weight = self.adaptive_weights[strategy] - print(f" {strategy.upper()}: {count} tips (Weight: {weight:.2f})") - - all_tips = [] - - print(f"\n🎲 GENERATING {num_tips} ULTIMATE TIPS:") - print("=" * 85) - print("Nr 6 Ultimate Numbers SZ Strategy AI-Score Pattern-W Confidence") - print("-" * 85) - - tip_counter = 1 - - # AI-ML Tips - if strategies['ai_ml'] > 0: - ai_tips = self._generate_ai_ml_tips(strategies['ai_ml'], tip_counter) - all_tips.extend(ai_tips) - tip_counter += len(ai_tips) - - # Pattern Tips - if strategies['pattern'] > 0: - pattern_tips = self._generate_pattern_tips(strategies['pattern'], tip_counter) - all_tips.extend(pattern_tips) - tip_counter += len(pattern_tips) - - # Hybrid Tips - if strategies['hybrid'] > 0: - hybrid_tips = self._generate_hybrid_tips(strategies['hybrid'], tip_counter) - all_tips.extend(hybrid_tips) - - # Output all tips - for tip in all_tips: - self._print_tip_line(tip) - - # Performance Analysis - self._analyze_tip_portfolio(all_tips) - - # Update adaptive weights - self._update_adaptive_weights(all_tips) - - return all_tips - - def _determine_strategy_distribution(self, num_tips): - """Bestimmt Strategy-Verteilung basierend auf Performance.""" - strategies = {} - - # Basis-Verteilung basierend auf Adaptive Weights - ai_count = max(1, int(num_tips * self.adaptive_weights['ai_ml'])) - pattern_count = max(1, int(num_tips * self.adaptive_weights['pattern'])) - hybrid_count = num_tips - ai_count - pattern_count - - # Sicherstellen dass hybrid_count >= 0 - if hybrid_count < 0: - if ai_count > pattern_count: - ai_count += hybrid_count - else: - pattern_count += hybrid_count - hybrid_count = 0 - - strategies['ai_ml'] = ai_count - strategies['pattern'] = pattern_count - strategies['hybrid'] = hybrid_count - - return strategies - - def _generate_ai_ml_tips(self, count, start_number): - """Generiert AI-ML basierte Tipps.""" - tips = [] - - if not ML_AVAILABLE: - # Fallback zu frequency-based - for i in range(count): - tip = self._generate_frequency_tip(start_number + i, 'AI-ML-FALLBACK') - tips.append(tip) - return tips - - # AI Predictions - ai_predictions = self.ai_ml_system.get_predictions() - - for i in range(count): - tip_number = start_number + i - - # AI-optimierte Kombination - numbers = self._select_ai_optimized_numbers(ai_predictions, tip_number) - superzahl = self._get_smart_superzahl(tip_number) - - # Scores - ai_score = np.mean([ai_predictions.get(n, 0.1) for n in numbers]) - pattern_weight = self.pattern_system.calculate_pattern_weight(numbers) - confidence = ai_score * 0.7 + pattern_weight * 0.3 - - tip = { - 'tip_number': tip_number, - 'numbers': numbers, - 'superzahl': superzahl, - 'strategy': 'AI-ML', - 'ai_score': ai_score, - 'pattern_weight': pattern_weight, - 'confidence': confidence - } - - tips.append(tip) - - return tips - - def _generate_pattern_tips(self, count, start_number): - """Generiert Pattern-basierte Tipps.""" - tips = [] - - # Top Patterns aus historischen Daten - top_patterns = self.pattern_system.get_top_patterns(count) - - for i in range(count): - tip_number = start_number + i - - # Wähle Pattern - target_pattern = top_patterns[i % len(top_patterns)] if top_patterns else 'NNMMHH' - - # Pattern-optimierte Kombination - numbers = self.pattern_system.optimize_for_pattern(target_pattern, tip_number) - superzahl = self._get_smart_superzahl(tip_number) - - # Scores - pattern_weight = self.pattern_system.calculate_pattern_weight(numbers) - ai_score = 0.3 + random.random() * 0.2 # Mock AI score für Pattern-Tips - confidence = pattern_weight * 0.7 + ai_score * 0.3 - - tip = { - 'tip_number': tip_number, - 'numbers': numbers, - 'superzahl': superzahl, - 'strategy': 'PATTERN', - 'ai_score': ai_score, - 'pattern_weight': pattern_weight, - 'confidence': confidence, - 'target_pattern': target_pattern - } - - tips.append(tip) - - return tips - - def _generate_hybrid_tips(self, count, start_number): - """Generiert Hybrid-optimierte Tipps.""" - tips = [] - - for i in range(count): - tip_number = start_number + i - - # Hybrid optimization - hybrid_result = self.hybrid_optimizer.optimize_combination(tip_number) - - numbers = hybrid_result['numbers'] - superzahl = self._get_smart_superzahl(tip_number) - - tip = { - 'tip_number': tip_number, - 'numbers': numbers, - 'superzahl': superzahl, - 'strategy': 'HYBRID', - 'ai_score': hybrid_result['ai_score'], - 'pattern_weight': hybrid_result['pattern_weight'], - 'confidence': hybrid_result['confidence'] - } - - tips.append(tip) - - return tips - - def _select_ai_optimized_numbers(self, ai_predictions, tip_number): - """Wählt AI-optimierte Zahlen aus.""" - if not ai_predictions: - return sorted(random.sample(range(1, 50), 6)) - - # Top AI candidates - sorted_predictions = sorted(ai_predictions.items(), key=lambda x: x[1], reverse=True) - - selected = [] - random.seed(42 + tip_number) # Konsistenz mit Variation - - # Strategy: Top AI + Diversität - for i in range(6): - candidates = [num for num, score in sorted_predictions[:25] if num not in selected] - - if not candidates: - candidates = [n for n in range(1, 50) if n not in selected] - - if candidates: - # Gewichtete Auswahl mit etwas Zufall - weights = [ai_predictions.get(c, 0.1) + random.random() * 0.1 for c in candidates] - selected.append(random.choices(candidates, weights=weights)[0]) - - return sorted(selected) - - def _get_smart_superzahl(self, tip_number): - """Intelligente Superzahl-Auswahl.""" - base_sz = [7, 6, 3, 2, 0, 1, 4, 5, 8, 9] - - # Aus historischen Daten - if 'SZ' in self.df.columns and len(self.df) > 10: - recent_sz = self.df['SZ'].tail(20).dropna() - if len(recent_sz) > 0: - sz_freq = Counter(recent_sz) - frequent_sz = [int(sz) for sz, _ in sz_freq.most_common(5) if 0 <= sz <= 9] - if frequent_sz: - base_sz = frequent_sz - - return base_sz[tip_number % len(base_sz)] - - def _generate_frequency_tip(self, tip_number, strategy): - """Fallback frequency-based tip.""" - if len(self.df) == 0: - numbers = sorted(random.sample(range(1, 50), 6)) - else: - # Frequency analysis - number_freq = Counter() - for _, row in self.df.tail(30).iterrows(): - for col in ['Z1', 'Z2', 'Z3', 'Z4', 'Z5', 'Z6']: - if col in row and pd.notna(row[col]): - number_freq[int(row[col])] += 1 - - # Mix frequent + random - frequent = [num for num, _ in number_freq.most_common(20)] - numbers = random.sample(frequent[:15], 4) + random.sample(range(1, 50), 2) - numbers = sorted(list(set(numbers))[:6]) - - while len(numbers) < 6: - candidates = [n for n in range(1, 50) if n not in numbers] - numbers.append(random.choice(candidates)) - numbers = sorted(numbers) - - return { - 'tip_number': tip_number, - 'numbers': numbers, - 'superzahl': self._get_smart_superzahl(tip_number), - 'strategy': strategy, - 'ai_score': 0.3, - 'pattern_weight': 0.3, - 'confidence': 0.3 - } - - def _print_tip_line(self, tip): - """Druckt eine Tipp-Zeile.""" - zahlen_str = '-'.join([f"{n:2d}" for n in tip['numbers']]) - - print(f"{tip['tip_number']:2d} {zahlen_str} {tip['superzahl']:2d} " - f"{tip['strategy']:<9} {tip['ai_score']:.3f} {tip['pattern_weight']:.3f} {tip['confidence']:.3f}") - - def _analyze_tip_portfolio(self, tips): - """Analysiert das Tipp-Portfolio.""" - print(f"\n📊 PORTFOLIO ANALYSIS:") - print("=" * 50) - - # Strategy-wise stats - strategy_stats = defaultdict(list) - for tip in tips: - strategy_stats[tip['strategy']].append(tip) - - for strategy, strategy_tips in strategy_stats.items(): - avg_confidence = np.mean([t['confidence'] for t in strategy_tips]) - avg_ai = np.mean([t['ai_score'] for t in strategy_tips]) - avg_pattern = np.mean([t['pattern_weight'] for t in strategy_tips]) - - print(f"{strategy}:") - print(f" Tips: {len(strategy_tips)}, Avg Confidence: {avg_confidence:.3f}") - print(f" Avg AI-Score: {avg_ai:.3f}, Avg Pattern-Weight: {avg_pattern:.3f}") - - # Best tip - best_tip = max(tips, key=lambda x: x['confidence']) - print(f"\n⭐ BEST TIP:") - zahlen_str = '-'.join([f"{n:2d}" for n in best_tip['numbers']]) - print(f" #{best_tip['tip_number']}: {zahlen_str} + SZ {best_tip['superzahl']}") - print(f" Strategy: {best_tip['strategy']}, Confidence: {best_tip['confidence']:.3f}") - - def _update_adaptive_weights(self, tips): - """Updated adaptive weights basierend auf tip quality.""" - strategy_confidence = defaultdict(list) - - for tip in tips: - strategy_confidence[tip['strategy']].append(tip['confidence']) - - # Update weights basierend auf average confidence - total_confidence = 0 - strategy_avg = {} - - for strategy, confidences in strategy_confidence.items(): - avg_conf = np.mean(confidences) - strategy_avg[strategy] = avg_conf - total_confidence += avg_conf - - # Normalize to weights - if total_confidence > 0: - for strategy in ['ai_ml', 'pattern', 'hybrid']: - strategy_key = strategy.upper().replace('_', '-') - if strategy_key in strategy_avg: - self.adaptive_weights[strategy] = strategy_avg[strategy_key] / total_confidence - - print(f"\n🔄 UPDATED ADAPTIVE WEIGHTS:") - for strategy, weight in self.adaptive_weights.items(): - print(f" {strategy.upper()}: {weight:.3f}") - -# Subsystem Classes - -class AIMLSubsystem: - def __init__(self): - self.predictions = {} - self.is_trained = False - - def initialize(self, df): - if ML_AVAILABLE and len(df) > 50: - self._train_simple_model(df) - else: - self._create_fallback_predictions(df) - - def _train_simple_model(self, df): - # Simplified ML training - number_freq = Counter() - for _, row in df.iterrows(): - for col in ['Z1', 'Z2', 'Z3', 'Z4', 'Z5', 'Z6']: - if col in row and pd.notna(row[col]): - number_freq[int(row[col])] += 1 - - max_freq = max(number_freq.values()) if number_freq else 1 - - for num in range(1, 50): - freq = number_freq.get(num, 0) - base_pred = freq / max_freq - # Add ML-like variation - ml_variation = np.random.normal(0, 0.1) - self.predictions[num] = max(0.1, min(0.9, base_pred + ml_variation)) - - self.is_trained = True - - def _create_fallback_predictions(self, df): - # Simple frequency-based predictions - for num in range(1, 50): - self.predictions[num] = 0.1 + random.random() * 0.4 - - def get_predictions(self): - return self.predictions - -class PatternSubsystem: - def __init__(self): - self.pattern_frequencies = Counter() - self.pattern_weights = {} - - def initialize(self, df): - self._analyze_patterns(df) - - def _analyze_patterns(self, df): - total = len(df) - - for _, row in df.iterrows(): - numbers = sorted([row['Z1'], row['Z2'], row['Z3'], row['Z4'], row['Z5'], row['Z6']]) - pattern = self._get_pattern(numbers) - self.pattern_frequencies[pattern] += 1 - - # Calculate weights - for pattern, count in self.pattern_frequencies.items(): - self.pattern_weights[pattern] = count / total - - def _get_pattern(self, numbers): - pattern = "" - for num in numbers: - if 1 <= num <= 16: - pattern += "N" - elif 17 <= num <= 32: - pattern += "M" - else: - pattern += "H" - return pattern - - def calculate_pattern_weight(self, numbers): - pattern = self._get_pattern(sorted(numbers)) - return self.pattern_weights.get(pattern, 0.01) - - def get_top_patterns(self, count): - return [pattern for pattern, _ in self.pattern_frequencies.most_common(count)] - - def optimize_for_pattern(self, target_pattern, seed): - random.seed(42 + seed) - - ranges = { - 'N': list(range(1, 17)), - 'M': list(range(17, 33)), - 'H': list(range(33, 50)) - } - - pattern_counts = Counter(target_pattern) - selected = [] - - for char, count in pattern_counts.items(): - if char in ranges and count > 0: - available = [n for n in ranges[char] if n not in selected] - if len(available) >= count: - selected.extend(random.sample(available, count)) - - while len(selected) < 6: - all_available = [n for n in range(1, 50) if n not in selected] - if all_available: - selected.append(random.choice(all_available)) - - return sorted(selected[:6]) - -class HybridOptimizer: - def __init__(self): - self.ai_system = None - self.pattern_system = None - - def initialize(self, df, ai_system, pattern_system): - self.ai_system = ai_system - self.pattern_system = pattern_system - - def optimize_combination(self, seed): - random.seed(42 + seed) - - # Get AI predictions - ai_preds = self.ai_system.get_predictions() - - # Multi-objective optimization - best_score = -1 - best_combination = None - - for attempt in range(100): # Limited search - # Generate candidate - candidate = self._generate_candidate(ai_preds, attempt) - - # Score combination - ai_score = np.mean([ai_preds.get(n, 0.1) for n in candidate]) - pattern_weight = self.pattern_system.calculate_pattern_weight(candidate) - - # Multi-objective score - combined_score = ai_score * 0.6 + pattern_weight * 0.4 - - if combined_score > best_score: - best_score = combined_score - best_combination = candidate - - return { - 'numbers': best_combination or sorted(random.sample(range(1, 50), 6)), - 'ai_score': np.mean([ai_preds.get(n, 0.1) for n in best_combination]) if best_combination else 0.3, - 'pattern_weight': self.pattern_system.calculate_pattern_weight(best_combination) if best_combination else 0.3, - 'confidence': best_score if best_score > 0 else 0.3 - } - - def _generate_candidate(self, ai_preds, attempt): - # Verschiedene Generierungsstrategien - if attempt < 30: - # AI-focused - candidates = sorted(ai_preds.items(), key=lambda x: x[1], reverse=True)[:20] - return sorted(random.sample([num for num, _ in candidates], 6)) - elif attempt < 60: - # Pattern-focused - target_patterns = ['NNMMHH', 'NMMHHH', 'NMMMHH'] - pattern = random.choice(target_patterns) - return self.pattern_system.optimize_for_pattern(pattern, attempt) - else: - # Random with bias - return sorted(random.sample(range(1, 50), 6)) - -def main(): - """Startet den Ultimate Hybrid Generator.""" - data_path = "/Users/sebastianfrohlich/Library/Mobile Documents/com~apple~CloudDocs/Jupyter Notebooks/AlleLottozahlen.csv" - - try: - # Initialize Ultimate Generator - generator = UltimateHybridLottoGenerator(data_path) - - # Generate ultimate tips - ultimate_tips = generator.generate_ultimate_tips(10) - - print(f"\n🏆 ULTIMATE GENERATION COMPLETED!") - print("=" * 50) - print(f"🚀 {len(ultimate_tips)} Ultimate Tips generiert") - print(f"🤖 AI-ML System: {'✅' if ML_AVAILABLE else '⚠️ Fallback'}") - print(f"🎨 Pattern System: ✅") - print(f"⚡ Hybrid Optimizer: ✅") - print(f"📊 Adaptive Strategy Selection: ✅") - - print(f"\n💡 SYSTEM ADVANTAGES:") - print(f" 🔬 Wissenschaftlich: Multi-System Validation") - print(f" 🎯 Adaptiv: Performance-basierte Gewichtung") - print(f" ⚖️ Ausgewogen: AI + Pattern + Hybrid Balance") - print(f" 📈 Lernend: Kontinuierliche Verbesserung") - - except Exception as e: - print(f"❌ Error: {e}") - -if __name__ == "__main__": - random.seed(42) - np.random.seed(42) - - main() diff --git a/ultimate_lotto_6aus49_generator.py b/ultimate_lotto_6aus49_generator.py deleted file mode 100644 index 76f8c44..0000000 --- a/ultimate_lotto_6aus49_generator.py +++ /dev/null @@ -1,840 +0,0 @@ -#!/usr/bin/env python3 -""" -Ultimate Lotto 6aus49 Generator mit Multi-Ziehungs-Trend-Analyse - -Speziell optimiert für deutsches Lotto 6 aus 49: -- 6 Zahlen aus 49 (statt 5 aus 50) -- 1 Superzahl 0-9 (statt 2 Eurozahlen) -- Angepasste N/M/H-Bereiche für 49er-System -- Multi-Ziehungs-Trend-Analyse -- Momentum-Tracking über mehrere Ziehungen -- Sequenzielle Abhängigkeiten -- Zyklische Muster-Erkennung -""" - -import pandas as pd -import random -import numpy as np -from itertools import combinations -from collections import Counter, defaultdict, deque -import datetime - -class UltimateLotto6aus49Generator: - def __init__(self, data_path=None): - # Pfad zur Lotto-Daten CSV-Datei - self.data_path = data_path or input("Pfad zur Lotto 6aus49 CSV-Datei: ").strip() - self.df = None - self.drawn_combinations = set() - - # Basis-Analyse - self.number_frequencies = Counter() - self.position_frequencies = defaultdict(Counter) - self.pattern_frequencies = Counter() - self.supernumber_frequencies = Counter() # Nur 1 Superzahl beim Lotto - self.number_distances = [] - - # Multi-Ziehungs-Trend-Analyse - self.number_sequences = defaultdict(list) - self.momentum_scores = {} - self.trend_predictions = {} - self.sequential_dependencies = defaultdict(lambda: defaultdict(int)) - self.cycle_patterns = {} - self.hot_numbers = [] - self.warm_numbers = [] - self.cold_numbers = [] - - # Lotto 6aus49 spezifische Bereiche (angepasst für 1-49) - self.lotto_ranges = { - 'N': list(range(1, 17)), # Niedrig: 1-16 (etwa 1/3) - 'M': list(range(17, 33)), # Mittel: 17-32 (etwa 1/3) - 'H': list(range(33, 50)) # Hoch: 33-49 (etwa 1/3) - } - - # Initialisierung - if self._file_exists(): - self.load_and_analyze_all_data() - - def _file_exists(self): - """Prüft ob Datei existiert.""" - try: - with open(self.data_path, 'r'): - return True - except FileNotFoundError: - print(f"❌ Datei nicht gefunden: {self.data_path}") - print("💡 Bitte stellen Sie sicher, dass die Lotto-Daten im korrekten Format vorliegen:") - print(" Spalten: Datum, Z1, Z2, Z3, Z4, Z5, Z6, SZ (Superzahl)") - return False - - def load_and_analyze_all_data(self): - """Lädt Lotto-Daten und führt alle Analysen durch.""" - try: - # CSV laden mit flexibler Spaltenerkennung - self.df = pd.read_csv(self.data_path, sep=';') - - # Spalten-Mapping für verschiedene CSV-Formate - column_mapping = { - 'Ziehungsdatum': 'Datum', - 'Gewinnzahl1': 'Z1', 'Gewinnzahl2': 'Z2', 'Gewinnzahl3': 'Z3', - 'Gewinnzahl4': 'Z4', 'Gewinnzahl5': 'Z5', 'Gewinnzahl6': 'Z6', - 'Superzahl': 'SZ', 'SuperZahl': 'SZ' - } - - # Spalten umbenennen falls nötig - for old_name, new_name in column_mapping.items(): - if old_name in self.df.columns and new_name not in self.df.columns: - self.df.rename(columns={old_name: new_name}, inplace=True) - - # Benötigte Spalten prüfen - required_columns = ['Z1', 'Z2', 'Z3', 'Z4', 'Z5', 'Z6'] - missing_columns = [col for col in required_columns if col not in self.df.columns] - - if missing_columns: - print(f"❌ Fehlende Spalten: {missing_columns}") - print(f"🔍 Verfügbare Spalten: {list(self.df.columns)}") - return False - - # Chronologische Sortierung - if 'Datum' in self.df.columns: - # Verschiedene Datumsformate versuchen - date_formats = ['%d.%m.%Y', '%Y-%m-%d', '%d/%m/%Y'] - for date_format in date_formats: - try: - self.df['Datum'] = pd.to_datetime(self.df['Datum'], format=date_format) - break - except: - continue - - if pd.api.types.is_datetime64_any_dtype(self.df['Datum']): - self.df = self.df.sort_values('Datum') - - print(f"🎲 ULTIMATE LOTTO 6AUS49 GENERATOR") - print("=" * 60) - print(f"📊 Analysiere {len(self.df)} Lotto-Ziehungen...") - print(f"🎯 System: 6 aus 49 + Superzahl (0-9)") - - # Alle Analysen durchführen - self._perform_lotto_basic_analysis() - self._perform_lotto_momentum_analysis() - self._perform_lotto_sequential_analysis() - self._perform_lotto_cycle_analysis() - self._generate_lotto_trend_predictions() - - print(f"✅ Komplette Lotto-Analyse abgeschlossen!") - self._print_lotto_analysis_summary() - - except Exception as e: - print(f"❌ Fehler beim Laden der Lotto-Daten: {e}") - print("💡 Stellen Sie sicher, dass die CSV-Datei das korrekte Format hat.") - return False - - return True - - def _perform_lotto_basic_analysis(self): - """Führt Basis-Analysen für Lotto 6aus49 durch.""" - for _, row in self.df.iterrows(): - # 6 Gewinnzahlen - numbers = [row['Z1'], row['Z2'], row['Z3'], row['Z4'], row['Z5'], row['Z6']] - combo = tuple(sorted(numbers)) - self.drawn_combinations.add(combo) - - # Zahlenfrequenzen (1-49) - for num in numbers: - if 1 <= num <= 49: # Validierung für Lotto-Bereich - self.number_frequencies[num] += 1 - - # Positionsfrequenzen - sorted_numbers = sorted(numbers) - for i, num in enumerate(sorted_numbers): - self.position_frequencies[f'pos_{i+1}'][num] += 1 - - # Lotto-Muster analysieren (angepasste Bereiche) - pattern = self._get_lotto_pattern(sorted_numbers) - self.pattern_frequencies[pattern] += 1 - - # Superzahl (0-9) - if 'SZ' in row and pd.notna(row['SZ']): - superzahl = int(row['SZ']) - if 0 <= superzahl <= 9: - self.supernumber_frequencies[superzahl] += 1 - - # Zahlenabstände (für 6 Zahlen) - distances = [sorted_numbers[i+1] - sorted_numbers[i] for i in range(5)] - self.number_distances.extend(distances) - - def _get_lotto_pattern(self, numbers): - """Bestimmt N/M/H-Muster für Lotto 6aus49.""" - pattern = [] - for num in numbers: - if 1 <= num <= 16: - pattern.append('N') # Niedrig - elif 17 <= num <= 32: - pattern.append('M') # Mittel - else: - pattern.append('H') # Hoch (33-49) - return ''.join(pattern) - - def _perform_lotto_momentum_analysis(self, window_size=12): - """Momentum-Analyse für Lotto 6aus49.""" - print(f"\n🔥 LOTTO MOMENTUM-ANALYSE (Fenster: {window_size})") - - # Zahlensequenzen für 1-49 - for number in range(1, 50): - sequence = [] - for _, row in self.df.iterrows(): - drawn_numbers = [row['Z1'], row['Z2'], row['Z3'], row['Z4'], row['Z5'], row['Z6']] - sequence.append(1 if number in drawn_numbers else 0) - self.number_sequences[number] = sequence - - # Momentum-Scores - momentum_results = {} - for number in range(1, 50): - recent_sequence = self.number_sequences[number][-window_size:] - - hit_rate = sum(recent_sequence) / len(recent_sequence) - trend_score = self._calculate_trend_score(recent_sequence) - recency_score = self._calculate_recency_score(recent_sequence) - - # Lotto-angepasste Gewichtung (6 aus 49 vs 5 aus 50) - momentum_score = (hit_rate * 0.45) + (trend_score * 0.35) + (recency_score * 0.2) - - momentum_results[number] = { - 'hit_rate': hit_rate, - 'trend_score': trend_score, - 'recency_score': recency_score, - 'momentum_score': momentum_score, - 'status': self._get_momentum_status(momentum_score) - } - - self.momentum_scores = momentum_results - - # Kategorisierung für Lotto - sorted_momentum = sorted(momentum_results.items(), - key=lambda x: x[1]['momentum_score'], reverse=True) - - self.hot_numbers = [num for num, data in sorted_momentum[:18] - if data['momentum_score'] > 0.25] # Angepasst für 6aus49 - self.warm_numbers = [num for num, data in sorted_momentum[18:30] - if 0.15 <= data['momentum_score'] <= 0.25] - self.cold_numbers = [num for num, data in sorted_momentum[30:] - if data['momentum_score'] < 0.15][:20] - - print(f"🔥 {len(self.hot_numbers)} heiße Lotto-Zahlen identifiziert") - print(f"🌡️ {len(self.warm_numbers)} warme Lotto-Zahlen identifiziert") - print(f"🧊 {len(self.cold_numbers)} kalte Lotto-Zahlen identifiziert") - - def _perform_lotto_sequential_analysis(self, look_back=3): - """Sequenzielle Abhängigkeiten für Lotto.""" - print(f"\n🔗 LOTTO SEQUENZIELLE ABHÄNGIGKEITEN") - - for i in range(look_back, len(self.df)): - current_numbers = set([self.df.iloc[i]['Z1'], self.df.iloc[i]['Z2'], - self.df.iloc[i]['Z3'], self.df.iloc[i]['Z4'], - self.df.iloc[i]['Z5'], self.df.iloc[i]['Z6']]) - - for j in range(1, look_back + 1): - prev_numbers = set([self.df.iloc[i-j]['Z1'], self.df.iloc[i-j]['Z2'], - self.df.iloc[i-j]['Z3'], self.df.iloc[i-j]['Z4'], - self.df.iloc[i-j]['Z5'], self.df.iloc[i-j]['Z6']]) - - for prev_num in prev_numbers: - for curr_num in current_numbers: - self.sequential_dependencies[f"lag_{j}"][f"{prev_num}_{curr_num}"] += 1 - - def _perform_lotto_cycle_analysis(self, max_cycle_length=15): - """Zyklische Muster-Analyse für Lotto.""" - print(f"\n🔄 LOTTO ZYKLUS-ANALYSE") - - pattern_sequence = [] - for _, row in self.df.iterrows(): - numbers = sorted([row['Z1'], row['Z2'], row['Z3'], row['Z4'], row['Z5'], row['Z6']]) - pattern = self._get_lotto_pattern(numbers) - pattern_sequence.append(pattern) - - self.cycle_patterns = {} - for cycle_length in range(3, max_cycle_length + 1): - cycles = self._find_pattern_cycles(pattern_sequence, cycle_length) - if cycles: - self.cycle_patterns[cycle_length] = cycles - - cycle_count = sum(len(cycles) for cycles in self.cycle_patterns.values()) - print(f"🔄 {cycle_count} Lotto-Zyklen erkannt") - - def _generate_lotto_trend_predictions(self): - """Trend-Vorhersagen für Lotto 6aus49.""" - print(f"\n🎯 LOTTO TREND-VORHERSAGEN") - - for number in range(1, 50): - if number in self.momentum_scores: - momentum_data = self.momentum_scores[number] - - # Lotto-spezifische Gewichtung - momentum_weight = momentum_data['momentum_score'] * 0.4 - frequency_weight = (self.number_frequencies[number] / (len(self.df) * 6)) * 0.35 # 6 Zahlen pro Ziehung - trend_weight = max(0, momentum_data['trend_score']) * 0.25 - - prediction_score = momentum_weight + frequency_weight + trend_weight - - self.trend_predictions[number] = { - 'prediction_score': prediction_score, - 'recommendation': self._get_prediction_recommendation(prediction_score), - 'confidence': self._get_confidence_level(prediction_score) - } - - def generate_lotto_ultimate_combination(self): - """Generiert ultimative Lotto 6aus49 Kombination.""" - max_attempts = 1000 - - for attempt in range(max_attempts): - numbers = [] - - # Lotto-Strategie: 6 Zahlen aus 49 - # 50% Top-Trend, 30% Heiß, 20% Balance - - # 3 Zahlen aus Top-Trends - top_trend_numbers = [num for num, data in sorted(self.trend_predictions.items(), - key=lambda x: x[1]['prediction_score'], reverse=True)[:20] - if data['recommendation'] in ['SEHR EMPFOHLEN', 'EMPFOHLEN']] - - if len(top_trend_numbers) >= 3: - trend_picks = random.sample(top_trend_numbers[:12], 3) - numbers.extend(trend_picks) - - # 2 heiße Zahlen - if len(self.hot_numbers) >= 2: - remaining_hot = [n for n in self.hot_numbers if n not in numbers] - if len(remaining_hot) >= 2: - hot_picks = random.sample(remaining_hot[:10], min(2, len(remaining_hot))) - numbers.extend(hot_picks) - - # 1 warme/kalte Zahl für Balance - remaining_slots = 6 - len(numbers) - if remaining_slots > 0: - balance_pool = self.warm_numbers + self.cold_numbers[:5] - remaining_balance = [n for n in balance_pool if n not in numbers] - if remaining_balance: - balance_picks = random.sample(remaining_balance, min(remaining_slots, len(remaining_balance))) - numbers.extend(balance_picks) - - # Auffüllen bis 6 Zahlen - while len(numbers) < 6: - available_numbers = [n for n in range(1, 50) if n not in numbers] - weights = [self.trend_predictions[n]['prediction_score'] for n in available_numbers] - - if sum(weights) > 0: - additional_number = random.choices(available_numbers, weights=weights)[0] - else: - additional_number = random.choice(available_numbers) - - numbers.append(additional_number) - - # Sortieren und validieren - numbers = sorted(numbers[:6]) - - if self._validate_lotto_combination(numbers): - return numbers - - # Fallback - return self._generate_lotto_fallback() - - def _validate_lotto_combination(self, numbers): - """Validierung für Lotto 6aus49.""" - if tuple(numbers) in self.drawn_combinations: - return False - - if len(set(numbers)) != 6: - return False - - # Lotto-spezifische Validierungen - hot_count = sum(1 for n in numbers if n in self.hot_numbers) - trend_count = sum(1 for n in numbers - if self.trend_predictions[n]['recommendation'] == 'SEHR EMPFOHLEN') - - # Mindestens 1 heiße oder sehr empfohlene Zahl - if hot_count == 0 and trend_count == 0: - return False - - # Abstände prüfen (für 6 Zahlen) - distances = [numbers[i+1] - numbers[i] for i in range(5)] - if min(distances) < 1 or max(distances) > 15: - return False - - # Gerade/Ungerade Balance - even_count = sum(1 for n in numbers if n % 2 == 0) - if even_count == 0 or even_count == 6: - return False - - # Summen-Validierung für 6aus49 - total = sum(numbers) - if total < 90 or total > 200: - return False - - return True - - def _generate_lotto_fallback(self): - """Fallback für Lotto 6aus49.""" - numbers = [] - - # Erweiterte Verteilung für 6 Zahlen: 2N + 2M + 2H - numbers.extend(random.sample(self.lotto_ranges['N'], 2)) - numbers.extend(random.sample(self.lotto_ranges['M'], 2)) - numbers.extend(random.sample(self.lotto_ranges['H'], 2)) - - return sorted(numbers) - - def get_optimized_supernumber(self): - """Optimierte Superzahl-Auswahl (0-9).""" - if not self.supernumber_frequencies: - return random.randint(0, 9) - - # Trend-gewichtete Superzahl-Auswahl - recent_df = self.df.tail(8) if len(self.df) >= 8 else self.df - supernumber_trends = {} - - for sz in range(0, 10): - recent_count = (recent_df['SZ'] == sz).sum() if 'SZ' in recent_df.columns else 0 - total_count = self.supernumber_frequencies[sz] - trend_score = (recent_count / len(recent_df)) * 0.6 + (total_count / len(self.df)) * 0.4 - supernumber_trends[sz] = trend_score - - # Gewichtete Auswahl - candidates = list(supernumber_trends.keys()) - weights = list(supernumber_trends.values()) - - if sum(weights) > 0: - return random.choices(candidates, weights=weights)[0] - else: - return random.randint(0, 9) - - def generate_lotto_ultimate_tips(self, num_tips=10): - """Generiert ultimate Lotto 6aus49 Tipps.""" - print(f"\n🚀 ULTIMATE LOTTO 6AUS49 TIPP-GENERIERUNG") - print("=" * 55) - print(f"🎯 System: 6 Zahlen aus 49 + 1 Superzahl (0-9)") - print(f"🔬 Multi-Trend-Analyse für maximale Trefferquote") - - generated_tips = [] - strategy_distribution = Counter() - - print(f"\n🎲 GENERIERE {num_tips} ULTIMATE LOTTO-TIPPS:") - print("=" * 65) - print(f"{'Nr':<3} {'6 Zahlen aus 49':<25} {'SZ':<3} {'Muster':<8} {'🔥':<3} {'🎯':<3} {'Strategie'}") - print("-" * 65) - - attempts = 0 - max_attempts = num_tips * 50 - - while len(generated_tips) < num_tips and attempts < max_attempts: - attempts += 1 - - combination = self.generate_lotto_ultimate_combination() - - if combination and tuple(combination) not in [tuple(tip['zahlen']) for tip in generated_tips]: - pattern = self._get_lotto_pattern(combination) - - # Lotto-Trend-Analyse - hot_count = sum(1 for n in combination if n in self.hot_numbers) - trend_count = sum(1 for n in combination - if self.trend_predictions[n]['recommendation'] in ['SEHR EMPFOHLEN', 'EMPFOHLEN']) - - # Superzahl - superzahl = self.get_optimized_supernumber() - - # Strategie-Klassifikation - if hot_count >= 4: - strategy = "🔥 MOMENTUM" - elif trend_count >= 4: - strategy = "🎯 TREND" - elif pattern in ['NNMMHH', 'NMMHHH', 'NNNMMM']: - strategy = "🎨 MUSTER" - else: - strategy = "⚖️ BALANCE" - - strategy_distribution[strategy] += 1 - - tip = { - 'tipp_nr': len(generated_tips) + 1, - 'zahlen': combination, - 'z1': combination[0], 'z2': combination[1], 'z3': combination[2], - 'z4': combination[3], 'z5': combination[4], 'z6': combination[5], - 'superzahl': superzahl, - 'muster': pattern, - 'summe': sum(combination), - 'hot_count': hot_count, - 'trend_count': trend_count, - 'strategy': strategy - } - - generated_tips.append(tip) - - # Output - zahlen_str = f"{combination[0]:2}-{combination[1]:2}-{combination[2]:2}-{combination[3]:2}-{combination[4]:2}-{combination[5]:2}" - print(f"{len(generated_tips):2}. {zahlen_str:<25} {superzahl:<3} {pattern:<8} {hot_count:<3} {trend_count:<3} {strategy}") - - # Lotto-Zusammenfassung - self._print_lotto_summary(generated_tips, attempts, strategy_distribution) - - # Export - self._export_lotto_tips(generated_tips) - - return generated_tips - - def _print_lotto_summary(self, tips, attempts, strategy_distribution): - """Druckt Lotto-spezifische Zusammenfassung.""" - print(f"\n🏆 ULTIMATE LOTTO 6AUS49 ZUSAMMENFASSUNG:") - print("=" * 50) - print(f"✅ {len(tips)} Ultimate Lotto-Tipps generiert") - print(f"🎯 Erfolgsrate: {(len(tips)/attempts)*100:.1f}%") - print(f"🔥 Durchschnitt {sum(tip['hot_count'] for tip in tips)/len(tips):.1f} heiße Zahlen pro Tipp") - print(f"📈 Durchschnitt {sum(tip['trend_count'] for tip in tips)/len(tips):.1f} Trend-Zahlen pro Tipp") - - # Strategie-Verteilung - print(f"\n📊 STRATEGIE-VERTEILUNG:") - for strategy, count in strategy_distribution.most_common(): - print(f" {strategy}: {count} Tipps") - - # Lotto-spezifische Insights - print(f"\n💡 LOTTO 6AUS49 INSIGHTS:") - - # Top Trend-Zahlen - top_trend = sorted(self.trend_predictions.items(), - key=lambda x: x[1]['prediction_score'], reverse=True)[:6] - print(f"🎯 TOP 6 TREND-ZAHLEN:") - for i, (number, data) in enumerate(top_trend): - status = self.momentum_scores[number]['status'] - print(f" {i+1}. Zahl {number:2}: {data['recommendation']} {status}") - - # Häufigste Superzahlen - if self.supernumber_frequencies: - top_sz = self.supernumber_frequencies.most_common(3) - print(f"\n🎲 TOP 3 SUPERZAHLEN:") - for sz, count in top_sz: - percentage = (count / len(self.df)) * 100 - print(f" Superzahl {sz}: {count}x ({percentage:.1f}%)") - - # Empfohlene Muster - top_patterns = self.pattern_frequencies.most_common(3) - print(f"\n🎨 TOP 3 LOTTO-MUSTER:") - for pattern, count in top_patterns: - percentage = (count / len(self.drawn_combinations)) * 100 - print(f" {pattern}: {count}x ({percentage:.1f}%)") - - def _export_lotto_tips(self, tips): - """Exportiert Lotto-Tipps.""" - timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") - output_file = f"ultimate_lotto_6aus49_tipps_{timestamp}.csv" - - # Export-Daten erweitern - export_data = [] - for tip in tips: - tip_data = tip.copy() - tip_data['trend_scores'] = [self.trend_predictions[n]['prediction_score'] - for n in tip['zahlen']] - tip_data['avg_trend_score'] = np.mean(tip_data['trend_scores']) - export_data.append(tip_data) - - tips_df = pd.DataFrame(export_data) - tips_df.to_csv(output_file, sep=';', index=False) - - print(f"\n💾 LOTTO-EXPORT:") - print("=" * 25) - print(f"✅ Lotto-Tipps gespeichert: {output_file}") - print(f"🎲 Format: 6 Zahlen aus 49 + Superzahl") - print(f"🚀 Ultimate Multi-Trend-Optimierung") - - def _print_lotto_analysis_summary(self): - """Druckt Lotto-Analyse-Zusammenfassung.""" - print(f"\n📈 LOTTO 6AUS49 ANALYSE-ZUSAMMENFASSUNG:") - print("=" * 55) - - # Top Zahlen - print(f"\n🔢 HÄUFIGSTE LOTTO-ZAHLEN:") - for i, (number, count) in enumerate(self.number_frequencies.most_common(10)): - percentage = (count / (len(self.df) * 6)) * 100 - print(f"{i+1:2}. Zahl {number:2}: {count:3}x ({percentage:.2f}%)") - - # Top Muster - print(f"\n🎨 ERFOLGREICHSTE LOTTO-MUSTER:") - for pattern, count in self.pattern_frequencies.most_common(5): - percentage = (count / len(self.drawn_combinations)) * 100 - print(f" {pattern}: {count}x ({percentage:.1f}%)") - - # Hilfsfunktionen (gleich wie Eurojackpot) - def _calculate_trend_score(self, sequence): - if len(sequence) < 2: - return 0 - x = np.arange(len(sequence)) - y = np.array(sequence) - weights = np.exp(x / len(x)) - try: - coeffs = np.polyfit(x, y, 1, w=weights) - return coeffs[0] - except: - return 0 - - def _calculate_recency_score(self, sequence): - try: - last_hit_index = len(sequence) - 1 - sequence[::-1].index(1) - recency = 1 - (len(sequence) - 1 - last_hit_index) / len(sequence) - return recency - except ValueError: - return 0 - - def _get_momentum_status(self, score): - if score > 0.4: - return "🔥 SEHR HEISS" - elif score > 0.25: - return "🌡️ HEISS" - elif score > 0.15: - return "😐 WARM" - elif score > 0.08: - return "🧊 KÜHL" - else: - return "❄️ EISKALT" - - def _get_prediction_recommendation(self, score): - if score > 0.3: - return "SEHR EMPFOHLEN" - elif score > 0.2: - return "EMPFOHLEN" - elif score > 0.12: - return "NEUTRAL" - else: - return "VERMEIDEN" - - def _get_confidence_level(self, score): - if score > 0.3: - return "HOCH" - elif score > 0.2: - return "MITTEL" - else: - return "NIEDRIG" - - def _find_pattern_cycles(self, sequence, cycle_length): - cycle_patterns = defaultdict(list) - for i in range(len(sequence) - cycle_length): - pattern = ''.join(sequence[i:i+cycle_length]) - cycle_patterns[pattern].append(i) - return {pattern: positions for pattern, positions in cycle_patterns.items() - if len(positions) >= 2} - -# Zusätzliche Lotto-spezifische Analysefunktionen - -def analyze_lotto_tip_quality(generator, tip_numbers): - """Analysiert Qualität eines Lotto 6aus49 Tipps.""" - quality_score = 0 - analysis = {} - - # Momentum-Analyse - hot_count = sum(1 for n in tip_numbers if n in generator.hot_numbers) - analysis['hot_numbers'] = hot_count - quality_score += hot_count * 0.15 # Angepasst für 6 Zahlen - - # Trend-Analyse - trend_scores = [generator.trend_predictions[n]['prediction_score'] for n in tip_numbers] - avg_trend = np.mean(trend_scores) - analysis['avg_trend_score'] = avg_trend - quality_score += avg_trend * 0.35 - - # Positions-Analyse (6 Positionen) - position_quality = 0 - for i, num in enumerate(sorted(tip_numbers)): - pos_freq = generator.position_frequencies[f'pos_{i+1}'][num] - if pos_freq > 0: - position_quality += pos_freq - analysis['position_quality'] = position_quality - quality_score += (position_quality / len(generator.df)) * 0.25 - - # Muster-Analyse - pattern = generator._get_lotto_pattern(sorted(tip_numbers)) - pattern_freq = generator.pattern_frequencies[pattern] - pattern_score = pattern_freq / len(generator.df) - analysis['pattern'] = pattern - analysis['pattern_score'] = pattern_score - quality_score += pattern_score * 0.25 - - analysis['total_quality_score'] = quality_score - analysis['quality_rating'] = get_lotto_quality_rating(quality_score) - - return analysis - -def get_lotto_quality_rating(score): - """Lotto-spezifische Quality-Ratings.""" - if score > 0.7: - return "🏆 LOTTO PREMIUM" - elif score > 0.5: - return "🥇 SEHR GUT" - elif score > 0.35: - return "🥈 GUT" - elif score > 0.2: - return "🥉 DURCHSCHNITT" - else: - return "⚠️ SCHWACH" - -def predict_lotto_jackpot_probability(generator, tip_numbers): - """Schätzt Lotto-Jackpot-Wahrscheinlichkeit.""" - base_probability = 1 / 13983816 # Lotto 6aus49 Grundwahrscheinlichkeit - - trend_multiplier = 1.0 - for number in tip_numbers: - momentum_score = generator.momentum_scores[number]['momentum_score'] - trend_score = generator.trend_predictions[number]['prediction_score'] - - # Lotto-angepasste Gewichtung - number_multiplier = 1 + (momentum_score * 0.08) + (trend_score * 0.12) - trend_multiplier *= number_multiplier - - # Pattern-Bonus für Lotto - pattern = generator._get_lotto_pattern(sorted(tip_numbers)) - pattern_frequency = generator.pattern_frequencies[pattern] / len(generator.df) - pattern_multiplier = 1 + (pattern_frequency * 0.15) - - estimated_probability = base_probability * trend_multiplier * pattern_multiplier - - return { - 'base_probability': base_probability, - 'trend_multiplier': trend_multiplier, - 'pattern_multiplier': pattern_multiplier, - 'estimated_probability': estimated_probability, - 'improvement_factor': (estimated_probability / base_probability) - } - -def create_lotto_sample_data(): - """Erstellt Beispiel-Daten für Lotto 6aus49 (für Tests).""" - print("📋 BEISPIEL LOTTO-DATEN ERSTELLEN") - print("=" * 35) - - sample_data = [] - base_date = datetime.datetime(2020, 1, 4) # Erster Samstag 2020 - - for i in range(100): # 100 Beispiel-Ziehungen - # Datum (jeden Samstag) - date = base_date + datetime.timedelta(weeks=i) - - # 6 zufällige Zahlen aus 1-49 - numbers = sorted(random.sample(range(1, 50), 6)) - - # Superzahl 0-9 - superzahl = random.randint(0, 9) - - sample_data.append({ - 'Datum': date.strftime('%d.%m.%Y'), - 'Z1': numbers[0], 'Z2': numbers[1], 'Z3': numbers[2], - 'Z4': numbers[3], 'Z5': numbers[4], 'Z6': numbers[5], - 'SZ': superzahl - }) - - # CSV speichern - df_sample = pd.DataFrame(sample_data) - sample_file = "lotto_sample_data.csv" - df_sample.to_csv(sample_file, sep=';', index=False) - - print(f"✅ Beispiel-Daten erstellt: {sample_file}") - print(f"📊 {len(sample_data)} Lotto-Ziehungen") - print(f"💡 Verwenden Sie diese Datei zum Testen des Generators!") - - return sample_file - -def main(): - """Hauptfunktion für Ultimate Lotto 6aus49 Generator.""" - print("🎲 ULTIMATE LOTTO 6AUS49 GENERATOR") - print("🚀 Mit Multi-Ziehungs-Trend-Analyse") - print("=" * 50) - - # Datei-Pfad abfragen - print("📁 LOTTO-DATEN LADEN:") - print("Geben Sie den Pfad zur Lotto 6aus49 CSV-Datei ein.") - print("(Oder drücken Sie Enter für Beispiel-Daten)") - - data_path = input("CSV-Pfad: ").strip() - - # Beispiel-Daten erstellen falls kein Pfad angegeben - if not data_path: - print("\n🔧 Erstelle Beispiel-Daten für Demonstration...") - data_path = create_lotto_sample_data() - print(f"📂 Verwende Beispiel-Datei: {data_path}") - - try: - # Generator initialisieren - generator = UltimateLotto6aus49Generator(data_path) - - if not hasattr(generator, 'df') or generator.df is None: - print("❌ Generator konnte nicht initialisiert werden!") - return - - # Ultimate Tipps generieren - tips = generator.generate_lotto_ultimate_tips(10) - - if tips: - print(f"\n🏆 ULTIMATE LOTTO 6AUS49 OPTIMIERUNG ABGESCHLOSSEN!") - print("=" * 55) - print(f"🎲 10 Ultimate Lotto-Tipps generiert") - print(f"📈 Maximale Trefferwahrscheinlichkeit durch:") - print(f" • Multi-Ziehungs-Momentum-Analyse") - print(f" • Sequenzielle Abhängigkeiten") - print(f" • Zyklische Muster-Erkennung") - print(f" • Lotto-spezifische Optimierungen") - print(f"🍀 Viel Erfolg bei der nächsten Lotto-Ziehung!") - - # Erweiterte Analyse (optional) - print(f"\n📊 ERWEITERTE LOTTO-ANALYSE:") - print("=" * 35) - - # Beispiel-Analyse für ersten Tipp - if len(tips) > 0: - sample_tip = tips[0]['zahlen'] - quality_analysis = analyze_lotto_tip_quality(generator, sample_tip) - probability_analysis = predict_lotto_jackpot_probability(generator, sample_tip) - - print(f"\n🔍 BEISPIEL-ANALYSE für Lotto-Tipp 1:") - tip_str = '-'.join([f"{n:2}" for n in sample_tip]) - print(f" 🎲 Zahlen: {tip_str} + SZ: {tips[0]['superzahl']}") - print(f" 🏆 Quality: {quality_analysis['quality_rating']}") - print(f" 📈 Score: {quality_analysis['total_quality_score']:.3f}") - print(f" 🔥 Heiße Zahlen: {quality_analysis['hot_numbers']}/6") - print(f" 🎯 Trend-Score: {quality_analysis['avg_trend_score']:.3f}") - print(f" 🎨 Muster: {quality_analysis['pattern']}") - print(f" 📊 Verbesserungs-Faktor: {probability_analysis['improvement_factor']:.2f}x") - - # Strategische Empfehlungen - print(f"\n💡 STRATEGISCHE LOTTO-EMPFEHLUNGEN:") - print("=" * 40) - - # Top Trend-Zahlen - top_trend = sorted(generator.trend_predictions.items(), - key=lambda x: x[1]['prediction_score'], reverse=True)[:8] - print(f"🎯 TOP 8 TREND-ZAHLEN für kommende Ziehungen:") - for i, (number, data) in enumerate(top_trend): - status = generator.momentum_scores[number]['status'] - print(f" {i+1}. Zahl {number:2}: {data['recommendation']} {status}") - - # Momentum-Verteilung - very_hot_lotto = [n for n in generator.hot_numbers - if generator.momentum_scores[n]['momentum_score'] > 0.3] - if very_hot_lotto: - print(f"\n🔥 MOMENTUM-ALERT für Lotto:") - print(f" Sehr heiße Zahlen: {very_hot_lotto}") - print(f" → Verwenden Sie 2-3 dieser Zahlen in Ihren Tipps!") - - # Superzahl-Empfehlung - if generator.supernumber_frequencies: - top_superzahl = generator.supernumber_frequencies.most_common(3) - print(f"\n🎲 TOP SUPERZAHL-EMPFEHLUNGEN:") - for sz, count in top_superzahl: - percentage = (count / len(generator.df)) * 100 - print(f" Superzahl {sz}: {count}x ({percentage:.1f}%)") - - else: - print("❌ Keine Tipps generiert!") - - except Exception as e: - print(f"❌ Fehler: {e}") - print("💡 Stellen Sie sicher, dass die CSV-Datei korrekt formatiert ist:") - print(" Spalten: Datum, Z1, Z2, Z3, Z4, Z5, Z6, SZ") - -if __name__ == "__main__": - # Reproduzierbarer Zufallsseed - random.seed(42) - np.random.seed(42) - - # Ultimate Lotto Generator starten - main() \ No newline at end of file