Crypto-Analyst / app.py
menikev's picture
Update app.py
08ff8b3 verified
import streamlit as st
import plotly.graph_objs as go
import plotly.express as px
from plotly.subplots import make_subplots
from main import CryptoCrew
import time
import os
import pandas as pd
st.set_page_config(page_title="Advanced Crypto Analyst", page_icon="πŸ“ˆ", layout="wide")
# Custom CSS for better styling
st.markdown("""
<style>
.metric-card {
background-color: #f0f2f6;
padding: 1rem;
border-radius: 0.5rem;
margin: 0.5rem 0;
}
.positive { color: #00ff00; }
.negative { color: #ff0000; }
.neutral { color: #808080; }
</style>
""", unsafe_allow_html=True)
st.title("⚑ Advanced Crypto Analyst")
st.markdown("*Powered by Together AI with Enhanced Multi-Agent Analysis*")
# Enhanced caching with longer TTL for detailed analysis
@st.cache_data(ttl=600) # Cache for 10 minutes
def analyze_crypto(crypto_name):
crypto_crew = CryptoCrew(crypto_name.lower())
return crypto_crew.run()
# Input section
col1, col2 = st.columns([3, 1])
with col1:
crypto = st.text_input("Enter cryptocurrency name:", placeholder="bitcoin, ethereum, solana, cardano...")
with col2:
st.markdown("<br>", unsafe_allow_html=True)
analyze_btn = st.button("πŸš€ Analyze", type="primary", use_container_width=True)
if analyze_btn and crypto:
start_time = time.time()
with st.spinner("πŸ” Performing comprehensive analysis... This may take 30-60 seconds for detailed results!"):
try:
result = analyze_crypto(crypto)
end_time = time.time()
# Enhanced header metrics
st.markdown("## πŸ“Š Analysis Dashboard")
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("Analysis Time", f"{end_time - start_time:.1f}s", "βœ… Complete")
with col2:
rec = result.get("recommendation", {}).get("action", "HOLD")
confidence = result.get("recommendation", {}).get("confidence", "Medium")
st.metric("Recommendation", rec, f"Confidence: {confidence}")
with col3:
risk = result.get("risk_assessment", "Moderate Risk")
st.metric("Risk Level", risk)
with col4:
last_updated = result.get("last_updated", "Unknown")
st.metric("Last Updated", last_updated.split()[1] if " " in last_updated else "N/A")
# Market Data Section
st.markdown("## πŸ’° Market Metrics")
market_data = result.get("market_data", {})
col1, col2, col3 = st.columns(3)
with col1:
price = market_data.get("current_price", "N/A")
price_change_24h = market_data.get("price_change_24h", "N/A")
st.metric("Current Price", price, price_change_24h)
with col2:
market_cap = market_data.get("market_cap", "N/A")
st.metric("Market Cap", market_cap)
with col3:
volume_24h = market_data.get("volume_24h", "N/A")
st.metric("24h Volume", volume_24h)
col4, col5, col6 = st.columns(3)
with col4:
price_change_7d = market_data.get("price_change_7d", "N/A")
st.metric("7-Day Change", price_change_7d)
with col5:
dominance = market_data.get("market_dominance", "N/A")
st.metric("Market Dominance", dominance)
with col6:
st.metric("Analysis Depth", "Advanced", "🎯 Multi-Agent")
# Technical Analysis Section
st.markdown("## πŸ“ˆ Technical Analysis")
technical_data = result.get("technical_data", {})
col1, col2 = st.columns(2)
with col1:
rsi = technical_data.get("rsi", "N/A")
rsi_signal = technical_data.get("rsi_signal", "Neutral")
st.metric("RSI (14)", rsi, rsi_signal)
trend = technical_data.get("trend", "Neutral")
st.metric("Current Trend", trend)
with col2:
ma_7d = technical_data.get("moving_average_7d", "N/A")
st.metric("7-Day MA", ma_7d)
support = technical_data.get("support_level", "N/A")
resistance = technical_data.get("resistance_level", "N/A")
st.metric("Support | Resistance", f"{support} | {resistance}")
# Enhanced Sentiment Analysis with Fixed Chart
st.markdown("## πŸ’­ Multi-Source Sentiment Analysis")
sentiment_data = result.get("sentiment", {})
# Create properly differentiated sentiment chart
categories = list(sentiment_data.keys())
values = []
colors = []
sentiment_texts = []
for category, sentiment in sentiment_data.items():
sentiment_texts.append(sentiment)
if sentiment == "Positive":
values.append(1)
colors.append('#00C851') # Green
elif sentiment == "Negative":
values.append(-1)
colors.append('#FF4444') # Red
else:
values.append(0)
colors.append('#FFBB33') # Orange for neutral
# Create sentiment visualization
fig = go.Figure(data=[go.Bar(
x=categories,
y=values,
marker_color=colors,
text=sentiment_texts,
textposition='auto',
hovertemplate='<b>%{x}</b><br>Sentiment: %{text}<br>Score: %{y}<extra></extra>'
)])
fig.update_layout(
title="Sentiment Distribution Across Sources",
xaxis_title="Analysis Source",
yaxis_title="Sentiment Score",
yaxis=dict(
tickvals=[-1, 0, 1],
ticktext=["Negative", "Neutral", "Positive"],
range=[-1.2, 1.2]
),
height=500,
showlegend=False,
plot_bgcolor='rgba(0,0,0,0)',
paper_bgcolor='rgba(0,0,0,0)'
)
st.plotly_chart(fig, use_container_width=True)
# Sentiment Details
col1, col2, col3, col4 = st.columns(4)
sentiments = ["overall", "social_media", "news", "community"]
columns = [col1, col2, col3, col4]
for sentiment_type, col in zip(sentiments, columns):
sentiment_val = sentiment_data.get(sentiment_type, "Neutral")
color_class = "positive" if sentiment_val == "Positive" else "negative" if sentiment_val == "Negative" else "neutral"
col.markdown(f"**{sentiment_type.replace('_', ' ').title()}**")
col.markdown(f'<span class="{color_class}">{sentiment_val}</span>', unsafe_allow_html=True)
# Investment Recommendation Section
st.markdown("## 🎯 Investment Recommendation")
recommendation = result.get("recommendation", {})
action = recommendation.get("action", "HOLD")
confidence = recommendation.get("confidence", "Medium")
reasoning = recommendation.get("reasoning", "Standard analysis completed")
# Color-coded recommendation
rec_colors = {"BUY": "🟒", "SELL": "πŸ”΄", "HOLD": "🟑"}
rec_bg_colors = {"BUY": "#d4edda", "SELL": "#f8d7da", "HOLD": "#fff3cd"}
st.markdown(f"""
<div style="background-color: {rec_bg_colors.get(action, '#f8f9fa')};
padding: 1rem; border-radius: 0.5rem; margin: 1rem 0;">
<h3>{rec_colors.get(action, '🟑')} Investment Recommendation: {action}</h3>
<p><strong>Confidence Level:</strong> {confidence}</p>
<p><strong>Reasoning:</strong> {reasoning}</p>
</div>
""", unsafe_allow_html=True)
# Additional recommendation details
col1, col2, col3 = st.columns(3)
with col1:
time_horizon = recommendation.get("time_horizon", "Medium-term")
st.info(f"**Time Horizon:** {time_horizon}")
with col2:
risk_level = recommendation.get("risk_level", "Moderate")
st.info(f"**Risk Level:** {risk_level}")
with col3:
st.info(f"**Analysis Type:** Multi-Agent AI")
# Detailed Analysis Summary
st.markdown("## πŸ“‹ Detailed Analysis Summary")
with st.expander("View Full Analysis Report", expanded=False):
st.write(result.get("summary", "No detailed summary available"))
# Risk Assessment
st.markdown("## ⚠️ Risk Assessment")
st.warning(f"**Risk Level:** {result.get('risk_assessment', 'Moderate Risk')}")
except Exception as e:
st.error(f"Analysis failed: {str(e)}")
st.info("""
πŸ’‘ **Troubleshooting Tips:**
- Use full cryptocurrency names (e.g., 'bitcoin' not 'btc')
- Ensure your API key is properly configured
- Try again if the analysis times out
- Check network connectivity
""")
# Enhanced Sidebar
with st.sidebar:
st.header("βš™οΈ System Status")
# API Status Check
api_key_status = "βœ… Connected" if os.getenv("TOGETHER_API_KEY") else "❌ Missing API Key"
st.write(f"**Together AI:** {api_key_status}")
if not os.getenv("TOGETHER_API_KEY"):
st.error("Add TOGETHER_API_KEY to your environment variables")
else:
st.success("API Configuration Valid")
st.markdown("---")
st.markdown("### πŸ“Š Analysis Features")
st.markdown("""
βœ… **Market Data Analysis**
- Real-time price & volume
- Market cap & dominance
- Price change tracking
βœ… **Technical Analysis**
- RSI & Moving Averages
- Support/Resistance levels
- Trend identification
βœ… **Sentiment Analysis**
- Social media monitoring
- News sentiment tracking
- Community analysis
βœ… **AI Recommendations**
- Multi-agent analysis
- Risk assessment
- Entry/exit strategies
""")
st.markdown("---")
st.markdown("### ⚑ Performance")
st.markdown("""
- **Analysis Time:** 30-60s
- **Model:** Llama 3.1 8B Turbo
- **Agents:** 3 Specialized AI Agents
- **Data Sources:** Multiple APIs
""")
# Footer
st.markdown("---")
st.markdown("### πŸš€ Advanced Analytics Dashboard")
cols = st.columns(4)
with cols[0]:
st.metric("AI Agents", "3", "πŸ€– Specialized")
with cols[1]:
st.metric("Data Sources", "Multiple", "πŸ”„ Real-time")
with cols[2]:
st.metric("Analysis Depth", "Professional", "⭐ Institutional Grade")
with cols[3]:
st.metric("Update Frequency", "Real-time", "πŸ• Live Data")