IBM watsonx Integration

Create intelligent research assistants using IBM watsonx.ai and OpenTools API

Prerequisites

Before you start, make sure you have: Note: This guide is only available in Python

Overview

By the end of this guide, you will be able to create a financial research assistant that gathers real-time market data and provides AI-powered investment insights. You’ll learn how to:
  1. Gather real-time financial news and market data using OpenTools API’s web search capabilities
  2. Analyze the collected data with IBM watsonx.ai’s foundation models
  3. Generate comprehensive investment research reports
This integration is useful for:
  • Real-time Analysis: Access current market data instead of relying on training cutoff dates
  • Comprehensive Research: Combine multiple data sources for thorough analysis
  • Investment Insights: Leverage IBM watsonx’s reasoning capabilities for market analysis
  • Automated Reporting: Generate formatted research reports at scale

Build a Financial Research Assistant

1. Set up your environment

Install the required dependencies and set up your API keys.
pip install openai ibm-watsonx-ai python-dotenv
Create a .env file with your API keys:
IBM_API_KEY=your_ibm_api_key
IBM_PROJECT_ID=your_ibm_project_id

OPENTOOLS_API_KEY=your_opentools_api_key

2. Gather real-time market data

Use OpenTools API to search for recent news and analysis about a specific stock:
import os
from openai import OpenAI
from dotenv import load_dotenv

load_dotenv()

def gather_stock_data(symbol):
    """Gather recent news and market data for a stock symbol"""

    client = OpenAI(
        api_key=os.getenv("OPENTOOLS_API_KEY"),
        base_url="https://api.opentools.com/v1"
    )

    response = client.chat.completions.create(
        model="anthropic/claude-3.5-sonnet",
        messages=[
            {
                "role": "system",
                "content": "You are a financial research assistant. Search for and summarize recent news, earnings reports, analyst opinions, and market data about the requested stock. Focus on factual information and recent developments."
            },
            {
                "role": "user",
                "content": f"Find recent news, earnings data, and analyst opinions about {symbol} stock. Include any significant market movements or company developments from the past month."
            }
        ],
        tools=[{"type": "mcp", "ref": "exa"}]
    )

    return response.choices[0].message.content

if __name__ == "__main__":
    market_data = gather_stock_data("NVDA")
    print("Market Data Gathered:")
    print(market_data)

3. Analyze with IBM watsonx.ai

Use IBM watsonx.ai to provide investment insights based on the gathered data:
from ibm_watsonx_ai import APIClient, Credentials
from ibm_watsonx_ai.foundation_models import ModelInference

def analyze_with_watsonx(symbol, market_data):
    """Analyze market data using IBM watsonx.ai"""

    # Set up IBM watsonx.ai client
    credentials = Credentials(
        url="https://us-south.ml.cloud.ibm.com",  # Use your region's URL
        api_key=os.getenv("IBM_API_KEY")
    )

    client = APIClient(credentials)
    project_id = os.getenv("IBM_PROJECT_ID")

    print(f"Using IBM watsonx.ai project ID: {project_id}")

    # Initialize the model
    model = ModelInference(
        model_id="ibm/granite-3-8b-instruct",
        api_client=client,
        project_id=project_id,
        params={
            "max_new_tokens": 1000,
            "temperature": 0.3
        }
    )

    # Create analysis prompt
    analysis_prompt = f"""
    As a senior financial analyst, analyze the following market data for {symbol} and provide:

    1. Key market developments and their potential impact
    2. Risk assessment (Low/Medium/High)
    3. Investment recommendation (Buy/Hold/Sell) with reasoning
    4. Price target considerations
    5. Key factors to monitor going forward

    Market Data:
    {market_data}

    Provide a clear, structured analysis suitable for investment decision-making.
    """

    # Generate analysis
    print(f"Analyzing {symbol} with IBM watsonx.ai...")
    response = model.generate_text(
        prompt=analysis_prompt,
        params={
            "input_type": "text"
        }
    )

    return response

if __name__ == "__main__":
    # Example usage
    market_data = "Sample market data would go here..."
    analysis = analyze_with_watsonx("NVDA", market_data)
    print("Investment Analysis:")
    print(analysis)

