Spaces:
Sleeping
Sleeping
File size: 5,292 Bytes
20822e7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 | import pandas as pd
import requests
import random
from datetime import datetime, timedelta
# -----------------------------
# Fetch BTC Data
# -----------------------------
def fetch_btc_data():
try:
url = "https://api.coingecko.com/api/v3/coins/bitcoin/market_chart?vs_currency=usd&days=50"
res = requests.get(url, timeout=10)
res.raise_for_status()
data = res.json()
prices = data['prices']
df = pd.DataFrame(prices, columns=['time', 'close'])
df['time'] = pd.to_datetime(df['time'], unit='ms')
return df
except Exception as e:
print(f"Error fetching BTC data: {e}")
return pd.DataFrame()
# -----------------------------
# Simulated Prediction
# -----------------------------
def simulate_lstm_prediction(df, hours_ahead=0):
if df.empty or len(df) < 5:
return None, None, None
current_price = df.iloc[-1]['close']
momentum = (df.iloc[-1]['close'] - df.iloc[-5]['close']) / df.iloc[-5]['close']
time_factor = hours_ahead * 0.015
variance = (random.random() - 0.5) * (0.04 + time_factor)
pred_price = current_price * (1 + (momentum * 0.35) + variance)
trend = "HIGH β" if pred_price > current_price else "LOW β"
confidence = random.uniform(65, 92)
return pred_price, trend, confidence
# -----------------------------
# Create Plot
# -----------------------------
def create_plot(df):
import plotly.graph_objects as go
if df.empty:
fig = go.Figure()
fig.update_layout(template="plotly_dark", height=400,
annotations=[dict(text="No data available", x=0.5, y=0.5, showarrow=False, font=dict(size=20))])
return fig
fig = go.Figure()
fig.add_trace(go.Scatter(x=df['time'], y=df['close'], mode='lines', name='BTC Price',
line=dict(color='#3b82f6', width=4), fill='tozeroy', fillcolor='rgba(59, 130, 246, 0.1)'))
fig.update_layout(template="plotly_dark", height=400, margin=dict(l=0,r=0,t=0,b=0),
xaxis=dict(showgrid=False, title="Date"),
yaxis=dict(showgrid=True, gridcolor='rgba(255,255,255,0.05)', title="Price (USD)"))
return fig
# -----------------------------
# Main Backend Function
# -----------------------------
def run_dashboard():
df = fetch_btc_data()
current_time = datetime.utcnow() + timedelta(hours=5) # PKT Time
if df.empty:
error_html = "<div style='text-align:center;padding:30px;color:#ef4444;'>β οΈ Unable to fetch data</div>"
return None, error_html, error_html, error_html, error_html, error_html
current_price = df.iloc[-1]['close']
current_box = f"""
<div class='current-price-card' style='text-align: center; padding: 20px;'>
<div style='margin-bottom: 8px;'><span style='font-size: 0.75rem; color: #fbbf24;'>π {current_time.strftime('%H:%M')}</span></div>
<div style='font-size: 2rem; font-weight: 900; color: #fbbf24;'>${current_price:,.2f}</div>
<div style='font-size: 0.75rem; color: #fcd34d;'>Current Bitcoin Price</div>
</div>
"""
# 1 Hour
p1, t1, c1 = simulate_lstm_prediction(df, 1)
time1 = current_time + timedelta(hours=1)
pred1 = format_prediction_box(time1.strftime("%H:%M"), p1, t1, c1)
# 2 Hours
p2, t2, c2 = simulate_lstm_prediction(df, 2)
time2 = current_time + timedelta(hours=2)
pred2 = format_prediction_box(time2.strftime("%H:%M"), p2, t2, c2)
# 1 Day
p3, t3, c3 = simulate_lstm_prediction(df, 24)
time3 = current_time + timedelta(hours=24)
pred3 = format_prediction_box(time3.strftime("%b %d, %H:%M"), p3, t3, c3)
plot = create_plot(df)
analysis = f"""
<div class='analysis-box' style='text-align: center; padding: 16px;'>
<p style='color: #e0e7ff; font-size: 0.85rem; font-style: italic;'>π‘ {random.choice([
"Momentum persistence detected in recent sequences.",
"Strong correlation with historical breakout patterns.",
"Attention mechanisms highlighting key support levels."
])}</p>
</div>
"""
return plot, current_box, pred1, pred2, pred3, analysis
# Helper function for prediction box
def format_prediction_box(time_str, price, trend, confidence):
if price is None:
return "<div class='price-card' style='text-align:center;padding:20px;'><p style='color:#ef4444;'>Prediction unavailable</p></div>"
if "HIGH" in trend:
color = "#34d399"; icon = "π"; bg = "rgba(52, 211, 153, 0.1)"
else:
color = "#f87171"; icon = "π"; bg = "rgba(248, 113, 113, 0.1)"
return f"""
<div class='price-card' style='text-align: center; padding: 20px;'>
<div style='margin-bottom:5px;'><span style='font-size:0.75rem;color:#94a3b8;'>π {time_str}</span></div>
<div style='font-size:1.5rem;font-weight:800;color:#e0e7ff;margin:8px 0;'>${price:,.2f}</div>
<div style='background:{bg};padding:6px 12px;border-radius:16px;display:inline-block;'>
<span style='color:{color};font-weight:700;'>{icon} {trend}</span>
</div>
<div style='margin-top:5px;font-size:0.7rem;color:#cbd5e1;'>Confidence: {confidence:.0f}%</div>
</div>
""" |