Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import requests | |
| import pandas as pd | |
| import plotly.graph_objects as go | |
| # 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) | |
| response.raise_for_status() # Will raise an HTTPError for bad responses | |
| data = response.json() | |
| prices = data.get('prices', []) | |
| return prices | |
| except requests.RequestException as e: | |
| return str(e) | |
| # Function to fetch current prices from CoinGecko | |
| def fetch_current_price(coin_id): | |
| url = f"https://api.coingecko.com/api/v3/simple/price?ids={coin_id}&vs_currencies=usd" | |
| try: | |
| response = requests.get(url) | |
| response.raise_for_status() | |
| data = response.json() | |
| return data[coin_id]['usd'] | |
| except requests.RequestException as e: | |
| return str(e) | |
| # Function to convert dates to timestamps | |
| 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): | |
| 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): # In case of error | |
| return go.Figure() | |
| 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 from {from_date} to {to_date}', xaxis_title='Date', yaxis_title='Price (USD)') | |
| return fig | |
| # 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 CoinGecko | |
| def get_real_time_trade_data(): | |
| url = "https://api.coingecko.com/api/v3/coins/bitcoin/market_chart?vs_currency=usd&days=1" | |
| try: | |
| response = requests.get(url) | |
| response.raise_for_status() | |
| data = response.json() | |
| latest_price = data['prices'][-1][1] if data['prices'] else "N/A" | |
| return f"Latest trading data for Bitcoin is: ${latest_price}" | |
| except requests.RequestException as e: | |
| return str(e) | |
| # Function to analyze Bitcoin based on the prompt | |
| def analyze_btc(prompt): | |
| """Analyze the prompt and provide information.""" | |
| if "price" in prompt.lower(): | |
| return f"Current Bitcoin price: ${fetch_current_price('bitcoin')}" | |
| elif "trade data" in prompt.lower(): | |
| return get_real_time_trade_data() | |
| elif "chart" in prompt.lower(): | |
| 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 | |
| # Historical Price Chart Interface | |
| crypto_price_chart_interface = gr.Interface( | |
| fn=plot_historical_prices, | |
| inputs=[ | |
| gr.Dropdown(choices=['bitcoin'], 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)" | |
| ) | |
| # 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" | |
| ) | |
| # AI Bitcoin Analyzer Interface | |
| ai_btc_analyzer_interface = gr.Interface( | |
| fn=analyze_btc, | |
| inputs="text", | |
| outputs="html", # Ensure output is HTML | |
| title="AI 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" | |
| ) | |
| # Combining all interfaces into a single tabbed app | |
| gr.TabbedInterface( | |
| [crypto_price_chart_interface, real_time_trade_interface, ai_btc_analyzer_interface, tradingview_interface], | |
| tab_names=["Price Chart", "Real-Time Trade Data", "AI BTC Analysis", "TradingView Chart"] | |
| ).launch() | |