import os from langchain.tools import Tool from langchain_community.utilities import GoogleSearchAPIWrapper import requests from bs4 import BeautifulSoup import google.generativeai as genai import os from dotenv import load_dotenv import os import google.generativeai as genai import streamlit as st import pandas as pd # Load all the environment variables load_dotenv() # Initialte the Google Search search = GoogleSearchAPIWrapper() def top5_results(query): return search.results(query, 10) def google_search(user_input): tool = Tool( name="Google Search Snippets", description="Search Google for recent news.", func=top5_results, ) res = tool.run("Latest Stock news about" + user_input) print(res) urls = [] for i in range(len(res)): print(res[i]['link']) urls.append(res[i]['link']) update = extract_content(urls,user_input) return update def extract_content(urls,user_input): # Get the relevent element from the news content_list = [] for url in urls: try: # Make an HTTP GET request to the URL response = requests.get(url) # Check if the request was successful (status code 200) if response.status_code == 200: # Parse the HTML content using BeautifulSoup soup = BeautifulSoup(response.text, 'html.parser') # Find and extract relevant content based on user input relevant_content = "" for paragraph in soup.find_all('p'): if user_input.lower() in paragraph.get_text().lower(): relevant_content += paragraph.get_text() + '\n' # Append the relevant content to the list content_list.append({'url': url, 'content': relevant_content.strip()}) except Exception as e: print(f"Error fetching content from {url}: {e}") # Print the extracted content for content in content_list: print(f"URL: {content['url']}") print(f"Relevant Content:\n{content['content']}\n{'='*50}\n") # Store the content into a list text_input = [] for content in content_list: text_input.append(content['content']) update = initiate_gemini(text_input) return update def initiate_gemini(text_input): # Initiate the Gemini pro genai.configure(api_key=os.environ.get("GOOGLE_API_KEY")) model = genai.GenerativeModel(model_name = "gemini-pro") genai.configure(api_key=os.getenv("GOOGLE_API_KEY")) update = input_prompt(text_input) return update def get_gemini_response(input_text): model = genai.GenerativeModel('gemini-pro') response = model.generate_content(input_text) return response.text def input_prompt(text_input): input_prompt = """ You are an expert in stock market analysis. Your task is to conduct a thorough analysis of a specific stock based on recent news. Provide results only in English. Your detailed analysis should cover the following aspects: 1. **SEBI Warning:** Begin with a disclaimer stating that the analysis is for informational purposes only. Include a SEBI warning to highlight the speculative nature of stock market investments. 2. **Stock Information:** - Current market performance: Include recent stock prices, market capitalization, and any significant fluctuations. - Financial indicators: Provide key financial metrics such as earnings per share (EPS), price-to-earnings ratio (P/E), and debt-equity ratio. 3. **Recent News Analysis in Detail:** - Summarize news articles related to the stock. - Assess the impact of each news piece on the stock's performance. - Identify any emerging trends or patterns. - Provide the Sentiment for each news with this block and should include the sentiment scale between 1 to 5 4. **Short Story about the Stock:** - Provide a concise narrative on the stock's history and evolution. - Highlight key milestones, mergers, or acquisitions that have shaped its trajectory. 5. **Key Strength:** - Identify and elaborate on the primary strengths of the stock. - Discuss factors such as competitive advantages, market leadership, or innovative products. 6. **Key Weakness:** - Highlight the main weaknesses or challenges faced by the stock. - Consider factors such as industry competition, regulatory risks, or financial vulnerabilities. 7. **Products:** - Describe the core products or services offered by the company. - Discuss the significance of these products in driving the stock's performance. For each section, provide detailed insights, backed by data and relevant examples. Ensure that your analysis is objective and considers both positive and negative aspects. Conclude with a summary that synthesizes the key findings and offers potential insights into the stock's future prospects. --- consider the following news for analysis. Dont provide false dates """ text_input.insert(0,input_prompt) #print(text_input) #print(stock_ref) response = get_gemini_response(text_input) print(response) return response # Function to save feedback locally def save_feedback(name, email, feedback): feedback_data = pd.DataFrame({'Name': [name], 'Email': [email], 'Feedback': [feedback]}) # Check if the feedback file exists if not os.path.exists('feedback.csv'): feedback_data.to_csv('feedback.csv', index=False) else: # Append feedback to the existing file feedback_data.to_csv('feedback.csv', mode='a', header=False, index=False) # Streamlit app def main(): st.title('Stock Insights App') # User Input user_input = st.text_input('Enter a Stock Name for analysis:', '') # Display response if st.button('Submit'): response = google_search(user_input) st.success('Analysis Result:') st.write(response) # Feedback box # st.subheader('Provide Feedback:') # name = st.text_input('Your Name*', '') # email = st.text_input('Your Email*', '') # feedback = st.text_area('Feedback*', '') # if st.button('Submit Feedback'): # if name.strip() == '' or email.strip() == '' or feedback.strip() == '': # st.markdown('
Please fill in all required fields.
', unsafe_allow_html=True) # else: # save_feedback(name, email, feedback) # st.success('Thank you for your feedback!') # Execute the main function main()