4. Create a comprehensive research report

Combine data gathering and analysis into a complete research workflow:
from datetime import datetime

def create_research_report(symbol):
    """Generate a complete research report for a stock symbol"""

    print(f"🔍 Generating research report for {symbol}...")
    print("=" * 50)

    # Step 1: Gather market data
    print("Step 1: Gathering real-time market data...")
    market_data = gather_stock_data(symbol)

    # Step 2: Analyze with IBM watsonx
    print("\nStep 2: Analyzing with IBM watsonx.ai...")
    analysis = analyze_with_watsonx(symbol, market_data)

    # Step 3: Format the report
    report = f"""
📊 INVESTMENT RESEARCH REPORT
{'=' * 50}
Stock Symbol: {symbol}
Report Date: {datetime.now().strftime('%Y-%m-%d %H:%M')}
Generated by: IBM watsonx.ai + OpenTools API

📈 MARKET DATA SUMMARY
{'-' * 30}
{market_data}

🧠 AI INVESTMENT ANALYSIS
{'-' * 30}
{analysis}

📋 REPORT METHODOLOGY
{'-' * 30}
• Real-time data gathered via OpenTools API web search
• Analysis powered by IBM watsonx.ai foundation models
• Report generated: {datetime.now().strftime('%Y-%m-%d %H:%M UTC')}
    """

    return report

def main():
    """Main function to run the research assistant"""
    symbol = "NVDA"  # You can change this to any stock symbol

    try:
        report = create_research_report(symbol)
        print(report)

        # Optionally save to file
        filename = f"{symbol}_research_report_{datetime.now().strftime('%Y%m%d_%H%M')}.txt"
        with open(filename, 'w') as f:
            f.write(report)
        print(f"\n💾 Report saved as: {filename}")

    except Exception as e:
        print(f"❌ Error generating report: {str(e)}")

if __name__ == "__main__":
    main()
Example output:
🔍 Generating research report for NVDA...
==================================================
Step 1: Gathering real-time market data...
Step 2: Analyzing with IBM watsonx.ai...

📊 INVESTMENT RESEARCH REPORT
==================================================
Stock Symbol: NVDA
Report Date: 2024-12-19 14:30
Generated by: IBM watsonx.ai + OpenTools API

📈 MARKET DATA SUMMARY
------------------------------
Based on recent search results, NVIDIA (NVDA) has shown strong performance
driven by AI chip demand. Recent earnings exceeded expectations with revenue
growth of 206% year-over-year. Key developments include new data center
partnerships and expanded AI infrastructure investments...

🧠 AI INVESTMENT ANALYSIS
------------------------------
Key Market Developments:
- Strong AI chip demand continues to drive revenue growth
- Data center segment showing exceptional performance
- New partnerships expanding market reach

Risk Assessment: MEDIUM
- Market volatility in tech sector
- Potential regulatory changes in AI space
- Competition from other chip manufacturers

Investment Recommendation: BUY
The fundamental strength in AI infrastructure demand, combined with NVIDIA's
market leadership position, supports a positive outlook despite short-term
market volatility...

💾 Report saved as: NVDA_research_report_20241219_1430.txt
🎉 You’ve created a financial research assistant with IBM watsonx.ai and OpenTools API!

Next Steps

With this foundation, you can build more advanced workflows:
  • Multi-stock Analysis: Compare multiple stocks simultaneously
  • Automated Monitoring: Schedule regular reports and track changes over time
  • Portfolio Optimization: Analyze entire portfolios and suggest rebalancing
  • Risk Management: Set up alerts for significant market movements
  • Custom Models: Fine-tune IBM watsonx models for specific investment strategies

Best Practices

  • Rate Limiting: Implement appropriate delays between API calls to respect rate limits
  • Error Handling: Add robust error handling for network issues and API failures
  • Data Validation: Verify the quality and recency of gathered market data
  • Security: Never expose API keys in code or public repositories
  • Cost Monitoring: Track API usage across both services to manage costs effectively
For more information, explore: