Skip to main content
You can also check this cookbook in colab here This notebook demonstrates how to set up and leverage LangChain’s powerful chaining capabilities combined with Dappier’s DappierRealTimeSearchTool for real-time market insights and trading strategies. By integrating real-time financial news, stock trends, and advanced language models, this notebook walks you through an innovative approach to identifying top investment opportunities and crafting data-driven trading strategies. In this notebook, you’ll explore:
  • LangChain: A versatile framework for chaining together language models and other components to create sophisticated AI-driven workflows. It enables seamless integration of LLMs with external tools and data sources, making it ideal for tasks like summarization, question-answering, and more.
  • Dappier: A platform connecting LLMs and Agentic AI agents to real-time, rights-cleared data from trusted sources, specializing in domains like web search, finance, and news. It delivers enriched, prompt-ready data, empowering AI with verified and up-to-date information for diverse applications.
  • OpenAI: A leading provider of advanced AI models capable of natural language understanding, contextual reasoning, and content generation. It enables intelligent, human-like interactions and supports a wide range of applications across various domains.
  • LangSmith: A platform for debugging, testing, and monitoring LangChain applications. It provides detailed tracing and analytics to help you understand and optimize the performance of your AI workflows.
This setup not only demonstrates a practical application of AI-driven real-time market insights and trading strategies but also provides a flexible framework that can be adapted to other real-world scenarios requiring real-time financial data integration from Dappier and advanced language model capabilities. Disclaimer: This notebook is for educational and informational purposes only. It does not constitute financial or trading advice. Trading in financial markets involves risk, and you should consult with a qualified financial advisor before making any investment decisions.

Watch the Video Guide

If you prefer a visual walkthrough, check out the accompanying video guide below:

πŸ“¦ Installation

First, install the Langchain Dappier integration package with all its dependencies:
Python
!pip install langchain langchain-dappier langchain-openai

πŸ”‘ Setting Up API Keys

You’ll need to set up your API keys for Dappier, OpenAI and LangSmith You can go to here to get API Key from Dappier with free credits. The API Key could be found under Settings -> Profile.
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
Your can go to here to get API Key from Open AI.
Python
# Prompt for the Open AI API key securely
openai_api_key = getpass('Enter your API key: ')
os.environ["OPENAI_API_KEY"] = openai_api_key
Your can go to here to get API Key from LangSmith.
Python
# Prompt for the LangSmith API key securely
langsmith_api_key = getpass('Enter your API key: ')
os.environ["LANGSMITH_API_KEY"] = langsmith_api_key
os.environ["LANGSMITH_TRACING"] = "true"

πŸ›°οΈ Access Real Time Data with Dappier Tool

The DappierRealTimeSearchTool is a powerful tool designed to empower AI applications with real-time, up-to-date information across diverse domains such as news, weather, travel, and financial markets. By integrating seamlessly with LangChain, it enables developers to retrieve and process real-time data efficiently. Key features include access to the latest news, weather updates, travel deals, financial news, stock prices, and AI-enhanced insights for accurate and fast information retrieval. With its easy-to-use API and customizable parameters, the tool is ideal for building dynamic, data-driven applications that require real-time intelligence. In this section, we will search for the latest news related to Langchain as an example. Explore a wide range of data models in our marketplace at marketplace.dappier.com. For list of all parameters supported for Dappier retriever visit Dappier docs.
Python
from langchain_dappier import DappierRealTimeSearchTool

tool = DappierRealTimeSearchTool()

response = tool.invoke({"query": "Latest news on Langchain AI"})

print(response)
Here’s the latest on Langchain AI:

1. **Interrupt Conference**: LangChain is hosting the "Interrupt: The AI Agent Conference"! πŸŽ‰ It's a great opportunity to dive deep into AI agents and their applications.

2. **New Evals Framework**: They’ve introduced a new way to run evaluations using LangSmith's Pytest and Vitest/Jest, making it easier for developers to assess performance. πŸ§ͺ

