missbaj commited on
Commit
d56614c
·
verified ·
1 Parent(s): f1bc452
Files changed (1) hide show
  1. app.py +160 -0
app.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import requests
3
+ import pandas as pd
4
+ import plotly.graph_objs as go
5
+ import time
6
+
7
+ # Function to fetch historical price data from CoinGecko
8
+ def fetch_historical_data(coin_id, from_timestamp, to_timestamp):
9
+ url = f"https://api.coingecko.com/api/v3/coins/{coin_id}/market_chart/range?vs_currency=usd&from={from_timestamp}&to={to_timestamp}"
10
+ try:
11
+ response = requests.get(url)
12
+ response.raise_for_status()
13
+ data = response.json()
14
+ prices = data.get('prices', [])
15
+ return prices
16
+ except requests.RequestException as e:
17
+ return f"Error fetching historical data for {coin_id}: {e}"
18
+
19
+ # Function to fetch current prices from CoinGecko
20
+ def fetch_current_price(coin_id):
21
+ url = f"https://api.coingecko.com/api/v3/simple/price?ids={coin_id}&vs_currencies=usd"
22
+ try:
23
+ response = requests.get(url)
24
+ response.raise_for_status()
25
+ data = response.json()
26
+ return data.get(coin_id, {}).get('usd', 'N/A')
27
+ except requests.RequestException as e:
28
+ return f"Error fetching current price for {coin_id}: {e}"
29
+
30
+ # Function to convert dates to timestamps
31
+ def date_to_timestamp(date_str):
32
+ return int(pd.Timestamp(date_str).timestamp())
33
+
34
+ # Function to plot historical prices using Plotly
35
+ def plot_historical_prices(coin_name, from_date, to_date):
36
+ from_timestamp = date_to_timestamp(from_date)
37
+ to_timestamp = date_to_timestamp(to_date)
38
+
39
+ prices = fetch_historical_data(coin_name, from_timestamp, to_timestamp)
40
+
41
+ if isinstance(prices, str): # In case of error
42
+ return prices
43
+
44
+ try:
45
+ df = pd.DataFrame(prices, columns=['timestamp', 'price'])
46
+ df['date'] = pd.to_datetime(df['timestamp'], unit='ms')
47
+
48
+ fig = go.Figure()
49
+ fig.add_trace(go.Scatter(x=df['date'], y=df['price'], mode='lines', name=coin_name))
50
+ fig.update_layout(title=f'{coin_name.capitalize()} Prices from {from_date} to {to_date}', xaxis_title='Date', yaxis_title='Price (USD)')
51
+ return fig
52
+ except Exception as e:
53
+ return f"Error plotting historical prices: {e}"
54
+
55
+ # Function to provide TradingView widget HTML
56
+ def tradingview_widget():
57
+ return """
58
+ <iframe
59
+ src="https://www.tradingview.com/widgetembed/?frameElementId=tradingview_ea33b&symbol=BINANCE:BTCUSDT&interval=60"
60
+ width="800"
61
+ height="600"
62
+ frameborder="0"
63
+ allowtransparency="true"
64
+ scrolling="no"
65
+ allowfullscreen="true">
66
+ </iframe>
67
+ """
68
+
69
+ # Functions for mocked analyses
70
+ def analyze_order_book():
71
+ return "Order book analysis: Buying pressure above, selling pressure below."
72
+
73
+ def analyze_technicals():
74
+ return "Technical analysis: Divergence detected, RSI showing overbought."
75
+
76
+ def analyze_funding_rate():
77
+ return "Funding rate: Higher on longs, suggesting bullish sentiment."
78
+
79
+ def analyze_on_chain():
80
+ return "On-chain analysis: Ichimoku cloud shows potential reversal."
81
+
82
+ def analyze_news():
83
+ return "News analysis: Positive sentiment with increasing institutional interest."
84
+
85
+ def btc_analysis():
86
+ order_book = analyze_order_book()
87
+ technicals = analyze_technicals()
88
+ funding_rate = analyze_funding_rate()
89
+ on_chain = analyze_on_chain()
90
+ news = analyze_news()
91
+
92
+ return f"""
93
+ {order_book}
94
+ {technicals}
95
+ {funding_rate}
96
+ {on_chain}
97
+ {news}
98
+ """
99
+
100
+ # Function to fetch real-time trade data from CoinGecko
101
+ def fetch_real_time_trade_data(coin_id):
102
+ url = f"https://api.coingecko.com/api/v3/coins/{coin_id}/market_chart?vs_currency=usd&days=1"
103
+ try:
104
+ response = requests.get(url)
105
+ response.raise_for_status()
106
+ data = response.json()
107
+ prices = data.get('prices', [])
108
+ if prices:
109
+ return prices[-1] # Latest price data
110
+ return "No real-time data available"
111
+ except requests.RequestException as e:
112
+ return f"Error fetching real-time trade data for {coin_id}: {e}"
113
+
114
+ # Streamlit App Layout
115
+ st.title("Cryptocurrency Dashboard")
116
+
117
+ # Dropdown for selecting cryptocurrency
118
+ top_100_cryptos = [
119
+ 'bitcoin', 'ethereum', 'binancecoin', 'ripple', 'solana', 'cardano', 'dogecoin', 'polygon', 'polkadot', 'tron',
120
+ # Add more top coins as necessary
121
+ ]
122
+
123
+ selected_crypto = st.sidebar.selectbox("Select Cryptocurrency", top_100_cryptos)
124
+
125
+ # Tabs for different functionalities
126
+ tab = st.sidebar.radio("Choose a Tab", ["Price Chart", "Current Price", "Real-Time Trade Data", "AI BTC Analysis", "TradingView Chart"])
127
+
128
+ if tab == "Price Chart":
129
+ st.header("Cryptocurrency Price Chart")
130
+ from_date = st.date_input("From Date", value=pd.Timestamp("2024-01-01"))
131
+ to_date = st.date_input("To Date", value=pd.Timestamp("2025-12-31"))
132
+
133
+ if st.button("Plot Chart"):
134
+ fig = plot_historical_prices(selected_crypto, from_date, to_date)
135
+ if isinstance(fig, str): # In case of error
136
+ st.error(fig)
137
+ else:
138
+ st.plotly_chart(fig)
139
+
140
+ elif tab == "Current Price":
141
+ st.header("Current Cryptocurrency Price")
142
+ price = fetch_current_price(selected_crypto)
143
+ st.write(f"The current price of {selected_crypto.capitalize()} is: ${price}")
144
+
145
+ elif tab == "Real-Time Trade Data":
146
+ st.header("Real-Time Cryptocurrency Trade Data")
147
+ data = fetch_real_time_trade_data(selected_crypto)
148
+ if isinstance(data, str): # In case of error
149
+ st.error(data)
150
+ else:
151
+ st.write(f"The latest trading data for {selected_crypto.capitalize()} is: ${data[1]}")
152
+
153
+ elif tab == "AI BTC Analysis":
154
+ st.header("AI-Powered BTC Analysis")
155
+ analysis = btc_analysis()
156
+ st.write(analysis)
157
+
158
+ elif tab == "TradingView Chart":
159
+ st.header("Live TradingView Chart")
160
+ st.markdown(tradingview_widget(), unsafe_allow_html=True)