menikev commited on
Commit
08ff8b3
Β·
verified Β·
1 Parent(s): b23e8ef

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +216 -52
app.py CHANGED
@@ -1,123 +1,287 @@
1
  import streamlit as st
2
  import plotly.graph_objs as go
 
 
3
  from main import CryptoCrew
4
- import asyncio
5
  import time
6
  import os
 
7
 
8
- st.set_page_config(page_title="Crypto Analyst", page_icon="πŸ“ˆ", layout="wide")
9
 
10
- st.title("⚑Crypto Analyst")
11
- st.markdown("*Powered by Together AI for lightning-fast analysis*")
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
- # Add caching for repeated analyses
14
- @st.cache_data(ttl=300) # Cache for 5 minutes
 
 
 
15
  def analyze_crypto(crypto_name):
16
  crypto_crew = CryptoCrew(crypto_name.lower())
17
  return crypto_crew.run()
18
 
19
- col1, col2 = st.columns([2, 1])
20
-
21
  with col1:
22
- crypto = st.text_input("Enter cryptocurrency name:", placeholder="bitcoin, ethereum, cardano...")
23
 
24
  with col2:
25
  st.markdown("<br>", unsafe_allow_html=True)
26
- analyze_btn = st.button("πŸš€ Analyze", type="primary")
27
 
28
  if analyze_btn and crypto:
29
  start_time = time.time()
30
 
31
- with st.spinner("πŸ” Analyzing... This should only take 10-30 seconds!"):
32
  try:
33
  result = analyze_crypto(crypto)
34
  end_time = time.time()
35
 
36
- # Success metrics
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  col1, col2, col3 = st.columns(3)
38
  with col1:
39
- st.metric("Analysis Time", f"{end_time - start_time:.1f}s")
 
 
 
40
  with col2:
41
- st.metric("Recommendation", result.get("recommendation", "HOLD"))
 
 
42
  with col3:
43
- st.metric("Confidence", result.get("confidence", "Medium"))
 
44
 
45
- # Display summary
46
- st.subheader("πŸ“Š Analysis Summary")
47
- st.write(result["summary"])
 
 
 
 
 
 
 
 
 
 
48
 
