Skip to content

cflack/PrimoAgent

 
 

Repository files navigation

PrimoAgent: Multi-Agent Stock Analysis

Overview

PrimoAgent is an multi agent AI stock analysis system built on LangGraph architecture that orchestrates four specialized agents to provide comprehensive daily trading insights and next-day price predictions. The system integrates Natural Language Processing (NLP) with technical analysis and portfolio management to enhance decision-making in stock markets, aiming to minimize risk and potential losses through deep financial market analysis.

Core Architecture

Sequential Pipeline Design

The system implements a linear LangGraph workflow where each specialized agent processes and enhances the shared state:

Data Collection Agent
    ↓ (Market data, company info, financial metrics)
Technical Analysis Agent  
    ↓ (SMA, RSI, MACD, Bollinger Bands, ADX, CCI)
News Intelligence Agent
    ↓ (7 quantified NLP features from financial news)
Portfolio Manager Agent
    ↓ (Trading signals with confidence levels)

Key Components

1. Data Collection Agent (src/agents/data_collection_agent.py)

  • Collects real-time market data via yFinance and TwelveData APIs
  • Retrieves company profiles, financial metrics, and recent news
  • Handles weekend/holiday news periods automatically

2. Technical Analysis Agent (src/agents/technical_analysis_agent.py)

  • Calculates 6 technical indicators: SMA, RSI, MACD, Bollinger Bands, ADX, CCI
  • Provides momentum and trend analysis for informed decision-making

3. News Intelligence Agent (src/agents/news_intelligence_agent.py)

  • Retrieves financial news from Yahoo Finance (free, no API key required)
  • Processes financial news through 7 quantified NLP features:
    • news_relevance (-2 to 2)
    • sentiment (-2 to 2)
    • price_impact_potential (-2 to 2)
    • trend_direction (-2 to 2)
    • earnings_impact (-2 to 2)
    • investor_confidence (-2 to 2)
    • risk_profile_change (-2 to 2)
  • Filters trusted financial sources and extracts significant news content
  • Automatic retry logic for OpenAI API calls with intelligent backoff

4. Portfolio Manager Agent (src/agents/portfolio_manager_agent.py)

  • Integrates all previous analysis into trading signals (BUY/SELL/HOLD)
  • Provides confidence levels (0.0-1.0) and position sizing recommendations
  • Uses historical context from previous decisions for adaptive strategies

Project Structure

src/
  agents/            # Four specialized agents
  backtesting/       # Backtest engine, strategies, reporting
  config/            # Configuration management and model factory
  prompts/           # LLM prompt templates for each agent
  tools/             # External API integrations
  workflows/         # LangGraph state management and workflow

output/
  csv/               # Daily analysis results per symbol
  backtests/         # Backtest charts and reports

Performance Results

Recent Multi-Stock Backtest Results

Our latest backtest results demonstrate PrimoAgent's effectiveness across diverse stocks:

Stock Strategy Final Value Return % Volatility % Sharpe Max DD % Trades
AAPL PrimoAgent $93,122 -6.88% 8.03% -2.042 9.82% 36
AAPL Buy & Hold $84,750 -15.25% 40.05% -0.707 29.76% 1
AMZN PrimoAgent $100,152 +0.15% 21.47% 0.028 18.07% 25
AMZN Buy & Hold $98,602 -1.40% 38.10% 0.058 30.79% 1
META PrimoAgent $131,967 +31.97% 19.75% 2.899 8.99% 26
META Buy & Hold $122,165 +22.16% 43.10% 1.124 34.04% 1
NFLX PrimoAgent $128,606 +28.61% 20.25% 2.570 12.13% 20
NFLX Buy & Hold $149,506 +49.51% 36.60% 2.399 19.01% 1
TSLA PrimoAgent $96,647 -3.35% 6.52% -1.355 7.72% 33
TSLA Buy & Hold $83,407 -16.59% 75.75% -0.149 47.84% 1

Performance Comparison Charts

Returns Comparison

Individual stock performance charts available in output/backtests/:

Quick Start

Docker build

./docker/scripts.sh build ./docker/scripts.sh build-fresh # No cache

Analysis

./docker/scripts.sh analyze ./docker/scripts.sh batch AAPL 2024-01-01 2024-12-31

Testing Commands

./docker/scripts.sh backtest ./docker/scripts.sh single AAPL ./docker/scripts.sh multi

Development Commands

./docker/scripts.sh dev-start ./docker/scripts.sh dev-stop ./docker/scripts.sh shell ./docker/scripts.sh health

Environment Setup

  1. Create and activate virtual environment
python3 -m venv venv
source venv/bin/activate
  1. Install dependencies
pip install -r requirements.txt
  1. Configure API keys
cp .env.example .env

Required API keys in .env:

OPENAI_API_KEY=your_openai_key_here
TWELVEDATA_API_KEY=your_twelvedata_key_here
FIRECRAWL_API_KEY=your_firecrawl_key_here
PERPLEXITY_API_KEY=your_perplexity_key_here
# Optional: News provider selection (defaults to yahoo)
NEWS_PROVIDER=yahoo

Note: Yahoo Finance news is used by default and requires no API key. TwelveData is used for market data and company profiles.

Two-Step Workflow

Step 1: Data Collection and Analysis

python main.py

This must be run first to collect and analyze market data. The system will interactively prompt for:

  • Stock symbol (e.g., AAPL, TSLA, META)
  • Start date in YYYY-MM-DD format (e.g., 2025-05-28)
  • End date in YYYY-MM-DD format (e.g., 2025-06-30)

Step 2: Backtesting (Only After Step 1 Complete)

python backtest.py

License and Disclaimer

Recent Updates

Yahoo Finance News Integration (2025-10-17)

News Provider Change: TwelveData → Yahoo Finance

PrimoAgent now uses Yahoo Finance for financial news retrieval, providing:

  • Free news data - no API key required
  • Reliable news access - no more 404 errors from TwelveData news endpoint
  • Automatic retry logic - intelligent exponential backoff for OpenAI API quota issues
  • Provider abstraction - easy switching between news sources via NEWS_PROVIDER environment variable

Key Improvements:

  • Resolved TwelveData news API 404 errors that were blocking analysis
  • Added comprehensive retry logic for all OpenAI API calls with quota handling
  • Yahoo Finance provides 10-50 recent news articles per symbol
  • Maintains same news analysis workflow and NLP feature extraction

API Provider Migration (2024-10-17)

Market Data Provider: Finnhub → TwelveData

TwelveData is used for market data and company information:

  • More reliable market data API
  • Better calendar-based trading day detection using pandas-market-calendars
  • Enhanced company profile and financial data
  • Consistent API rate limiting

Action Required:

  • Replace FINNHUB_API_KEY with TWELVEDATA_API_KEY in your .env file
  • Obtain a TwelveData API key from twelvedata.com
  • Rebuild Docker containers with ./docker/scripts.sh build-fresh

This project is licensed under the MIT License. This repository contains academic research code intended for educational purposes only. Nothing herein constitutes financial advice or trading recommendations. The trading strategies and analyses are experimental in nature and have not been validated for real-world trading. Users should be aware that trading involves substantial risk of loss and should always consult financial professionals before making investment decisions.

About

PrimoAgent: Multi-Agent Stock Analysis

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Python 93.6%
  • Shell 6.0%
  • Dockerfile 0.4%