missbaj commited on
Commit
4d46cc7
·
verified ·
1 Parent(s): 922b457
Files changed (1) hide show
  1. app.py +79 -151
app.py CHANGED
@@ -4,7 +4,7 @@ import pandas as pd
4
  import plotly.graph_objs as go
5
  import time
6
 
7
- # Fallback data in case both APIs fail
8
  fallback_historical_data = {
9
  'bitcoin': [
10
  [1633046400000, 42000], [1633132800000, 42250], [1633219200000, 41500],
@@ -18,205 +18,133 @@ fallback_current_prices = {
18
  'binancecoin': 380
19
  }
20
 
21
- # Function to fetch historical price data from CoinGecko with retry logic
22
  def fetch_historical_data(coin_id, from_timestamp, to_timestamp):
23
  url = f"https://api.coingecko.com/api/v3/coins/{coin_id}/market_chart/range?vs_currency=usd&from={from_timestamp}&to={to_timestamp}"
24
- for _ in range(3): # Retry 3 times before failing
25
- try:
26
- response = requests.get(url, timeout=10)
27
- response.raise_for_status()
28
- data = response.json()
29
- prices = data['prices']
30
- return prices
31
- except requests.exceptions.RequestException:
32
- time.sleep(1) # Wait 1 second before retrying
33
- return fallback_historical_data.get(coin_id, f"Error fetching historical data for {coin_id}")
34
 
35
- # Function to fetch current prices from CoinGecko and fallback to CryptoCompare
36
  def fetch_current_price(coin_id):
37
  gecko_url = f"https://api.coingecko.com/api/v3/simple/price?ids={coin_id}&vs_currencies=usd"
38
  compare_url = f"https://min-api.cryptocompare.com/data/price?fsym={coin_id.upper()}&tsyms=USD"
39
 
40
- # First, try CoinGecko API
41
- for _ in range(3): # Retry 3 times before failing
42
- try:
43
- response = requests.get(gecko_url, timeout=10)
44
- response.raise_for_status()
45
- data = response.json()
46
- return data[coin_id]['usd']
47
- except requests.exceptions.RequestException:
48
- time.sleep(1)
49
-
50
- # If CoinGecko fails, try CryptoCompare API
51
  try:
52
- response = requests.get(compare_url, timeout=10)
53
  response.raise_for_status()
54
  data = response.json()
55
- return data['USD']
56
- except requests.exceptions.RequestException:
57
- # Return fallback data if both APIs fail
58
- return fallback_current_prices.get(coin_id, f"Error fetching current price for {coin_id}")
 
 
 
 
 
 
 
 
 
59
 
60
- # Function to convert dates to timestamps
61
  def date_to_timestamp(date_str):
62
  return int(pd.Timestamp(date_str).timestamp())
63
 
64
  # Function to plot historical prices using Plotly
65
  def plot_historical_prices(coin_name, from_date, to_date):
66
- from_timestamp = date_to_timestamp(from_date)
67
- to_timestamp = date_to_timestamp(to_date)
68
-
69
- prices = fetch_historical_data(coin_name, from_timestamp, to_timestamp)
70
-
71
- if isinstance(prices, str): # In case of error (fallback or API error)
72
- return prices
73
-
74
- df = pd.DataFrame(prices, columns=['timestamp', 'price'])
75
- df['date'] = pd.to_datetime(df['timestamp'], unit='ms')
76
-
77
- fig = go.Figure()
78
- fig.add_trace(go.Scatter(x=df['date'], y=df['price'], mode='lines', name=coin_name))
79
- fig.update_layout(title=f'{coin_name.capitalize()} Prices from {from_date} to {to_date}', xaxis_title='Date', yaxis_title='Price (USD)')
80
- return fig
81
-
82
- # Function to provide TradingView widget HTML
83
- def tradingview_widget():
84
- widget_html = """
85
- <iframe
86
- src="https://www.tradingview.com/widgetembed/?frameElementId=tradingview_ea33b&symbol=BINANCE:BTCUSDT&interval=60"
87
- width="800"
88
- height="600"
89
- frameborder="0"
90
- allowtransparency="true"
91
- scrolling="no"
92
- allowfullscreen="true">
93
- </iframe>
94
- """
95
- return widget_html
96
-
97
- # Function to analyze order book data (mocked for demo)
98
- def analyze_order_book():
99
- return "Order book analysis: Buying pressure above, selling pressure below."
100
-
101
- # Function to analyze technical indicators (mocked for demo)
102
- def analyze_technicals():
103
- return "Technical analysis: Divergence detected, RSI showing overbought."
104
-
105
- # Function to analyze funding rates (mocked for demo)
106
- def analyze_funding_rate():
107
- return "Funding rate: Higher on longs, suggesting bullish sentiment."
108
-
109
- # Function to analyze on-chain metrics (mocked for demo)
110
- def analyze_on_chain():
111
- return "On-chain analysis: Ichimoku cloud shows potential reversal."
112
-
113
- # Function to fetch and analyze news sentiment (mocked for demo)
114
- def analyze_news():
115
- return "News analysis: Positive sentiment with increasing institutional interest."
116
-
117
- # Function to combine all AI BTC analysis into one output
118
  def btc_analysis():
119
- order_book = analyze_order_book()
120
- technicals = analyze_technicals()
121
- funding_rate = analyze_funding_rate()
122
- on_chain = analyze_on_chain()
123
- news = analyze_news()
124
-
125
- return f"""
126
- {order_book}
127
- {technicals}
128
- {funding_rate}
129
- {on_chain}
130
- {news}
131
- """
132
-
133
- # Function to fetch real-time trade data from CoinGecko (with retry and backup logic)
134
  def fetch_real_time_trade_data(coin_id):
135
- fallback_data = {
136
- 'bitcoin': [1633039200000, 42000],
137
- 'ethereum': [1633039200000, 3100],
138
- 'binancecoin': [1633039200000, 380],
139
- }
140
 
141
  gecko_url = f"https://api.coingecko.com/api/v3/coins/{coin_id}/market_chart?vs_currency=usd&days=1"
142
- compare_url = f"https://min-api.cryptocompare.com/data/price?fsym={coin_id.upper()}&tsyms=USD"
143
 
144
- # First, try CoinGecko API
145
- for _ in range(3): # Retry 3 times before failing
146
- try:
147
- response = requests.get(gecko_url, timeout=10)
148
- response.raise_for_status()
149
- data = response.json()
150
- return data['prices'][-1] # Latest price data
151
- except requests.exceptions.RequestException:
152
- time.sleep(1)
153
-
154
- # If CoinGecko fails, try CryptoCompare API
155
  try:
156
- response = requests.get(compare_url, timeout=10)
157
  response.raise_for_status()
158
  data = response.json()
159
- return [None, data['USD']]
160
- except requests.exceptions.RequestException:
161
- # If both APIs fail, return fallback data
162
- return fallback_data.get(coin_id, f"Error fetching real-time trade data for {coin_id}")
163
 
164
  # Function to display real-time trade data
165
  def real_time_trade_dashboard(coin):
166
- data = fetch_real_time_trade_data(coin)
167
- if isinstance(data, str): # In case of error
168
- return data
169
- return f"The latest trading data for {coin.capitalize()} is: ${data[1]}"
170
-
171
- # Top 100 Cryptocurrencies (by CoinGecko IDs)
172
- top_100_cryptos = [
173
- 'bitcoin', 'ethereum', 'binancecoin', 'ripple', 'solana', 'cardano', 'dogecoin', 'polygon', 'polkadot', 'tron',
174
- ]
175
-
176
- # Gradio Interface Setup
177
 
178
- # AI BTC Analysis Interface
179
  btc_analysis_interface = gr.Interface(
180
  fn=btc_analysis,
181
  inputs=[],
182
  outputs=gr.Textbox(label="BTC Analysis"),
183
- title="AI-Powered BTC Analysis"
184
  )
185
 
186
- # TradingView Interface for live charts
187
- tradingview_interface = gr.Interface(
188
- fn=tradingview_widget,
189
- inputs=[],
190
- outputs=gr.HTML(label="TradingView Chart"),
191
- title="Live TradingView Chart"
192
- )
193
-
194
- # Real-time Trade Data Interface
195
  real_time_trade_interface = gr.Interface(
196
  fn=real_time_trade_dashboard,
197
- inputs=gr.Dropdown(choices=top_100_cryptos, label="Cryptocurrency"),
198
  outputs=gr.Textbox(label="Real-Time Trade Data"),
199
- title="Real-Time Cryptocurrency Trade Data"
200
  )
201
 
202
- # Price Chart Interface
203
  crypto_price_chart_interface = gr.Interface(
204
  fn=plot_historical_prices,
205
  inputs=[
206
- gr.Dropdown(choices=top_100_cryptos, label="Cryptocurrency"),
207
  gr.Textbox(value="2024-01-01", label="From Date (YYYY-MM-DD)"),
208
  gr.Textbox(value="2025-12-31", label="To Date (YYYY-MM-DD)")
209
  ],
210
- outputs=gr.Plot(label="Cryptocurrency Price Chart"),
211
- title="Cryptocurrency Price Chart (2024-2025)"
212
  )
213
 
214
- # Current Price Interface
215
  current_price_interface = gr.Interface(
216
  fn=fetch_current_price,
217
- inputs=gr.Dropdown(choices=top_100_cryptos, label="Cryptocurrency"),
218
  outputs=gr.Textbox(label="Current Price"),
219
- title="Current Cryptocurrency Price"
 
 
 
 
 
 
220
  )
221
 
222
- # Combining all interfaces into a single
 
4
  import plotly.graph_objs as go
5
  import time
6
 
7
+ # Fallback data for demonstration purposes
8
  fallback_historical_data = {
9
  'bitcoin': [
10
  [1633046400000, 42000], [1633132800000, 42250], [1633219200000, 41500],
 
18
  'binancecoin': 380
19
  }
20
 
21
+ # Function to fetch historical price data from CoinGecko
22
  def fetch_historical_data(coin_id, from_timestamp, to_timestamp):
23
  url = f"https://api.coingecko.com/api/v3/coins/{coin_id}/market_chart/range?vs_currency=usd&from={from_timestamp}&to={to_timestamp}"
24
+ try:
25
+ response = requests.get(url, timeout=10)
26
+ response.raise_for_status()
27
+ data = response.json()
28
+ return data['prices']
29
+ except requests.exceptions.RequestException as e:
30
+ print(f"Error fetching historical data: {e}")
31
+ return fallback_historical_data.get(coin_id, f"Error fetching historical data for {coin_id}")
 
 
32
 
33
+ # Function to fetch current prices with fallback
34
  def fetch_current_price(coin_id):
35
  gecko_url = f"https://api.coingecko.com/api/v3/simple/price?ids={coin_id}&vs_currencies=usd"
36
  compare_url = f"https://min-api.cryptocompare.com/data/price?fsym={coin_id.upper()}&tsyms=USD"
37
 
 
 
 
 
 
 
 
 
 
 
 
38
  try:
39
+ response = requests.get(gecko_url, timeout=10)
40
  response.raise_for_status()
41
  data = response.json()
42
+ return data[coin_id]['usd']
43
+ except requests.exceptions.RequestException as e:
44
+ print(f"Error fetching CoinGecko price: {e}")
45
+
46
+ # Try CryptoCompare if CoinGecko fails
47
+ try:
48
+ response = requests.get(compare_url, timeout=10)
49
+ response.raise_for_status()
50
+ data = response.json()
51
+ return data['USD']
52
+ except requests.exceptions.RequestException as e2:
53
+ print(f"Error fetching CryptoCompare price: {e2}")
54
+ return fallback_current_prices.get(coin_id, "Price not available")
55
 
56
+ # Convert date string to timestamp
57
  def date_to_timestamp(date_str):
58
  return int(pd.Timestamp(date_str).timestamp())
59
 
60
  # Function to plot historical prices using Plotly
61
  def plot_historical_prices(coin_name, from_date, to_date):
62
+ try:
63
+ from_timestamp = date_to_timestamp(from_date)
64
+ to_timestamp = date_to_timestamp(to_date)
65
+
66
+ prices = fetch_historical_data(coin_name, from_timestamp, to_timestamp)
67
+
68
+ if isinstance(prices, str):
69
+ return prices
70
+
71
+ df = pd.DataFrame(prices, columns=['timestamp', 'price'])
72
+ df['date'] = pd.to_datetime(df['timestamp'], unit='ms')
73
+
74
+ fig = go.Figure()
75
+ fig.add_trace(go.Scatter(x=df['date'], y=df['price'], mode='lines', name=coin_name))
76
+ fig.update_layout(title=f'{coin_name.capitalize()} Prices', xaxis_title='Date', yaxis_title='Price (USD)')
77
+ return fig
78
+ except Exception as e:
79
+ return f"Error in plotting chart: {e}"
80
+
81
+ # Function to analyze BTC (mock data)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  def btc_analysis():
83
+ try:
84
+ return "BTC Analysis: Market is bullish with increasing buying pressure."
85
+ except Exception as e:
86
+ return f"Error in BTC analysis: {e}"
87
+
88
+ # Function to fetch real-time trade data
 
 
 
 
 
 
 
 
 
89
  def fetch_real_time_trade_data(coin_id):
90
+ fallback_data = {'bitcoin': [1633039200000, 42000]}
 
 
 
 
91
 
92
  gecko_url = f"https://api.coingecko.com/api/v3/coins/{coin_id}/market_chart?vs_currency=usd&days=1"
 
93
 
 
 
 
 
 
 
 
 
 
 
 
94
  try:
95
+ response = requests.get(gecko_url, timeout=10)
96
  response.raise_for_status()
97
  data = response.json()
98
+ return data['prices'][-1] # Latest price data
99
+ except requests.exceptions.RequestException as e:
100
+ print(f"Error fetching trade data: {e}")
101
+ return fallback_data.get(coin_id, "Trade data not available")
102
 
103
  # Function to display real-time trade data
104
  def real_time_trade_dashboard(coin):
105
+ try:
106
+ data = fetch_real_time_trade_data(coin)
107
+ return f"The latest trade data for {coin.capitalize()}: ${data[1]}"
108
+ except Exception as e:
109
+ return f"Error in real-time trade dashboard: {e}"
 
 
 
 
 
 
110
 
111
+ # Gradio Interfaces
112
  btc_analysis_interface = gr.Interface(
113
  fn=btc_analysis,
114
  inputs=[],
115
  outputs=gr.Textbox(label="BTC Analysis"),
116
+ title="BTC Market Analysis"
117
  )
118
 
 
 
 
 
 
 
 
 
 
119
  real_time_trade_interface = gr.Interface(
120
  fn=real_time_trade_dashboard,
121
+ inputs=gr.Dropdown(choices=['bitcoin', 'ethereum'], label="Cryptocurrency"),
122
  outputs=gr.Textbox(label="Real-Time Trade Data"),
123
+ title="Real-Time Trade Data"
124
  )
125
 
 
126
  crypto_price_chart_interface = gr.Interface(
127
  fn=plot_historical_prices,
128
  inputs=[
129
+ gr.Dropdown(choices=['bitcoin', 'ethereum'], label="Cryptocurrency"),
130
  gr.Textbox(value="2024-01-01", label="From Date (YYYY-MM-DD)"),
131
  gr.Textbox(value="2025-12-31", label="To Date (YYYY-MM-DD)")
132
  ],
133
+ outputs=gr.Plot(label="Price Chart"),
134
+ title="Cryptocurrency Price Chart"
135
  )
136
 
 
137
  current_price_interface = gr.Interface(
138
  fn=fetch_current_price,
139
+ inputs=gr.Dropdown(choices=['bitcoin', 'ethereum'], label="Cryptocurrency"),
140
  outputs=gr.Textbox(label="Current Price"),
141
+ title="Current Price"
142
+ )
143
+
144
+ # Launch Gradio app
145
+ app = gr.TabbedInterface(
146
+ [btc_analysis_interface, real_time_trade_interface, crypto_price_chart_interface, current_price_interface],
147
+ ["BTC Analysis", "Real-Time Trade Data", "Price Chart", "Current Price"]
148
  )
149
 
150
+ app.launch()