Skip to main content
You can also check this cookbook in Colab here. This notebook demonstrates how to set up and leverage OpenAI Function Calling combined with Dappier for detailed stock market analysis. By integrating real-time trading data and automated function execution, this notebook walks you through a practical approach to generating intelligent, up-to-date investment strategies. In this notebook, you’ll explore:
  • OpenAI Function Calling: A powerful feature that enables large language models to automatically detect and invoke external tools to accomplish tasks in a structured and contextual manner.
  • Dappier: A platform connecting LLMs to real-time, rights-cleared data from trusted sources, specializing in domains like finance, web search, and news. It delivers enriched, prompt-ready data, empowering AI with verified and up-to-date information for diverse applications.
  • Stock Market Analysis: A real-world use case where the assistant reasons over live stock price changes, breaking news, and trade volume in the last 24 hours to deliver a comprehensive financial analysis and investment strategy for a selected company.
This setup not only demonstrates a flexible architecture for building intelligent financial assistants but also serves as a foundation for developing other real-world applications requiring real-time information retrieval, structured tool use, and contextual decision-making. Here’s the Video Walkthrough section, following the same format and tone as the original:

πŸ“Ί Video Walkthrough

Prefer watching? Here’s a video version of this notebook:

πŸ“¦ Installation

Install the required packages:
!pip install openai dappier

πŸ”‘ Setting Up API Keys

You’ll need to set up your API keys for OpenAI, Dappier.
This ensures that the tools can interact with external services securely.
You can go to here to get API Key from Dappier with free credits.
Python
import os
from getpass import getpass

# Prompt for the Dappier API key securely
dappier_api_key = getpass('Enter your API key: ')
os.environ["DAPPIER_API_KEY"] = dappier_api_key
You can go to here to get API Key from Open AI.
Python
# Prompt for the API key securely
openai_api_key = getpass('Enter your API key: ')
os.environ["OPENAI_API_KEY"] = openai_api_key

βš™οΈ Initialize Clients

Set up the OpenAI and Dappier Python SDK clients.
Python
from openai import OpenAI
from dappier import Dappier

# Initialize clients
openai_client = OpenAI()
dappier_client = Dappier()

πŸ›°οΈ Define the Dappier Tool Function

This function will be called by the LLM to fetch real-time stock market data, including the latest news and trades.
Python
def dappier_real_time_stock_analysis(query: str) -> str:
    response = dappier_client.search_real_time_data(
        query=query,
        ai_model_id="am_01j749h8pbf7ns8r1bq9s2evrh"
    )
    return response.message if response else "No data found."

πŸ“‹ Define the User Prompt

This prompt instructs the assistant to gather recent news, trades, and performance metrics, and generate an investment strategy based on those findings.
Python
user_prompt = """
Analyze the stock performance of Tesla (TSLA) using the latest 24-hour news and trading activity. Follow these steps:

1. Fetch Recent News:
Retrieve breaking news and any financial updates affecting Tesla in the last 24 hours.

2. Fetch Trade Data:
Retrieve major trades, price movements, and volume data from the last trading session.

3. Generate a detailed Investment Strategy:
Analyze both data sources to recommend a short-term or long-term investment strategy. Include clear reasoning based on the fetched data.
"""

🧠 Define the Tool Schema for OpenAI

We’ll register dappier_real_time_stock_analysis as a callable tool for OpenAI’s function calling.
Python
tools = [{
    "type": "function",
    "function": {
        "name": "dappier_real_time_stock_analysis",
        "description": "Accesses real-time stock market data including news, trades, and more.",
        "parameters": {
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": "Search query (e.g., 'Tesla stock news and trades in last 24 hours')"
                }
            },
            "required": ["query"]
        }
    }
}]

πŸ€– Run the Assistant Workflow

This function runs the full interaction: the model decides which tools to use, retrieves the data, and then generates a final response.
Python
import json

def run_conversation(user_prompt: str):
    messages = [{"role": "user", "content": user_prompt}]

    # Step 1: Let OpenAI decide on needed functions
    response = openai_client.chat.completions.create(
        model="gpt-4o",
        messages=messages,
        tools=tools,
        tool_choice="auto",
        temperature=0
    )

    response_message = response.choices[0].message

    # Step 2: Call Dappier for each function the model requested
    if tool_calls := response_message.tool_calls:
        messages.append(response_message)

        for tool_call in tool_calls:
            function_args = json.loads(tool_call.function.arguments)
            tool_output = dappier_real_time_stock_analysis(query=function_args["query"])

            messages.append({
                "tool_call_id": tool_call.id,
                "role": "tool",
                "name": tool_call.function.name,
                "content": tool_output,
            })

    # Step 3: Final call to OpenAI with all gathered data
    final_response = openai_client.chat.completions.create(
        model="gpt-4o-mini",
        messages=messages,
        temperature=0,
        stream=True
    )

    return final_response

πŸš€ Generate the Stock Analysis & Strategy

Run the full conversation and stream the final response as the investment report and strategy.
Python
if __name__ == "__main__":
    print("Processing stock analysis...\n")

    response = run_conversation(user_prompt)

    print("\nπŸ“Š Investment Strategy:\n")
    for chunk in response:
        print(chunk.choices[0].delta.content or "", end='', flush=True)
Processing stock analysis...


πŸ“Š Investment Strategy:

### Investment Strategy for Tesla (TSLA)

#### Recent News Analysis:
1. **Positive Developments:**
   - Tesla's stock has surged by 10.3% due to the approval of its Full Self-Driving feature in China and potential expansion plans in India. This indicates strong growth prospects in two major markets, which could significantly boost Tesla's revenue and market share.
   - The broader market rally, influenced by potential easing of tariff plans by the Trump administration, has also positively impacted Tesla's stock, with a 4% rise in pre-market trading.

2. **Negative Sentiments:**
   - Despite recent gains, there are concerns about Tesla's valuation and its first-ever decline in EV deliveries in 2024. This suggests potential challenges in maintaining its growth trajectory amidst increasing competition in the EV market.

#### Trade Data Analysis:
- The trading activity shows a consistent price range around $282.36 to $282.40, with significant volumes being traded. This indicates a stable interest in the stock at this price level, suggesting a consolidation phase after recent gains.

### Investment Recommendation:
**Short-Term Strategy:**
- **Buy:** Given the positive news about Tesla's expansion in China and India, and the current market rally, there is a short-term opportunity to capitalize on the momentum. The stock's recent surge and stable trading range suggest potential for further gains in the near term.

**Long-Term Strategy:**
- **Hold/Monitor:** While the short-term outlook is positive, the long-term strategy should be cautious. The concerns about Tesla's valuation and delivery decline highlight the need for careful monitoring of its financial performance and market position. Investors should watch for further developments in Tesla's expansion plans and competitive positioning in the EV market.

**Conclusion:**
- For short-term investors, the current positive momentum presents a buying opportunity. However, long-term investors should remain vigilant and consider the broader market dynamics and Tesla's strategic initiatives before making significant commitments.

🌟 Highlights

This notebook has guided you through setting up and running a real-time stock analysis workflow using OpenAI Function Calling and Dappier. You can adapt and expand this example for various other scenarios requiring live financial insights, contextual understanding, and intelligent decision-making. Key tools utilized in this notebook include:
  • OpenAI Function Calling: Allows the model to automatically determine when to invoke external tools, enabling dynamic decision-making during a conversation.
  • Dappier: A platform connecting LLMs to real-time, rights-cleared data from trusted sources, specializing in domains like finance, news, and trading. It delivers enriched, prompt-ready data, empowering AI with verified and up-to-date information for diverse applications.
  • Streamed Response Generation: Leverages OpenAI’s streaming capability to output responses incrementally, improving performance and responsiveness when generating long-form content.
This comprehensive setup allows you to adapt and expand the example for various financial use cases requiring real-time information retrieval, AI-powered orchestration, and live strategy generation.