gauri-sharan commited on
Commit
1b9e5f6
·
verified ·
1 Parent(s): 981e745

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -36
app.py CHANGED
@@ -5,7 +5,7 @@ import yfinance as yf
5
  # Initialize the ChatGroq model using the secret API key
6
  llm = ChatGroq(model_name="Llama3-8b-8192", api_key=st.secrets['groq_api_key'])
7
 
8
- # Initialize chat history in session state
9
  if "messages" not in st.session_state:
10
  st.session_state.messages = [{"role": "assistant", "content": "Hello! How can I assist you with stock information today?"}]
11
 
@@ -14,6 +14,42 @@ for message in st.session_state.messages:
14
  with st.chat_message(message["role"]):
15
  st.markdown(message["content"], unsafe_allow_html=True)
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  # Accept user input
18
  if prompt := st.chat_input("Ask me about stocks..."):
19
  # Display user message in chat message container
@@ -23,44 +59,17 @@ if prompt := st.chat_input("Ask me about stocks..."):
23
  # Add user message to chat history
24
  st.session_state.messages.append({"role": "user", "content": prompt})
25
 
26
- # Fetch stock data or generate response based on user input
27
- if "invest" in prompt.lower() or "should I invest" in prompt.lower():
28
  company_name = prompt.split()[-1] # Assuming the last word is the ticker symbol or company name
29
 
30
- try:
31
- stock_data = yf.Ticker(company_name).info
32
-
33
- # Check if stock_data contains valid information
34
- if 'currentPrice' in stock_data and stock_data['currentPrice'] is not None:
35
- # Extract relevant information into a structured format
36
- stock_info = {
37
- "Company": stock_data.get("longName", "N/A"),
38
- "Current Price": stock_data.get("currentPrice", "N/A"),
39
- "Market Cap": stock_data.get("marketCap", "N/A"),
40
- "PE Ratio": stock_data.get("trailingPE", "N/A"),
41
- "Dividend Yield": stock_data.get("dividendYield", "N/A"),
42
- "52 Week High": stock_data.get("fiftyTwoWeekHigh", "N/A"),
43
- "52 Week Low": stock_data.get("fiftyTwoWeekLow", "N/A"),
44
- "Sector": stock_data.get("sector", "N/A"),
45
- "Industry": stock_data.get("industry", "N/A")
46
- }
47
-
48
- # Prepare response string with line breaks for readability
49
- response = f"Here is the data for {company_name}:\n"
50
- for key, value in stock_info.items():
51
- response += f"{key}: {value}\n"
52
-
53
- # Simple investment recommendation logic (this can be improved)
54
- if stock_info["PE Ratio"] != "N/A" and float(stock_info["PE Ratio"]) < 20: # Example condition for recommendation
55
- response += "\n**Recommendation:** Yes, consider investing!"
56
- else:
57
- response += "\n**Recommendation:** No, it might not be a good time to invest."
58
- else:
59
- response = f"Sorry, I couldn't find valid data for {company_name}. Please check the ticker symbol."
60
 
61
- except Exception as e:
62
- response = f"An error occurred while fetching data: {str(e)}"
63
-
64
  else:
65
  try:
66
  # Use the LLM for general questions or topics not related to stocks
 
5
  # Initialize the ChatGroq model using the secret API key
6
  llm = ChatGroq(model_name="Llama3-8b-8192", api_key=st.secrets['groq_api_key'])
7
 
8
+ # Initialize chat history in session state if it doesn't exist
9
  if "messages" not in st.session_state:
10
  st.session_state.messages = [{"role": "assistant", "content": "Hello! How can I assist you with stock information today?"}]
11
 
 
14
  with st.chat_message(message["role"]):
15
  st.markdown(message["content"], unsafe_allow_html=True)
16
 
17
+ # Function to fetch stock data
18
+ def fetch_stock_data(company_name):
19
+ try:
20
+ stock_data = yf.Ticker(company_name).info
21
+ if 'currentPrice' in stock_data and stock_data['currentPrice'] is not None:
22
+ return {
23
+ "Company": stock_data.get("longName", "N/A"),
24
+ "Current Price": stock_data.get("currentPrice", "N/A"),
25
+ "Market Cap": stock_data.get("marketCap", "N/A"),
26
+ "PE Ratio": stock_data.get("trailingPE", "N/A"),
27
+ "Dividend Yield": stock_data.get("dividendYield", "N/A"),
28
+ "52 Week High": stock_data.get("fiftyTwoWeekHigh", "N/A"),
29
+ "52 Week Low": stock_data.get("fiftyTwoWeekLow", "N/A"),
30
+ "Sector": stock_data.get("sector", "N/A"),
31
+ "Industry": stock_data.get("industry", "N/A")
32
+ }
33
+ else:
34
+ return None
35
+ except Exception as e:
36
+ return f"An error occurred while fetching data: {str(e)}"
37
+
38
+ # Function to generate response for investment queries
39
+ def generate_investment_response(stock_info, company_name):
40
+ response = f"Here is the data for {company_name}:\n"
41
+ for key, value in stock_info.items():
42
+ response += f"{key}: {value}\n"
43
+
44
+ # Simple investment recommendation logic
45
+ pe_ratio = stock_info.get("PE Ratio")
46
+ if pe_ratio != "N/A" and float(pe_ratio) < 20: # Example condition for recommendation
47
+ response += "\n**Recommendation:** Yes, consider investing!"
48
+ else:
49
+ response += "\n**Recommendation:** No, it might not be a good time to invest."
50
+
51
+ return response
52
+
53
  # Accept user input
54
  if prompt := st.chat_input("Ask me about stocks..."):
55
  # Display user message in chat message container
 
59
  # Add user message to chat history
60
  st.session_state.messages.append({"role": "user", "content": prompt})
61
 
62
+ # Check if the prompt is related to investment
63
+ if any(keyword in prompt.lower() for keyword in ["invest", "should I invest"]):
64
  company_name = prompt.split()[-1] # Assuming the last word is the ticker symbol or company name
65
 
66
+ stock_info = fetch_stock_data(company_name)
67
+
68
+ if isinstance(stock_info, dict):
69
+ response = generate_investment_response(stock_info, company_name)
70
+ else:
71
+ response = f"Sorry, I couldn't find valid data for {company_name}. Please check the ticker symbol."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
 
 
 
 
73
  else:
74
  try:
75
  # Use the LLM for general questions or topics not related to stocks