I am currentlty building a stcok advisor agent, i created some tools using beautiful soup to extract information about a particular company stocks this is the code below:
llm = ChatGoogleGenerativeAI(model = "gemini-pro")
def get_info_stock(ticker):
try:
result = llm.invoke(f"What is ticker symbol for the company {ticker}").content.strip()
ticker_symbol = result.lower()
base_url = f'https://stockanalysis.com/stocks/{ticker_symbol}/'
# Fetch and parse main stock information
front_soup = get_soup(base_url)
data = front_soup.find('div', "order-1 flex flex-row space-x-2 tiny:space-x-3 xs:space-x-4").text
analyst_information = front_soup.find("p", "mb-4").text
pattern = re.compile(r'(Market Cap|Revenue (ttm)|Net Income (ttm)|Shares Out|EPS (ttm)|PE Ratio|Forward PE|Dividend|Ex-Dividend Date|Volume|Open|Previous Close|Day's Range|52-Week Range|Beta|Analysts Hold|Price Target|Earnings Date) (n/a|[d,.]+[BMT]?|[d,.]+ - [d,.]+|[d,.]+ (+d+.d+%)|[A-Za-z]+s+d{1,2}, d{4})')
matches = pattern.findall(data)
data_dict = {key: value for key, value in matches}
print(f"The Stock information for {ticker} ({ticker_symbol.upper()}):")
for key, value in data_dict.items():
print(f"{key}: {value}")
print()
print("Analyst Information:")
print(analyst_information)
print()
# Fetch and parse financial statements
sections = ["financials/?p=quarterly", "financials/balance-sheet/?p=quarterly", "financials/cash-flow-statement/?p=quarterly"]
labels = ["Financial Information", "Balance Sheet", "Cash Flow"]
for section, label in zip(sections, labels):
url_finance = base_url + section
stock_soup = get_soup(url_finance)
table_quarterly = stock_soup.find("table", "w-full border-separate border-spacing-0 whitespace-nowrap")
print(label + ":")
table = get_table(table_quarterly)
for row in table:
print(row)
print()
# Fetch and parse company information
company_soup = get_soup(base_url + "company/")
company_info = company_soup.find("div", "lg:float-left lg:w-[calc(100%-336px-40px)]").text
print("Company Information:")
print(company_info)
# Fetch and parse additional statistics
stats_soup = get_soup(base_url + "statistics/")
company_stat = stats_soup.find("div", "space-y-5 xs:space-y-6 lg:grid lg:grid-cols-3 lg:space-x-10 lg:space-y-0 mt-3.5").text
print("Company Statistics:")
print(company_stat)
print()
return company_stat
except Exception as e:
print(f"An error occurred: {e}")
get_stock_info = StructuredTool.from_function(
func= get_info_stock,
name="get-info-stock",
description="Use this tool to get information about any company or stock",
# coroutine= ... <- you can specify an async method if desired as well
)
i created another function to get information on top and worst performing stocks too:
@tool
def get_latest_info():
"""Always use this tool to get latest information about the top , hottest and worst performing stocks in market"""
url = f"https://stockanalysis.com/markets/gainers/"
trend_soup = get_soup(url)
stock_stat = trend_soup.find("table","symbol-table svelte-eurwtr")
gainer_table = get_table(stock_stat)
print("Top Gainers: ")
print(gainer_table)
print()
url = "https://stockanalysis.com/markets/losers/"
print("Top Lossers: ")
loser_soup = get_soup(url)
stock_stat = loser_soup.find("table","symbol-table svelte-eurwtr")
loser_table = get_table(stock_stat)
print(loser_table)
print()
return f"Top Gainers {gainer_table}",f"Top Stocks lossers {loser_table}"
and i have a prompt like this:
prompt = PromptTemplate.from_template(template = """
You are an artificial intelligence designed to provide financial advice. You can utilize the tools at your disposal: {tools}.
Follow this structure:
Question: The inquiry you need to address.
Consideration: If the question asks for a definition, you can provide your own definition.
Consideration: If the inquiry requires information about a stock, you can use the tools in [{tool_names}].
Consideration: If the inquiry asks for financial advice, use the tools in [{tool_names}] to gather information about good performing stocks, then give your own view on whether the stocks are worth investing in.
Consideration: If you don't have any knowledge of the inquiry or if it is not related to finance, politely state that you do not have knowledge about that.
Action: If the inquiry is about investing in a particular stock, use [{tool_names}], then give your view based on the output on whether the stock is worth investing in.
Action Input: The input required for the action.
Observation: The outcome of the action.
...(this Consideration/Action/Action Input/Observation process can repeat when necessary)...
Consideration: I have determined the final answer.
Final Answer: The definitive answer to the initial inquiry.
Let’s get started!
Question: {input}
Consideration: {agent_scratchpad}
""")
But for some reason i keep on having this output from my agentexecutor even for the most straightforward question:
`> Entering new AgentExecutor chain...
Action: get-info-stock(ticker="TSLA")
Action Input: TSLAget-info-stock(ticker="TSLA") is not a valid tool, try one of [get-info-stock, get_latest_info, wikipedia, ticker-symbol-search].Consideration: Action: get_info_stock(ticker="TSLA")
Action Input: TSLAget_info_stock(ticker="TSLA") is not a valid tool, try one of [get-info-stock, get_latest_info, wikipedia, ticker-symbol-search].Consideration: Action: wikipedia("What is Tesla market cap")
Action Input: What is Tesla market capwikipedia("What is Tesla market cap") is not a valid tool, try one of [get-info-stock, get_latest_info, wikipedia, ticker-symbol-search].Consideration: Action: ticker-symbol-search(query='What is Tesla market cap')
Action Input: What is Tesla market capticker-symbol-search(query='What is Tesla market cap') is not a valid tool, try one of [get-info-stock, get_latest_info, wikipedia, ticker-symbol-search].Could not parse LLM output: `I am sorry, I am unable to answer this question.`Check your output and make sure it conforms, use the Action/Action Input syntaxQuestion: What is Tesla market cap
Consideration: Action: get_info_stock(ticker="TSLA")
Action Input: TSLAget_info_stock(ticker="TSLA") is not a valid tool, try one of [get-info-stock, get_latest_info, wikipedia, ticker-symbol-search].Consideration: Action: get_latest_info()
Action Input: No inputs requiredget_latest_info() is not a valid tool, try one of [get-info-stock, get_latest_info, wikipedia, ticker-symbol-search].Question: What is Tesla market cap
Consideration: Action: ticker-symbol-search(query='What is Tesla market cap')
Action Input: What is Tesla market capticker-symbol-search(query='What is Tesla market cap') is not a valid tool, try one of [get-info-stock, get_latest_info, wikipedia, ticker-symbol-search].Question: What is Tesla market cap
Consideration: Action: wikipedia("What is Tesla market cap")
Action Input: What is Tesla market capwikipedia("What is Tesla market cap") is not a valid tool, try one of [get-info-stock, get_latest_info, wikipedia, ticker-symbol-search].Consideration: Action: get_info_stock(ticker="TSLA")
Action Input: TSLAget_info_stock(ticker="TSLA") is not a valid tool, try one of [get-info-stock, get_latest_info, wikipedia, ticker-symbol-search].Consideration: I do not have the knowledge to answer that question.
Final Answer: I apologize, but I do not have any knowledge about that topic.
> Finished chain.
{'input': 'What is Tesla market cap',
'output': 'I apologize, but I do not have any knowledge about that topic.'}`
Please help thanks.