Skip to content

A stock portfolio agent that helps users track stocks, analyze investments, and gain actionable insights for better decision-making.

License

Notifications You must be signed in to change notification settings

sailorworks/stock-portfolio-analysis-agent

Repository files navigation

πŸ“ˆ Stock Portfolio Analysis Agent

An intelligent stock portfolio analysis agent built with Composio Tool Router, OpenAI GPT-4o-mini, and yFinance. The agent analyzes hypothetical investment opportunities, tracks stock performance, simulates portfolio allocations, and generates AI-powered bull/bear insights.

πŸŽ₯ Live Demo (CLI in Action)

CLI Demo

✨ Features

  • πŸ—£οΈ Natural Language Queries - Ask investment questions in plain English
  • πŸ“Š Historical Stock Data - Fetch up to 4 years of stock data via yFinance
  • πŸ’° Portfolio Simulation - Single-shot or DCA (Dollar-Cost Averaging) strategies
  • πŸ“ˆ Performance Metrics - Calculate returns, allocations, and total value
  • πŸ“‰ S&P 500 Benchmark - Compare your portfolio against SPY
  • πŸ‚πŸ» AI Insights - Generate bull (positive) and bear (risk) analysis
  • πŸ–₯️ Interactive CLI - Beautiful terminal interface built with Textual
  • 🌐 REST API - FastAPI backend with real-time SSE streaming

πŸ—οΈ Architecture

flowchart TB
    subgraph User["πŸ‘€ User Interface"]
        CLI["πŸ–₯️ CLI (Textual App)"]
        API["🌐 REST API (FastAPI)"]
    end

    subgraph Agent["πŸ€– Agent Layer"]
        Orchestrator["Agent Orchestrator"]
        PortfolioAgent["Portfolio Analysis Agent"]
        InsightsAgent["Insights Generator Agent"]
    end

    subgraph Composio["πŸ”§ Composio Tool Router"]
        ToolRouter["Tool Router"]
        FetchStock["fetch_stock_data"]
        FetchBenchmark["fetch_benchmark_data"]
        SimulatePortfolio["simulate_portfolio"]
        SimulateSPY["simulate_spy_investment"]
        CalcMetrics["calculate_metrics"]
    end

    subgraph External["🌍 External Services"]
        OpenAI["OpenAI API\n(GPT-4o-mini)"]
        YFinance["yFinance API\n(Yahoo Finance)"]
    end

    subgraph Data["πŸ’Ύ Data Layer"]
        Session["Session Manager"]
        Portfolio["Portfolio Manager"]
        Models["Pydantic Models"]
    end

    CLI --> Orchestrator
    API --> Orchestrator
    
    Orchestrator --> PortfolioAgent
    Orchestrator --> InsightsAgent
    
    PortfolioAgent --> ToolRouter
    InsightsAgent --> OpenAI
    
    ToolRouter --> FetchStock
    ToolRouter --> FetchBenchmark
    ToolRouter --> SimulatePortfolio
    ToolRouter --> SimulateSPY
    ToolRouter --> CalcMetrics
    
    FetchStock --> YFinance
    FetchBenchmark --> YFinance
    
    PortfolioAgent --> OpenAI
    
    Orchestrator --> Session
    Session --> Portfolio
    Portfolio --> Models
Loading

Follow on X

πŸš€ Setup

Prerequisites

  • Python 3.11+
  • uv (Python package manager)

1. Clone the Repository

git clone https://github.com/your-username/stock-portfolio-analysis-agent.git
cd stock-portfolio-analysis-agent

2. Create Virtual Environment

uv venv
source .venv/bin/activate  # On macOS/Linux
# or
.venv\Scripts\activate     # On Windows

3. Install Dependencies

uv sync

4. Configure API Keys

Copy the example environment file and add your API keys:

cp .env.example .env

Edit .env and add your keys:

# Composio API Key - Get from https://platform.composio.dev
COMPOSIO_API_KEY=your_composio_api_key_here

# OpenAI API Key - Get from https://platform.openai.com
OPENAI_API_KEY=your_openai_api_key_here

# Server Configuration (optional)
HOST=0.0.0.0
PORT=8000
RELOAD=false
WORKERS=1

# Logging Configuration (optional)
LOG_LEVEL=INFO

πŸ”‘ Getting API Keys

Composio API Key

  1. Go to Composio Platform
  2. Sign up or log in to your account
  3. Navigate to Settings β†’ API Keys
  4. Create a new API key and copy it
  5. Paste it in your .env file as COMPOSIO_API_KEY

OpenAI API Key

  1. Go to OpenAI Platform
  2. Sign up or log in to your account
  3. Navigate to API Keys section
  4. Click Create new secret key
  5. Copy the key and paste it in your .env file as OPENAI_API_KEY

⚠️ Note: Ensure you have sufficient credits in your OpenAI account. The agent uses gpt-4o-mini which is cost-effective but still requires API credits.


πŸ–₯️ Running the Application

Launch the beautiful terminal interface:

uv run portfolio-cli  

Or using the main entry point:

uv run python main.py  # Starts the API server

The API will be available at http://localhost:8000

Run with Docker (production)

# Build
docker build -t spa-agent .

# Run (set your API keys)
docker run \
  -e COMPOSIO_API_KEY=your_composio_api_key \
  -e OPENAI_API_KEY=your_openai_api_key \
  -e PORT=8000 -e HOST=0.0.0.0 \
  -p 8000:8000 \
  spa-agent

Test the API:

# Health check
curl http://localhost:8000/health

# Analyze a portfolio (sync)
curl -X POST http://localhost:8000/analyze/sync \
  -H "Content-Type: application/json" \
  -d '{"query": "What if I invested $10,000 in AAPL since 2020?"}'