3. **Funding Success**: LangChain recently secured $25 million in funding to enhance their platform, focusing on supporting the full lifecycle of Large Language Models (LLMs). πŸš€

4. **Growing Adoption of AI Agents**: A recent report revealed that 78% of companies plan to implement AI agents soon, with 51% already using them in production. Mid-sized companies are leading the charge at 63%. πŸ“ˆ

5. **Hugging Face Collaboration**: There’s a new partnership with Hugging Face, allowing users to run thousands of AI models locally for free! πŸ€–

Exciting developments ahead for LangChain!
πŸŽ‰ Dappier effortlessly retrieves the latest on Langchain AI, providing valuable data for AI integration!

πŸ“ˆπŸ’° Real-Time Market Insights & Trading Strategies

This section sets up an automated workflow where LangChain and the DappierRealTimeSearchTool collaborate to generate real-time market insights and trading strategies. We will guide the system in retrieving real-time financial news and stock trends, leveraging OpenAI models to analyze data and craft dynamic, actionable trading recommendations.
Python
from langchain.chat_models import init_chat_model
from langchain_dappier import DappierRealTimeSearchTool
from langchain_core.messages import HumanMessage, ToolMessage
from langchain_core.runnables import RunnableConfig
import json
Define the task prompt
Python
TASK_PROMPT = """
Generate a Stock Trading Strategy for the US Market, Tailored to Real-Time
Financial News and Stock Trends. Follow These Steps:

Fetch Current Financial News:
Retrieve the latest financial news in the US using Dappier real-time search to
identify market-moving events, economic updates, or sector-specific
developments.

Fetch Stock Trends:
Retrieve the latest stock market trends in the US using Dappier real-time
search to analyze price movements, volume changes, and sector performance.

Select Top 5 Stocks:
Based on the financial news and stock trends, pick the top 5 stocks that show
strong potential for growth or stability. Include an analysis of why these
stocks were chosen.

Design a Trading Strategy:
Create a dynamic trading strategy tailored to the selected stocks.
Include details such as:

Entry and exit points

Risk management techniques (e.g., stop-loss levels)

Time horizon (short-term, medium-term, or long-term)

Sector diversification (if applicable)

How current financial news and trends influence the strategy.

Final Response:
The final response should include:

A summary of the latest financial news and stock trends.

The top 5 selected stocks with analysis.

A detailed trading strategy with actionable steps.
"""
Here we set up our language model and the Dappier real-time search tool. For list of all parameters supported for Dappier retriever visit Dappier docs. Explore a wide range of data models in our marketplace at marketplace.dappier.com.
Python
# Set up model and tools
llm = init_chat_model("gpt-4o", model_provider="openai", streaming=True)
dappier_tool = DappierRealTimeSearchTool()
llm_with_tools = llm.bind_tools([dappier_tool])
Setup a function to handle the streaming output from the language model.
Python
async def stream_llm_response(stream):
    """Print the LLM's response as it comes in"""
    async for event in stream:
        # Handle streaming chunks
        if event["event"] == "on_chat_model_stream":
            content = event["data"]["chunk"].content
            if content:
                print(content, end="", flush=True)

        # Return final output when stream ends
        if event["event"] == "on_chat_model_end":
            return event["data"]["output"]
Create a function to process any tool calls made by the language model.
Python
async def process_tool_calls(tool_calls, messages):
    """Handle any tool calls the LLM makes"""
    print("\n\nProcessing tool calls...")
    for i, call in enumerate(tool_calls, 1):
        # Print tool call information
        print(f"\nTool Call {i}:")
        print(f"Name: {call['function']['name']}")
        print(f"Arguments: {call['function']['arguments']}")

        # Extract and process query
        args = call.get('function', {}).get('arguments', '{}')
        if isinstance(args, str):
            args = json.loads(args)
        query = args.get("query", "")

        # Execute tool and show result
        print(f"\nTool Response {i}:")
        result = await dappier_tool.ainvoke({"query": query})
        print(result)

        # Add tool response to message history
        messages.append(ToolMessage(
            content=result,
            tool_call_id=call['id'],
            name=call['function']['name']
        ))
