Spaces:
Sleeping
Sleeping
import gradio as gr | |
import requests | |
import pandas as pd | |
import plotly.graph_objs as go | |
import time | |
# Fallback data for demonstration purposes | |
fallback_historical_data = { | |
'bitcoin': [ | |
[1633046400000, 42000], [1633132800000, 42250], [1633219200000, 41500], | |
[1633305600000, 43000], [1633392000000, 43500], [1633478400000, 44000] | |
] | |
} | |
fallback_current_prices = { | |
'bitcoin': 42000, | |
'ethereum': 3100, | |
'binancecoin': 380 | |
} | |
# Function to fetch historical price data from CoinGecko | |
def fetch_historical_data(coin_id, from_timestamp, to_timestamp): | |
url = f"https://api.coingecko.com/api/v3/coins/{coin_id}/market_chart/range?vs_currency=usd&from={from_timestamp}&to={to_timestamp}" | |
try: | |
response = requests.get(url, timeout=10) | |
response.raise_for_status() | |
data = response.json() | |
return data['prices'] | |
except requests.exceptions.RequestException as e: | |
print(f"Error fetching historical data: {e}") | |
return fallback_historical_data.get(coin_id, f"Error fetching historical data for {coin_id}") | |
# Function to fetch current prices with fallback | |
def fetch_current_price(coin_id): | |
gecko_url = f"https://api.coingecko.com/api/v3/simple/price?ids={coin_id}&vs_currencies=usd" | |
compare_url = f"https://min-api.cryptocompare.com/data/price?fsym={coin_id.upper()}&tsyms=USD" | |
try: | |
response = requests.get(gecko_url, timeout=10) | |
response.raise_for_status() | |
data = response.json() | |
return data[coin_id]['usd'] | |
except requests.exceptions.RequestException as e: | |
print(f"Error fetching CoinGecko price: {e}") | |
# Try CryptoCompare if CoinGecko fails | |
try: | |
response = requests.get(compare_url, timeout=10) | |
response.raise_for_status() | |
data = response.json() | |
return data['USD'] | |
except requests.exceptions.RequestException as e2: | |
print(f"Error fetching CryptoCompare price: {e2}") | |
return fallback_current_prices.get(coin_id, "Price not available") | |
# Convert date string to timestamp | |
def date_to_timestamp(date_str): | |
return int(pd.Timestamp(date_str).timestamp()) | |
# Function to plot historical prices using Plotly | |
def plot_historical_prices(coin_name, from_date, to_date): | |
try: | |
from_timestamp = date_to_timestamp(from_date) | |
to_timestamp = date_to_timestamp(to_date) | |
prices = fetch_historical_data(coin_name, from_timestamp, to_timestamp) | |
if isinstance(prices, str): | |
return prices | |
df = pd.DataFrame(prices, columns=['timestamp', 'price']) | |
df['date'] = pd.to_datetime(df['timestamp'], unit='ms') | |
fig = go.Figure() | |
fig.add_trace(go.Scatter(x=df['date'], y=df['price'], mode='lines', name=coin_name)) | |
fig.update_layout(title=f'{coin_name.capitalize()} Prices', xaxis_title='Date', yaxis_title='Price (USD)') | |
return fig | |
except Exception as e: | |
return f"Error in plotting chart: {e}" | |
# Function to analyze BTC (mock data) | |
def btc_analysis(): | |
try: | |
return "BTC Analysis: Market is bullish with increasing buying pressure." | |
except Exception as e: | |
return f"Error in BTC analysis: {e}" | |
# Function to fetch real-time trade data | |
def fetch_real_time_trade_data(coin_id): | |
fallback_data = {'bitcoin': [1633039200000, 42000]} | |
gecko_url = f"https://api.coingecko.com/api/v3/coins/{coin_id}/market_chart?vs_currency=usd&days=1" | |
try: | |
response = requests.get(gecko_url, timeout=10) | |
response.raise_for_status() | |
data = response.json() | |
return data['prices'][-1] # Latest price data | |
except requests.exceptions.RequestException as e: | |
print(f"Error fetching trade data: {e}") | |
return fallback_data.get(coin_id, "Trade data not available") | |
# Function to display real-time trade data | |
def real_time_trade_dashboard(coin): | |
try: | |
data = fetch_real_time_trade_data(coin) | |
return f"The latest trade data for {coin.capitalize()}: ${data[1]}" | |
except Exception as e: | |
return f"Error in real-time trade dashboard: {e}" | |
# Gradio Interfaces | |
btc_analysis_interface = gr.Interface( | |
fn=btc_analysis, | |
inputs=[], | |
outputs=gr.Textbox(label="BTC Analysis"), | |
title="BTC Market Analysis" | |
) | |
real_time_trade_interface = gr.Interface( | |
fn=real_time_trade_dashboard, | |
inputs=gr.Dropdown(choices=['bitcoin', 'ethereum'], label="Cryptocurrency"), | |
outputs=gr.Textbox(label="Real-Time Trade Data"), | |
title="Real-Time Trade Data" | |
) | |
crypto_price_chart_interface = gr.Interface( | |
fn=plot_historical_prices, | |
inputs=[ | |
gr.Dropdown(choices=['bitcoin', 'ethereum'], label="Cryptocurrency"), | |
gr.Textbox(value="2024-01-01", label="From Date (YYYY-MM-DD)"), | |
gr.Textbox(value="2025-12-31", label="To Date (YYYY-MM-DD)") | |
], | |
outputs=gr.Plot(label="Price Chart"), | |
title="Cryptocurrency Price Chart" | |
) | |
current_price_interface = gr.Interface( | |
fn=fetch_current_price, | |
inputs=gr.Dropdown(choices=['bitcoin', 'ethereum'], label="Cryptocurrency"), | |
outputs=gr.Textbox(label="Current Price"), | |
title="Current Price" | |
) | |
# Launch Gradio app | |
app = gr.TabbedInterface( | |
[btc_analysis_interface, real_time_trade_interface, crypto_price_chart_interface, current_price_interface], | |
["BTC Analysis", "Real-Time Trade Data", "Price Chart", "Current Price"] | |
) | |
app.launch() | |