Spaces:
Running
Running
Update script.js
Browse files12345678910111213141516171819202122234 unmodified lines282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702const API_URL = "https://caner7-pegos-data.hf.space/predictions";let dailyAnalysis = [];let rawPredictions = [];// Ana yükleme fonksiyonuasync function loadData() {try {const res = await fetch(API_URL);const data = await res.json();if (!data.items || data.items.length === 0) {showError("Veri bulunamadı");return;}// Ham tahminleri işlerawPredictions = data.items.map(d => ({timestamp: new Date(d.time),date: new Date(d.time).toISOString().split('T')[0],currentPrice: parseFloat(d["Kapanış Fiyatı (USD)"]),predictedPrice: d.predicted_price ? parseFloat(d.predicted_price) : null,predLabel: parseInt(d.pred_label),4 unmodified lines// Günlük analiz oluşturdailyAnalysis = createDailyAnalysis(rawPredictions);console.log('✅ Veri işleme başarılı:', {totalPredictions: rawPredictions.length,uniqueDays: dailyAnalysis.length,dateRange: dailyAnalysis.length > 0 ? {first: dailyAnalysis[0].date,last: dailyAnalysis[dailyAnalysis.length - 1].date} : null});updateDashboard();} catch (err) {console.error('❌ Veri yükleme hatası:', err);showError("Veri alınamadı: " + err.message);}}// Günlük analiz oluştur - Ağırlıklı ortalama ilefunction createDailyAnalysis(predictions) {const groupedByDate = {};// Tarihe göre gruplapredictions.forEach(pred => {if (!groupedByDate[pred.date]) {groupedByDate[pred.date] = [];}groupedByDate[pred.date].push(pred);});// Her gün için ağırlıklı analiz yapreturn Object.entries(groupedByDate).map(([date, preds]) => {// Ağırlıklı ortalama hesapla (güven seviyesine göre)const totalWeight = preds.reduce((sum, p) => sum + p.confidence, 0);const weightedPredictedPrice = preds.reduce((sum, p) =>sum + (p.predictedPrice * p.confidence), 0) / totalWeight;const weightedPriceDiff = preds.reduce((sum, p) =>sum + (p.priceDiff * p.confidence), 0) / totalWeight;// Ortalama güvenconst avgConfidence = totalWeight / preds.length;// Ağırlıklı tahmin yönü (güvene göre)const bullishWeight = preds.filter(p => p.predLabel === 1).reduce((sum, p) => sum + p.confidence, 0);const bearishWeight = preds.filter(p => p.predLabel === 0).reduce((sum, p) => sum + p.confidence, 0);const predictedDirection = bullishWeight > bearishWeight ? 1 : 0;const directionConfidence = Math.max(bullishWeight, bearishWeight) / totalWeight * 100;// Günün verilericonst firstPred = preds[0];const lastPred = preds[preds.length - 1];return {date: date,displayDate: new Date(date).toLocaleDateString('tr-TR', {day: '2-digit',month: 'long',year: 'numeric'}),currentPrice: lastPred.currentPrice,predictedPrice: weightedPredictedPrice,priceDiff: weightedPriceDiff,predictedDirection: predictedDirection,directionConfidence: directionConfidence,avgConfidence: avgConfidence,predictionCount: preds.length,bullishCount: preds.filter(p => p.predLabel === 1).length,bearishCount: preds.filter(p => p.predLabel === 0).length,highConfCount: preds.filter(p => p.confidence >= 80).length,medConfCount: preds.filter(p => p.confidence >= 60 && p.confidence < 80).length,lowConfCount: preds.filter(p => p.confidence < 60).length,timestamp: new Date(date)};}).sort((a, b) => a.timestamp - b.timestamp);}// Dashboard güncellefunction updateDashboard() {updateSummaryCards();updatePerformanceStats();updateChart();updatePredictionsTable();updateAnalysisSummary();updateLastUpdate();document.getElementById('chartStatus').style.display = 'none';}// Özet kartları güncellefunction updateSummaryCards() {if (dailyAnalysis.length === 0) return;const latest = dailyAnalysis[dailyAnalysis.length - 1];const previous = dailyAnalysis.length > 1 ? dailyAnalysis[dailyAnalysis.length - 2] : null;// Güncel fiyatdocument.getElementById('currentPrice').innerHTML =`$${latest.currentPrice.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}`;// Fiyat değişimiif (previous) {const change = ((latest.currentPrice - previous.currentPrice) / previous.currentPrice * 100);const changeElem = document.getElementById('priceChange');changeElem.textContent = `${change >= 0 ? '▲' : '▼'} ${Math.abs(change).toFixed(2)}% (Günlük)`;changeElem.className = 'card-change ' + (change >= 0 ? 'positive' : 'negative');}// Model güvenidocument.getElementById('modelAccuracy').textContent = `${latest.avgConfidence.toFixed(1)}%`;// Tahmin sinyaliconst signal = latest.predictedDirection === 1 ? '📈 YÜKSELİŞ' : '📉 DÜŞÜŞ';document.getElementById('predictionSignal').textContent = signal;document.getElementById('confidence').textContent = `Yön Güveni: ${latest.directionConfidence.toFixed(1)}%`;// Toplam analiz sayısıdocument.getElementById('totalPredictions').textContent = `${dailyAnalysis.length} Gün`;}// Performans istatistiklerifunction updatePerformanceStats() {if (dailyAnalysis.length === 0) return;const totalPredictions = rawPredictions.length;const totalDays = dailyAnalysis.length;// Tüm günlerdeki toplamlarconst totals = dailyAnalysis.reduce((acc, day) => ({highConf: acc.highConf + day.highConfCount,medConf: acc.medConf + day.medConfCount,lowConf: acc.lowConf + day.lowConfCount,bullish: acc.bullish + day.bullishCount,bearish: acc.bearish + day.bearishCount,confidence: acc.confidence + day.avgConfidence}), { highConf: 0, medConf: 0, lowConf: 0, bullish: 0, bearish: 0, confidence: 0 });const avgConfidence = totals.confidence / totalDays;const highConfRatio = (totals.highConf / totalPredictions) * 100;document.getElementById('correctPredictions').textContent = totals.highConf;document.getElementById('wrongPredictions').textContent = totals.lowConf;document.getElementById('bullishCount').textContent = totals.bullish;document.getElementById('bearishCount').textContent = totals.bearish;document.getElementById('avgConfidence').textContent = `${avgConfidence.toFixed(1)}%`;document.getElementById('successRate').textContent = `${highConfRatio.toFixed(1)}%`;}// Gelişmiş interaktif grafikfunction updateChart() {if (dailyAnalysis.length === 0) return;// Gerçek fiyat çizgisi - Daha büyük ve belirginconst realPriceLine = {x: dailyAnalysis.map(d => d.displayDate),y: dailyAnalysis.map(d => d.currentPrice),mode: 'lines+markers',name: '💰 Gerçek Bitcoin Fiyatı',line: {color: '#00ff88',width: 4,shape: 'spline'},marker: {size: 12,color: '#00ff88',line: {color: '#ffffff',width: 3},symbol: 'circle'},hovertemplate:'<b style="font-size: 16px; color: #00ff88;">💰 GERÇEKLEŞEn FİYAT</b><br><br>' +'<b>📅 Tarih:</b> %{x}<br>' +'<b>💵 Fiyat:</b> $%{y:,.2f}<br>' +'<b>📊 Değişim:</b> %{customdata[0]}<br>' +'<b>📈 Trend:</b> %{customdata[1]}<br>' +'<extra></extra>',customdata: dailyAnalysis.map((d, i) => {if (i === 0) return ['-', 'İlk Gün'];const prev = dailyAnalysis[i - 1];const change = ((d.currentPrice - prev.currentPrice) / prev.currentPrice * 100);const changeText = change >= 0? `<span style="color: #00ff88;">▲ +${change.toFixed(2)}%</span>`: `<span style="color: #ff4757;">▼ ${change.toFixed(2)}%</span>`;const trendText = change >= 0? '<span style="color: #00ff88;">🔥 Yükseliş</span>': '<span style="color: #ff4757;">📉 Düşüş</span>';return [changeText, trendText];})};// Model tahmin çizgisi - Detaylı bilgilerleconst predictedPriceLine = {x: dailyAnalysis.map(d => d.displayDate),y: dailyAnalysis.map(d => d.predictedPrice),mode: 'lines+markers',name: '🤖 AI Model Tahmini',line: {color: '#00d4ff',width: 4,dash: 'dot',shape: 'spline'},marker: {size: 15,color: dailyAnalysis.map(d => d.predictedDirection === 1 ? '#00ff88' : '#ff4757'),symbol: dailyAnalysis.map(d => d.predictedDirection === 1 ? 'triangle-up' : 'triangle-down'),line: {color: '#ffffff',width: 3}},hovertemplate:'<b style="font-size: 16px; color: #00d4ff;">🤖 AI MODEL TAHMİNİ</b><br><br>' +'<b>📅 Tarih:</b> %{x}<br>' +'<b>💵 Tahmin Fiyat:</b> $%{y:,.2f}<br>' +'<b>📊 Beklenen:</b> %{customdata[0]}<br>' +'<b>🎯 Yön Tahmini:</b> %{customdata[1]}<br>' +'<b>⭐ Model Güveni:</b> %{customdata[2]}<br>' +'<b>🎲 Yön Güveni:</b> %{customdata[3]}<br>' +'<b>📝 Toplam Analiz:</b> %{customdata[4]} tahmin<br>' +'<extra></extra>',customdata: dailyAnalysis.map(d => {const diffText = d.priceDiff >= 0? `<span style="color: #00ff88;">▲ +$${d.priceDiff.toFixed(2)}</span>`: `<span style="color: #ff4757;">▼ -$${Math.abs(d.priceDiff).toFixed(2)}</span>`;const directionText = d.predictedDirection === 1? '<span style="color: #00ff88; font-size: 14px;">📈 YÜKSELİŞ</span>': '<span style="color: #ff4757; font-size: 14px;">📉 DÜŞÜŞ</span>';const confClass = d.avgConfidence >= 80 ? '#00ff88' : d.avgConfidence >= 60 ? '#ffa502' : '#ff4757';const confText = `<span style="color: ${confClass};">%${d.avgConfidence.toFixed(1)}</span>`;const dirConfClass = d.directionConfidence >= 80 ? '#00ff88' : d.directionConfidence >= 60 ? '#ffa502' : '#ff4757';const dirConfText = `<span style="color: ${dirConfClass};">%${d.directionConfidence.toFixed(1)}</span>`;return [diffText, directionText, confText, dirConfText, d.predictionCount];})};// Fiyat farkı barları - Daha görünürconst priceDiffArea = {x: dailyAnalysis.map(d => d.displayDate),y: dailyAnalysis.map(d => d.priceDiff),type: 'bar',name: '📊 Beklenen Değişim',marker: {color: dailyAnalysis.map(d => d.priceDiff >= 0 ? 'rgba(0, 255, 136, 0.4)' : 'rgba(255, 71, 87, 0.4)'),line: {color: dailyAnalysis.map(d => d.priceDiff >= 0 ? '#00ff88' : '#ff4757'),width: 2}},yaxis: 'y2',hovertemplate:'<b style="font-size: 16px; color: #ffa502;">📊 BEKLENEN DEĞİŞİM</b><br><br>' +'<b>📅 Tarih:</b> %{x}<br>' +'<b>💰 Değişim:</b> %{customdata[0]}<br>' +'<b>📈 Yüzde:</b> %{customdata[1]}<br>' +'<b>🎯 Anlamı:</b> %{customdata[2]}<br>' +'<extra></extra>',customdata: dailyAnalysis.map(d => {const diffText = d.priceDiff >= 0? `<span style="color: #00ff88;">▲ +$${d.priceDiff.toFixed(2)}</span>`: `<span style="color: #ff4757;">▼ $${d.priceDiff.toFixed(2)}</span>`;const percentChange = (d.priceDiff / d.currentPrice * 100);const percentText = percentChange >= 0? `<span style="color: #00ff88;">+${percentChange.toFixed(2)}%</span>`: `<span style="color: #ff4757;">${percentChange.toFixed(2)}%</span>`;const meaningText = Math.abs(percentChange) > 2? '<span style="color: #ff4757;">⚠️ Yüksek Volatilite</span>': Math.abs(percentChange) > 1? '<span style="color: #ffa502;">📊 Orta Hareket</span>': '<span style="color: #00ff88;">✅ Düşük Volatilite</span>';return [diffText, percentText, meaningText];})};const layout = {title: {text: '📊 Bitcoin Fiyat Analizi ve AI Model Tahminleri',font: { color: '#00d4ff', size: 24, weight: 700 },x: 0.5,y: 0.98},xaxis: {title: {text: '📅 Tarih',font: { size: 15, weight: 600 }},gridcolor: '#2d3548',color: '#b8c5d6',tickangle: -45,tickfont: { size: 12 },showgrid: true,gridwidth: 1},yaxis: {title: {text: '💵 Fiyat (USD)',font: { size: 15, weight: 600 }},gridcolor: '#2d3548',color: '#b8c5d6',rangemode: 'tozero',tickfont: { size: 12 },showgrid: true,gridwidth: 1,zeroline: false},yaxis2: {title: {text: '📊 Beklenen Değişim ($)',font: { size: 14, weight: 600 }},overlaying: 'y',side: 'right',gridcolor: 'rgba(45, 53, 72, 0.3)',color: '#b8c5d6',showgrid: false,tickfont: { size: 11 },zeroline: true,zerolinecolor: '#ffa502',zerolinewidth: 2},plot_bgcolor: '#1e2642',paper_bgcolor: '#1a1f3a',font: {color: '#ffffff',family: 'Inter, sans-serif',size: 13},hovermode: 'closest',hoverlabel: {bgcolor: 'rgba(30, 38, 66, 0.95)',bordercolor: '#00d4ff',font: {family: 'Inter, sans-serif',size: 14,color: '#ffffff'},align: 'left',namelength: -1},height: window.innerWidth < 768 ? 500 : window.innerWidth < 1200 ? 600 : 700,legend: {orientation: 'h',x: 0.5,xanchor: 'center',y: -0.22,bgcolor: 'rgba(30, 38, 66, 0.95)',bordercolor: '#00d4ff',borderwidth: 2,font: {size: 14,weight: 600}},margin: { t: 70, b: 100, l: 70, r: 70 },showlegend: true,dragmode: 'zoom',selectdirection: 'h'};const config = {responsive: true,displayModeBar: true,displaylogo: false,modeBarButtonsToRemove: ['pan2d', 'lasso2d', 'select2d'],toImageButtonOptions: {format: 'png',filename: 'pegos_bitcoin_analysis',height: 800,width: 1400,scale: 2},modeBarButtons: [['zoom2d', 'zoomIn2d', 'zoomOut2d', 'autoScale2d', 'resetScale2d'],['toImage']]};Plotly.newPlot('chart', [realPriceLine, predictedPriceLine, priceDiffArea], layout, config);}// Tahmin tablosufunction updatePredictionsTable() {const tbody = document.getElementById('predictionsTableBody');tbody.innerHTML = '';if (dailyAnalysis.length === 0) return;// Son 30 günü göster (varsa)const recentDays = dailyAnalysis.slice(-30).reverse();recentDays.forEach((day, idx) => {const prevDay = idx < recentDays.length - 1 ? recentDays[idx + 1] : null;const actualChange = prevDay ? ((day.currentPrice - prevDay.currentPrice) / prevDay.currentPrice * 100) : null;const priceDiffPercent = (day.priceDiff / day.currentPrice) * 100;// Tahmin doğruluğu kontrolület accuracy = '-';if (actualChange !== null) {const predictedUp = day.predictedDirection === 1;const actualUp = actualChange > 0;accuracy = predictedUp === actualUp ? '✅ Doğru' : '❌ Yanlış';}const row = document.createElement('tr');row.innerHTML = `<td><strong>${day.displayDate}</strong></td><td>$${day.currentPrice.toLocaleString('en-US', {minimumFractionDigits: 2})}</td><td>$${day.predictedPrice.toLocaleString('en-US', {minimumFractionDigits: 2})}</td><td class="${day.priceDiff >= 0 ? 'prediction-up' : 'prediction-down'}">${day.priceDiff >= 0 ? '▲' : '▼'} $${Math.abs(day.priceDiff).toFixed(2)}(${priceDiffPercent >= 0 ? '+' : ''}${priceDiffPercent.toFixed(2)}%)</td><td class="${day.predictedDirection === 1 ? 'prediction-up' : 'prediction-down'}"><strong>${day.predictedDirection === 1 ? '📈 Yükseliş' : '📉 Düşüş'}</strong></td><td><span class="confidence-badge ${getConfidenceClass(day.avgConfidence)}">${day.avgConfidence.toFixed(1)}%</span></td><td><span class="confidence-badge ${getConfidenceClass(day.directionConfidence)}">${day.directionConfidence.toFixed(1)}%</span></td><td>${day.predictionCount} tahmin</td><td class="${accuracy.includes('Doğru') ? 'result-success' : accuracy.includes('Yanlış') ? 'result-fail' : ''}">${accuracy}</td>`;tbody.appendChild(row);});}// Güven seviyesi sınıfıfunction getConfidenceClass(conf) {if (conf >= 80) return 'conf-high';if (conf >= 60) return 'conf-medium';return 'conf-low';}// Analiz özetifunction updateAnalysisSummary() {if (dailyAnalysis.length === 0) return;const latest = dailyAnalysis[dailyAnalysis.length - 1];const avgConf = dailyAnalysis.reduce((sum, d) => sum + d.avgConfidence, 0) / dailyAnalysis.length;// Son 7 günün analiziconst recent7Days = dailyAnalysis.slice(-7);const bullishDays = recent7Days.filter(d => d.predictedDirection === 1).length;// Tahmin doğruluğu hesaplalet correctPredictions = 0;let totalCheckable = 0;for (let i = 1; i < dailyAnalysis.length; i++) {const today = dailyAnalysis[i];const yesterday = dailyAnalysis[i - 1];const actualUp = today.currentPrice > yesterday.currentPrice;const predictedUp = today.predictedDirection === 1;if (actualUp === predictedUp) correctPredictions++;totalCheckable++;}const accuracy = totalCheckable > 0 ? (correctPredictions / totalCheckable * 100) : 0;// Model performansılet perfText = '';if (accuracy >= 70) {perfText = `Model <strong>%${accuracy.toFixed(1)}</strong> doğruluk oranıyla <span style="color: var(--accent-success)">mükemmel performans</span> gösteriyor. Ortalama güven: <strong>${avgConf.toFixed(1)}%</strong>`;} else if (accuracy >= 55) {perfText = `Model <strong>%${accuracy.toFixed(1)}</strong> doğruluk oranıyla <span style="color: var(--accent-primary)">iyi performans</span> sergiliyor. Ortalama güven: <strong>${avgConf.toFixed(1)}%</strong>`;} else if (totalCheckable > 0) {perfText = `Model <strong>%${accuracy.toFixed(1)}</strong> doğruluk gösteriyor. <span style="color: var(--accent-warning)">Daha fazla veri gerekli</span>. Ortalama güven: <strong>${avgConf.toFixed(1)}%</strong>`;} else {perfText = `Henüz yeterli veri yok. Model ortalama <strong>${avgConf.toFixed(1)}%</strong> güvenle tahminler yapıyor.`;}document.getElementById('modelPerformanceText').innerHTML = perfText;// Trend analiziconst trendText = bullishDays >= 5? `Son 7 günde <strong>${bullishDays}</strong> gün <span style="color: var(--accent-success)">yükseliş</span> bekleniyor. Pozitif trend hakim.`: bullishDays <= 2? `Son 7 günde <strong>${bullishDays}</strong> gün yükseliş var. <span style="color: var(--accent-danger)">Düşüş</span> trendi baskın.`: `Son 7 günde <strong>${bullishDays}</strong> gün yükseliş. <span style="color: var(--accent-warning)">Kararsız</span> piyasa.`;document.getElementById('trendAnalysisText').innerHTML = trendText;// Risk analiziconst avgPriceDiff = recent7Days.reduce((sum, d) => sum + Math.abs(d.priceDiff), 0) / recent7Days.length;let riskText = '';if (avgPriceDiff > 1000) {riskText = `Ortalama <strong>$${avgPriceDiff.toFixed(0)}</strong> fiyat hareketi bekleniyor. <span style="color: var(--accent-danger)">Yüksek volatilite</span> öngörülüyor.`;} else if (avgPriceDiff > 500) {riskText = `<strong>$${avgPriceDiff.toFixed(0)}</strong> civarı hareketler. <span style="color: var(--accent-warning)">Orta volatilite</span> bekleniyor.`;} else {riskText = `<strong>$${avgPriceDiff.toFixed(0)}</strong> gibi sakin hareketler. <span style="color: var(--accent-success)">Düşük volatilite</span> ortamı.`;}document.getElementById('riskLevelText').innerHTML = riskText;}// Son güncellemefunction updateLastUpdate() {const now = new Date();const nextUpdate = new Date(now.getTime() + 4 * 60 * 60 * 1000); // 4 saat sonradocument.getElementById('lastUpdate').innerHTML =`Son Güncelleme: ${now.toLocaleString('tr-TR')} <br><small>Sonraki güncelleme: ~${nextUpdate.toLocaleTimeString('tr-TR', {hour: '2-digit', minute: '2-digit'})}</small>`;}// Hata gösterfunction showError(message) {document.getElementById('chartStatus').innerHTML = `<span style="color: var(--accent-danger); font-size: 1.2rem;">❌ ${message}</span>`;}// Grafik kontrollerifunction changeTimeframe(timeframe) {// Gelecekte kullanılabilirconsole.log('Timeframe:', timeframe);}// Sayfa yüklendiğinde başlatwindow.addEventListener('DOMContentLoaded', () => {loadData();// 4 saatte bir otomatik güncelle (sunucu güncellemesine uygun)setInterval(loadData, 4 * 60 * 60 * 1000);});// Kâr/Zarar Hesaplama Fonksiyonufunction calculateProfit() {const btcAmount = parseFloat(document.getElementById('btcAmount').value);const resultsDiv = document.getElementById('calculatorResults');// Validasyonif (!btcAmount || btcAmount <= 0) {resultsDiv.innerHTML = `<div class="result-placeholder"><span class="placeholder-icon">⚠️</span><p>Lütfen geçerli bir Bitcoin miktarı girin</p></div>`;return;}if (dailyAnalysis.length === 0) {resultsDiv.innerHTML = `<div class="result-placeholder"><span class="placeholder-icon">⏳</span><p>Veriler yükleniyor, lütfen bekleyin...</p></div>`;return;}const latest = dailyAnalysis[dailyAnalysis.length - 1];const currentPrice = latest.currentPrice;const predictedDirection = latest.predictedDirection;const confidence = latest.directionConfidence;const modelPriceDiff = latest.priceDiff; // Model'in beklediği fiyat değişimi// Mevcut değer (güncel fiyattan)const currentValue = btcAmount * currentPrice;// Model beklentisine göre tahmin edilen değerconst expectedPriceByModel = currentPrice + modelPriceDiff;const predictedValue = btcAmount * expectedPriceByModel;// Model'in beklediği değişim (güncel fiyattan)const potentialChange = btcAmount * modelPriceDiff;const potentialChangePercent = ((modelPriceDiff / currentPrice) * 100);// Toplam değişim yüzdesiconst totalChangePercent = ((predictedValue - currentValue) / currentValue * 100);// Sonuçları gösterresultsDiv.innerHTML = `<div class="results-grid"><!-- Güncel Değer --><div class="result-card neutral"><div class="result-label"><span>💰</span><span>Güncel Değer</span></div><div class="result-value">$${currentValue.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}</div><div class="result-subtitle">${btcAmount} BTC × $${currentPrice.toLocaleString('en-US', {maximumFractionDigits: 2})}</div></div><!-- Model Beklenen Değişim --><div class="result-card ${potentialChange > 0 ? 'profit' : potentialChange < 0 ? 'loss' : 'neutral'}"><div class="result-label"><span>${predictedDirection === 1 ? '🚀' : '⚠️'}</span><span>Model Beklentisi</span></div><div class="result-value">${potentialChange >= 0 ? '+' : ''}$${potentialChange.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}</div><div class="result-subtitle">${potentialChangePercent >= 0 ? '+' : ''}${potentialChangePercent.toFixed(2)}% değişim(Güven: ${confidence.toFixed(1)}%)</div></div><!-- Beklenen Toplam Değer --><div class="result-card ${potentialChange > 0 ? 'profit' : potentialChange < 0 ? 'loss' : 'neutral'}"><div class="result-label"><span>🎯</span><span>Beklenen Toplam</span></div><div class="result-value">$${predictedValue.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}</div><div class="result-subtitle">${btcAmount} BTC × $${expectedPriceByModel.toLocaleString('en-US', {maximumFractionDigits: 2})}(${totalChangePercent >= 0 ? '+' : ''}${totalChangePercent.toFixed(2)}%)</div></div><!-- Detaylı Bilgi --><div class="result-card neutral"><div class="result-label"><span>📊</span><span>Detaylı Analiz</span></div><div style="font-size: 0.9rem; color: var(--text-secondary); line-height: 1.6;"><p style="margin: 5px 0;"><strong style="color: var(--text-primary);">Bitcoin:</strong> ${btcAmount} BTC</p><p style="margin: 5px 0;"><strong style="color: var(--text-primary);">Güncel Fiyat:</strong> $${currentPrice.toLocaleString('en-US', {maximumFractionDigits: 2})}</p><p style="margin: 5px 0;"><strong style="color: var(--text-primary);">Güncel Değer:</strong> $${currentValue.toLocaleString('en-US', {maximumFractionDigits: 2})}</p><p style="margin: 5px 0; padding-top: 5px; border-top: 1px solid var(--border-color);"><strong style="color: var(--text-primary);">Model Değişim:</strong><span style="color: ${modelPriceDiff >= 0 ? 'var(--accent-success)' : 'var(--accent-danger)'};">${modelPriceDiff >= 0 ? '+' : ''}$${modelPriceDiff.toLocaleString('en-US', {maximumFractionDigits: 2})}</span></p><p style="margin: 5px 0;"><strong style="color: var(--text-primary);">Beklenen Fiyat:</strong>$${expectedPriceByModel.toLocaleString('en-US', {maximumFractionDigits: 2})}</p><p style="margin: 5px 0;"><strong style="color: var(--text-primary);">Beklenen Değer:</strong>$${predictedValue.toLocaleString('en-US', {maximumFractionDigits: 2})}</p><p style="margin: 10px 0 5px 0; padding-top: 8px; border-top: 1px solid var(--border-color);"><strong style="color: ${predictedDirection === 1 ? 'var(--accent-success)' : 'var(--accent-danger)'};">${predictedDirection === 1 ? '📈 Yükseliş Bekleniyor' : '📉 Düşüş Bekleniyor'}</strong></p></div></div></div>`;}// Global fonksiyonlarwindow.changeTimeframe = changeTimeframe;window.calculateProfit = calculateProfit;123456789101112131415161718192021222324252627282930313233343536373839404142434445464 unmodified lines51525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251// ==================================================// 🔗 PEGOS DASHBOARD SCRIPT (Hugging Face Compatible)// ==================================================// ✅ API bağlantı adresi (backend Space)const API_URL = "https://caner7-pegos-data.hf.space/predictions";// Global değişkenlerlet dailyAnalysis = [];let rawPredictions = [];// ==================================================// 📦 Ana veri yükleme fonksiyonu// ==================================================async function loadData() {const statusEl = document.getElementById("chartStatus");statusEl.style.display = "flex";statusEl.innerHTML = `<div class="loader"></div><span>Veri yükleniyor...</span>`;try {// Hugging Face CORS uyumlu fetch isteğiconst res = await fetch(API_URL, {method: "GET",headers: { "Accept": "application/json" },mode: "cors",cache: "no-cache"});if (!res.ok) {throw new Error(`API isteği başarısız: ${res.status}`);}const data = await res.json();if (!data.items || data.items.length === 0) {showError("⚠️ Veri bulunamadı. Model henüz sonuç üretmemiş olabilir.");return;}// Ham veriyi işlerawPredictions = data.items.map(d => ({timestamp: new Date(d.time),date: new Date(d.time).toISOString().split("T")[0],currentPrice: parseFloat(d["Kapanış Fiyatı (USD)"]),predictedPrice: d.predicted_price ? parseFloat(d.predicted_price) : null,predLabel: parseInt(d.pred_label),4 unmodified lines// Günlük analiz oluşturdailyAnalysis = createDailyAnalysis(rawPredictions);console.log("✅ Veri yüklendi:", {totalPredictions: rawPredictions.length,days: dailyAnalysis.length,first: dailyAnalysis[0]?.date,last: dailyAnalysis[dailyAnalysis.length - 1]?.date});updateDashboard();} catch (err) {console.error("❌ Veri yükleme hatası:", err);showError("Veri alınamadı. Lütfen sayfayı yenileyin veya daha sonra tekrar deneyin.");}}// ==================================================// 📅 Günlük analiz (güven ağırlıklı ortalama ile)// ==================================================function createDailyAnalysis(predictions) {const groupedByDate = {};// Gün bazlı gruplapredictions.forEach(pred => {if (!groupedByDate[pred.date]) groupedByDate[pred.date] = [];groupedByDate[pred.date].push(pred);});// Günlük ağırlıklı ortalama hesaplareturn Object.entries(groupedByDate).map(([date, preds]) => {const totalWeight = preds.reduce((sum, p) => sum + p.confidence, 0);const weightedPredictedPrice = preds.reduce((sum, p) => sum + (p.predictedPrice * p.confidence), 0) / totalWeight;const weightedPriceDiff = preds.reduce((sum, p) => sum + (p.priceDiff * p.confidence), 0) / totalWeight;const avgConfidence = totalWeight / preds.length;const bullishWeight = preds.filter(p => p.predLabel === 1).reduce((sum, p) => sum + p.confidence, 0);const bearishWeight = preds.filter(p => p.predLabel === 0).reduce((sum, p) => sum + p.confidence, 0);const predictedDirection = bullishWeight > bearishWeight ? 1 : 0;const directionConfidence = Math.max(bullishWeight, bearishWeight) / totalWeight * 100;const lastPred = preds[preds.length - 1];return {date: date,displayDate: new Date(date).toLocaleDateString("tr-TR", { day: "2-digit", month: "long", year: "numeric" }),currentPrice: lastPred.currentPrice,predictedPrice: weightedPredictedPrice,priceDiff: weightedPriceDiff,predictedDirection,directionConfidence,avgConfidence,predictionCount: preds.length,timestamp: new Date(date)};}).sort((a, b) => a.timestamp - b.timestamp);}// ==================================================// 📊 Dashboard bileşenlerini güncelle// ==================================================function updateDashboard() {updateSummaryCards();updateChart();updatePredictionsTable();updateLastUpdate();const statusEl = document.getElementById("chartStatus");statusEl.style.display = "none";}// ==================================================// 💰 Özet Bilgiler// ==================================================function updateSummaryCards() {if (dailyAnalysis.length === 0) return;const latest = dailyAnalysis.at(-1);const prev = dailyAnalysis.length > 1 ? dailyAnalysis.at(-2) : null;document.getElementById("currentPrice").innerHTML =`$${latest.currentPrice.toLocaleString("en-US", { minimumFractionDigits: 2 })}`;if (prev) {const change = ((latest.currentPrice - prev.currentPrice) / prev.currentPrice) * 100;const el = document.getElementById("priceChange");el.textContent = `${change >= 0 ? "▲" : "▼"} ${Math.abs(change).toFixed(2)}%`;el.className = `card-change ${change >= 0 ? "positive" : "negative"}`;}document.getElementById("modelAccuracy").textContent = `${latest.avgConfidence.toFixed(1)}%`;document.getElementById("predictionSignal").textContent = latest.predictedDirection === 1 ? "📈 YÜKSELİŞ" : "📉 DÜŞÜŞ";document.getElementById("confidence").textContent = `Yön Güveni: ${latest.directionConfidence.toFixed(1)}%`;document.getElementById("totalPredictions").textContent = `${dailyAnalysis.length} Gün`;}// ==================================================// 📈 Plotly Grafik// ==================================================function updateChart() {if (dailyAnalysis.length === 0) return;const realLine = {x: dailyAnalysis.map(d => d.displayDate),y: dailyAnalysis.map(d => d.currentPrice),mode: "lines+markers",name: "Gerçek Fiyat",line: { color: "#00ff88", width: 3, shape: "spline" },marker: { color: "#00ff88", size: 10 }};const predictedLine = {x: dailyAnalysis.map(d => d.displayDate),y: dailyAnalysis.map(d => d.predictedPrice),mode: "lines+markers",name: "AI Tahmin",line: { color: "#00d4ff", width: 3, dash: "dot" },marker: {color: dailyAnalysis.map(d => d.predictedDirection === 1 ? "#00ff88" : "#ff4757"),symbol: dailyAnalysis.map(d => d.predictedDirection === 1 ? "triangle-up" : "triangle-down"),size: 12}};const diffBars = {x: dailyAnalysis.map(d => d.displayDate),y: dailyAnalysis.map(d => d.priceDiff),type: "bar",name: "Beklenen Fark ($)",marker: {color: dailyAnalysis.map(d => d.priceDiff >= 0 ? "rgba(0,255,136,0.4)" : "rgba(255,71,87,0.4)")},yaxis: "y2"};const layout = {plot_bgcolor: "#1e2642",paper_bgcolor: "#1a1f3a",font: { color: "#ffffff", family: "Inter, sans-serif" },yaxis: { title: "Fiyat (USD)" },yaxis2: { title: "Değişim ($)", overlaying: "y", side: "right" },legend: { orientation: "h", x: 0.5, xanchor: "center", y: -0.25 },height: 700};Plotly.newPlot("chart", [realLine, predictedLine, diffBars], layout, { responsive: true });}// ==================================================// 📅 Tahmin Tablosu// ==================================================function updatePredictionsTable() {const tbody = document.getElementById("predictionsTableBody");tbody.innerHTML = "";if (dailyAnalysis.length === 0) return;const recent = dailyAnalysis.slice(-30).reverse();recent.forEach(day => {const row = document.createElement("tr");row.innerHTML = `<td>${day.displayDate}</td><td>$${day.currentPrice.toLocaleString("en-US", { minimumFractionDigits: 2 })}</td><td>$${day.predictedPrice.toLocaleString("en-US", { minimumFractionDigits: 2 })}</td><td class="${day.predictedDirection === 1 ? "prediction-up" : "prediction-down"}">${day.predictedDirection === 1 ? "📈 Yükseliş" : "📉 Düşüş"}</td><td>${day.avgConfidence.toFixed(1)}%</td>`;tbody.appendChild(row);});}// ==================================================// 🕒 Güncelleme zamanı// ==================================================function updateLastUpdate() {const now = new Date();const next = new Date(now.getTime() + 4 * 60 * 60 * 1000);document.getElementById("lastUpdate").innerHTML =`Son Güncelleme: ${now.toLocaleString("tr-TR")}<br><small>Sonraki tahmin: ~${next.toLocaleTimeString("tr-TR", { hour: "2-digit", minute: "2-digit" })}</small>`;}// ==================================================// ❌ Hata gösterimi// ==================================================function showError(msg) {const el = document.getElementById("chartStatus");el.style.display = "flex";el.innerHTML = `<span style="color:#ff4757;font-size:1.2rem;">${msg}</span>`;}// ==================================================// 🚀 Sayfa yüklendiğinde başlat// ==================================================window.addEventListener("DOMContentLoaded", () => {loadData();// Her 4 saatte bir yenile (model döngüsüne uygun)setInterval(loadData, 4 * 60 * 60 * 1000);});
script.js+137-588