dev2607 commited on
Commit
1ee6e16
·
verified ·
1 Parent(s): f1aae64

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +102 -72
app.py CHANGED
@@ -1,8 +1,7 @@
1
  import streamlit as st
2
- from phi.agent import Agent
3
- from phi.model.groq import Groq
4
- from phi.tools.duckduckgo import DuckDuckGo
5
- from phi.tools.yfinance import YFinanceTools
6
  import os
7
 
8
  # Streamlit App Configuration
@@ -12,52 +11,89 @@ st.set_page_config(
12
  layout="wide"
13
  )
14
 
15
- # Web Search Agent
16
- def create_web_search_agent():
17
- return Agent(
18
- name="Web Search Agent",
19
- role="Search the web for information",
20
- model=Groq(id="llama-3.2-3b-preview"),
21
- tools=[DuckDuckGo()],
22
- instructions=["Always include sources"],
23
- show_tools_call=True,
24
- markdown=True,
25
- )
26
 
27
- # Financial Agent
28
- def create_financial_agent():
29
- return Agent(
30
- name="Finance AI Agent",
31
- role="Analyze financial data and provide insights",
32
- model=Groq(id="llama-3.2-3b-preview"),
33
- tools=[
34
- YFinanceTools(
35
- stock_price=True,
36
- analyst_recommendations=True,
37
- stock_fundamentals=True,
38
- company_news=True
39
- )
40
- ],
41
- instructions=["Use tables to display the data"],
42
- show_tools_call=True,
43
- markdown=True,
44
- )
 
 
 
 
 
 
 
 
 
 
45
 
46
- # Create Multi-Agent
47
- multi_ai_agent = Agent(
48
- team=[create_web_search_agent(), create_financial_agent()],
49
- instructions=[
50
- "Always include sources",
51
- "Use tables to display the data"
52
- ],
53
- show_tools_call=True,
54
- markdown=True,
55
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
- # Streamlit App
58
  def main():
59
  st.title("🤖 Financial Analysis AI Agent")
60
- st.write("Get comprehensive financial insights using AI-powered web search and analysis!")
61
 
62
  # Sidebar for configuration
63
  st.sidebar.header("🔧 Query Configuration")
@@ -73,41 +109,35 @@ def main():
73
  query_type = st.sidebar.selectbox(
74
  "Select Analysis Type",
75
  [
 
76
  "Analyst Recommendations",
77
  "Latest Company News",
78
- "Stock Fundamentals",
79
- "Comprehensive Financial Overview"
80
  ]
81
  )
82
 
83
- # Generate Query
84
- if query_type == "Analyst Recommendations":
85
- query = f"Summarize analyst recommendations for {stock_symbol}"
86
- elif query_type == "Latest Company News":
87
- query = f"Provide the latest news for {stock_symbol}"
88
- elif query_type == "Stock Fundamentals":
89
- query = f"Analyze stock fundamentals for {stock_symbol}"
90
- else:
91
- query = f"Provide a comprehensive financial overview for {stock_symbol}"
92
-
93
  # Submit Button
94
  if st.sidebar.button("Generate Analysis"):
95
  with st.spinner("Analyzing financial data..."):
96
- # Capture the response
97
- response_container = st.container()
98
- with response_container:
99
- try:
100
- # Stream the response
101
- full_response = ""
102
- response_placeholder = st.empty()
103
- for chunk in multi_ai_agent.respond(query, stream=True):
104
- full_response += chunk
105
- response_placeholder.markdown(full_response)
106
-
107
- # Final display
108
- st.success("Analysis Complete!")
109
- except Exception as e:
110
- st.error(f"An error occurred: {e}")
 
 
 
 
111
 
112
  # Footer
113
  st.sidebar.markdown("---")
 
1
  import streamlit as st
2
+ import requests
3
+ import yfinance as yf
4
+ from groq import Groq
 
5
  import os
6
 
7
  # Streamlit App Configuration
 
11
  layout="wide"
12
  )
13
 
14
+ # Initialize Groq Client
15
+ def get_groq_client():
16
+ try:
17
+ groq_api_key = st.secrets.get("GROQ_API_KEY") or os.getenv("GROQ_API_KEY")
18
+ if not groq_api_key:
19
+ st.error("Groq API Key is missing. Please set it in Secrets or .env file.")
20
+ return None
21
+ return Groq(api_key=groq_api_key)
22
+ except Exception as e:
23
+ st.error(f"Error initializing Groq client: {e}")
24
+ return None
25
 
