Skip to content

Multi-agent stock analysis system with real-time collaboration, cost tracking, and knowledge ontology

Notifications You must be signed in to change notification settings

Replicant-Partners/efrain-ai

Repository files navigation

Efrain AI πŸ€–

Protocol-based multi-agent stock analysis system with real-time collaboration, cost tracking, and knowledge ontology.

Built with Claude AI β€’ Inspired by Fermi Framework β€’ Production Ready


🌟 What Makes Efrain AI Different?

Unlike traditional sequential analysis tools, Efrain AI features 4 specialized agents that collaborate in real-time through a protocol layer. Agents share insights during analysis, adjust their conclusions based on peer feedback, and produce emergent intelligence.

Key Innovation: Real-Time Agent Collaboration

Business Agent: "Strong ecosystem moat detected"
  ↓ (publishes to message bus)
Valuation Agent: (receives message)
  → "Premium P/E may be justified by moat strength"
  → Adjusts score from 6.5 to 7.5

✨ Features

🧠 Multi-Agent Intelligence

  • ValuationAgent - Financial metrics & pricing analysis (35% weight)
  • BusinessAgent - Competitive moat & business quality (40% weight)
  • ManagementAgent - Capital allocation & leadership (25% weight)
  • SynthesisAgent - Integrates all perspectives into comprehensive thesis

πŸ”Œ Protocol Architecture

  • Message Bus - Publish-subscribe pattern for agent communication
  • Shared Memory - Cross-agent context for richer insights
  • Real-time Collaboration - Agents adjust views based on peer input

πŸ’° Enterprise-Grade Tracking (Fermi-Inspired)

  • Cost Accounting - Track tokens and costs per agent, per analysis
  • Knowledge Ontology - Entity-relationship graph for company knowledge
  • Performance Metrics - Token usage, execution time, cost per analysis

πŸ“Š Comprehensive Reports

  • Executive summaries
  • Investment thesis (bull case)
  • Business & management analysis
  • Valuation framework with price targets
  • Risk assessment & value catalysts
  • Agent consensus analysis

πŸš€ Three Deployment Options

  1. CLI Tool - node test-protocol.js TICKER
  2. Discord Bot - Team collaboration in Discord channels
  3. Web Application - Next.js UI ready for Vercel deployment

πŸ“ˆ Sample Analysis Output

🔬 PROTOCOL ANALYSIS: NVDA
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

📡 Phase 1: Specialist agents analyzing in parallel...
💰 ValuationAgent: Score 3/10 (expensive at 29.5x P/E)
🏢 BusinessAgent: Score 9/10 (very wide moat, dominant position)
👔 ManagementAgent: Score 9/10 (world-class capital allocation)

📊 Protocol Activity:
   Messages exchanged: 3
   Shared memory entries: 3
   Agents communicated and adjusted views in real-time

🧬 Phase 2: Synthesis agent integrating results...

✅ ANALYSIS COMPLETE
🎯 Final Score: 6.9/10
📋 Verdict: Hold (Medium Conviction)
💰 Cost: $0.0259 (3,935 tokens)

💰 Cost Breakdown:
   ValuationAgent: 394 tokens ($0.0026)
   BusinessAgent: 693 tokens ($0.0046)
   ManagementAgent: 696 tokens ($0.0046)
   SynthesisAgent: 2,152 tokens ($0.0142)

🧠 Knowledge Graph:
   Entities: 1 (1 Company)
   Relationships: 0

📄 Report saved to: reports/NVDA_2026-02-07.md

πŸš€ Quick Start

Prerequisites

node >= 18.0.0
npm >= 9.0.0

Installation

# Clone the repository
git clone https://github.com/Replicant-Partners/efrain-ai.git
cd efrain-ai

# Install dependencies
npm install

# Set up environment variables
cp .env.example .env
# Edit .env and add your ANTHROPIC_API_KEY

Run Your First Analysis

# Analyze Apple
node test-protocol.js AAPL

# Analyze Microsoft
node test-protocol.js MSFT

# Analyze NVIDIA
node test-protocol.js NVDA

πŸ“ Project Structure

efrain-ai/
├── agents/
│   ├── base-agent.js              # Base class with ontology & cost tracking
│   ├── valuation-agent.js         # Financial valuation specialist
│   ├── business-agent.js          # Business quality specialist
│   ├── management-agent.js        # Management effectiveness specialist
│   └── synthesis-agent.js         # Integration & report generation
├── protocol/
│   └── agent-protocol.js          # Message bus, memory, ontology, costs
├── reports/                       # Generated analysis reports (gitignored)
├── orchestrator-protocol.js       # Main orchestrator
├── test-protocol.js               # CLI interface
├── discord-bot.js                 # Discord integration
├── efrain-web/                    # Next.js web application
│   ├── app/
│   │   ├── api/analyze/           # API endpoint
│   │   ├── components/            # React components
│   │   └── page.tsx               # Main page
│   └── ...
├── package.json
├── .env                           # API keys (not in git)
└── README.md

🎯 How It Works

1. Protocol Initialization

const protocol = new AgentProtocol();
// Creates message bus, shared memory, ontology, cost tracking

const valuationAgent = new ValuationAgent(protocol, apiKey);
const businessAgent = new BusinessAgent(protocol, apiKey);
const managementAgent = new ManagementAgent(protocol, apiKey);
const synthesisAgent = new SynthesisAgent(protocol, apiKey);
// All agents auto-register with protocol

2. Parallel Analysis with Real-Time Communication

