// Pegos Market Dashboard JavaScript class PegosDashboard { constructor() { this.apiBaseUrl = 'https://caner7-pegos-data.hf.space'; this.coinGeckoApiUrl = 'https://api.coingecko.com/api/v3'; this.data = { bitcoin: null, predictions: [], signals: [], history: [] }; this.refreshInterval = null; this.isConnected = false; this.chart = null; // Pagination state this.currentPage = 1; this.itemsPerPage = 20; this.allPredictions = []; this.init(); } async init() { console.log('Pegos Dashboard başlatılıyor...'); this.setupEventListeners(); console.log('Event listenerlar kuruldu'); await this.loadInitialData(); console.log('İlk veriler yüklendi'); this.startAutoRefresh(); console.log('Otomatik yenileme başlatıldı'); console.log('Dashboard başarıyla başlatıldı!'); } setupEventListeners() { // Calculator input const btcAmountInput = document.getElementById('btcAmount'); if (btcAmountInput) { btcAmountInput.addEventListener('input', () => { this.calculateProfit(); }); } } async checkConnection() { try { const response = await this.apiCall('/health'); this.isConnected = true; this.updateConnectionStatus('API Bağlı', 'connected'); } catch (error) { this.isConnected = false; this.updateConnectionStatus('API Bağlantı Hatası', 'error'); console.error('API bağlantı hatası:', error); } } updateConnectionStatus(message, status) { const statusContainer = document.getElementById('apiStatus'); if (statusContainer) { statusContainer.textContent = message; statusContainer.className = `api-status-container ${status}`; } } async apiCall(endpoint) { try { console.log(`API çağrısı yapılıyor: ${this.apiBaseUrl}${endpoint}`); const response = await fetch(`${this.apiBaseUrl}${endpoint}`, { method: 'GET', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', }, mode: 'cors', credentials: 'omit' }); console.log(`API yanıtı: ${response.status} ${response.statusText}`); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); console.log(`API verisi alındı:`, data); return data; } catch (error) { console.error(`API call failed for ${endpoint}:`, error); console.log(`Mock veri kullanılıyor...`); // Return mock data if API fails return this.getMockData(endpoint); } } async getBitcoinPrice() { try { console.log('Bitcoin fiyatı alınıyor...'); const response = await fetch(`${this.coinGeckoApiUrl}/simple/price?ids=bitcoin&vs_currencies=usd&include_24hr_change=true`, { method: 'GET', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', }, mode: 'cors', credentials: 'omit' }); console.log(`Bitcoin API yanıtı: ${response.status} ${response.statusText}`); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); console.log('Bitcoin verisi alındı:', data); // Gerçek API formatına göre düzenle return { price: data.bitcoin.usd, change24h: data.bitcoin.usd_24h_change, timestamp: new Date().toISOString() }; } catch (error) { console.error('Bitcoin price fetch failed:', error); console.log('Mock Bitcoin verisi kullanılıyor...'); // Return mock data if API fails return this.getMockBitcoinData(); } } getMockData(endpoint) { switch(endpoint) { case '/health': return { status: 'healthy', timestamp: new Date().toISOString() }; case '/latest': return this.generateMockLatestData(); case '/history': return this.generateMockHistoryData(); case '/predict': return this.generateMockPredictionData(); case '/signal': return this.generateMockSignalData(); default: return {}; } } getMockBitcoinData() { const basePrice = 45000 + Math.random() * 10000; const change = (Math.random() - 0.5) * 2000; return { price: Math.round(basePrice), change24h: Math.round((change / basePrice) * 100 * 100) / 100, timestamp: new Date().toISOString() }; } generateMockLatestData() { const basePrice = 45000 + Math.random() * 10000; const change = (Math.random() - 0.5) * 2000; return { price: basePrice, change: change, changePercent: (change / basePrice) * 100, volume: Math.random() * 1000000, timestamp: new Date().toISOString(), prediction: { nextHour: basePrice + (Math.random() - 0.5) * 1000, nextDay: basePrice + (Math.random() - 0.5) * 5000, confidence: 0.7 + Math.random() * 0.3 } }; } generateMockHistoryData() { const data = []; const now = new Date(); for (let i = 0; i < 30; i++) { const date = new Date(now.getTime() - i * 24 * 60 * 60 * 1000); const basePrice = 40000 + Math.random() * 20000; const high = basePrice + Math.random() * 2000; const low = basePrice - Math.random() * 2000; const close = low + Math.random() * (high - low); data.push({ date: date.toISOString().split('T')[0], open: basePrice, high: high, low: low, close: close, volume: Math.random() * 1000000, prediction: close + (Math.random() - 0.5) * 1000, actual: close + (Math.random() - 0.5) * 500 }); } return data.reverse(); } generateMockPredictionData() { const predictions = []; const now = new Date(); const basePrice = 45000; for (let i = 0; i < 20; i++) { const date = new Date(now.getTime() - i * 24 * 60 * 60 * 1000); const priceVariation = (Math.random() - 0.5) * 10000; const prediction = basePrice + priceVariation; const actual = prediction + (Math.random() - 0.5) * 2000; const confidence = 0.6 + Math.random() * 0.4; const direction = prediction > basePrice ? 'up' : 'down'; predictions.push({ date: date.toISOString().split('T')[0], prediction: Math.round(prediction), actual: Math.round(actual), confidence: Math.round(confidence * 100) / 100, direction: direction, accuracy: Math.abs(prediction - actual) / actual < 0.05 ? 'high' : 'low' }); } return predictions.reverse(); } generateMockSignalData() { return { signal: Math.random() > 0.5 ? 'bullish' : 'bearish', strength: 0.5 + Math.random() * 0.5, confidence: 0.6 + Math.random() * 0.4, timestamp: new Date().toISOString(), description: Math.random() > 0.5 ? 'Güçlü yükseliş sinyali tespit edildi' : 'Düşüş sinyali gözlemleniyor' }; } processPredictData(predictData) { // /predict endpoint'inden gelen GERÇEK MODEL TAHMİNLERİNİ kullan const predictions = []; let items = predictData.items || []; // Görüntülenme sayısına göre sırala (yüksekten düşüğe) items = items.sort((a, b) => (b.see_count || 0) - (a.see_count || 0)); console.log(`📊 Model tahminleri işleniyor: ${items.length} adet (görüntülenme sıralı)`); // Ağırlıklı ortalama için toplam değerler let totalWeightedChange = 0; let totalWeight = 0; items.forEach((item, index) => { const date = item.prediction_day || new Date().toISOString().split('T')[0]; // /predict endpoint'inden gelen GERÇEK MODEL DEĞERLERİNİ kullan const predLabel = item.pred_label; // 1=Yükseliş, 0=Düşüş const predProba = item.pred_proba || 0.5; // Model güveni (0-1) const predDiff = item.pred_diff || 0; // Tahmin edilen fark ($) const aiPrediction = item['AI_Model_Tahmini (%)'] || 0; // Tahmin fiyatı const aiDirection = item['AI_Model_Yonu'] || ''; // Yön metni const confidence = item['Güven (%)'] || (predProba * 100); // Güven yüzdesi // Engagement = ağırlık faktörü const engagement = item.like + item.retweet + item.comment; const totalEngagement = engagement + item.see_count; const weight = Math.max(1, totalEngagement); // En az 1 ağırlık // Tahmin edilen değişim yüzdesi (pred_diff bazlı) const currentPrice = this.data.bitcoin?.price || 108000; const predictedChangePercent = (predDiff / currentPrice) * 100; // Yön belirleme (API'den gelen label kullan) const direction = predLabel === 1 ? 'up' : predLabel === 0 ? 'down' : 'neutral'; // Ağırlıklı ortalama için ekle (model güveni * ağırlık) totalWeightedChange += predictedChangePercent * weight * predProba; totalWeight += weight * predProba; predictions.push({ date: date, tweet: item.tweet, engagement: engagement, prediction: currentPrice + predDiff, // Gerçek model tahmini actual: currentPrice, confidence: predProba, // Model güveni (0-1) confidencePercent: confidence, // Güven yüzdesi direction: direction, accuracy: predProba > 0.8 ? 'Yüksek' : predProba > 0.6 ? 'Orta' : 'Düşük', time: date, seeCount: item.see_count, keyword: 'bitcoin', // /predict sadece Bitcoin için // API'den gelen değerler predLabel: predLabel, predProba: predProba, predDiff: predDiff, aiPrediction: aiPrediction, aiDirection: aiDirection, // Hesaplanan değerler predictedChangePercent: predictedChangePercent, weight: weight, sentimentScore: predLabel === 1 ? 1 : predLabel === 0 ? -1 : 0 }); }); // Ağırlıklı ortalama artış yüzdesi hesapla const weightedAvgChangePercent = totalWeight > 0 ? totalWeightedChange / totalWeight : 0; console.log(`📊 Ağırlıklı Ortalama Tahmin Artışı: ${weightedAvgChangePercent.toFixed(4)}%`); // Güncel Bitcoin fiyatı const currentPrice = this.data.bitcoin?.price || 108000; if (!this.data.bitcoin || !this.data.bitcoin.price) { console.warn('⚠️ UYARI: Bitcoin fiyatı bulunamadı! Fallback değer kullanılıyor: $108,000'); console.warn('⚠️ Bitcoin data:', this.data.bitcoin); } // Ağırlıklı ortalama değerini sakla this.weightedAvgChangePercent = weightedAvgChangePercent; this.predictedPrice = currentPrice * (1 + weightedAvgChangePercent / 100); console.log(`💰 Güncel Fiyat: $${currentPrice.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`); console.log(`📈 Tahmin Edilen Fiyat: $${this.predictedPrice.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`); console.log(`📊 Beklenen Değişim: ${weightedAvgChangePercent > 0 ? '+' : ''}${weightedAvgChangePercent.toFixed(4)}%`); console.log(`✅ Toplam ${predictions.length} MODEL TAHMİNİ oluşturuldu (/predict endpoint)`); // Tahmin sayısını sakla (hesaplayıcıda kullanılacak) this.totalPredictionsCount = predictions.length; // Hesaplayıcı bilgisini güncelle const calculatorTweetCount = document.getElementById('calculatorTweetCount'); if (calculatorTweetCount) { calculatorTweetCount.textContent = predictions.length; } return predictions; // TÜM MODEL TAHMİNLERİNİ DÖNDÜR (200 adet) } processSignalData(signalData) { // YENİ API yapısını kullan console.log('🎯 Signal Data:', signalData); const upRate = signalData.up_rate || 0; const avgConf = signalData.avg_conf || 0; const aiPrediction = signalData['AI_Model_Tahmini (%)'] || 0; const aiDirection = signalData['AI_Model_Yonu'] || ''; const signalText = signalData.signal || 'Belirsiz'; const day = signalData.day || ''; const records = signalData.records || 0; let signal = 'neutral'; let strength = upRate; let confidence = avgConf; let description = ''; // Sinyal tipini belirle if (upRate > 0.6) { signal = 'bullish'; description = `${signalText} - ${records} tweet analiz edildi. AI Model ${aiDirection}. Güven: %${(avgConf * 100).toFixed(1)}`; } else if (upRate < 0.4) { signal = 'bearish'; description = `${signalText} - ${records} tweet analiz edildi. AI Model ${aiDirection}. Güven: %${(avgConf * 100).toFixed(1)}`; } else { signal = 'neutral'; description = `Nötr Piyasa - ${records} tweet analiz edildi. Kararsız sentiment.`; } return { signal: signal, strength: strength, confidence: confidence, timestamp: new Date().toISOString(), description: description, // Yeni alanlar aiPrediction: aiPrediction, aiDirection: aiDirection, signalText: signalText, upRate: upRate, avgConf: avgConf, day: day, records: records }; } processHistoryData(historyData) { // Gerçek API verilerini grafik formatına dönüştür - TÜM VERİLERİ GÖSTER const processedData = []; const bitcoinItems = historyData.items.filter(item => item.keyword === 'bitcoin'); console.log(`Tüm Bitcoin geçmiş verileri işleniyor: ${bitcoinItems.length} adet`); // Her tweet'i ayrı ayrı işle - şeffaflık için bitcoinItems.forEach((item, index) => { const date = new Date(item.time).toISOString().split('T')[0]; if (item['Açılış Fiyatı (USD)'] && item['Kapanış Fiyatı (USD)']) { const openPrice = item['Açılış Fiyatı (USD)']; const closePrice = item['Kapanış Fiyatı (USD)']; const diff = item['Fark (USD)'] || 0; processedData.push({ date: date, time: item.time, tweet: item.tweet, open: openPrice, close: closePrice, high: Math.max(openPrice, closePrice) + Math.abs(diff) * 0.5, low: Math.min(openPrice, closePrice) - Math.abs(diff) * 0.5, volume: item.see_count * 1000, prediction: closePrice * (1 + (Math.random() - 0.5) * 0.05), actual: closePrice, engagement: item.like + item.retweet + item.comment, keyword: item.keyword, target: item.target || 0 }); } }); console.log(`Toplam ${processedData.length} geçmiş veri işlendi`); return processedData.sort((a, b) => new Date(a.time) - new Date(b.time)); // TÜM VERİLERİ DÖNDÜR } async loadInitialData() { console.log('İlk veriler yükleniyor...'); try { // 1. ÖNCELİKLE Bitcoin fiyatını yükle (diğer hesaplamalar buna bağlı) await this.loadBitcoinData(); console.log('✅ Bitcoin verisi yüklendi, fiyat:', this.data.bitcoin?.price || 'N/A'); // 2. Predictions'ı yükle (Bitcoin fiyatını kullanır) await this.loadPredictions(); console.log('✅ Predictions yüklendi, sayı:', this.data.predictions?.length || 0); // 3. Signals'ı yükle await this.loadSignals(); console.log('✅ Signals yüklendi'); // 4. History'yi yükle await this.loadHistory(); console.log('✅ History yüklendi'); console.log('📊 Tüm veriler yüklendi, ekranlar güncelleniyor...'); console.log('🔍 Final Bitcoin Fiyatı:', this.data.bitcoin?.price || 'HATA!'); this.updateAllDisplays(); } catch (error) { console.error('❌ Veri yükleme hatası:', error); // Hata durumunda da mock verilerle çalışmaya devam et this.updateAllDisplays(); } } async loadBitcoinData() { console.log('Bitcoin verisi yükleniyor...'); try { const bitcoinData = await this.getBitcoinPrice(); this.data.bitcoin = bitcoinData; console.log('Bitcoin verisi yüklendi:', bitcoinData); this.updateBitcoinDisplay(bitcoinData); } catch (error) { console.error('Bitcoin veri yükleme hatası:', error); // Hata durumunda mock veri kullan const mockData = this.getMockBitcoinData(); this.data.bitcoin = mockData; this.updateBitcoinDisplay(mockData); } } async loadPredictions() { console.log('📊 Tahmin verileri yükleniyor (/predict endpoint)...'); try { const predictData = await this.apiCall('/predict'); console.log('✅ Predict verisi alındı:', predictData); // /predict endpoint'inden gelen gerçek model tahminlerini kullan if (predictData && predictData.items) { this.data.predictions = this.processPredictData(predictData); console.log(`✅ ${this.data.predictions.length} model tahmini işlendi`); } else { this.data.predictions = this.generateMockPredictionData(); } this.updatePredictionsTable(); // NOT: updateStats() çağrılmıyor - updateAllDisplays() içinde çağrılacak (signals yüklendikten sonra) } catch (error) { console.error('❌ Tahmin veri yükleme hatası:', error); // Hata durumunda mock veri kullan this.data.predictions = this.generateMockPredictionData(); this.updatePredictionsTable(); // NOT: updateStats() çağrılmıyor - updateAllDisplays() içinde çağrılacak } } async loadSignals() { console.log('Sinyal verileri yükleniyor...'); try { const signals = await this.apiCall('/signal'); console.log('Signal verisi alındı:', signals); // Gerçek API formatına göre sinyal verilerini işle if (signals && signals.up_rate !== undefined) { this.data.signals = this.processSignalData(signals); console.log('Sinyal verileri işlendi:', this.data.signals); } else { this.data.signals = this.generateMockSignalData(); } this.updateSignalDisplay(this.data.signals); } catch (error) { console.error('Sinyal veri yükleme hatası:', error); // Hata durumunda mock veri kullan this.data.signals = this.generateMockSignalData(); this.updateSignalDisplay(this.data.signals); } } async loadHistory() { console.log('Geçmiş veriler yükleniyor...'); try { const history = await this.apiCall('/history'); console.log('History verisi alındı:', history); // Gerçek API formatına göre geçmiş verilerini işle if (history && history.items) { this.data.history = this.processHistoryData(history); console.log('Geçmiş veriler işlendi:', this.data.history.length, 'adet'); } else { this.data.history = this.generateMockHistoryData(); } } catch (error) { console.error('Geçmiş veri yükleme hatası:', error); // Hata durumunda mock veri kullan this.data.history = this.generateMockHistoryData(); } } updateBitcoinDisplay(bitcoinData) { // Update current price const currentPriceElement = document.getElementById('currentPrice'); if (currentPriceElement) { currentPriceElement.innerHTML = `$${bitcoinData.price.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`; } // Update price change const priceChangeElement = document.getElementById('priceChange'); if (priceChangeElement) { const changeClass = bitcoinData.change24h >= 0 ? 'positive' : 'negative'; const changeSymbol = bitcoinData.change24h >= 0 ? '+' : ''; priceChangeElement.textContent = `${changeSymbol}${bitcoinData.change24h.toFixed(2)}%`; priceChangeElement.className = `card-change ${changeClass}`; } // Update last update time const lastUpdateElement = document.getElementById('lastUpdate'); if (lastUpdateElement) { const updateTime = new Date(bitcoinData.timestamp).toLocaleString('tr-TR'); lastUpdateElement.textContent = `Son Güncelleme: ${updateTime}`; } } updateCurrentAnalysis(bitcoinData) { // Update current price display const currentPriceDisplay = document.getElementById('currentPriceDisplay'); if (currentPriceDisplay) { currentPriceDisplay.textContent = `$${bitcoinData.price.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`; } // Update price change const currentPriceChange = document.getElementById('currentPriceChange'); if (currentPriceChange) { const changeClass = bitcoinData.change24h >= 0 ? 'positive' : 'negative'; const changeSymbol = bitcoinData.change24h >= 0 ? '+' : ''; currentPriceChange.textContent = `${changeSymbol}${bitcoinData.change24h.toFixed(2)}%`; currentPriceChange.className = `price-change ${changeClass}`; } // Update price change 24h const priceChange24h = document.getElementById('priceChange24h'); if (priceChange24h) { const changeAmount = bitcoinData.price * (bitcoinData.change24h / 100); const changeSymbol = bitcoinData.change24h >= 0 ? '+' : ''; priceChange24h.textContent = `${changeSymbol}$${changeAmount.toFixed(2)}`; } // Update timestamp const currentPriceTime = document.getElementById('currentPriceTime'); if (currentPriceTime) { const updateTime = new Date(bitcoinData.timestamp).toLocaleString('tr-TR'); currentPriceTime.textContent = updateTime; } const lastPriceUpdate = document.getElementById('lastPriceUpdate'); if (lastPriceUpdate) { const updateTime = new Date(bitcoinData.timestamp).toLocaleString('tr-TR'); lastPriceUpdate.textContent = updateTime; } // Update prediction if we have data if (this.data.predictions.length > 0) { this.updatePredictionDisplay(bitcoinData); } // Update analysis this.updateAnalysisText(bitcoinData); } updatePredictionDisplay(bitcoinData) { // Önce ağırlıklı ortalama tahmini kullan, yoksa API tahminini kullan const useWeightedPrediction = this.weightedAvgChangePercent !== undefined && this.predictedPrice !== undefined; if (!useWeightedPrediction && (!this.data.signals || !this.data.signals.aiPrediction)) { console.log('⚠️ updatePredictionDisplay: Tahmin verisi yok'); const predictionValue = document.getElementById('predictionValue'); if (predictionValue) predictionValue.textContent = 'Yükleniyor...'; const predictionDirection = document.getElementById('predictionDirection'); if (predictionDirection) predictionDirection.textContent = 'Veri Bekleniyor'; const modelConfidence = document.getElementById('modelConfidence'); if (modelConfidence) modelConfidence.textContent = 'Güven: -'; const expectedChange = document.getElementById('expectedChange'); if (expectedChange) expectedChange.textContent = '$0'; const predictionDate = document.getElementById('predictionDate'); if (predictionDate) predictionDate.textContent = '-'; return; } // Ağırlıklı ortalama varsa onu kullan let finalPrediction, finalDirection, finalConfidence, changePercent; if (useWeightedPrediction) { finalPrediction = this.predictedPrice; changePercent = this.weightedAvgChangePercent; finalDirection = changePercent > 0.1 ? '📈 Yükseliş Bekleniyor' : changePercent < -0.1 ? '📉 Düşüş Bekleniyor' : '➡️ Yatay Seyir'; finalConfidence = this.data.signals ? this.data.signals.avgConf : 0.7; console.log(`🔮 Ağırlıklı Ortalama Tahmin: $${finalPrediction.toFixed(2)} (${changePercent > 0 ? '+' : ''}${changePercent.toFixed(4)}%)`); } else { // API tahminini kullan const signals = this.data.signals; finalPrediction = signals.aiPrediction; finalDirection = signals.aiDirection; finalConfidence = signals.avgConf; changePercent = ((signals.aiPrediction - bitcoinData.price) / bitcoinData.price) * 100; console.log(`🔮 API AI Model Prediction: $${finalPrediction.toFixed(2)}`); } // Update prediction value const predictionValue = document.getElementById('predictionValue'); if (predictionValue) { predictionValue.textContent = `$${finalPrediction.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`; } // Update prediction direction const predictionDirection = document.getElementById('predictionDirection'); if (predictionDirection) { const isUp = finalDirection.includes('Yükseliş') || finalDirection.includes('Artış') || finalDirection.includes('📈'); const directionClass = isUp ? 'up' : 'down'; predictionDirection.textContent = finalDirection; predictionDirection.className = `prediction-direction ${directionClass}`; } // Update model confidence const modelConfidence = document.getElementById('modelConfidence'); if (modelConfidence) { modelConfidence.textContent = `Güven: ${(finalConfidence * 100).toFixed(1)}%`; } // Update expected change const expectedChange = document.getElementById('expectedChange'); if (expectedChange) { const changeAmount = finalPrediction - bitcoinData.price; const changeSymbol = changeAmount >= 0 ? '+' : ''; expectedChange.textContent = `${changeSymbol}$${changeAmount.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })} (${changeSymbol}${changePercent.toFixed(2)}%)`; } // Update prediction date const predictionDate = document.getElementById('predictionDate'); if (predictionDate) { const dateText = this.data.signals && this.data.signals.day ? this.data.signals.day : new Date().toLocaleDateString('tr-TR'); predictionDate.textContent = dateText; } } updateAnalysisText(bitcoinData) { const analysisText = document.getElementById('analysisText'); if (!analysisText) return; // Check if we have data (predictions veya signals) if ((!this.data.predictions || this.data.predictions.length === 0) && !this.data.signals) { analysisText.innerHTML = `
Model analizi yükleniyor... API'den tweet verileri bekleniyor.
`; const analyzedTweets = document.getElementById('analyzedTweets'); if (analyzedTweets) analyzedTweets.textContent = '0'; const avgConfidenceElement = document.getElementById('analysisAvgConfidence'); if (avgConfidenceElement) avgConfidenceElement.textContent = '0%'; const marketSentiment = document.getElementById('marketSentiment'); if (marketSentiment) { marketSentiment.textContent = 'Veri Yükleniyor'; marketSentiment.style.color = '#ffa500'; } console.log('⚠️ Predictions ve Signal verisi henüz yüklenmemiş'); return; } // Signal data'dan gelen gerçek bilgileri kullan (varsa) const records = this.data.signals && this.data.signals.records ? this.data.signals.records : this.data.predictions.length; const avgConfidence = this.data.signals && this.data.signals.avgConf ? this.data.signals.avgConf : this.data.predictions.reduce((sum, p) => sum + p.confidence, 0) / this.data.predictions.length; const upRate = this.data.signals && this.data.signals.upRate ? this.data.signals.upRate : 0.5; const bullishCount = this.data.predictions.filter(p => p.direction === 'up').length; const bearishCount = this.data.predictions.filter(p => p.direction === 'down').length; console.log(`📊 Analiz: ${records} tweet, Up Rate: ${(upRate * 100).toFixed(1)}%, Avg Confidence: ${(avgConfidence * 100).toFixed(1)}%`); let analysis = ''; let sentiment = ''; let sentimentColor = ''; // Signal data'dan gelen up_rate'e göre analiz if (upRate > 0.6) { sentiment = 'Pozitif'; sentimentColor = '#00ff88'; analysis = `Model analizi ${records} Bitcoin tweet'ini inceledi. Sonuçlar yükseliş yönünde pozitif sentiment gösteriyor (%${(upRate * 100).toFixed(1)} yükseliş oranı). Ortalama güven seviyesi %${(avgConfidence * 100).toFixed(1)} ile güçlü tahminler yapılıyor.`; } else if (upRate < 0.4) { sentiment = 'Negatif'; sentimentColor = '#ff4444'; analysis = `Model analizi ${records} Bitcoin tweet'ini inceledi. Sonuçlar düşüş yönünde negatif sentiment gösteriyor (%${(upRate * 100).toFixed(1)} yükseliş oranı). Ortalama güven seviyesi %${(avgConfidence * 100).toFixed(1)} ile dikkatli yaklaşım öneriliyor.`; } else { sentiment = 'Nötr'; sentimentColor = '#ffa500'; analysis = `Model analizi ${records} Bitcoin tweet'ini inceledi. Sonuçlar karışık sentiment gösteriyor (%${(upRate * 100).toFixed(1)} yükseliş oranı). Ortalama güven seviyesi %${(avgConfidence * 100).toFixed(1)} ile belirsizlik devam ediyor.`; } analysisText.innerHTML = `${analysis}
`; // Update metrics const analyzedTweets = document.getElementById('analyzedTweets'); if (analyzedTweets) { analyzedTweets.textContent = records; } const avgConfidenceElement = document.getElementById('analysisAvgConfidence'); if (avgConfidenceElement) { avgConfidenceElement.textContent = `${(avgConfidence * 100).toFixed(1)}%`; } const marketSentiment = document.getElementById('marketSentiment'); if (marketSentiment) { marketSentiment.textContent = sentiment; marketSentiment.style.color = sentimentColor; } } updatePredictionsTable() { const tbody = document.getElementById('predictionsTableBody'); if (!tbody || !this.data.predictions.length) return; // Tüm predictions'ı sakla this.allPredictions = this.data.predictions; // Pagination hesapla const totalItems = this.allPredictions.length; const totalPages = Math.ceil(totalItems / this.itemsPerPage); const startIndex = (this.currentPage - 1) * this.itemsPerPage; const endIndex = Math.min(startIndex + this.itemsPerPage, totalItems); // Sadece mevcut sayfa için verileri göster const pageData = this.allPredictions.slice(startIndex, endIndex); console.log(`📄 Pagination: Sayfa ${this.currentPage}/${totalPages}, Gösterilen ${startIndex + 1}-${endIndex}/${totalItems}`); tbody.innerHTML = pageData.map(pred => { // Her tweet için hesaplanan tahmin yüzdesini kullan const predictedChangePercent = pred.predictedChangePercent || 0; const accuracy = Math.abs(predictedChangePercent) < 1 ? 'Düşük' : Math.abs(predictedChangePercent) < 3 ? 'Orta' : 'Yüksek'; const accuracyClass = Math.abs(predictedChangePercent) < 1 ? 'text-warning' : Math.abs(predictedChangePercent) < 3 ? 'text-success' : 'text-danger'; // Sentiment skoru göster const sentimentEmoji = pred.sentimentScore > 0 ? '😊' : pred.sentimentScore < 0 ? '😟' : '😐'; const sentimentText = pred.sentimentScore > 0 ? 'Pozitif' : pred.sentimentScore < 0 ? 'Negatif' : 'Nötr'; return `${description}
Bitcoin miktarı girin (örn: 0.5)
Bitcoin fiyat verisi yükleniyor...
Model tahmini yükleniyor...
${btcAmount} BTC × Model Tahmini (${changePercent > 0 ? '+' : ''}${changePercent.toFixed(3)}% değişim)