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:
Gather real-time financial news and market data using OpenTools API’s web search capabilities
Analyze the collected data with IBM watsonx.ai’s foundation models
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
Use OpenTools API to search for recent news and analysis about a specific stock:
Copy
Ask AI
import osfrom openai import OpenAIfrom dotenv import load_dotenvload_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.contentif __name__ == "__main__": market_data = gather_stock_data("NVDA") print("Market Data Gathered:") print(market_data)
Use IBM watsonx.ai to provide investment insights based on the gathered data:
Copy
Ask AI
from ibm_watsonx_ai import APIClient, Credentialsfrom ibm_watsonx_ai.foundation_models import ModelInferencedef 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 responseif __name__ == "__main__": # Example usage market_data = "Sample market data would go here..." analysis = analyze_with_watsonx("NVDA", market_data) print("Investment Analysis:") print(analysis)
Combine data gathering and analysis into a complete research workflow:
Copy
Ask AI
from datetime import datetimedef 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 reportdef 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:
Copy
Ask AI
🔍 Generating research report for NVDA...==================================================Step 1: Gathering real-time market data...Step 2: Analyzing with IBM watsonx.ai...📊 INVESTMENT RESEARCH REPORT==================================================Stock Symbol: NVDAReport Date: 2024-12-19 14:30Generated by: IBM watsonx.ai + OpenTools API📈 MARKET DATA SUMMARY------------------------------Based on recent search results, NVIDIA (NVDA) has shown strong performancedriven by AI chip demand. Recent earnings exceeded expectations with revenuegrowth of 206% year-over-year. Key developments include new data centerpartnerships 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 reachRisk Assessment: MEDIUM- Market volatility in tech sector- Potential regulatory changes in AI space- Competition from other chip manufacturersInvestment Recommendation: BUYThe fundamental strength in AI infrastructure demand, combined with NVIDIA'smarket leadership position, supports a positive outlook despite short-termmarket volatility...💾 Report saved as: NVDA_research_report_20241219_1430.txt
🎉 You’ve created a financial research assistant with IBM watsonx.ai and OpenTools API!