Skip to content

y-randhal/autonomous-wealth-agent-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Autonomous Wealth Agent API

Python FastAPI LangGraph License

An AI-powered autonomous financial analysis API that provides comprehensive stock analysis and investment recommendations using LangGraph state management, technical indicators, and Claude 3.5 Sonnet.

Features

  • Real-time Stock Data: Live market data via yfinance
  • FIIs (Fundos Imobiliários): Analyze Brazilian Real Estate Investment Funds (use tickers like HGLG11.SA, XPML11.SA with asset_type: "fii")
  • Technical Analysis: RSI, 50-day MA, 200-day MA with trend analysis
  • AI-Powered Recommendations: Claude 3.5 Sonnet for intelligent Buy/Hold/Sell decisions
  • Response Language: Optional language parameter so analysis is returned in the user's language (e.g. en, pt, es)
  • LangGraph Orchestration: State-managed workflow for reliable analysis pipelines
  • Production-Ready: Structured logging, error handling, and comprehensive documentation

Architecture

autonomous_wealth_agent_api/
├── app/
│   ├── agents/           # LangGraph agent definitions
│   │   ├── __init__.py
│   │   └── graph.py      # State graph with nodes and routing
│   ├── tools/            # External tool integrations
│   │   ├── __init__.py
│   │   └── finance.py    # yfinance integration with indicators
│   ├── schemas/          # Pydantic V2 models
│   │   ├── __init__.py
│   │   ├── requests.py   # Request validation models
│   │   └── responses.py  # Response structure models
│   ├── core/             # Core utilities
│   │   ├── __init__.py
│   │   ├── config.py     # Settings management
│   │   └── logging.py    # Structured logging
│   ├── __init__.py
│   └── main.py           # FastAPI application entry
├── requirements.txt
├── .env.example
└── README.md

LangGraph Agent Flow

┌─────────────────┐
│   User Query    │
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│ Extract Ticker  │──── Error ────┐
└────────┬────────┘               │
         │                        │
         ▼                        │
┌─────────────────┐               │
│   Fetch Data    │──── Error ────┤
│  (yfinance)     │               │
└────────┬────────┘               │
         │                        │
         ▼                        │
┌─────────────────┐               │
│ Analyze & Gen   │──── Error ────┤
│ (Claude 3.5)    │               │
└────────┬────────┘               │
         │                        │
         ▼                        ▼
┌─────────────────┐     ┌─────────────────┐
│    Analysis     │     │  Error Response │
│    Response     │     │                 │
└─────────────────┘     └─────────────────┘

Quick Start

Prerequisites

  • Python 3.10+
  • pip

Installation

# Clone the repository
git clone https://github.com/yourusername/autonomous-wealth-agent-api.git
cd autonomous-wealth-agent-api

# Create virtual environment
python -m venv venv
source venv/bin/activate  # Windows: venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt

# Copy environment configuration
cp .env.example .env

Running the API

# Development mode
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000

# Production mode
uvicorn app.main:app --host 0.0.0.0 --port 8000 --workers 4

API Documentation

Once running, access the interactive documentation:

Example: Calling the API from Swagger UI

You can try the POST /analyze endpoint directly from Swagger UI. The response includes live stock data, technical indicators (RSI, moving averages), an AI recommendation with confidence, and trend/risk analysis. Example response for AAPL:

Swagger UI example — POST /analyze response for AAPL (200 OK)

API Endpoints

POST /analyze

Analyze a stock or a Brazilian FII (Fundo Imobiliário) with AI-powered recommendations. You can request the response in a specific language.

Request:

{
  "query": "Is it worth looking at AAPL now?",
  "ticker": "AAPL",
  "language": "pt",
  "asset_type": "stock"
}
Field Type Required Description
query string Yes Natural language query about the stock or FII.
ticker string No Explicit ticker symbol. If omitted, extracted from the query. Use .SA for Brazilian assets (e.g. PETR4.SA, HGLG11.SA).
language string No Language code so the analysis is returned in that language (e.g. en, pt, pt-BR, es).
asset_type string No "stock" (default) or "fii". Use "fii" for Brazilian Real Estate Funds (Fundos Imobiliários).

Response:

