> ## Documentation Index
> Fetch the complete documentation index at: https://docs.dappier.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 🛠️ Real-Time Stock Market Analyst with OpenAI Function Calling + Stock Market Data via Dappier

You can also check this cookbook in Colab [here](https://colab.research.google.com/drive/1DQGn4lKY1ioV3C0cSpvPCkkPlcQGNCf6?usp=sharing).

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:

<iframe width="560" height="315" src="https://www.youtube.com/embed/ry6hOHit__s?si=0m046ETmBnwdFQr2" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen />

***

## 📦 Installation

Install the required packages:

```bash theme={null}
!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](https://platform.dappier.com/profile/api-keys) to get API Key from Dappier with **free** credits.

```python Python theme={null}
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](https://platform.openai.com/settings/organization/api-keys) to get API Key from Open AI.

```python Python theme={null}
# 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 Python theme={null}
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 Python theme={null}
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 Python theme={null}
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 Python theme={null}
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 Python theme={null}
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 Python theme={null}
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)
```

```json theme={null}
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.
