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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import time
|
3 |
+
import re
|
4 |
+
import requests
|
5 |
+
import yfinance as yf
|
6 |
+
import warnings
|
7 |
+
warnings.filterwarnings("ignore")
|
8 |
+
|
9 |
+
from bs4 import BeautifulSoup
|
10 |
+
from langchain_community.tools import WikipediaQueryRun
|
11 |
+
from langchain_community.utilities import WikipediaAPIWrapper
|
12 |
+
from langchain_community.utilities.alpha_vantage import AlphaVantageAPIWrapper
|
13 |
+
from langchain.agents import AgentType, initialize_agent, load_tools
|
14 |
+
from langchain_community.tools import ShellTool
|
15 |
+
from langchain_community.llms import HuggingFaceEndpoint
|
16 |
+
from langchain.tools import BaseTool, StructuredTool, Tool, tool,DuckDuckGoSearchRun
|
17 |
+
from langchain import LLMMathChain
|
18 |
+
from pydantic import BaseModel, Field
|
19 |
+
from langchain.tools import DuckDuckGoSearchRun
|
20 |
+
|
21 |
+
search=DuckDuckGoSearchRun()
|
22 |
+
llm = HuggingFaceEndpoint(repo_id="mistralai/Mistral-7B-Instruct-v0.2")
|
23 |
+
|
24 |
+
# Fetch stock data from Yahoo Finance
|
25 |
+
def get_stock_price(ticker,history=5):
|
26 |
+
# time.sleep(4) #To avoid rate limit error
|
27 |
+
if "." in ticker:
|
28 |
+
ticker=ticker.split(".")[0]
|
29 |
+
ticker=ticker+".NS"
|
30 |
+
stock = yf.Ticker(ticker)
|
31 |
+
df = stock.history(period="1y")
|
32 |
+
df=df[["Close","Volume"]]
|
33 |
+
df.index=[str(x).split()[0] for x in list(df.index)]
|
34 |
+
df.index.rename("Date",inplace=True)
|
35 |
+
df=df[-history:]
|
36 |
+
# print(df.columns)
|
37 |
+
|
38 |
+
return df.to_string()
|
39 |
+
|
40 |
+
# Script to scrap top5 googgle news for given company name
|
41 |
+
def google_query(search_term):
|
42 |
+
if "news" not in search_term:
|
43 |
+
search_term=search_term+" stock news"
|
44 |
+
url=f"https://www.google.com/search?q={search_term}&cr=countryIN"
|
45 |
+
url=re.sub(r"\s","+",url)
|
46 |
+
return url
|
47 |
+
|
48 |
+
def get_recent_stock_news(company_name):
|
49 |
+
# time.sleep(4) #To avoid rate limit error
|
50 |
+
headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36'}
|
51 |
+
|
52 |
+
g_query=google_query(company_name)
|
53 |
+
res=requests.get(g_query,headers=headers).text
|
54 |
+
soup=BeautifulSoup(res,"html.parser")
|
55 |
+
news=[]
|
56 |
+
for n in soup.find_all("div","n0jPhd ynAwRc tNxQIb nDgy9d"):
|
57 |
+
news.append(n.text)
|
58 |
+
for n in soup.find_all("div","IJl0Z"):
|
59 |
+
news.append(n.text)
|
60 |
+
|
61 |
+
if len(news)>6:
|
62 |
+
news=news[:4]
|
63 |
+
else:
|
64 |
+
news=news
|
65 |
+
news_string=""
|
66 |
+
for i,n in enumerate(news):
|
67 |
+
news_string+=f"{i}. {n}\n"
|
68 |
+
top5_news="Recent News:\n\n"+news_string
|
69 |
+
|
70 |
+
return top5_news
|
71 |
+
|
72 |
+
|
73 |
+
# Fetch financial statements from Yahoo Finance
|
74 |
+
def get_financial_statements(ticker):
|
75 |
+
# time.sleep(4) #To avoid rate limit error
|
76 |
+
if "." in ticker:
|
77 |
+
ticker=ticker.split(".")[0]
|
78 |
+
else:
|
79 |
+
ticker=ticker
|
80 |
+
ticker=ticker+".NS"
|
81 |
+
company = yf.Ticker(ticker)
|
82 |
+
balance_sheet = company.balance_sheet
|
83 |
+
if balance_sheet.shape[1]>=3:
|
84 |
+
balance_sheet=balance_sheet.iloc[:,:3] # Remove 4th years data
|
85 |
+
balance_sheet=balance_sheet.dropna(how="any")
|
86 |
+
balance_sheet = balance_sheet.to_string()
|
87 |
+
return balance_sheet
|
88 |
+
|
89 |
+
|
90 |
+
#Openai function calling
|
91 |
+
function=[
|
92 |
+
{
|
93 |
+
"name": "get_company_Stock_ticker",
|
94 |
+
"description": "This will get the indian NSE/BSE stock ticker of the company",
|
95 |
+
"parameters": {
|
96 |
+
"type": "object",
|
97 |
+
"properties": {
|
98 |
+
"ticker_symbol": {
|
99 |
+
"type": "string",
|
100 |
+
"description": "This is the stock symbol of the company.",
|
101 |
+
},
|
102 |
+
|
103 |
+
"company_name": {
|
104 |
+
"type": "string",
|
105 |
+
"description": "This is the name of the company given in query",
|
106 |
+
}
|
107 |
+
},
|
108 |
+
"required": ["company_name","ticker_symbol"],
|
109 |
+
},
|
110 |
+
}
|
111 |
+
]
|
112 |
+
|
113 |
+
|
114 |
+
def get_stock_ticker(query):
|
115 |
+
response = openai.ChatCompletion.create(
|
116 |
+
model="gpt-3.5-turbo",
|
117 |
+
temperature=0,
|
118 |
+
messages=[{
|
119 |
+
"role":"user",
|
120 |
+
"content":f"Given the user request, what is the comapany name and the company stock ticker ?: {query}?"
|
121 |
+
}],
|
122 |
+
functions=function,
|
123 |
+
function_call={"name": "get_company_Stock_ticker"},
|
124 |
+
)
|
125 |
+
message = response["choices"][0]["message"]
|
126 |
+
arguments = json.loads(message["function_call"]["arguments"])
|
127 |
+
company_name = arguments["company_name"]
|
128 |
+
company_ticker = arguments["ticker_symbol"]
|
129 |
+
return company_name,company_ticker
|
130 |
+
|
131 |
+
def Anazlyze_stock(query):
|
132 |
+
#agent.run(query) Outputs Company name, Ticker
|
133 |
+
Company_name,ticker=get_stock_ticker(query)
|
134 |
+
print({"Query":query,"Company_name":Company_name,"Ticker":ticker})
|
135 |
+
stock_data=get_stock_price(ticker,history=10)
|
136 |
+
stock_financials=get_financial_statements(ticker)
|
137 |
+
stock_news=get_recent_stock_news(Company_name)
|
138 |
+
|
139 |
+
available_information=f"Stock Price: {stock_data}\n\nStock Financials: {stock_financials}\n\nStock News: {stock_news}"
|
140 |
+
#available_information=f"Stock Financials: {stock_financials}\n\nStock News: {stock_news}"
|
141 |
+
|
142 |
+
# print("\n\nAnalyzing.....\n")
|
143 |
+
analysis=llm(f"Give detail stock analysis, Use the available data and provide investment recommendation. \
|
144 |
+
The user is fully aware about the investment risk, dont include any kind of warning like 'It is recommended to conduct further research and analysis or consult with a financial advisor before making an investment decision' in the answer \
|
145 |
+
User question: {query} \
|
146 |
+
You have the following information available about {Company_name}. Write (5-8) pointwise investment analysis to answer user query, At the end conclude with proper explaination.Try to Give positives and negatives : \
|
147 |
+
{available_information} "
|
148 |
+
)
|
149 |
+
# print(analysis)
|
150 |
+
|
151 |
+
return analysis
|
152 |
+
|
153 |
+
|
154 |
+
|
155 |
+
# Making tool list
|
156 |
+
tools=[
|
157 |
+
Tool(
|
158 |
+
name="get stock data",
|
159 |
+
func=get_stock_price,
|
160 |
+
description="Use when you are asked to evaluate or analyze a stock. This will output historic share price data. You should input the the stock ticker to it "
|
161 |
+
),
|
162 |
+
Tool(
|
163 |
+
name="DuckDuckGo Search",
|
164 |
+
func=search.run,
|
165 |
+
description="Use only when you need to get NSE/BSE stock ticker from internet, you can also get recent stock related news. Dont use it for any other analysis or task"
|
166 |
+
),
|
167 |
+
Tool(
|
168 |
+
name="get recent news",
|
169 |
+
func=get_recent_stock_news,
|
170 |
+
description="Use this to fetch recent news about stocks"
|
171 |
+
),
|
172 |
+
|
173 |
+
Tool(
|
174 |
+
name="get financial statements",
|
175 |
+
func=get_financial_statements,
|
176 |
+
description="Use this to get financial statement of the company. With the help of this data companys historic performance can be evaluaated. You should input stock ticker to it"
|
177 |
+
)
|
178 |
+
|
179 |
+
|
180 |
+
]
|
181 |
+
|
182 |
+
|
183 |
+
|
184 |
+
agent = initialize_agent(
|
185 |
+
tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True, max_iterations=4,
|
186 |
+
handle_parsing_errors=True
|
187 |
+
)
|
188 |
+
#Adding predefine evaluation steps in the agent Prompt
|
189 |
+
|
190 |
+
new_prompt="""You are a financial advisor. Give stock recommendations for given query.
|
191 |
+
Everytime first you should identify the company name and get the stock ticker symbole for indian stock.
|
192 |
+
Answer the following questions as best you can. You have access to the following tools:
|
193 |
+
|
194 |
+
get stock data: Use when you are asked to evaluate or analyze a stock. This will output historic share price data. You should input the the stock ticker to it
|
195 |
+
DuckDuckGo Search: Use only when you need to get NSE/BSE stock ticker from internet, you can also get recent stock related news. Dont use it for any other analysis or task
|
196 |
+
get recent news: Use this to fetch recent news about stocks
|
197 |
+
get financial statements: Use this to get financial statement of the company. With the help of this data companys historic performance can be evaluaated. You should input stock ticker to it
|
198 |
+
|
199 |
+
steps-
|
200 |
+
Note- if you fail in satisfying any of the step below, Just move to next one
|
201 |
+
1) Get the company name and search for the "company name + NSE/BSE stock ticker" on internet. Dont hallucinate extract stock ticker as it is from the text. Output- stock ticker
|
202 |
+
2) Use "get stock data" tool to gather stock info. Output- Stock data
|
203 |
+
3) Get company's historic financial data using "get financial statements". Output- Financial statement
|
204 |
+
4) Use this "get recent news" tool to search for latest stock realted news. Output- Stock news
|
205 |
+
5) Analyze the stock based on gathered data and give detail analysis for investment choice. provide numbers and reasons to justify your answer. Output- Detailed stock Analysis
|
206 |
+
|
207 |
+
Use the following format:
|
208 |
+
|
209 |
+
Question: the input question you must answer
|
210 |
+
Thought: you should always think about what to do, Also try to follow steps mentioned above
|
211 |
+
Action: the action to take, should be one of [get stock data, DuckDuckGo Search, get recent news, get financial statements]
|
212 |
+
Action Input: the input to the action
|
213 |
+
Observation: the result of the action
|
214 |
+
... (this Thought/Action/Action Input/Observation can repeat N times)
|
215 |
+
Thought: I now know the final answer
|
216 |
+
Final Answer: the final answer to the original input question
|
217 |
+
Begin!
|
218 |
+
|
219 |
+
Question: {input}
|
220 |
+
Thought:{agent_scratchpad}"""
|
221 |
+
|
222 |
+
|
223 |
+
|
224 |
+
#Setting up new prompt
|
225 |
+
agent.agent.llm_chain.prompt.template=new_prompt
|
226 |
+
|
227 |
+
|
228 |
+
#App UI starts here
|
229 |
+
st.set_page_config(page_title="STOCK Analyzer", page_icon=":robot:")
|
230 |
+
st.header("STOCK Analyzer")
|
231 |
+
|
232 |
+
#Gets the user input
|
233 |
+
def get_text():
|
234 |
+
input_text = st.text_input("You:", "Is ITC stock a good investment choice right now? OR Shall I invest in Asian paints?.......")
|
235 |
+
if input_text.isalpha():
|
236 |
+
st.write(text, 'string', )
|
237 |
+
else:
|
238 |
+
st.write('Please type in a string Only')
|
239 |
+
return input_text
|
240 |
+
|
241 |
+
user_input=get_text()
|
242 |
+
response = agent(user_input)
|
243 |
+
|
244 |
+
submit = st.button('Generate')
|
245 |
+
|
246 |
+
#If generate button is clicked
|
247 |
+
if submit:
|
248 |
+
|
249 |
+
st.subheader("Answer:")
|
250 |
+
|
251 |
+
st.write(response)
|
252 |
+
|
253 |
+
|