Spaces:
Sleeping
Sleeping
import gradio as gr | |
import requests | |
import pandas as pd | |
import plotly.graph_objects as go | |
# Define your CryptoCompare API key | |
API_KEY = 'c1e07b0b9a72b6f5ea096763a17a2a1eec7a925a10faadd615b2d152f208a98d' | |
# Function to fetch historical price data from CryptoCompare | |
def fetch_historical_data(coin_id, from_date, to_date): | |
try: | |
url = "https://min-api.cryptocompare.com/data/v2/histoday" | |
params = { | |
'fsym': coin_id, | |
'tsym': 'USD', | |
'limit': 2000, # Maximum number of data points | |
'toTs': pd.Timestamp(to_date).timestamp(), | |
'api_key': API_KEY | |
} | |
response = requests.get(url, params=params) | |
response.raise_for_status() | |
data = response.json() | |
df = pd.DataFrame(data['Data']['Data']) | |
df['time'] = pd.to_datetime(df['time'], unit='s') | |
df = df[['time', 'close']].rename(columns={'time': 'timestamp', 'close': 'price'}) | |
return df | |
except Exception as e: | |
return f"Error fetching historical data for {coin_id}: {e}" | |
# Function to fetch current prices from CryptoCompare | |
def fetch_current_price(coin_id): | |
try: | |
url = "https://min-api.cryptocompare.com/data/price" | |
params = { | |
'fsym': coin_id, | |
'tsyms': 'USD', | |
'api_key': API_KEY | |
} | |
response = requests.get(url, params=params) | |
response.raise_for_status() | |
data = response.json() | |
return f"${data['USD']}" | |
except Exception as e: | |
return f"Error fetching current price for {coin_id}: {e}" | |
# Function to provide TradingView widget HTML | |
def get_tradingview_chart(): | |
widget_html = """ | |
<iframe | |
src="https://www.tradingview.com/widgetembed/?frameElementId=tradingview_ea33b&symbol=BINANCE:BTCUSDT&interval=60" | |
width="800" | |
height="600" | |
frameborder="0" | |
allowtransparency="true" | |
scrolling="no" | |
allowfullscreen="true"> | |
</iframe> | |
""" | |
return widget_html | |
# Function to fetch real-time trade data from CryptoCompare | |
def get_real_time_trade_data(): | |
try: | |
return fetch_current_price('BTC') | |
except Exception as e: | |
return f"Error fetching real-time trade data: {e}" | |
# Function to plot historical prices using Plotly | |
def plot_historical_prices(coin_name, from_date, to_date): | |
df = fetch_historical_data(coin_name, from_date, to_date) | |
if isinstance(df, str): # In case of error | |
return df | |
fig = go.Figure() | |
fig.add_trace(go.Scatter(x=df['timestamp'], y=df['price'], mode='lines', name=coin_name)) | |
fig.update_layout(title=f'{coin_name.capitalize()} Prices from {from_date} to {to_date}', xaxis_title='Date', yaxis_title='Price (USD)') | |
return fig | |
# Function to analyze Bitcoin based on the prompt | |
def analyze_btc(prompt): | |
"""Analyze the prompt and provide information.""" | |
prompt = prompt.lower() | |
if "price" in prompt: | |
return f"Current Bitcoin price: {fetch_current_price('BTC')}" | |
elif "trade data" in prompt: | |
return get_real_time_trade_data() | |
elif "chart" in prompt: | |
return get_tradingview_chart() # Use HTML component for TradingView chart | |
return "Try asking about the Bitcoin price, real-time trade data, or TradingView chart." | |
# Gradio Interface Setup | |
# AI BTC Analysis Interface | |
btc_analysis_interface = gr.Interface( | |
fn=analyze_btc, | |
inputs="text", | |
outputs="html", # Ensure output is HTML | |
title="Bitcoin Analyzer", | |
description="Ask about the current Bitcoin price, real-time trade data, or TradingView chart." | |
) | |
# TradingView Interface for live charts | |
tradingview_interface = gr.Interface( | |
fn=get_tradingview_chart, | |
inputs=[], | |
outputs=gr.HTML(label="TradingView Chart"), | |
title="Live TradingView Chart" | |
) | |
# Real-time Trade Data Interface | |
real_time_trade_interface = gr.Interface( | |
fn=get_real_time_trade_data, | |
inputs=[], | |
outputs=gr.Textbox(label="Real-Time Trade Data"), | |
title="Real-Time Cryptocurrency Trade Data" | |
) | |
# Price Chart Interface | |
crypto_price_chart_interface = gr.Interface( | |
fn=plot_historical_prices, | |
inputs=[ | |
gr.Dropdown(choices=['BTC'], 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="Cryptocurrency Price Chart"), | |
title="Cryptocurrency Price Chart (2024-2025)" | |
) | |
# Current Price Interface | |
current_price_interface = gr.Interface( | |
fn=fetch_current_price, | |
inputs=gr.Dropdown(choices=['BTC'], label="Cryptocurrency"), | |
outputs=gr.Textbox(label="Current Price"), | |
title="Current Cryptocurrency Price" | |
) | |
# Combining all interfaces into a single tabbed app | |
gr.TabbedInterface( | |
[crypto_price_chart_interface, current_price_interface, real_time_trade_interface, btc_analysis_interface, tradingview_interface], | |
tab_names=["Price Chart", "Current Price", "Real-Time Trade Data", "AI BTC Analysis", "TradingView Chart"] | |
).launch() | |