dev2607 commited on
Commit
c2091ec
Β·
verified Β·
1 Parent(s): 8dbcbb3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -15
app.py CHANGED
@@ -3,6 +3,8 @@ import yfinance as yf
3
  import pandas as pd
4
  from groq import Groq
5
  import os
 
 
6
 
7
  # Streamlit App Configuration
8
  st.set_page_config(
@@ -52,31 +54,62 @@ def get_stock_info(symbol):
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 = "\n".join([f"{k}: {v}" for k, v in stock_info.items()])
 
 
 
 
 
 
 
 
 
64
 
65
  # Generate prompt based on query type
66
  if query_type == "Analyst Recommendations":
67
- prompt = f"Provide a professional analysis of the stock's potential based on these details:\n{context}\nFocus on analyst recommendations and future outlook."
68
- elif query_type == "Company Overview":
69
- prompt = f"Give a comprehensive overview of the company based on these financial details:\n{context}\nHighlight key strengths and potential challenges."
70
- elif query_type == "Investment Potential":
71
- prompt = f"Analyze the investment potential of this stock using these financial metrics:\n{context}\nProvide insights on potential growth and risks."
72
  else:
73
- prompt = f"Provide a detailed financial analysis of the stock using these details:\n{context}"
74
 
75
  # Generate response using Groq
76
  response = client.chat.completions.create(
77
  model="llama3-70b-8192",
78
  messages=[
79
- {"role": "system", "content": "You are a professional financial analyst providing detailed stock insights."},
80
  {"role": "user", "content": prompt}
81
  ]
82
  )
@@ -87,8 +120,8 @@ def generate_ai_analysis(stock_info, query_type):
87
 
88
  # Main Streamlit App
89
  def main():
90
- st.title("πŸš€ Financial Insight AI")
91
- st.markdown("Get comprehensive stock analysis powered by AI")
92
 
93
  # Sidebar Configuration
94
  st.sidebar.header("πŸ” Stock Analysis")
@@ -104,15 +137,15 @@ def main():
104
  query_type = st.sidebar.selectbox(
105
  "Select Analysis Type",
106
  [
107
- "Company Overview",
108
  "Analyst Recommendations",
109
- "Investment Potential"
110
  ]
111
  )
112
 
113
  # Generate Analysis Button
114
  if st.sidebar.button("Generate Analysis"):
115
- with st.spinner("Analyzing stock data..."):
116
  try:
117
  # Fetch Stock Information
118
  stock_info = get_stock_info(stock_symbol)
@@ -123,8 +156,19 @@ def main():
123
  info_df = pd.DataFrame.from_dict(stock_info, orient='index', columns=['Value'])
124
  st.table(info_df)
125
 
 
 
 
 
 
 
 
 
 
 
 
126
  # Generate AI Analysis
127
- ai_analysis = generate_ai_analysis(stock_info, query_type)
128
 
129
  # Display AI Analysis
130
  st.subheader("πŸ€– AI-Powered Insights")
 
3
  import pandas as pd
4
  from groq import Groq
5
  import os
6
+ import requests
7
+ from duckduckgo_search import DDGS
8
 
9
  # Streamlit App Configuration
10
  st.set_page_config(
 
54
  st.error(f"Error fetching stock information: {e}")
55
  return None
56
 
57
+ # Fetch News Using DuckDuckGo
58
+ def get_duckduckgo_news(symbol, limit=5):
59
+ try:
60
+ with DDGS() as ddgs:
61
+ # Search for recent news about the stock
62
+ news_results = list(ddgs.news(f"{symbol} stock recent news", max_results=limit))
63
+
64
+ # Transform results to a consistent format
65
+ formatted_news = [
66
+ {
67
+ "title": result.get('title', 'N/A'),
68
+ "link": result.get('url', ''),
69
+ "publisher": result.get('source', 'N/A'),
70
+ "source": "DuckDuckGo"
71
+ } for result in news_results
72
+ ]
73
+
74
+ return formatted_news
75
+ except Exception as e:
76
+ st.warning(f"DuckDuckGo news search error: {e}")
77
+ return []
78
+
79
  # Generate AI Analysis
80
+ def generate_ai_analysis(stock_info, news, query_type):
81
  client = get_groq_client()
82
  if not client:
83
  return "Unable to generate AI analysis due to client initialization error."
84
 
85
  try:
86
  # Prepare context for AI
87
+ stock_context = "\n".join([f"{k}: {v}" for k, v in stock_info.items()])
88
+
89
+ # Prepare news context
90
+ news_context = "Recent News:\n" + "\n".join([
91
+ f"- {news['title']} (Source: {news['publisher']})"
92
+ for news in news
93
+ ])
94
+
95
+ # Full context
96
+ full_context = f"{stock_context}\n\n{news_context}"
97
 
98
  # Generate prompt based on query type
99
  if query_type == "Analyst Recommendations":
100
+ prompt = f"Provide a comprehensive analysis of analyst recommendations for this stock. Consider the following details:\n{full_context}\n\nFocus on: current analyst ratings, price targets, and recent sentiment changes."
101
+ elif query_type == "Latest News Analysis":
102
+ prompt = f"Analyze the latest news and its potential impact on the stock. Consider these details:\n{full_context}\n\nProvide insights on how recent news might affect the stock's performance."
103
+ elif query_type == "Comprehensive Analysis":
104
+ prompt = f"Provide a holistic analysis of the stock, integrating financial metrics and recent news:\n{full_context}\n\nOffer a balanced perspective on investment potential."
105
  else:
106
+ prompt = f"Generate a detailed financial and news-based analysis:\n{full_context}"
107
 
108
  # Generate response using Groq
109
  response = client.chat.completions.create(
110
  model="llama3-70b-8192",
111
  messages=[
112
+ {"role": "system", "content": "You are a professional financial analyst providing nuanced stock insights."},
113
  {"role": "user", "content": prompt}
114
  ]
115
  )
 
120
 
121
  # Main Streamlit App
122
  def main():
123
+ st.title("πŸš€ Advanced Financial Insight AI")
124
+ st.markdown("Comprehensive stock analysis with DuckDuckGo news search")
125
 
126
  # Sidebar Configuration
127
  st.sidebar.header("πŸ” Stock Analysis")
 
137
  query_type = st.sidebar.selectbox(
138
  "Select Analysis Type",
139
  [
140
+ "Comprehensive Analysis",
141
  "Analyst Recommendations",
142
+ "Latest News Analysis"
143
  ]
144
  )
145
 
146
  # Generate Analysis Button
147
  if st.sidebar.button("Generate Analysis"):
148
+ with st.spinner("Fetching and analyzing stock data..."):
149
  try:
150
  # Fetch Stock Information
151
  stock_info = get_stock_info(stock_symbol)
 
156
  info_df = pd.DataFrame.from_dict(stock_info, orient='index', columns=['Value'])
157
  st.table(info_df)
158
 
159
+ # Fetch News via DuckDuckGo
160
+ real_time_news = get_duckduckgo_news(stock_symbol)
161
+
162
+ # Display News
163
+ st.subheader("πŸ“° Latest News")
164
+ for news in real_time_news:
165
+ st.markdown(f"**{news['title']}**")
166
+ st.markdown(f"*Source: {news['publisher']}*")
167
+ st.markdown(f"[Read more]({news['link']})")
168
+ st.markdown("---")
169
+
170
  # Generate AI Analysis
171
+ ai_analysis = generate_ai_analysis(stock_info, real_time_news, query_type)
172
 
173
  # Display AI Analysis
174
  st.subheader("πŸ€– AI-Powered Insights")