analyze_natural_query
Process natural language queries about companies, financials, governance, or markets to analyze relationships in the Spanish stock exchange.
Instructions
Process and execute complex natural language queries about companies, financials, governance, or markets
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| context | No | Optional context or previous query results to build upon | |
| query | Yes | Natural language query (e.g., "Which banking stocks have grown most in the last month?", "Show me companies with high governance risk", "Compare energy sector performance") |
Implementation Reference
- src/index.ts:362-378 (schema)Tool schema definition including input schema for natural language query and optional context.name: 'analyze_natural_query', description: 'Process and execute complex natural language queries about companies, financials, governance, or markets', inputSchema: { type: 'object', properties: { query: { type: 'string', description: 'Natural language query (e.g., "Which banking stocks have grown most in the last month?", "Show me companies with high governance risk", "Compare energy sector performance")', }, context: { type: 'string', description: 'Optional context or previous query results to build upon', }, }, required: ['query'], }, },
- src/index.ts:657-659 (registration)Registration in the tool dispatcher switch statement, delegating to analytics.analyzeNaturalQuery.case 'analyze_natural_query': result = await this.analytics.analyzeNaturalQuery((args as any)?.query, (args as any)?.context); break;
- src/analytics.ts:185-311 (handler)Core handler function that interprets natural language queries using regex patterns, dispatches to appropriate analytics methods (e.g., sector analysis, risk assessment), and returns structured results with suggestions.async analyzeNaturalQuery(query: string, context?: string): Promise<any> { const lowerQuery = query.toLowerCase(); const analysis = { original_query: query, context: context, interpretation: '', suggested_actions: [], results: {}, execution_plan: [] }; try { // Banking-related queries if (lowerQuery.match(/\b(bank|banking|financial)\b.*\b(grow|growth|performance|best|worst)\b/)) { analysis.interpretation = 'Banking sector performance analysis'; analysis.execution_plan.push('Get banking sector companies', 'Analyze recent performance', 'Rank by growth'); const bankingCompanies = await this.db.getCompaniesBySector('banking'); const performances = await this.analyzeCompanyPerformances(bankingCompanies, 30); analysis.results = { sector: 'Banking', companies_analyzed: bankingCompanies.length, top_performers: performances.slice(0, 5), analysis_period: '30 days' }; } // High risk queries else if (lowerQuery.match(/\b(risk|risky|governance|red flag)\b/)) { analysis.interpretation = 'Risk assessment analysis'; analysis.execution_plan.push('Analyze governance risks', 'Check market risks', 'Generate risk report'); const companies = await this.db.getAllCompanies(); const interlocks = await this.db.getBoardInterlocks(); const governanceRisks = await this.getGovernanceRiskFactors(companies, interlocks); analysis.results = { total_companies_analyzed: companies.length, governance_risks: governanceRisks, high_risk_companies: governanceRisks.governance_red_flags.filter(f => f.severity === 'high').length, recommendations: this.generateRiskRecommendations(governanceRisks) }; } // Comparison queries else if (lowerQuery.match(/\b(compare|vs|versus|against)\b/)) { analysis.interpretation = 'Company comparison analysis'; // Try to extract company names from the query const companyPatterns = [ /\b(santander|san\.mc|san)\b/i, /\b(bbva|bbva\.mc)\b/i, /\b(iberdrola|ibe\.mc|ibe)\b/i, /\b(telefonica|tef\.mc|tef)\b/i, /\b(inditex|itx\.mc|itx)\b/i ]; const foundCompanies = []; for (const pattern of companyPatterns) { if (lowerQuery.match(pattern)) { const match = lowerQuery.match(pattern); if (match) foundCompanies.push(match[0].toUpperCase()); } } if (foundCompanies.length >= 2) { analysis.results = await this.compareCompanies(foundCompanies, ['all']); } else { analysis.results = { error: 'Could not identify companies to compare', suggestion: 'Try: "Compare Santander vs BBVA" or use company symbols like SAN.MC vs BBVA.MC' }; } } // Sector performance queries else if (lowerQuery.match(/\b(sector|industry).*\b(performance|trend|growth)\b/)) { const sectorMatch = lowerQuery.match(/\b(banking|energy|telecom|textile|steel|aviation|infrastructure)\b/); const sector = sectorMatch ? sectorMatch[1] : 'energy'; // default to energy as example analysis.interpretation = `${sector} sector performance analysis`; const sectorResults = await this.getSectorCorrelationAnalysis(30); analysis.results = { ...sectorResults, focused_sector: sector }; } // Price/trend queries else if (lowerQuery.match(/\b(price|trend|forecast|prediction)\b/)) { analysis.interpretation = 'Price trend analysis'; const companies = await this.db.getAllCompanies(); const topPerformers = await this.db.getTopPerformers(30, 10); analysis.results = { analysis_type: 'Price trends over 30 days', top_performers: topPerformers, trend_summary: this.generateTrendSummary(topPerformers) }; } // General fallback else { analysis.interpretation = 'General market overview'; const companies = await this.db.getAllCompanies(); const recent_news = await this.db.getRecentNews(undefined, 5); const top_performers = await this.db.getTopPerformers(7, 5); analysis.results = { total_companies: companies.length, recent_market_news: recent_news.length, weekly_top_performers: top_performers, market_snapshot: 'Current IBEX 35 overview' }; } analysis.suggested_actions = this.generateActionSuggestions(analysis.interpretation, analysis.results); return analysis; } catch (error) { return { ...analysis, error: `Failed to process natural language query: ${error}`, fallback_suggestion: 'Try using specific tool names like get_all_companies, get_recent_news, or get_board_interlocks' }; } }