Ajii007 commited on
Commit
ea7a6df
·
verified ·
1 Parent(s): b3d5992

Upload 2 files

Browse files
Files changed (2) hide show
  1. new_app.py +184 -0
  2. requirements.txt +16 -0
new_app.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from langchain.tools import Tool
3
+ from langchain_community.utilities import GoogleSearchAPIWrapper
4
+ import requests
5
+ from bs4 import BeautifulSoup
6
+ import google.generativeai as genai
7
+ import os
8
+ from dotenv import load_dotenv
9
+ import os
10
+ import google.generativeai as genai
11
+ import streamlit as st
12
+ import pandas as pd
13
+
14
+ # Load all the environment variables
15
+ load_dotenv()
16
+
17
+ # Initialte the Google Search
18
+ search = GoogleSearchAPIWrapper()
19
+
20
+ def top5_results(query):
21
+ return search.results(query, 10)
22
+
23
+ def google_search(user_input):
24
+ tool = Tool(
25
+ name="Google Search Snippets",
26
+ description="Search Google for recent news.",
27
+ func=top5_results,
28
+ )
29
+ res = tool.run("Latest Stock news about" + user_input)
30
+ print(res)
31
+ urls = []
32
+ for i in range(len(res)):
33
+ print(res[i]['link'])
34
+ urls.append(res[i]['link'])
35
+ update = extract_content(urls,user_input)
36
+ return update
37
+
38
+ def extract_content(urls,user_input):
39
+ # Get the relevent element from the news
40
+ content_list = []
41
+
42
+ for url in urls:
43
+ try:
44
+ # Make an HTTP GET request to the URL
45
+ response = requests.get(url)
46
+
47
+ # Check if the request was successful (status code 200)
48
+ if response.status_code == 200:
49
+ # Parse the HTML content using BeautifulSoup
50
+ soup = BeautifulSoup(response.text, 'html.parser')
51
+
52
+ # Find and extract relevant content based on user input
53
+ relevant_content = ""
54
+ for paragraph in soup.find_all('p'):
55
+ if user_input.lower() in paragraph.get_text().lower():
56
+ relevant_content += paragraph.get_text() + '\n'
57
+
58
+ # Append the relevant content to the list
59
+ content_list.append({'url': url, 'content': relevant_content.strip()})
60
+
61
+ except Exception as e:
62
+ print(f"Error fetching content from {url}: {e}")
63
+
64
+ # Print the extracted content
65
+ for content in content_list:
66
+ print(f"URL: {content['url']}")
67
+ print(f"Relevant Content:\n{content['content']}\n{'='*50}\n")
68
+
69
+ # Store the content into a list
70
+ text_input = []
71
+ for content in content_list:
72
+ text_input.append(content['content'])
73
+
74
+ update = initiate_gemini(text_input)
75
+ return update
76
+
77
+ def initiate_gemini(text_input):
78
+ # Initiate the Gemini pro
79
+ genai.configure(api_key=os.environ.get("GOOGLE_API_KEY"))
80
+ model = genai.GenerativeModel(model_name = "gemini-pro")
81
+ genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
82
+ update = input_prompt(text_input)
83
+ return update
84
+
85
+ def get_gemini_response(input_text):
86
+ model = genai.GenerativeModel('gemini-pro')
87
+ response = model.generate_content(input_text)
88
+ return response.text
89
+
90
+ def input_prompt(text_input):
91
+ input_prompt = """
92
+ You are an expert in stock market analysis. Your task is to conduct a thorough analysis of a specific stock based on recent news. Your detailed analysis should cover the following aspects:
93
+
94
+ 1. **SEBI Warning:**
95
+ 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.
96
+
97
+ 2. **Stock Information:**
98
+ - Current market performance: Include recent stock prices, market capitalization, and any significant fluctuations.
99
+ - Financial indicators: Provide key financial metrics such as earnings per share (EPS), price-to-earnings ratio (P/E), and debt-equity ratio.
100
+
101
+ 3. **Recent News Analysis in Detailed Summary:**
102
+ - Summarize at least three recent news articles related to the stock.
103
+ - Assess the impact of each news piece on the stock's performance.
104
+ - Identify any emerging trends or patterns.
105
+
106
+ 4. **Short Story about the Stock:**
107
+ - Provide a concise narrative on the stock's history and evolution.
108
+ - Highlight key milestones, mergers, or acquisitions that have shaped its trajectory.
109
+
110
+ 5. **Key Strength:**
111
+ - Identify and elaborate on the primary strengths of the stock.
112
+ - Discuss factors such as competitive advantages, market leadership, or innovative products.
113
+
114
+ 6. **Key Weakness:**
115
+ - Highlight the main weaknesses or challenges faced by the stock.
116
+ - Consider factors such as industry competition, regulatory risks, or financial vulnerabilities.
117
+
118
+ 7. **Products:**
119
+ - Describe the core products or services offered by the company.
120
+ - Discuss the significance of these products in driving the stock's performance.
121
+
122
+ 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.
123
+
124
+ ---
125
+
126
+ Feel free to adjust or expand upon the instructions to meet your specific requirements!
127
+
128
+
129
+ consider the following news for analysis.
130
+ """
131
+ text_input.insert(0,input_prompt)
132
+ #print(text_input)
133
+ #print(stock_ref)
134
+ response = get_gemini_response(text_input)
135
+ print(response)
136
+ return response
137
+
138
+
139
+ # Function to save feedback locally
140
+ def save_feedback(name, email, feedback):
141
+ feedback_data = pd.DataFrame({'Name': [name], 'Email': [email], 'Feedback': [feedback]})
142
+
143
+ # Check if the feedback file exists
144
+ if not os.path.exists('feedback.csv'):
145
+ feedback_data.to_csv('feedback.csv', index=False)
146
+ else:
147
+ # Append feedback to the existing file
148
+ feedback_data.to_csv('feedback.csv', mode='a', header=False, index=False)
149
+
150
+ # Streamlit app
151
+ def main():
152
+ st.title('Stock Analysis Feedback App')
153
+
154
+ # User Input
155
+ user_input = st.text_input('Enter a Stock Name for analysis:', '')
156
+
157
+ # Display response
158
+ if st.button('Submit'):
159
+ response = google_search(user_input)
160
+ st.success('Analysis Result:')
161
+ st.write(response)
162
+
163
+ # Feedback box
164
+ st.subheader('Provide Feedback:')
165
+ name = st.text_input('Your Name*', '')
166
+ email = st.text_input('Your Email*', '')
167
+ feedback = st.text_area('Feedback*', '')
168
+
169
+ if st.button('Submit Feedback'):
170
+ if name.strip() == '' or email.strip() == '' or feedback.strip() == '':
171
+ st.markdown('<p style="color:red;">Please fill in all required fields.</p>', unsafe_allow_html=True)
172
+ else:
173
+ save_feedback(name, email, feedback)
174
+ st.success('Thank you for your feedback!')
175
+
176
+ # Execute the main function
177
+ main()
178
+
179
+
180
+
181
+
182
+
183
+ #user_input = str(input("Enter the stock name -- "))
184
+ #google_search(user_input)
requirements.txt ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ pandas
2
+ numpy
3
+ matplotlib
4
+ seaborn
5
+ scikit-learn
6
+ pillow
7
+ langchain
8
+ google-api-python-client
9
+ beautifulsoup4
10
+ html5lib
11
+ tqdm
12
+ html2text
13
+ google-generativeai
14
+ langchain-google-genai
15
+ yfinance
16
+ python-dotenv