dev2607 commited on
Commit
45474bc
·
verified ·
1 Parent(s): 117a535

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -50
app.py CHANGED
@@ -1,6 +1,6 @@
1
  import streamlit as st
2
- import requests
3
  import yfinance as yf
 
4
  from groq import Groq
5
  import os
6
 
@@ -14,10 +14,13 @@ st.set_page_config(
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}")
@@ -31,23 +34,20 @@ def get_stock_info(symbol):
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
@@ -60,28 +60,23 @@ def generate_ai_analysis(stock_info, query_type):
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
  )
@@ -90,60 +85,59 @@ Current Price: {stock_info['basic_info'].get('Current Price', 'N/A')}
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")
100
 
101
  # Stock Symbol Input
102
  stock_symbol = st.sidebar.text_input(
103
  "Enter Stock Symbol",
104
  value="NVDA",
105
- help="Enter a valid stock ticker symbol"
106
  )
107
 
108
- # Query Type Selection
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("---")
144
- st.sidebar.info(
145
- "💡 Tip: Use this tool to get quick financial insights. "
146
- "Always verify important financial decisions independently."
147
  )
148
 
149
  # Run the Streamlit app
 
1
  import streamlit as st
 
2
  import yfinance as yf
3
+ import pandas as pd
4
  from groq import Groq
5
  import os
6
 
 
14
  # Initialize Groq Client
15
  def get_groq_client():
16
  try:
17
+ # Try to get API key from Hugging Face secrets first
18
  groq_api_key = st.secrets.get("GROQ_API_KEY") or os.getenv("GROQ_API_KEY")
19
+
20
  if not groq_api_key:
21
  st.error("Groq API Key is missing. Please set it in Secrets or .env file.")
22
  return None
23
+
24
  return Groq(api_key=groq_api_key)
25
  except Exception as e:
26
  st.error(f"Error initializing Groq client: {e}")
 
34
  # Fetch key information
35
  info = stock.info
36
 
37
+ # Create a structured dictionary of key financial metrics
38
+ stock_data = {
39
+ "Company Name": info.get('longName', 'N/A'),
40
+ "Current Price": f"${info.get('currentPrice', 'N/A'):.2f}",
41
+ "Market Cap": f"${info.get('marketCap', 'N/A'):,}",
42
+ "PE Ratio": info.get('trailingPE', 'N/A'),
43
+ "Dividend Yield": f"{info.get('dividendYield', 'N/A'):.2%}",
44
+ "52 Week High": f"${info.get('fiftyTwoWeekHigh', 'N/A'):.2f}",
45
+ "52 Week Low": f"${info.get('fiftyTwoWeekLow', 'N/A'):.2f}",
46
+ "Sector": info.get('sector', 'N/A'),
47
+ "Industry": info.get('industry', 'N/A')
 
 
 
 
 
48
  }
49
+
50
+ return stock_data
51
  except Exception as e:
52
  st.error(f"Error fetching stock information: {e}")
53
  return None
 
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
  )
 
85
  except Exception as e:
86
  return f"Error generating AI analysis: {e}"
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")
95
 
96
  # Stock Symbol Input
97
  stock_symbol = st.sidebar.text_input(
98
  "Enter Stock Symbol",
99
  value="NVDA",
100
+ help="Enter a valid stock ticker (e.g., AAPL, GOOGL)"
101
  )
102
 
103
+ # Analysis Type Selection
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)
119
 
120
  if stock_info:
121
+ # Display Stock Information
122
+ st.subheader(f"Financial Snapshot: {stock_symbol}")
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")
131
  st.write(ai_analysis)
132
 
133
  except Exception as e:
134
  st.error(f"An error occurred: {e}")
135
 
136
+ # Disclaimer
137
  st.sidebar.markdown("---")
138
+ st.sidebar.warning(
139
+ "🚨 Disclaimer: This is an AI-generated analysis. "
140
+ "Always consult with a financial advisor before making investment decisions."
141
  )
142
 
143
  # Run the Streamlit app