Setup a function to finally generate a trading strategy using real-time data
Python
async def generate_trading_strategy():
    """Generate a trading strategy using real-time data"""
    # Initialize message history and config
    messages = [HumanMessage(content=TASK_PROMPT)]
    config = RunnableConfig(callbacks=None)

    # Get initial response and handle tool calls
    print("Initial LLM response:")
    print("-------------------")
    initial_response = await stream_llm_response(
        llm_with_tools.astream_events(messages, config=config, version="v1")
    )

    # Process tool calls and get final response
    messages.append(initial_response)
    tool_calls = initial_response.additional_kwargs.get("tool_calls", [])
    if tool_calls:
        await process_tool_calls(tool_calls, messages)

    # Generate final response incorporating tool results
    print("\nFinal LLM response:")
    print("------------------")
    await stream_llm_response(
        llm_with_tools.astream_events(messages, config=config, version="v1")
    )
Execute the trading strategy generator
Python
await generate_trading_strategy()
Initial LLM response:
-------------------

Processing tool calls...

Tool Call 1:
Name: dappier_real_time_search
Arguments: {"query": "latest US financial news"}

Tool Response 1:
Here’s the latest scoop on US financial news:

- **Treasury Yields**: They’ve fallen slightly as investors are on the lookout for more economic data. πŸ“‰

- **Stock Movements**: Stocks are making waves after hours, so keep an eye on that!

- **Sustainability Attacks**: US financial firms are distancing themselves from right-wing attacks on sustainability, while the Transition Finance Council is working with cities to ramp up decarbonization efforts. 🌍

- **Alibaba's Performance**: Chinese giant Alibaba reported a profit and revenue beat for the December quarter, driven by strength in its cloud unit. πŸ“Š

- **Palantir’s Plunge**: Palantir's stock took a hit after CEO Alex Karp changed share sales, causing some market jitters.

- **Inflation and Fed Outlook**: December's inflation data is complicating the Federal Reserve's outlook on potential interest rate cuts. πŸ“ˆ

- **Student Debt Relief**: More relief is on the way as President Biden prepares to exit office.

If you want more details on any specific topic, just let me know! 😊

Tool Call 2:
Name: dappier_real_time_search
Arguments: {"query": "latest US stock market trends"}

Tool Response 2:
Here’s the latest on US stock market trends:

- **Dow Index**: 44,627.59 (+71.25, +0.16%)
- **S&P 500 Index**: 6,144.15 (+14.57, +0.24%)

### After-Hours:
- **Bitcoin**: $95,620.00 (-$534.00, -0.56%)
- **Ether**: $2,723.90 (+$63.10, +2.37%)

### Currency Rates:
- **Euro/US Dollar**: 1.0424 (-0.00, -0.02%)
- **British Pound/US Dollar**: 1.2584 (-0.00, -0.01%)

Looks like the markets are showing some positive movement overall! πŸ“ˆ If you need more details or specific stocks, just let me know! 😊

Final LLM response:
------------------
### Summary of Latest Financial News and Stock Trends:

#### Latest US Financial News:
- **Treasury Yields**: Slight drop as investors anticipate more economic data.
- **After-Hours Stock Movements**: Some fluctuations observed in post-market trading.
- **Sustainability and Decarbonization**: Financial firms distancing from right-wing attacks as cities gear up for decarbonization.
- **Alibaba**: Reports a profit and revenue beat, driven by cloud services.
- **Palantir**: Sees a stock dip due to CEO's share sales changes.
- **Inflation Data**: Complicates Federal Reserve's interest rate decisions.
- **Student Debt Relief**: More expected as part of President Biden's agenda.