26
+ # Fetch Stock Information
27
+ def get_stock_info(symbol):
28
+ try:
29
+ stock = yf.Ticker(symbol)
30
+
31
+ # Fetch key information
32
+ info = stock.info
33
+
34
+ # Fetch analyst recommendations
35
+ recommendations = stock.recommendations
36
+
37
+ # Fetch recent news
38
+ news = stock.news[:5] # Get last 5 news items
39
+
40
+ return {
41
+ "basic_info": {
42
+ "Company Name": info.get('longName', 'N/A'),
43
+ "Sector": info.get('sector', 'N/A'),
44
+ "Industry": info.get('industry', 'N/A'),
45
+ "Market Cap": f"${info.get('marketCap', 'N/A'):,}",
46
+ "Current Price": f"${info.get('currentPrice', 'N/A'):.2f}"
47
+ },
48
+ "recommendations": recommendations,
49
+ "news": news
50
+ }
51
+ except Exception as e:
52
+ st.error(f"Error fetching stock information: {e}")
53
+ return None
54
 
55
+ # Generate AI Analysis
56
+ def generate_ai_analysis(stock_info, query_type):
57
+ client = get_groq_client()
58
+ if not client:
59
+ return "Unable to generate AI analysis due to client initialization error."
60
+
61
+ try:
62
+ # Prepare context for AI
63
+ context = f"""Stock Information:
64
+ Company: {stock_info['basic_info'].get('Company Name', 'N/A')}
65
+ Sector: {stock_info['basic_info'].get('Sector', 'N/A')}
66
+ Market Cap: {stock_info['basic_info'].get('Market Cap', 'N/A')}
67
+ Current Price: {stock_info['basic_info'].get('Current Price', 'N/A')}
68
+ """
69
+
70
+ # Generate prompt based on query type
71
+ if query_type == "Analyst Recommendations":
72
+ prompt = f"{context}\n\nProvide a detailed analysis of the recent analyst recommendations for this stock."
73
+ elif query_type == "Latest Company News":
74
+ prompt = f"{context}\n\nSummarize the key points from the latest company news and their potential impact on the stock."
75
+ elif query_type == "Stock Fundamentals":
76
+ prompt = f"{context}\n\nProvide an in-depth analysis of the stock's fundamental financial health."
77
+ else:
78
+ prompt = f"{context}\n\nGenerate a comprehensive overview of the stock, including its market position, recent performance, and potential outlook."
79
+
80
+ # Generate response using Groq
81
+ response = client.chat.completions.create(
82
+ model="llama3-70b-8192",
83
+ messages=[
84
+ {"role": "system", "content": "You are a financial analyst providing professional stock insights."},
85
+ {"role": "user", "content": prompt}
86
+ ]
87
+ )
88
+
89
+ return response.choices[0].message.content
90
+ except Exception as e:
91
+ return f"Error generating AI analysis: {e}"
92
 
93
+ # Streamlit App Main Function
94
  def main():
95
  st.title("🤖 Financial Analysis AI Agent")
96
+ st.write("Get comprehensive financial insights using AI-powered analysis!")
97
 
98
  # Sidebar for configuration
99
  st.sidebar.header("🔧 Query Configuration")
 
109
  query_type = st.sidebar.selectbox(
110
  "Select Analysis Type",
111
  [
112
+ "Comprehensive Financial Overview",
113
  "Analyst Recommendations",
114
  "Latest Company News",
115
+ "Stock Fundamentals"
 
116
  ]
117
  )
118
 
 
 
 
 
 
 
 
 
 
 
119
  # Submit Button
120
  if st.sidebar.button("Generate Analysis"):
121
  with st.spinner("Analyzing financial data..."):
122
+ try:
123
+ # Fetch Stock Information
124
+ stock_info = get_stock_info(stock_symbol)
125
+
126
+ if stock_info:
127
+ # Display Basic Stock Information
128
+ st.subheader(f"Basic Information for {stock_symbol}")
129
+ info_df = pd.DataFrame.from_dict(stock_info['basic_info'], orient='index', columns=['Value'])
130
+ st.table(info_df)
131
+
132
+ # Generate AI Analysis
133
+ ai_analysis = generate_ai_analysis(stock_info, query_type)
134
+
135
+ # Display AI Analysis
136
+ st.subheader("AI-Powered Analysis")
137
+ st.write(ai_analysis)
138
+
139
+ except Exception as e:
140
+ st.error(f"An error occurred: {e}")
141
 
142
  # Footer
143
  st.sidebar.markdown("---")