Spaces:
Sleeping
Sleeping
app.py
Browse files
app.py
CHANGED
@@ -2,7 +2,7 @@ import gradio as gr
|
|
2 |
import requests
|
3 |
import pandas as pd
|
4 |
import plotly.graph_objs as go
|
5 |
-
from datetime import datetime
|
6 |
|
7 |
# Fallback data for demonstration purposes
|
8 |
fallback_historical_data = {
|
@@ -20,12 +20,14 @@ fallback_current_prices = {
|
|
20 |
|
21 |
# Function to fetch current price from CoinGecko with fallback to CryptoCompare
|
22 |
def fetch_current_price(coin_id):
|
|
|
23 |
compare_symbol_map = {
|
24 |
'bitcoin': 'BTC',
|
25 |
'ethereum': 'ETH',
|
26 |
'binancecoin': 'BNB',
|
27 |
}
|
28 |
|
|
|
29 |
gecko_url = f"https://api.coingecko.com/api/v3/simple/price?ids={coin_id}&vs_currencies=usd"
|
30 |
compare_url = f"https://min-api.cryptocompare.com/data/price?fsym={compare_symbol_map.get(coin_id, 'BTC')}&tsyms=USD"
|
31 |
|
@@ -34,10 +36,7 @@ def fetch_current_price(coin_id):
|
|
34 |
response = requests.get(gecko_url, timeout=10)
|
35 |
response.raise_for_status()
|
36 |
data = response.json()
|
37 |
-
|
38 |
-
return f"${data[coin_id]['usd']:.2f} (from CoinGecko)"
|
39 |
-
else:
|
40 |
-
return f"Unexpected response from CoinGecko: {data}"
|
41 |
except requests.exceptions.RequestException as gecko_error:
|
42 |
print(f"Error fetching price from CoinGecko: {gecko_error}")
|
43 |
|
@@ -46,10 +45,7 @@ def fetch_current_price(coin_id):
|
|
46 |
response = requests.get(compare_url, timeout=10)
|
47 |
response.raise_for_status()
|
48 |
data = response.json()
|
49 |
-
|
50 |
-
return f"${data['USD']:.2f} (from CryptoCompare)"
|
51 |
-
else:
|
52 |
-
return f"Unexpected response from CryptoCompare: {data}"
|
53 |
except requests.exceptions.RequestException as compare_error:
|
54 |
print(f"Error fetching price from CryptoCompare: {compare_error}")
|
55 |
return "Price data not available"
|
@@ -66,12 +62,19 @@ def fetch_historical_data(coin_id, from_timestamp, to_timestamp):
|
|
66 |
print(f"Error fetching historical data: {e}")
|
67 |
return fallback_historical_data.get(coin_id, f"Error fetching historical data for {coin_id}")
|
68 |
|
|
|
|
|
|
|
|
|
69 |
# Function to plot historical prices using Plotly
|
70 |
-
def plot_historical_prices(coin_name,
|
71 |
try:
|
72 |
-
#
|
73 |
-
|
74 |
-
|
|
|
|
|
|
|
75 |
|
76 |
prices = fetch_historical_data(coin_name, from_timestamp, to_timestamp)
|
77 |
|
@@ -83,7 +86,7 @@ def plot_historical_prices(coin_name, start_date, end_date):
|
|
83 |
|
84 |
fig = go.Figure()
|
85 |
fig.add_trace(go.Scatter(x=df['date'], y=df['price'], mode='lines', name=coin_name))
|
86 |
-
fig.update_layout(title=f'{coin_name.capitalize()} Prices
|
87 |
xaxis_title='Date', yaxis_title='Price (USD)')
|
88 |
return fig
|
89 |
except Exception as e:
|
@@ -146,19 +149,26 @@ crypto_price_chart_interface = gr.Interface(
|
|
146 |
fn=plot_historical_prices,
|
147 |
inputs=[
|
148 |
gr.Dropdown(choices=['bitcoin', 'ethereum', 'binancecoin'], label="Cryptocurrency"),
|
149 |
-
gr.
|
150 |
-
gr.Date(label="End Date", value=datetime.now().strftime('%Y-%m-%d'))
|
151 |
],
|
152 |
outputs=gr.Plot(label="Cryptocurrency Price Chart"),
|
153 |
-
title="Cryptocurrency Price Chart (
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
154 |
)
|
155 |
|
156 |
# Combining all interfaces into a single tabbed app
|
157 |
block = gr.TabbedInterface(
|
158 |
-
[crypto_price_chart_interface, real_time_trade_interface, btc_analysis_interface],
|
159 |
-
tab_names=["Price Chart", "Real-Time Trade Data", "AI BTC Analysis"]
|
160 |
)
|
161 |
|
162 |
# Launch the Gradio app
|
163 |
if __name__ == "__main__":
|
164 |
-
block.launch()
|
|
|
2 |
import requests
|
3 |
import pandas as pd
|
4 |
import plotly.graph_objs as go
|
5 |
+
from datetime import datetime, timedelta
|
6 |
|
7 |
# Fallback data for demonstration purposes
|
8 |
fallback_historical_data = {
|
|
|
20 |
|
21 |
# Function to fetch current price from CoinGecko with fallback to CryptoCompare
|
22 |
def fetch_current_price(coin_id):
|
23 |
+
# Mapping between CoinGecko and CryptoCompare coin symbols
|
24 |
compare_symbol_map = {
|
25 |
'bitcoin': 'BTC',
|
26 |
'ethereum': 'ETH',
|
27 |
'binancecoin': 'BNB',
|
28 |
}
|
29 |
|
30 |
+
# API URLs
|
31 |
gecko_url = f"https://api.coingecko.com/api/v3/simple/price?ids={coin_id}&vs_currencies=usd"
|
32 |
compare_url = f"https://min-api.cryptocompare.com/data/price?fsym={compare_symbol_map.get(coin_id, 'BTC')}&tsyms=USD"
|
33 |
|
|
|
36 |
response = requests.get(gecko_url, timeout=10)
|
37 |
response.raise_for_status()
|
38 |
data = response.json()
|
39 |
+
return f"${data[coin_id]['usd']:.2f} (from CoinGecko)"
|
|
|
|
|
|
|
40 |
except requests.exceptions.RequestException as gecko_error:
|
41 |
print(f"Error fetching price from CoinGecko: {gecko_error}")
|
42 |
|
|
|
45 |
response = requests.get(compare_url, timeout=10)
|
46 |
response.raise_for_status()
|
47 |
data = response.json()
|
48 |
+
return f"${data['USD']:.2f} (from CryptoCompare)"
|
|
|
|
|
|
|
49 |
except requests.exceptions.RequestException as compare_error:
|
50 |
print(f"Error fetching price from CryptoCompare: {compare_error}")
|
51 |
return "Price data not available"
|
|
|
62 |
print(f"Error fetching historical data: {e}")
|
63 |
return fallback_historical_data.get(coin_id, f"Error fetching historical data for {coin_id}")
|
64 |
|
65 |
+
# Convert date string to timestamp
|
66 |
+
def date_to_timestamp(date_str):
|
67 |
+
return int(pd.Timestamp(date_str).timestamp())
|
68 |
+
|
69 |
# Function to plot historical prices using Plotly
|
70 |
+
def plot_historical_prices(coin_name, days_back):
|
71 |
try:
|
72 |
+
# Set dynamic date range: from X days ago to today
|
73 |
+
to_date = datetime.now()
|
74 |
+
from_date = to_date - timedelta(days=days_back)
|
75 |
+
|
76 |
+
from_timestamp = int(from_date.timestamp())
|
77 |
+
to_timestamp = int(to_date.timestamp())
|
78 |
|
79 |
prices = fetch_historical_data(coin_name, from_timestamp, to_timestamp)
|
80 |
|
|
|
86 |
|
87 |
fig = go.Figure()
|
88 |
fig.add_trace(go.Scatter(x=df['date'], y=df['price'], mode='lines', name=coin_name))
|
89 |
+
fig.update_layout(title=f'{coin_name.capitalize()} Prices (Last {days_back} Days)',
|
90 |
xaxis_title='Date', yaxis_title='Price (USD)')
|
91 |
return fig
|
92 |
except Exception as e:
|
|
|
149 |
fn=plot_historical_prices,
|
150 |
inputs=[
|
151 |
gr.Dropdown(choices=['bitcoin', 'ethereum', 'binancecoin'], label="Cryptocurrency"),
|
152 |
+
gr.Slider(minimum=1, maximum=365, step=1, value=30, label="Number of Days Back")
|
|
|
153 |
],
|
154 |
outputs=gr.Plot(label="Cryptocurrency Price Chart"),
|
155 |
+
title="Cryptocurrency Price Chart (Last X Days)"
|
156 |
+
)
|
157 |
+
|
158 |
+
# Current Price Interface
|
159 |
+
current_price_interface = gr.Interface(
|
160 |
+
fn=fetch_current_price,
|
161 |
+
inputs=gr.Dropdown(choices=['bitcoin', 'ethereum', 'binancecoin'], label="Cryptocurrency"),
|
162 |
+
outputs=gr.Textbox(label="Current Price"),
|
163 |
+
title="Current Cryptocurrency Price"
|
164 |
)
|
165 |
|
166 |
# Combining all interfaces into a single tabbed app
|
167 |
block = gr.TabbedInterface(
|
168 |
+
[crypto_price_chart_interface, current_price_interface, real_time_trade_interface, btc_analysis_interface],
|
169 |
+
tab_names=["Price Chart", "Current Price", "Real-Time Trade Data", "AI BTC Analysis"]
|
170 |
)
|
171 |
|
172 |
# Launch the Gradio app
|
173 |
if __name__ == "__main__":
|
174 |
+
block.launch()
|