#### Latest US Stock Market Trends:
- **Dow Index**: 44,627.59, up by 0.16%.
- **S&P 500 Index**: 6,144.15, up by 0.24%.
- **Bitcoin**: Dropped slightly in after-hours trading.
- **Ether**: Notable increase in value after hours.

### Top 5 Selected Stocks:

1. **Alibaba (BABA)**:
    - **Analysis**: Strong quarterly performance with profit and revenue beats, particularly in cloud services. Positive outlook on tech sector and digital transformation efforts.

2. **Palantir Technologies (PLTR)**:
    - **Analysis**: Recent stock dip provides a potential buying opportunity. The company remains pivotal in the data analytics sector, with focus on government and corporate contracts.

3. **TESLA (TSLA)**:
    - **Analysis**: Growing advancements in electric vehicles and sustainability; long-term growth potential.

4. **Apple Inc. (AAPL)**:
    - **Analysis**: New product launches and strong ecosystem create consistent market performance. The tech giant’s adaptability to market demands is commendable.

5. **NVIDIA Corporation (NVDA)**:
    - **Analysis**: Strength as a leader in semiconductor space, heavily involved in AI and gaming industries.

### Trading Strategy:

- **Entry and Exit Points**:
    - **Alibaba**: Enter at current levels or slight pullbacks, targeting upside with expected growth from cloud services expansion.
    - **Palantir**: Enter on further dips to leverage volatility, aiming for recovery to previous high levels.
    - **Tesla, Apple, NVIDIA**: Enter at current levels with plans to hold for medium-term appreciating valuation. Expect short-term fluctuations, yet long-term upward potential due to sector leadership.

- **Risk Management Techniques**:
    - Implement stop-loss orders around 5% below entry price to safeguard against unexpected downturns.
    - Diversify holdings to mitigate sector-specific risks.

- **Time Horizon**:
    - Primarily medium-term (6-12 months), with potential for some long-term positions based on stock performance and sector evolution.

- **Sector Diversification**:
    - Technology focus, with exposure to electric vehicles (Tesla), semiconductors (NVIDIA), and cloud services (Alibaba).

- **Influence of Current News and Trends**:
    - Market-moving news such as inflation and Federal Reserve actions are immediate focus areas to gauge broader economic impact.
    - Positive corporate earnings and sustainability initiatives serve as strong catalysts for tech and related sectors.

This strategy leverages the latest financial insights and trends, aiming to capitalize on economic shifts and sector strengths. Please invest wisely, considering personal risk tolerance and financial objectives.

🌟 Highlights

This notebook has guided you through setting up and running a Langchain RAG workflow with Dappier for a generating Real-Time Market Analysis & Trading Strategy. You can adapt and expand this example for various other scenarios requiring advanced web information retrieval and AI collaboration. Key tools utilized in this notebook include:
  • LangChain: A versatile framework for chaining together language models and other components to create sophisticated AI-driven workflows. It enables seamless integration of LLMs with external tools and data sources, making it ideal for tasks like summarization, question-answering, and more.
  • Dappier: A platform connecting LLMs and Agentic AI agents to real-time, rights-cleared data from trusted sources, specializing in domains like web search, finance, and news. It delivers enriched, prompt-ready data, empowering AI with verified and up-to-date information for diverse applications.
  • OpenAI: A leading provider of advanced AI models capable of natural language understanding, contextual reasoning, and content generation. It enables intelligent, human-like interactions and supports a wide range of applications across various domains.
  • LangSmith: A platform for debugging, testing, and monitoring LangChain applications. It provides detailed tracing and analytics to help you understand and optimize the performance of your AI workflows.
This comprehensive setup allows you to adapt and expand the example for various scenarios requiring advanced web information retrieval, AI collaboration, and multi-source data aggregation.