OpenAI Function Calling for Financial Data Retrieval
OpenAI Function Calling for Financial Data Retrieval
import os
import requests
"""
url = f"https://financialmodelingprep.com/api/v3/quote-order/{symbol}?
↪apikey={FINANCIAL_MODELING_PREP_API_KEY}"
response = requests.get(url)
data = response.json()
try:
price = data[0]['price']
volume = data[0]['volume']
priceAvg50 = data[0]['priceAvg50']
priceAvg200 = data[0]['priceAvg200']
eps = data[0]['eps']
pe = data[0]['pe']
earningsAnnouncement = data[0]['earningsAnnouncement']
return {"symbol": symbol.upper(), "price": price, "volume":
↪volume,"priceAvg50":priceAvg50, "priceAvg200":priceAvg200, "EPS":eps, "PE":
↪pe, "earningsAnnouncement":earningsAnnouncement }
1
except (IndexError, KeyError):
return {"error": f"Could not fetch price for symbol: {symbol}"}
def get_company_financials(symbol):
"""
Fetch basic financial information for the given company symbol such as the␣
↪industry, the sector, the name of the company, and the market capitalization.
"""
url = f"https://financialmodelingprep.com/api/v3/profile/{symbol}?
↪apikey={FINANCIAL_MODELING_PREP_API_KEY}"
response = requests.get(url)
data = response.json()
try:
results = data[0]
financials = {
"symbol": results["symbol"],
"companyName": results["companyName"],
"marketCap": results["mktCap"],
"industry": results["industry"],
"sector": results["sector"],
"website": results["website"],
"beta":results["beta"],
"price":results["price"],
}
return financials
except (IndexError, KeyError):
return {"error": f"Could not fetch financials for symbol: {symbol}"}
def get_income_statement(symbol):
"""
Fetch last income statement for the given company symbol such as revenue,␣
↪gross profit, net income, EBITDA, EPS.
"""
url = f"https://financialmodelingprep.com/api/v3/income-statement/{symbol}?
↪period=annual&apikey={FINANCIAL_MODELING_PREP_API_KEY}"
response = requests.get(url)
data = response.json()
try:
results = data[0]
financials = {
"date": results["date"],
"revenue": results["revenue"],
"gross profit": results["grossProfit"],
"net Income": results["netIncome"],
"ebitda": results["ebitda"],
"EPS": results["eps"],
"EPS diluted":results["epsdiluted"]
2
}
return data, financials
except (IndexError, KeyError):
return {"error": f"Could not fetch financials for symbol: {symbol}"}
"parameters": {
"type": "object",
"properties": {
"symbol": {
"type": "string",
"description": "The stock ticker symbol, e.g., AAPL for␣
↪Apple."
}
},
"required": ["symbol"],
},
},
{
"name": "get_company_financials",
"description": "Get basic financial information for a given company.",
"parameters": {
"type": "object",
"properties": {
"symbol": {
"type": "string",
"description": "The stock ticker symbol, e.g., GOOGL for␣
↪Alphabet Inc."
}
},
"required": ["symbol"],
},
},
{
"name": "get_income_statement",
"description": "Get the last income statement for a given company␣
↪symbol.",
"parameters": {
"type": "object",
3
"properties": {
"symbol": {
"type": "string",
"description": "The stock ticker symbol, e.g., AMZN for␣
↪Amazon."
}
},
"required": ["symbol"],
},
},
]
while True:
user_input = input("\nYou: ")
if user_input.lower() in ["exit", "quit"]:
print("Assistant: The discussion is terminated!")
break
response = client.chat.completions.create(
model=MODEL_NAME,
messages=messages,
functions=functions,
function_call="auto", # Let the model decide if a function needs␣
↪to be called
response_message = response.choices[0].message
4
# Call the appropriate function
if function_name == "get_stock_price":
function_response = get_stock_price(**args)
elif function_name == "get_company_financials":
function_response = get_company_financials(**args)
elif function_name == "get_income_statement":
function_response = get_income_statement(**args)
else:
function_response = {"error": "Function not found."}
final_message = second_response.choices[0].message.content
print(f"Assistant: {final_message}")
messages.append({"role": "assistant", "content": final_message})
else:
# If no function call is needed, just output the assistant's message
assistant_reply = response_message.content
print(f"Assistant: {assistant_reply}")
messages.append({"role": "assistant", "content": assistant_reply})
I'm your Financial Analyst Assistant! Ask me anything about stock prices,
company financials, or income statement.
5
You: What was the last revenue reported by Apple?
Assistant: Apple's last reported revenue for the fiscal year 2023 was $383.29
billion.
You: exit
Assistant: The discussion is terminated!