OpenAI_Call_functions_Financial_Data
September 22, 2024
[ ]: !pip install openai -q
Specify the API Keys
[3]: from google.colab import userdata
OPENAI_API_KEY = userdata.get('OPENAI_API_KEY')
FINANCIAL_MODELING_PREP_API_KEY = userdata.
↪get('FINANCIAL_MODELING_PREP_API_KEY')
import os
import requests
from openai import OpenAI
client = OpenAI(api_key=OPENAI_API_KEY)
1 Define Your Functions
[ ]: def get_stock_price(symbol):
"""
Fetch the current stock price for the given symbol, the current volume, the␣
↪average price 50d and 200d, EPS, PE and the next earnings Announcement.
"""
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}"}
2 Set Up Function Schemas
[ ]: # Define the function schemas for OpenAI
functions = [
{
"name": "get_stock_price",
"description": "Get the current stock price for a given company 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"],
},
},
]
3 Invoke the Model: GPT-4o-mini and CHAT
[28]: # Chat Function:
MODEL_NAME = "gpt-4o-mini"
def chat_with_LLM(model_name = MODEL_NAME):
messages = []
print("I'm your Financial Analyst Assistant! Ask me anything about stock␣
↪prices, company financials, or income statement.")
while True:
user_input = input("\nYou: ")
if user_input.lower() in ["exit", "quit"]:
print("Assistant: The discussion is terminated!")
break
messages.append({"role": "user", "content": user_input})
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
# Check if the assistant wants to call a function
if response_message.function_call:
function_name = response_message.function_call.name
arguments = response_message.function_call.arguments
# Parse the arguments
import json
args = json.loads(arguments)
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."}
# Add the function's response to the conversation
messages.append(response_message) # Assistant's function call
messages.append({
"role": "function",
"name": function_name,
"content": json.dumps(function_response),
})
# Get the assistant's final response
second_response = client.chat.completions.create(
model=MODEL_NAME,
messages=messages,
)
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})
# Run the chat function
if __name__ == "__main__":
chat_with_LLM()
I'm your Financial Analyst Assistant! Ask me anything about stock prices,
company financials, or income statement.
You: What is the last price of Amazon?
Assistant: The last price of Amazon (AMZN) is $191.60.
You: what was the income revenue of NVIDIA?
Assistant: NVIDIA's revenue for the fiscal year 2024 was $60.92 billion.
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: What is the sector of AMD?
Assistant: The sector of Advanced Micro Devices, Inc. (AMD) is Technology.
You: exit
Assistant: The discussion is terminated!