dev2607's picture
Update app.py
75b661f verified
raw
history blame
6.42 kB
import streamlit as st
import yfinance as yf
import pandas as pd
from groq import Groq
import os
from duckduckgo_search import DDGS
import json
class FinancialIntelligentAgent:
def __init__(self, api_key):
self.groq_client = Groq(api_key=api_key)
self.tools = {
"stock_info": self.get_stock_info,
"news_search": self.get_duckduckgo_news,
"market_sentiment": self.analyze_market_sentiment,
"risk_assessment": self.assess_investment_risk
}
def get_stock_info(self, symbol):
"""Retrieve comprehensive stock information"""
try:
stock = yf.Ticker(symbol)
info = stock.info
return {
"basic_info": {
"Company Name": info.get('longName', 'N/A'),
"Current Price": f"${info.get('currentPrice', 'N/A'):.2f}",
"Market Cap": f"${info.get('marketCap', 'N/A'):,}",
"Sector": info.get('sector', 'N/A'),
"Industry": info.get('industry', 'N/A')
},
"financial_metrics": {
"PE Ratio": info.get('trailingPE', 'N/A'),
"Dividend Yield": f"{info.get('dividendYield', 'N/A'):.2%}",
"52 Week Range": f"${info.get('fiftyTwoWeekLow', 'N/A')} - ${info.get('fiftyTwoWeekHigh', 'N/A')}"
}
}
except Exception as e:
return {"error": str(e)}
def get_duckduckgo_news(self, symbol, limit=5):
"""Search and retrieve news about the stock"""
try:
with DDGS() as ddgs:
news_results = list(ddgs.news(f"{symbol} stock recent news", max_results=limit))
return [
{
"title": result.get('title', 'N/A'),
"link": result.get('url', ''),
"source": result.get('source', 'N/A')
} for result in news_results
]
except Exception as e:
return [{"error": str(e)}]
def analyze_market_sentiment(self, symbol, news):
"""Analyze market sentiment based on news"""
try:
news_context = "\n".join([news['title'] for news in news])
response = self.groq_client.chat.completions.create(
model="llama3-70b-8192",
messages=[
{"role": "system", "content": "You are a market sentiment analyst."},
{"role": "user", "content": f"Analyze the market sentiment for {symbol} based on these news headlines:\n{news_context}"}
]
)
return response.choices[0].message.content
except Exception as e:
return f"Sentiment analysis error: {e}"
def assess_investment_risk(self, stock_info):
"""Perform comprehensive risk assessment"""
try:
stock_context = json.dumps(stock_info, indent=2)
response = self.groq_client.chat.completions.create(
model="llama3-70b-8192",
messages=[
{"role": "system", "content": "You are a risk assessment expert in financial investments."},
{"role": "user", "content": f"Conduct a detailed investment risk assessment based on these stock details:\n{stock_context}"}
]
)
return response.choices[0].message.content
except Exception as e:
return f"Risk assessment error: {e}"
def generate_comprehensive_analysis(self, symbol):
"""Generate a comprehensive financial analysis using multiple tools"""
# Autonomous tool selection and execution
analysis_results = {}
# Step 1: Gather Stock Information
analysis_results['stock_info'] = self.tools['stock_info'](symbol)
# Step 2: Retrieve News
analysis_results['news'] = self.tools['news_search'](symbol)
# Step 3: Analyze Market Sentiment
analysis_results['market_sentiment'] = self.tools['market_sentiment'](
symbol,
analysis_results['news']
)
# Step 4: Assess Investment Risk
analysis_results['risk_assessment'] = self.tools['risk_assessment'](
analysis_results['stock_info']
)
return analysis_results
# Streamlit Application
def main():
st.title("πŸ€– Agentic AI Financial Analyst")
st.markdown("Advanced autonomous financial intelligence platform")
# API Key Management
groq_api_key = st.secrets.get("GROQ_API_KEY") or os.getenv("GROQ_API_KEY")
if not groq_api_key:
st.error("Groq API Key is required!")
return
# Initialize Intelligent Agent
agent = FinancialIntelligentAgent(groq_api_key)
# Stock Symbol Input
stock_symbol = st.text_input(
"Enter Stock Symbol",
value="NVDA",
help="Enter a valid stock ticker"
)
# Analysis Button
if st.button("Generate Comprehensive Analysis"):
with st.spinner("Autonomous analysis in progress..."):
try:
# Execute Agentic Analysis
analysis_results = agent.generate_comprehensive_analysis(stock_symbol)
# Display Stock Information
st.subheader(f"πŸ“Š Stock Overview: {stock_symbol}")
st.json(analysis_results['stock_info'])
# Display News
st.subheader("πŸ“° Recent News")
for news in analysis_results['news']:
st.markdown(f"**{news.get('title', 'N/A')}**")
st.markdown(f"[Read more]({news.get('link', '#')})")
st.markdown("---")
# Display Market Sentiment
st.subheader("πŸ“ˆ Market Sentiment Analysis")
st.write(analysis_results['market_sentiment'])
# Display Risk Assessment
st.subheader("βš–οΈ Investment Risk Assessment")
st.write(analysis_results['risk_assessment'])
except Exception as e:
st.error(f"Analysis failed: {e}")
st.sidebar.warning(
"🚨 Disclaimer: AI-generated insights. "
"Consult financial professionals for decisions."
)
if __name__ == "__main__":
main()