Available Endpoints:

  • GET /health β€” Check if API is running
  • POST /analyze/sync β€” Analyze query (wait for full response)
  • POST /analyze β€” Analyze with SSE streaming (real-time)

Set CORS_ORIGINS env var (comma-separated) to restrict cross-origin access in production.


πŸ‘€ User Flow

flowchart LR
    A[πŸ§‘ User opens CLI] --> B[πŸ’¬ Types investment query]
    B --> C[πŸ”„ Agent processes query]
    C --> D[πŸ“Š Fetches stock data]
    D --> E[πŸ’° Simulates portfolio]
    E --> F[πŸ“ˆ Calculates metrics]
    F --> G[πŸ‚πŸ» Generates insights]
    G --> H[πŸ“‹ Displays results]
    H --> I{New query?}
    I -->|Yes| B
    I -->|No| J[πŸ‘‹ Exit with Ctrl+Q]
Loading

Step-by-Step User Journey

  1. Launch the CLI - Start the application with uv run portfolio-cli
  2. Enter your query - Type a natural language investment question
  3. Wait for analysis - The agent fetches data and processes your request
  4. View results - See holdings, performance metrics, and AI insights
  5. Exit - Press Ctrl+Q to quit the application

πŸ’‘ Sample Questions to Ask

Basic Investment Queries

What if I invested $10,000 in AAPL since 2020?
How would $5k in Tesla perform from January 2022?
Analyze a $20,000 investment in Microsoft starting 2021

Multi-Stock Portfolios

What if I invested $15,000 split between GOOGL and AMZN since 2021?
Compare investing $10k equally in AAPL, MSFT, and NVDA from 2022
Simulate $50,000 portfolio: 40% TSLA, 30% AAPL, 30% META since 2020

DCA (Dollar-Cost Averaging) Strategies

What if I DCA'd $1,000 monthly into AAPL since 2020?
Simulate monthly investments of $500 in SPY from 2021
Compare lump sum vs DCA for $12,000 in NVDA over 2022

Comparative Analysis

Would AAPL or GOOGL have been a better investment since 2020?
How does a tech portfolio compare to S&P 500 since 2021?
Compare returns: $10k in TSLA vs $10k in SPY from 2020

Specific Timeframes

How much would $10k in AAPL be worth if invested on March 15, 2020?
Analyze NVDA performance from the start of 2023 to now
What's the return on $5k in Amazon for the last 2 years?

πŸ“ Project Structure

stock-portfolio-analysis-agent/
β”œβ”€β”€ agent/
β”‚   β”œβ”€β”€ __init__.py           # Package initialization
β”‚   β”œβ”€β”€ agent_config.py       # Agent setup & orchestration
β”‚   β”œβ”€β”€ api.py                # FastAPI endpoints
β”‚   β”œβ”€β”€ cli/
β”‚   β”‚   β”œβ”€β”€ __init__.py
β”‚   β”‚   β”œβ”€β”€ app.py            # Textual CLI application
β”‚   β”‚   β”œβ”€β”€ client.py         # API client for CLI
β”‚   β”‚   └── widgets.py        # Custom UI widgets
β”‚   β”œβ”€β”€ errors.py             # Custom error definitions
β”‚   β”œβ”€β”€ insights.py           # AI insights generation
β”‚   β”œβ”€β”€ models.py             # Pydantic data models
β”‚   β”œβ”€β”€ portfolio.py          # Portfolio management
β”‚   β”œβ”€β”€ prompts.py            # System prompts for agents
β”‚   β”œβ”€β”€ session.py            # Session management
β”‚   └── tools.py              # Composio custom tools
β”œβ”€β”€ tests/
β”‚   β”œβ”€β”€ __init__.py
β”‚   └── test_*.py             # Unit and property tests
β”œβ”€β”€ .env.example              # Environment variables template
β”œβ”€β”€ .gitignore
β”œβ”€β”€ main.py                   # API server entry point
β”œβ”€β”€ pyproject.toml            # Project dependencies
β”œβ”€β”€ README.md
└── uv.lock                   # Dependency lock file

πŸ› οΈ Custom Tools (Composio)

The agent uses the following custom tools registered with Composio:

Tool Description
fetch_stock_data Fetches historical closing prices from yFinance
fetch_benchmark_data Fetches SPY prices aligned to portfolio dates
simulate_portfolio Simulates stock purchases (single-shot or DCA)
simulate_spy_investment Simulates equivalent SPY investment
calculate_metrics Computes returns, allocations, and performance

⌨️ Keyboard Shortcuts (CLI)

Shortcut Action
Enter Submit query
Ctrl+C Cancel current analysis / Clear input
Ctrl+Q Quit the application

πŸ§ͺ Running Tests

uv run pytest tests/ -v

πŸ“ Environment Variables

Variable Required Default Description
COMPOSIO_API_KEY βœ… Yes - Your Composio API key
OPENAI_API_KEY βœ… Yes - Your OpenAI API key
HOST No 0.0.0.0 Server host address
PORT No 8000 Server port
RELOAD No false Enable hot reload for development
WORKERS No 1 Number of uvicorn workers
LOG_LEVEL No INFO Logging level (DEBUG, INFO, WARNING, ERROR)

🀝 Contributing

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


πŸ“„ License

This project is licensed under the MIT License.


πŸ™ Acknowledgments

  • Composio - Tool Router for AI agents
  • OpenAI - GPT-4o-mini language model
  • yFinance - Yahoo Finance data API
  • Textual - Beautiful TUI framework
  • FastAPI - Modern web framework for APIs

About

A stock portfolio agent that helps users track stocks, analyze investments, and gain actionable insights for better decision-making.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published