// Agents run in parallel
const [valuation, business, management] = await Promise.all([
  valuationAgent.analyze('AAPL'),
  businessAgent.analyze('AAPL'),
  managementAgent.analyze('AAPL'),
]);

// During analysis, agents communicate:
// BusinessAgent publishes: "Strong moat detected"
// ValuationAgent receives and adjusts: "May justify premium"

3. Synthesis & Report Generation

const synthesis = await synthesisAgent.synthesize('AAPL');
// Reads shared memory, integrates findings, generates report

πŸ’‘ Advanced Features

Cost Tracking

// Automatic cost tracking per agent
const costStats = protocol.getCostStats();

console.log(costStats);
// {
//   lifetime: { totalTokens: 50000, totalCost: 0.25 },
//   byAgent: {
//     ValuationAgent: { tokens: 12000, cost: 0.05, avgPerExecution: 400 },
//     BusinessAgent: { tokens: 18000, cost: 0.08, avgPerExecution: 600 },
//     ...
//   }
// }

Knowledge Ontology

// Agents automatically build knowledge graphs
agent.addEntity('AAPL', 'Company', {
  name: 'Apple Inc.',
  sector: 'Technology',
  marketCap: 2.8e12
});

agent.addEntity('iPhone', 'Product', {
  revenue: '200B'
});

agent.addRelationship('AAPL', 'iPhone', 'produces', {
  revenueContribution: '50%'
});

// Query the knowledge graph
const companies = protocol.getEntitiesByType('Company');
const relationships = protocol.getRelationshipsForEntity('AAPL');

🎨 Deployment Options

1. CLI Tool (Already Working)

node test-protocol.js TSLA

2. Discord Bot

# Set DISCORD_BOT_TOKEN in .env
node discord-bot.js

# In Discord:
!analyze AAPL

See DISCORD_SETUP.md for setup guide.

3. Web Application

cd efrain-web
npm install
npm run dev
# Open http://localhost:3000

Deploy to Vercel:

cd efrain-web
vercel

See WEB_APP_COMPLETE.md for deployment guide.


πŸ“Š Sample Report Structure

Each analysis generates a comprehensive markdown report:

  • Executive Summary - Key findings at a glance
  • Component Scores - Valuation (35%), Business (40%), Management (25%)
  • Investment Thesis - Detailed bull case (3-4 paragraphs)
  • Business Analysis - Moat, competitive advantages, growth opportunities
  • Management Analysis - Leadership profile, capital allocation, governance
  • Valuation Analysis - Framework, metrics, fair value estimate
  • Key Risks - Business-specific, macro, execution risks
  • Value Catalysts - Events that could unlock value
  • Future Outlook - Revenue projections, new initiatives
  • Agent Consensus - How agents agreed/disagreed
  • Final Recommendation - Verdict + conviction level + price target

πŸ”¬ Architecture Comparison

Feature Efrain AI Traditional Tools Fermi Framework
Agent Collaboration βœ… Real-time message bus ❌ Sequential only ❌ Independent agents
Emergent Intelligence βœ… Agents adjust scores ❌ Static analysis ❌ No cross-agent learning
Cost Tracking βœ… Per-agent, per-analysis ❌ No tracking βœ… Per-agent with 30-day windows
Knowledge Ontology βœ… Entity-relationship graph ❌ No persistent knowledge βœ… Episodic/semantic memory
Report Quality βœ… Comprehensive thesis ⚠️ Basic metrics ⚠️ Prediction-focused
Cost per Analysis $0.026 Varies $0.14 (typical)
Multi-Interface βœ… CLI, Discord, Web ⚠️ Usually one ⚠️ Web catalog only

πŸŽ“ Inspiration & Credits

Inspired by Fermi Framework for:

  • Enterprise-grade cost tracking
  • Knowledge ontology architecture
  • Agent performance metrics

Unique to Efrain AI:

  • Real-time multi-agent collaboration
  • Protocol-based communication
  • Emergent intelligence from agent interactions
  • Investment-specific domain expertise

πŸ“ˆ Performance Metrics

Analysis Speed: ~40 seconds per stock
Cost per Analysis: $0.026 (5.4x more efficient than typical forecasting agents)
Token Usage: ~4,000 tokens average
Report Length: 2,000+ words with full thesis

Agent Breakdown:

  • Synthesis: 55% of tokens (generates comprehensive report)
  • Business: 18% of tokens
  • Management: 17% of tokens
  • Valuation: 10% of tokens (most efficient)

πŸ›£οΈ Roadmap

Implemented βœ…

  • Multi-agent collaboration with message bus
  • Shared memory for cross-agent context
  • Comprehensive report generation
  • Cost tracking & accounting
  • Knowledge ontology system
  • CLI interface
  • Discord bot
  • Web application

Planned 🚧

  • Historical analysis tracking & validation
  • Prediction accuracy scoring (Brier scores)
  • Agent versioning & evolution tracking
  • Persistent knowledge graph storage
  • Cost optimization dashboard
  • Multi-stock comparative analysis
  • PDF report export
  • Email notifications

🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.


πŸ“„ License

MIT License - see LICENSE file for details


πŸ’¬ Support

For questions or issues:

  • Open an issue on GitHub
  • Contact: [Your contact info]

πŸ™ Acknowledgments

  • Anthropic for Claude AI
  • Fermi Framework for architecture inspiration
  • Replicant Partners for the vision

Built with ❀️ by Marito

Efrain AI - Where AI agents collaborate to uncover investment insights πŸš€

About

Multi-agent stock analysis system with real-time collaboration, cost tracking, and knowledge ontology

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published