Autonomous Financial Analysis & Trading Agent
2025

Financial Analysis & Trading Agent - Comprehensive Guide
Introduction & Project Overview
What Is This Project?
This is an AI-powered autonomous trading agent that:
Why Was It Created?
The goal is to demonstrate how AI agents can be used for financial analysis and automated trading. This project combines:
Key Features
✓ AI-Powered Market Analysis using free/open-source LLMs
✓ LangGraph-Based Workflow (7 intelligent nodes)
✓ Real-Time Market Data from Alpaca API
✓ Backtesting Engine for strategy validation
✓ Paper Trading (risk-free simulation)
✓ Beautiful CLI Interface with Rich library
✓ Multi-LLM Support (Ollama, Hugging Face, Groq, OpenAI)
✓ Self-Improvement Capabilities
Requirements & Technology Stack
Python 3.11+ (Tested with Python 3.14)
WHY:** Modern Python features, better performance, type hints support
WHERE USED: Entire project is Python-based
LangChain & LangGraph
WHY:
WHERE USED:
Alpaca Trade API
WHY:
WHERE USED:
yFinance (Fallback)
WHY:
WHERE USED:
LLM Providers (Multiple Options)
WHY MULTIPLE OPTIONS:
WHERE USED:
InfluxDB (Optional)
WHY:
WHERE USED:
Rich Library
WHY:
WHERE USED:
Architecture & Design
Project Structure
The project follows a modular architecture:
Main Components:
LangGraph Workflow (7 Nodes)
The agent follows a stateful workflow with 7 nodes:
1. FETCH_DATA → Fetches market data for symbols
2. ANALYZE_DATA → LLM analyzes each symbol
3. BUILD_STRATEGY → LLM creates trading strategy
4. SIMULATE_STRATEGY → Backtests on historical data
5. EXECUTE_TRADES → Paper trades (if backtest positive)
6. EVALUATE_PERFORMANCE → Calculates metrics
7. SELF_IMPROVE → LLM suggests improvements
State Management
The agent uses a TypedDict for state management, tracking symbols, market data, analysis results, strategy, backtest results, execution plans, performance metrics, iteration count, and errors.
Complete Code Walkthrough
Entry Point: main.py
EXECUTION FLOW:
1. Parses command-line arguments for symbols
2. Initializes CLI interface
3. Creates TradingAgent instance
4. Runs workflow with symbols
5. Displays results using CLI
Node 1: FETCH_DATA
WHAT IT DOES:
CODE LOCATION: agents/trading_agent.py, _fetch_data_node()
The data fetcher tries Alpaca first, then falls back to yfinance if needed. It uses 60+ day old data to avoid SIP subscription restrictions on free Alpaca accounts.
Node 2: ANALYZE_DATA
WHAT IT DOES:
CODE LOCATION: agents/trading_agent.py, _analyze_data_node()
strategies/strategy_builder.py, analyze_market_data()
The LLM receives formatted market data including recent prices, technical indicators, and price changes, then provides analysis with sentiment and confidence scores.
Node 3: BUILD_STRATEGY
WHAT IT DOES:
CODE LOCATION: agents/trading_agent.py, _build_strategy_node()
strategies/strategy_builder.py, build_strategy()
The strategy builder uses LLM to create a cohesive trading strategy from all symbol analyses, with capital allocation based on sentiment (bullish gets higher allocation) and confidence levels.
Node 4: SIMULATE_STRATEGY (Backtesting)
WHAT IT DOES:
CODE LOCATION: agents/trading_agent.py, _simulate_strategy_node()
simulation/backtester.py, run_backtest()
The backtester simulates day-by-day, checking entry conditions (flexible 5% tolerance on entry price) and exit conditions (target price or 10% stop loss). It tracks all trades and calculates final performance metrics.
Node 5: EXECUTE_TRADES
WHAT IT DOES:
CODE LOCATION: agents/trading_agent.py, _execute_trades_node()
trading/paper_trader.py, execute_buy_order()
Only executes if backtest shows positive returns. Checks buying power, places market orders via Alpaca API, and stores trades in database.
Node 6: EVALUATE_PERFORMANCE
WHAT IT DOES:
CODE LOCATION: agents/trading_agent.py, _evaluate_performance_node()
Tracks portfolio value, backtest returns, win rate, and stores metrics for future analysis.
Node 7: SELF_IMPROVE
WHAT IT DOES:
CODE LOCATION: agents/trading_agent.py, _self_improve_node()
The LLM analyzes backtest results, portfolio performance, and suggests improvements for entry/exit criteria, position sizing, risk management, and symbol selection.
How Everything Works Together
Complete Execution Flow
STEP 1: USER RUNS COMMAND
User executes: python main.py --symbols "AAPL,MSFT,TSLA"
STEP 2: AGENT INITIALIZATION
TradingAgent creates all components: MarketDataFetcher, TimeSeriesDB, StrategyBuilder, Backtester, PaperTrader, and builds the LangGraph workflow.
STEP 3: WORKFLOW EXECUTION
The workflow executes all 7 nodes sequentially:
STEP 4: RESULTS DISPLAY
CLI displays all results with beautiful formatting using Rich library.
Features & Capabilities
AI-Powered Analysis
Multi-LLM Support
Supports 4 LLM providers:
1. Ollama (Free, Local, Recommended) - No API limits, privacy-focused
2. Hugging Face (Free API) - Many models available
3. Groq (Free Tier, Fast) - Very fast inference
4. OpenAI (Paid) - Best quality
Flexible Backtesting
Paper Trading
Beautiful CLI
Setup & Configuration
Installation Steps
1. Install Python 3.11+
2. Clone repository
3. Install dependencies: pip install -r requirements.txt
4. Copy env.example to .env
5. Configure API keys in .env
6. Run: python main.py
Environment Variables (.env)
Required:
LLM Provider (choose one):
Optional:
Usage Examples
Basic Usage
# Run with default symbols from .env
python main.py
# Run with custom symbols
python main.py --symbols "AAPL,MSFT,TSLA"
# Run with multiple symbols
python main.py --symbols "AAPL,MSFT,GOOGL,AMZN,TSLA"Windows Quick Start
# Double-click:
start_trading_agent.bat # Uses default symbols
start_trading_agent_custom.bat # Prompts for symbolsTroubleshooting & Common Issues
Issue: "Python is not installed"
SOLUTION: Install Python 3.11+ from python.org. Make sure to check "Add Python to PATH"
Issue: "Module not found"
SOLUTION: Run pip install -r requirements.txt. Use virtual environment: python -m venv venv
Issue: "Ollama not found"
SOLUTION: Install from ollama.ai. Run ollama serve in terminal. Download model: ollama pull llama3.2
Issue: "Alpaca API error"
SOLUTION: Check API keys in .env. Verify paper trading account is active. Free accounts have data limitations (use older dates)
Issue: "Backtest shows 0% return"
SOLUTION: Check entry conditions in strategy. Verify historical data is available. See issues/14-fixed-backtest-zero-trades.md
Fixes Applied
1. Flexible entry price matching (5% tolerance)
2. Fallback entry logic for bullish stocks
3. Improved date matching
4. Better error handling
5. Rate limiting for API calls
Future Enhancements
Potential improvements include:
Conclusion
This Financial Analysis & Trading Agent demonstrates:
The project is fully functional and can be extended with additional features as needed. All code is well-documented and follows best practices.
Key Takeaways
1. LangGraph enables stateful agent workflows
2. LLMs can analyze financial data effectively
3. Paper trading is essential for testing
4. Backtesting validates strategies before execution
5. Multi-provider support increases flexibility
6. Beautiful CLI improves user experience
7. Error handling ensures robustness