49
- # Enhanced sentiment visualization
50
- st.subheader("πŸ’­ Sentiment Analysis")
51
- sentiment_data = result["sentiment"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
- # Create sentiment chart
54
  categories = list(sentiment_data.keys())
55
  values = []
56
  colors = []
 
57
 
58
- for sentiment in sentiment_data.values():
 
59
  if sentiment == "Positive":
60
  values.append(1)
61
- colors.append('#00ff00')
62
  elif sentiment == "Negative":
63
  values.append(-1)
64
- colors.append('#ff0000')
65
  else:
66
  values.append(0)
67
- colors.append('#808080')
68
 
 
69
  fig = go.Figure(data=[go.Bar(
70
  x=categories,
71
  y=values,
72
  marker_color=colors,
73
- text=[sentiment_data[cat] for cat in categories],
74
- textposition='auto'
 
75
  )])
76
 
77
  fig.update_layout(
78
- title="Sentiment Distribution",
79
- xaxis_title="Analysis Category",
80
  yaxis_title="Sentiment Score",
81
- yaxis=dict(tickvals=[-1, 0, 1], ticktext=["Negative", "Neutral", "Positive"]),
82
- height=400,
83
- showlegend=False
 
 
 
 
 
 
84
  )
85
 
86
  st.plotly_chart(fig, use_container_width=True)
87
 
88
- # Recommendation box
89
- rec_color = {"BUY": "🟒", "SELL": "πŸ”΄", "HOLD": "🟑"}
90
- st.info(f"{rec_color.get(result.get('recommendation', 'HOLD'), '🟑')} **Investment Recommendation: {result.get('recommendation', 'HOLD')}**")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
 
92
  except Exception as e:
93
  st.error(f"Analysis failed: {str(e)}")
94
- st.info("πŸ’‘ **Tips:**\n- Use full cryptocurrency names (e.g., 'bitcoin' not 'btc')\n- Check your API key setup\n- Try again if the first attempt fails")
 
 
 
 
 
 
95
 
96
- # Sidebar with setup info
97
  with st.sidebar:
98
- st.header("βš™οΈ Setup Status")
99
 
100
- # Check if API key is available
101
- import os
102
  api_key_status = "βœ… Connected" if os.getenv("TOGETHER_API_KEY") else "❌ Missing API Key"
103
- st.write(f"Together AI: {api_key_status}")
104
 
105
  if not os.getenv("TOGETHER_API_KEY"):
106
- st.error("Add TOGETHER_API_KEY as a secret in HF Spaces settings")
 
 
107
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  st.markdown("""
109
- **Expected Performance:**
110
- - Analysis Time: 10-30s
111
- - Memory Usage: ~50MB
112
- - No local model loading
113
  """)
114
 
 
115
  st.markdown("---")
116
- st.markdown("### πŸš€ System Status")
117
- cols = st.columns(3)
118
  with cols[0]:
119
- st.metric("Model Loading", "0s", "βœ… Cloud-based")
120
  with cols[1]:
121
- st.metric("Memory Usage", "~50MB", "βœ… Optimized")
122
  with cols[2]:
123
- st.metric("API Status", "Ready" if os.getenv("TOGETHER_API_KEY") else "Setup Needed", "πŸ”„")
 
 
 
1
  import streamlit as st
2
  import plotly.graph_objs as go
3
+ import plotly.express as px
4
+ from plotly.subplots import make_subplots
5
  from main import CryptoCrew
 
6
  import time
7
  import os
8
+ import pandas as pd
9
 
10
+ st.set_page_config(page_title="Advanced Crypto Analyst", page_icon="πŸ“ˆ", layout="wide")
11
 
12
+ # Custom CSS for better styling
13
+ st.markdown("""
14
+ <style>
15
+ .metric-card {
16
+ background-color: #f0f2f6;
17
+ padding: 1rem;
18
+ border-radius: 0.5rem;
19
+ margin: 0.5rem 0;
20
+ }
21
+ .positive { color: #00ff00; }
22
+ .negative { color: #ff0000; }
23
+ .neutral { color: #808080; }
24
+ </style>
25
+ """, unsafe_allow_html=True)
26
 
27
+ st.title("⚑ Advanced Crypto Analyst")
28
+ st.markdown("*Powered by Together AI with Enhanced Multi-Agent Analysis*")
29
+
30
+ # Enhanced caching with longer TTL for detailed analysis
31
+ @st.cache_data(ttl=600) # Cache for 10 minutes
32
  def analyze_crypto(crypto_name):
33
  crypto_crew = CryptoCrew(crypto_name.lower())
34
  return crypto_crew.run()
35
 
36
+ # Input section
37
+ col1, col2 = st.columns([3, 1])
38
  with col1:
39
+ crypto = st.text_input("Enter cryptocurrency name:", placeholder="bitcoin, ethereum, solana, cardano...")
40
 
41
  with col2:
42
  st.markdown("<br>", unsafe_allow_html=True)
43
+ analyze_btn = st.button("πŸš€ Analyze", type="primary", use_container_width=True)
44
 
45
  if analyze_btn and crypto:
46
  start_time = time.time()
47
 
48
+ with st.spinner("πŸ” Performing comprehensive analysis... This may take 30-60 seconds for detailed results!"):
49
  try:
50
  result = analyze_crypto(crypto)
51
  end_time = time.time()
52
 
53
+ # Enhanced header metrics
54
+ st.markdown("## πŸ“Š Analysis Dashboard")
55
+
56
+ col1, col2, col3, col4 = st.columns(4)
57
+ with col1:
58
+ st.metric("Analysis Time", f"{end_time - start_time:.1f}s", "βœ… Complete")
59
+ with col2:
60
+ rec = result.get("recommendation", {}).get("action", "HOLD")
61
+ confidence = result.get("recommendation", {}).get("confidence", "Medium")
62
+ st.metric("Recommendation", rec, f"Confidence: {confidence}")
63
+ with col3:
64
+ risk = result.get("risk_assessment", "Moderate Risk")
65
+ st.metric("Risk Level", risk)
66
+ with col4:
67
+ last_updated = result.get("last_updated", "Unknown")
68
+ st.metric("Last Updated", last_updated.split()[1] if " " in last_updated else "N/A")
69
+
70
+ # Market Data Section
71
+ st.markdown("## πŸ’° Market Metrics")
72
+ market_data = result.get("market_data", {})
73
+
74
  col1, col2, col3 = st.columns(3)
75
  with col1:
76
+ price = market_data.get("current_price", "N/A")
77
+ price_change_24h = market_data.get("price_change_24h", "N/A")
78
+ st.metric("Current Price", price, price_change_24h)
79
+
80
  with col2:
81
+ market_cap = market_data.get("market_cap", "N/A")
82
+ st.metric("Market Cap", market_cap)
83
+
84
  with col3:
85
+ volume_24h = market_data.get("volume_24h", "N/A")
86
+ st.metric("24h Volume", volume_24h)
87
 
88
+ col4, col5, col6 = st.columns(3)
89
+ with col4:
90
+ price_change_7d = market_data.get("price_change_7d", "N/A")
91
+ st.metric("7-Day Change", price_change_7d)
92
+ with col5:
93
+ dominance = market_data.get("market_dominance", "N/A")
94
+ st.metric("Market Dominance", dominance)
95
+ with col6:
96
+ st.metric("Analysis Depth", "Advanced", "🎯 Multi-Agent")
97
+
98
+ # Technical Analysis Section
99
+ st.markdown("## πŸ“ˆ Technical Analysis")
100
+ technical_data = result.get("technical_data", {})
101
 
102
+ col1, col2 = st.columns(2)
103
+ with col1:
104
+ rsi = technical_data.get("rsi", "N/A")
105
+ rsi_signal = technical_data.get("rsi_signal", "Neutral")
106
+ st.metric("RSI (14)", rsi, rsi_signal)
107
+
108
+ trend = technical_data.get("trend", "Neutral")
109
+ st.metric("Current Trend", trend)
110
+
111
+ with col2:
112
+ ma_7d = technical_data.get("moving_average_7d", "N/A")
113
+ st.metric("7-Day MA", ma_7d)
114
+
115
+ support = technical_data.get("support_level", "N/A")
116
+ resistance = technical_data.get("resistance_level", "N/A")
117
+ st.metric("Support | Resistance", f"{support} | {resistance}")
118
+
119
+ # Enhanced Sentiment Analysis with Fixed Chart
120
+ st.markdown("## πŸ’­ Multi-Source Sentiment Analysis")
121
+ sentiment_data = result.get("sentiment", {})
122
 
123
+ # Create properly differentiated sentiment chart
124
  categories = list(sentiment_data.keys())
125
  values = []
126
  colors = []
127
+ sentiment_texts = []
128
 
129
+ for category, sentiment in sentiment_data.items():
130
+ sentiment_texts.append(sentiment)
131
  if sentiment == "Positive":
132
  values.append(1)
133
+ colors.append('#00C851') # Green
134
  elif sentiment == "Negative":
135
  values.append(-1)
136
+ colors.append('#FF4444') # Red
137
  else:
138
  values.append(0)
139
+ colors.append('#FFBB33') # Orange for neutral
140
 
141
+ # Create sentiment visualization
142
  fig = go.Figure(data=[go.Bar(
143
  x=categories,
144
  y=values,
145
  marker_color=colors,
146
+ text=sentiment_texts,
147
+ textposition='auto',
148
+ hovertemplate='<b>%{x}</b><br>Sentiment: %{text}<br>Score: %{y}<extra></extra>'
149
  )])
150
 
151
  fig.update_layout(
152
+ title="Sentiment Distribution Across Sources",
153
+ xaxis_title="Analysis Source",
154
  yaxis_title="Sentiment Score",
155
+ yaxis=dict(
156
+ tickvals=[-1, 0, 1],
157
+ ticktext=["Negative", "Neutral", "Positive"],
158
+ range=[-1.2, 1.2]
159
+ ),
160
+ height=500,
161
+ showlegend=False,
162
+ plot_bgcolor='rgba(0,0,0,0)',
163
+ paper_bgcolor='rgba(0,0,0,0)'
164
  )
165
 
166
  st.plotly_chart(fig, use_container_width=True)
167
 
168
+ # Sentiment Details
169
+ col1, col2, col3, col4 = st.columns(4)
170
+ sentiments = ["overall", "social_media", "news", "community"]
171
+ columns = [col1, col2, col3, col4]
172
+
173
+ for sentiment_type, col in zip(sentiments, columns):
174
+ sentiment_val = sentiment_data.get(sentiment_type, "Neutral")
175
+ color_class = "positive" if sentiment_val == "Positive" else "negative" if sentiment_val == "Negative" else "neutral"
176
+ col.markdown(f"**{sentiment_type.replace('_', ' ').title()}**")
177
+ col.markdown(f'<span class="{color_class}">{sentiment_val}</span>', unsafe_allow_html=True)
178
+
179
+ # Investment Recommendation Section
180
+ st.markdown("## 🎯 Investment Recommendation")
181
+ recommendation = result.get("recommendation", {})
182
+
183
+ action = recommendation.get("action", "HOLD")
184
+ confidence = recommendation.get("confidence", "Medium")
185
+ reasoning = recommendation.get("reasoning", "Standard analysis completed")
186
+
187
+ # Color-coded recommendation
188
+ rec_colors = {"BUY": "🟒", "SELL": "πŸ”΄", "HOLD": "🟑"}
189
+ rec_bg_colors = {"BUY": "#d4edda", "SELL": "#f8d7da", "HOLD": "#fff3cd"}
190
+
191
+ st.markdown(f"""
192
+ <div style="background-color: {rec_bg_colors.get(action, '#f8f9fa')};
193
+ padding: 1rem; border-radius: 0.5rem; margin: 1rem 0;">
194
+ <h3>{rec_colors.get(action, '🟑')} Investment Recommendation: {action}</h3>
195
+ <p><strong>Confidence Level:</strong> {confidence}</p>
196
+ <p><strong>Reasoning:</strong> {reasoning}</p>
197
+ </div>
198
+ """, unsafe_allow_html=True)
199
+
200
+ # Additional recommendation details
201
+ col1, col2, col3 = st.columns(3)
202
+ with col1:
203
+ time_horizon = recommendation.get("time_horizon", "Medium-term")
204
+ st.info(f"**Time Horizon:** {time_horizon}")
205
+ with col2:
206
+ risk_level = recommendation.get("risk_level", "Moderate")
207
+ st.info(f"**Risk Level:** {risk_level}")
208
+ with col3:
209
+ st.info(f"**Analysis Type:** Multi-Agent AI")
210
+
211
+ # Detailed Analysis Summary
212
+ st.markdown("## πŸ“‹ Detailed Analysis Summary")
213
+ with st.expander("View Full Analysis Report", expanded=False):
214
+ st.write(result.get("summary", "No detailed summary available"))
215
+
216
+ # Risk Assessment
217
+ st.markdown("## ⚠️ Risk Assessment")
218
+ st.warning(f"**Risk Level:** {result.get('risk_assessment', 'Moderate Risk')}")
219
 
220
  except Exception as e:
221
  st.error(f"Analysis failed: {str(e)}")
222
+ st.info("""
223
+ πŸ’‘ **Troubleshooting Tips:**
224
+ - Use full cryptocurrency names (e.g., 'bitcoin' not 'btc')
225
+ - Ensure your API key is properly configured
226
+ - Try again if the analysis times out
227
+ - Check network connectivity
228
+ """)
229
 
230
+ # Enhanced Sidebar
231
  with st.sidebar:
232
+ st.header("βš™οΈ System Status")
233
 
234
+ # API Status Check
 
235
  api_key_status = "βœ… Connected" if os.getenv("TOGETHER_API_KEY") else "❌ Missing API Key"
236
+ st.write(f"**Together AI:** {api_key_status}")
237
 
238
  if not os.getenv("TOGETHER_API_KEY"):
239
+ st.error("Add TOGETHER_API_KEY to your environment variables")
240
+ else:
241
+ st.success("API Configuration Valid")
242
 
243
+ st.markdown("---")
244
+ st.markdown("### πŸ“Š Analysis Features")
245
+ st.markdown("""
246
+ βœ… **Market Data Analysis**
247
+ - Real-time price & volume
248
+ - Market cap & dominance
249
+ - Price change tracking
250
+
251
+ βœ… **Technical Analysis**
252
+ - RSI & Moving Averages
253
+ - Support/Resistance levels
254
+ - Trend identification
255
+
256
+ βœ… **Sentiment Analysis**
257
+ - Social media monitoring
258
+ - News sentiment tracking
259
+ - Community analysis
260
+
261
+ βœ… **AI Recommendations**
262
+ - Multi-agent analysis
263
+ - Risk assessment
264
+ - Entry/exit strategies
265
+ """)
266
+
267
+ st.markdown("---")
268
+ st.markdown("### ⚑ Performance")
269
  st.markdown("""
270
+ - **Analysis Time:** 30-60s
271
+ - **Model:** Llama 3.1 8B Turbo
272
+ - **Agents:** 3 Specialized AI Agents
273
+ - **Data Sources:** Multiple APIs
274
  """)
275
 
276
+ # Footer
277
  st.markdown("---")
278
+ st.markdown("### πŸš€ Advanced Analytics Dashboard")
279
+ cols = st.columns(4)
280
  with cols[0]:
281
+ st.metric("AI Agents", "3", "πŸ€– Specialized")
282
  with cols[1]:
283
+ st.metric("Data Sources", "Multiple", "πŸ”„ Real-time")
284
  with cols[2]:
285
+ st.metric("Analysis Depth", "Professional", "⭐ Institutional Grade")
286
+ with cols[3]:
287
+ st.metric("Update Frequency", "Real-time", "πŸ• Live Data")