{
  "success": true,
  "timestamp": "2024-01-15T10:30:00Z",
  "query": "Is it worth looking at AAPL now?",
  "analysis": {
    "ticker": "AAPL",
    "stock_data": {
      "ticker": "AAPL",
      "current_price": 185.92,
      "daily_change": 2.34,
      "daily_change_percent": 1.27,
      "volume": 45678901,
      "previous_close": 183.58,
      "day_high": 186.50,
      "day_low": 183.20,
      "market_cap": 2890000000000,
      "pe_ratio": 28.5
    },
    "technical_indicators": {
      "rsi": 58.34,
      "ma_50": 178.45,
      "ma_200": 172.30,
      "price_vs_ma_50": 4.19,
      "price_vs_ma_200": 7.90
    },
    "recommendation": "HOLD",
    "confidence": 72,
    "analysis_summary": "AAPL is currently trading above both its 50-day and 200-day moving averages, indicating a bullish trend...",
    "trend_analysis": "The stock shows a bullish trend with price maintaining above key moving averages...",
    "risk_assessment": "MEDIUM"
  }
}

FIIs (Fundos Imobiliários Brasileiros)

To analyze Brazilian Real Estate Investment Funds:

  1. Use the B3 ticker with .SA suffix (e.g. HGLG11.SA, XPML11.SA).
  2. Set "asset_type": "fii" so the model considers FII-specific factors (yield, P/VP, liquidity).

Example:

{
  "query": "Vale a pena comprar HGLG11?",
  "ticker": "HGLG11.SA",
  "language": "pt-BR",
  "asset_type": "fii"
}

Response language

Set language to the desired language code (e.g. en, pt, pt-BR, es). The analysis summary, trend analysis, and risk explanation will be returned in that language.

GET /health

Health check endpoint for monitoring.

Response:

{
  "status": "healthy",
  "version": "1.0.0",
  "timestamp": "2024-01-15T10:30:00Z",
  "services": {
    "api": "healthy",
    "yfinance": "healthy",
    "llm": "healthy"
  }
}

Technical Indicators

RSI (Relative Strength Index)

  • > 70: Overbought territory (potential sell signal)
  • < 30: Oversold territory (potential buy signal)
  • 30-70: Neutral zone

Moving Averages

  • Price > 50-day MA: Short-term bullish
  • Price > 200-day MA: Long-term bullish
  • Golden Cross: 50-day MA crosses above 200-day MA (bullish)
  • Death Cross: 50-day MA crosses below 200-day MA (bearish)

Error Handling

The API provides structured error responses:

{
  "success": false,
  "timestamp": "2024-01-15T10:30:00Z",
  "error": {
    "code": "INVALID_TICKER",
    "message": "Ticker 'INVALID' not found or invalid",
    "field": null
  }
}

Error Codes

Code HTTP Status Description
INVALID_TICKER 400 Ticker symbol not found
TIMEOUT 504 Request timeout
DATA_FETCH_ERROR 502 Failed to fetch market data
INTERNAL_ERROR 500 Unexpected server error

Configuration

Variable Default Description
APP_NAME Autonomous Wealth Agent API Application name
APP_VERSION 1.0.0 Application version
ENVIRONMENT development Environment (development/staging/production)
DEBUG false Enable debug mode
LOG_LEVEL INFO Logging level
REQUEST_TIMEOUT 30 External API timeout (seconds)
YFINANCE_CACHE_TTL 300 Cache TTL for stock data (seconds)
MAX_HISTORY_DAYS 365 Max historical data for indicators

Development

Code Quality

  • Type hints on all functions (Python 3.10+ syntax)
  • Google-style docstrings
  • Clean code principles: SRP, DRY, meaningful names
  • Pydantic V2 for validation

Testing

# Stock analysis (English)
curl -X POST "http://localhost:8000/analyze" \
  -H "Content-Type: application/json" \
  -d '{"query": "Should I buy AAPL?"}'

# Stock analysis in Portuguese
curl -X POST "http://localhost:8000/analyze" \
  -H "Content-Type: application/json" \
  -d '{"query": "Vale a pena comprar PETR4?", "ticker": "PETR4.SA", "language": "pt"}'

# FII analysis (Brazilian Real Estate Fund)
curl -X POST "http://localhost:8000/analyze" \
  -H "Content-Type: application/json" \
  -d '{"query": "Analyze HGLG11", "ticker": "HGLG11.SA", "language": "pt-BR", "asset_type": "fii"}'

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

License

MIT License - See LICENSE file for details.

Author

Built by Yuri Randhal Rodrigues Braga using FastAPI, LangGraph, and Claude 3.5 Sonnet.

About

An intelligent backend infrastructure powered by AI agents to autonomously manage, analyze, and optimize financial portfolios and investment strategies.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages