AI-powered financial analysis tool that generates comprehensive reports with technical indicators, fundamental analysis, and portfolio metrics.
- π Technical Analysis: RSI, MACD, Bollinger Bands, Stochastic, Moving Averages, Volatility
- π° Fundamental Analysis: P/E ratios, revenue growth, earnings, cash flow, margins
- π Portfolio Analytics: Diversification ratio, correlation matrix, Sharpe ratio, max drawdown
- π― Options Analysis: Greeks (Delta/Gamma/Theta/Vega/Rho), IV analysis, strategy detection, P&L modeling
- π€ AI-Powered Insights: LLM-generated narratives and investment recommendations
- π Advanced Metrics: Alpha, Beta, Sortino, Calmar, Treynor, Information Ratio
- π Smart Alerts: Automated detection of overbought/oversold conditions
- πΎ Intelligent Caching: Reduces API calls with configurable TTL (dual-format: Parquet + Pickle)
- π Natural Language Requests: "Analyze tech stocks over 6 months"
- π HTML Reports: Professional, responsive HTML reports with embedded charts
- π Browser Launch: Optional browser opening with user confirmation (security best practice)
- π Optimized Operations: Vectorized DataFrame operations for speed
- π§ͺ Comprehensive Testing: Memory leak prevention, performance benchmarks
- π Security First: Path traversal protection, API key masking, no pickle vulnerabilities
- π¦ Clean Code: Type hints, DRY principles, explicit error handling
- Quick Start
- Installation
- Configuration
- Usage
- Architecture
- Output
- API Providers
- Development
- Troubleshooting
- Contributing
- License
π Documentation Index - Complete navigation guide to all documentation
- Architecture Guide - Complete system design with diagrams, concurrency model, and connection pooling
- Configuration Examples - LLM providers, performance tuning, and deployment (Docker, K8s, Lambda)
- Retry Behavior - Network resilience, error handling, and troubleshooting
- Development Guide - For contributors and Claude Code users
- Testing Guide - How to run tests
- Feature Docs - Comparative analysis feature
Get up and running in 3 minutes:
# 1. Clone the repository
git clone https://github.com/skanga/FinAgent
cd financial_reporting_agent
# 2. Install dependencies
pip install -r requirements.txt
# 3. Configure environment
cp .env.example .env
# Edit .env and add your OPENAI_API_KEY
# 4. Run your first analysis
python main.py --tickers AAPL,MSFT,GOOGL --period 1y
# 5. (Optional) Include options analysis
python main.py --tickers AAPL --period 1y --optionsThe application will prompt you to open the HTML report in your browser. Press Enter (or type 'y') to view the report with charts, metrics, and AI insights! Markdown and data files are also saved in ./financial_reports/.
- Python 3.8+ (3.10+ recommended)
- pip package manager
- API Key for OpenAI-compatible LLM (OpenAI, Groq, Azure, etc.)
# Install all required dependencies
pip install -r requirements.txtFor contributing or testing:
# Install with development dependencies
pip install -r requirements.txt
# Optionally install type checking
pip install mypy
# Run tests (all tests are now in tests/ directory)
pytest tests/ -v| Package | Purpose | Version |
|---|---|---|
pandas |
Data manipulation | β₯2.0.0 |
numpy |
Numerical operations | β₯1.24.0 |
yfinance |
Financial data fetching | β₯0.2.28 |
matplotlib |
Chart generation | β₯3.7.0 |
langchain-openai |
LLM integration | β₯0.1.0 |
python-dotenv |
Environment config | β₯1.0.0 |
π For extensive configuration examples and deployment scenarios, see CONFIG_EXAMPLES.md
Configuration is managed through environment variables, which can be set in a .env file or directly in your shell.
# Copy the example file
cp .env.example .env
# Edit with your favorite editor
nano .env # or vim, code, etc.# OpenAI-compatible API key (required)
OPENAI_API_KEY=your_api_key_here# API endpoint (default: https://api.openai.com/v1)
OPENAI_BASE_URL=https://api.openai.com/v1
# Model name (default: gpt-4o)
OPENAI_MODEL=gpt-4o
# Parallel processing threads (default: 3, range: 1-10)
MAX_WORKERS=3
# Cache expiration in hours (default: 24, range: 1-168)
CACHE_TTL_HOURS=24
# Benchmark for comparison (default: SPY)
BENCHMARK_TICKER=SPY
# HTML report generation (default: true)
GENERATE_HTML=true
# Embed images as base64 in HTML (default: false)
EMBED_IMAGES_IN_HTML=false
# Prompt to open reports in browser (default: true, press Enter to accept)
OPEN_IN_BROWSER=true
# Options analysis (default: false)
INCLUDE_OPTIONS=false
# Options cache TTL in hours (default: 1)
OPTIONS_CACHE_TTL_HOURS=1
# Number of options expirations to analyze (default: 3, max: 10)
OPTIONS_EXPIRATIONS=3The application validates all configuration on startup:
- API key must be present and non-empty
- Numeric values must be within acceptable ranges
- Invalid configuration will produce clear error messages
For CI/CD or containerized environments:
# Linux/macOS
export OPENAI_API_KEY="sk-..."
export OPENAI_BASE_URL="https://api.openai.com/v1"
# Windows PowerShell
$env:OPENAI_API_KEY="sk-..."
$env:OPENAI_BASE_URL="https://api.openai.com/v1"
# Windows CMD
set OPENAI_API_KEY=sk-...
set OPENAI_BASE_URL=https://api.openai.com/v1# Analyze single stock over 1 year
python main.py --tickers AAPL --period 1y
# Analyze multiple stocks
python main.py --tickers AAPL,MSFT,GOOGL --period 1y
# Shorter time periods
python main.py --tickers TSLA --period 3mo
python main.py --tickers NVDA --period 6mo# Specify output location
python main.py --tickers AAPL,MSFT --period 1y --output ./my_reports
# Output is validated for security (must be in cwd or home directory)# Equal weights (default)
python main.py --tickers AAPL,MSFT,GOOGL --period 1y
# Custom portfolio weights (must sum to 1.0)
python main.py --tickers AAPL,MSFT,GOOGL --weights 0.5,0.3,0.2 --period 1y# Clear expired cache before running
python main.py --tickers AAPL --period 1y --clear-cache
# Expired cache is automatically cleared on each run# Enable debug logging for troubleshooting
python main.py --tickers AAPL --period 1y --verbose# Disable HTML generation (markdown only)
python main.py --tickers AAPL --period 1y --no-html
# Don't open in browser automatically
python main.py --tickers AAPL --period 1y --no-browser
# Embed images as base64 (single-file HTML, larger size)
python main.py --tickers AAPL --period 1y --embed-images
# Combine options
python main.py --tickers AAPL,MSFT --period 6mo --embed-images --no-browser# Enable options analysis for a single ticker
python main.py --tickers AAPL --period 1y --options
# Analyze more expiration dates (default: 3, max: 10)
python main.py --tickers SPY --period 6mo --options --options-expirations 5
# Portfolio with options analysis
python main.py --tickers AAPL,MSFT,GOOGL --period 1y --options
# Combined with other flags
python main.py --tickers AAPL --period 3mo --options --embed-images --verboseWhat you get with --options:
- Greeks Analysis: Delta, Gamma, Theta, Vega, Rho for all contracts
- IV Analysis: Implied volatility skew, term structure, IV vs HV comparison
- Strategy Detection: 18+ strategies (straddles, spreads, condors, butterflies, etc.)
- P&L Modeling: Breakeven points, max profit/loss, probability of profit
- Portfolio Greeks: Aggregate exposure across all positions
- Visualizations: Options chain heatmaps, Greeks charts, P&L diagrams, IV surfaces
- AI Recommendations: LLM-generated strategy suggestions and hedging advice
Use natural language to specify your analysis:
# Natural language request
python main.py --request "Compare AAPL and MSFT over the past year"
# More examples
python main.py --request "Analyze tech stocks over 6 months"
python main.py --request "Show me Tesla's performance this quarter"
python main.py --request "Compare semiconductor stocks year to date"The LLM will parse your request and extract:
- Ticker symbols
- Time period
- Analysis type
| Period | Description |
|---|---|
1d |
1 day |
5d |
5 days |
1mo |
1 month |
3mo |
3 months |
6mo |
6 months |
1y |
1 year (default) |
2y |
2 years |
5y |
5 years |
10y |
10 years |
ytd |
Year to date |
max |
Maximum available |
# Show all available options
python main.py --help
# View examples
python main.py --help | grep -A 20 "Examples:"π For detailed architecture documentation with diagrams, see ARCHITECTURE.md
financial_reporting_agent/
βββ config.py # Configuration management with .env support
βββ models.py # Stock data models and type definitions
βββ models_options.py # Options data models (9 dataclasses)
βββ constants.py # Application constants and parameters
βββ cache.py # Dual-format caching (Parquet + Pickle)
βββ fetcher.py # yfinance stock data fetching
βββ options_fetcher.py # yfinance options data fetching
βββ analyzers.py # Financial metrics computation
β βββ AdvancedFinancialAnalyzer
β βββ PortfolioAnalyzer
β βββ PortfolioOptionsAnalyzer
βββ options_analyzer.py # Options Greeks, IV, and strategy detection
βββ charts.py # Matplotlib chart generation (stock + options)
βββ llm_interface.py # LLM integration for narratives
βββ html_generator.py # HTML report generation
βββ alerts.py # Alert detection system
βββ utils.py # Utility functions
βββ orchestrator.py # Main coordination logic
βββ main.py # CLI entry point
βββ templates/ # HTML templates
β βββ report_template.html
βββ tests/ # Test suite (600+ tests)
β βββ conftest.py # Shared test fixtures
β βββ test_*.py # Test modules
βββ requirements.txt # Python dependencies
βββ requirements-dev.txt # Development dependencies
βββ pytest.ini # Pytest configuration
βββ .env.example # Configuration template
βββ .gitignore # Git exclusions
βββ README.md # This file
Generated directories:
βββ .cache/ # Cached data (Parquet for DataFrames, Pickle for objects)
βββ financial_reports/ # Generated reports (HTML, MD) and charts
- Loads
.envfile automatically using python-dotenv - Validates all settings on startup
- Masks API keys in logs for security
- Detects LLM provider from base URL
- Wraps yfinance API with error handling
- Integrates with cache layer
- Timeout protection (configurable)
- Dual-Format Support:
- Parquet for pandas DataFrames (stock prices, fundamentals)
- Pickle for Python objects (options chains, expirations)
- TTL: Configurable expiration (stock: 24h default, options: 1h default)
- Security: Path traversal protection, MD5-based keys
- Performance: Snappy compression for Parquet
- Storage:
.cache/directory
AdvancedFinancialAnalyzer:
- Technical indicators (RSI, MACD, Bollinger Bands)
- Advanced metrics (Sharpe, Sortino, Calmar, Treynor)
- Fundamental data parsing (revenue, earnings, margins)
- Benchmark comparison (Alpha, Beta, Information Ratio)
PortfolioAnalyzer:
- Portfolio-level returns and volatility
- Correlation matrix
- Diversification ratio
- Top contributors analysis
- Concentration risk (Herfindahl index)
PortfolioOptionsAnalyzer:
- Aggregate portfolio Greeks (Delta, Vega, Theta)
- Cross-position hedging recommendations
- Greeks concentration risk
- Vega/Delta/Theta balancing suggestions
- Greeks Calculation: Black-Scholes-Merton for Delta, Gamma, Theta, Vega, Rho
- IV Solver: Newton-Raphson with Brent's method fallback
- Strategy Detection: 18+ patterns (straddles, spreads, condors, butterflies, etc.)
- P&L Modeling: Breakeven calculation, max profit/loss, probability of profit
- IV Analysis: Skew detection, term structure, IV vs historical volatility
- Caching: TTL-based caching of options chains (1 hour default)
- Stock Charts: Price with technical overlays, comparison charts, risk-reward scatter
- Options Charts:
- Options chain heatmaps (volume, OI, IV)
- Greeks visualization (Delta, Gamma, Theta, Vega)
- P&L diagrams with breakeven points
- IV surface/skew plots (3D and 2D)
- Thread-safe: Agg backend for concurrent generation
- Memory-optimized: Explicit cleanup with figure closing
- Natural language request parsing
- Comprehensive narrative generation (stock + options)
- Options-specific narratives:
- IV assessment and opportunities
- Strategy recommendations with rationale
- Portfolio hedging analysis
- Report quality review and scoring
- Temperature-controlled for consistency
- Chart embedding in markdown reports
- Markdown-to-HTML conversion (no external dependencies)
- Professional, responsive template
- Chart embedding (relative paths or base64)
- Print-friendly styling
- Coordinates all components
- Parallel ticker analysis
- Progress tracking
- Error handling and partial results
- Performance metrics collection
User Input (CLI)
β
Natural Language Parser (optional)
β
Orchestrator
β
βββββββββββββββ¬ββββββββββββββββ¬βββββββββββββββ
β Fetcher β Analyzer β LLM β
β (cached) β (vectorized) β (insights) β
βββββββββββββββ΄ββββββββββββββββ΄βββββββββββββββ
β β β
Cache (.parquet) Charts (.png) Report (.md)
β β
β HTML Generator
β β
βββββββββββββββ Output Directory (./financial_reports/)
βββ report.html β Prompt to open in browser
βββ report.md
βββ charts.png (embedded in reports)
βββ data.csv
Each analysis generates:
Primary output format - prompts to open in your browser (press Enter):
- Professional, responsive design
- Embedded technical charts with analysis
- Styled tables and metrics
- Print-friendly layout
- Works on desktop, tablet, and mobile
Source format for the HTML report:
# Financial Analysis Report
Generated: 2024-01-15 14:30:00 UTC
## Executive Summary
[AI-generated overview of findings]
## Technical Charts
### Portfolio Comparison

### AAPL Technical Analysis

## Individual Stock Analysis
### AAPL
- Latest Price: $185.50
- Sharpe Ratio: 1.45
- Max Drawdown: -12.5%
## Portfolio Analysis
- Total Value: $10,000
- Portfolio Return: 15.3%
- Sharpe Ratio: 1.67
- Diversification Ratio: 1.23
## Alerts
β οΈ AAPL: RSI indicates overbought (75.2)
## AI Insights
[Detailed analysis and recommendations]For each ticker:
{TICKER}_technical.png: Price, moving averages, Bollinger Bands, RSI, Stochastic
For portfolio:
comparison_chart.png: Normalized returns comparison
Charts are automatically embedded in both HTML and markdown reports.
For each ticker:
{TICKER}_prices.csv: Full historical data with computed indicators
Each report includes execution metrics:
{
"execution_time_seconds": 12.5,
"tickers_analyzed": 3,
"successful": 3,
"failed": 0,
"charts_generated": 4,
"quality_score": 8.5,
"portfolio_analyzed": true
}After running:
python main.py --tickers AAPL,MSFT,GOOGL --period 1yYou'll get:
financial_reports/
βββ financial_report_20240115T143000Z.html β Prompt to open in browser
βββ financial_report_20240115T143000Z.md
βββ AAPL_technical.png π Embedded in reports
βββ AAPL_prices.csv
βββ MSFT_technical.png π Embedded in reports
βββ MSFT_prices.csv
βββ GOOGL_technical.png π Embedded in reports
βββ GOOGL_prices.csv
βββ comparison_chart.png π Embedded in reports
The agent supports any OpenAI-compatible API endpoint.
# .env configuration
OPENAI_API_KEY=sk-...
OPENAI_BASE_URL=https://api.openai.com/v1
OPENAI_MODEL=gpt-4oGet API Key: platform.openai.com/api-keys
# .env configuration
OPENAI_API_KEY=gsk_...
OPENAI_BASE_URL=https://api.groq.com/openai/v1
OPENAI_MODEL=llama-3.1-70b-versatileAvailable Models:
llama-3.1-70b-versatile(recommended)llama-3.1-8b-instant(faster, lower quality)mixtral-8x7b-32768
Get API Key: console.groq.com
# .env configuration
OPENAI_API_KEY=your_azure_key
OPENAI_BASE_URL=https://your-resource.openai.azure.com/
OPENAI_MODEL=gpt-4Setup: Azure OpenAI Documentation
# .env configuration
OPENAI_API_KEY=not-needed
OPENAI_BASE_URL=http://localhost:11434/v1
OPENAI_MODEL=llama2Compatible with:
- Ollama
- LM Studio
- LocalAI
- vLLM
- Text Generation WebUI (with OpenAI extension)
| Provider | Speed | Cost | Quality | Free Tier |
|---|---|---|---|---|
| OpenAI GPT-4 | Medium | High | Excellent | No |
| OpenAI GPT-4o | Fast | Medium | Excellent | No |
| Groq (Llama 3.1) | Very Fast | Free/Low | Good | Yes |
| Azure OpenAI | Medium | High | Excellent | No |
| Local (Ollama) | Fast | Free | Varies | Yes |
The project includes 600+ comprehensive tests in the tests/ directory:
# Run all tests
pytest tests/ -v
# Run specific test file
pytest tests/test_memory_leaks.py -v
# Run tests by category
pytest tests/ -m unit # Fast unit tests
pytest tests/ -m integration # Integration tests
pytest tests/ -m "not slow" # Skip slow tests
# Run with coverage
pytest tests/ --cov=. --cov-report=html
# See TESTING_QUICK_START.md for more optionsOptimizations implemented:
- β Vectorized DataFrame operations
- β Single iloc[-1] extraction (1.44x speedup)
- β Pre-calculated window sizes
- β Explicit memory cleanup with gc.collect()
- β Helper methods to eliminate duplication
Security measures:
- β Path traversal protection
- β No pickle serialization (uses Parquet)
- β API key masking in logs
- β Input validation for tickers and weights
- β Specific exception handling (no broad catches)
Code standards:
- Type hints throughout
- Comprehensive docstrings
- DRY principle applied
- Explicit error messages
- No silent failures
From test_performance.py:
DataFrame Size Processing Time
500 rows 2.74 ms
1000 rows 2.69 ms
2500 rows 3.60 ms
5000 rows 4.18 ms
Scaling: 1.5x for 10x data (excellent)
iloc optimization: 1.44x speedup
From test_memory_leaks.py:
5 large charts: 0.47 MB increase
5 comparison charts: 0.44 MB increase
All figures properly closed β
Explicit garbage collection β
π For detailed retry behavior and network error handling, see RETRY_BEHAVIOR.md
Error: ValueError: OPENAI_API_KEY environment variable must be set
Solutions:
# Check if .env file exists
ls -la .env
# Verify .env format (no 'set' prefix)
cat .env
# Create from example
cp .env.example .env
nano .envError: ModuleNotFoundError: No module named 'dotenv'
Solution:
# Install all dependencies
pip install -r requirements.txt
# Verify installation
pip list | grep dotenvError: Failed to analyze INVALID: ValueError: Failed to fetch
Solutions:
- Verify ticker symbol is correct (use Yahoo Finance format)
- Check internet connectivity
- Some tickers may require exchange suffix (e.g.,
TSLA.Lfor London)
Error: OSError: [Errno 13] Permission denied: '.cache'
Solution:
# Remove cache directory and recreate
rm -rf .cache
mkdir .cache
# Or clear cache on next run
python main.py --tickers AAPL --clear-cacheError: Request timeout after 30 seconds
Solutions:
- Check API endpoint is accessible
- Verify API key is valid
- Try a different model (smaller/faster)
- Check your internet connection
Error: MemoryError: Unable to allocate array
Solutions:
# Reduce number of tickers
python main.py --tickers AAPL,MSFT # instead of 20 tickers
# Use shorter period
python main.py --tickers AAPL --period 3mo # instead of 10y
# Reduce worker threads
export MAX_WORKERS=1Enable verbose logging for troubleshooting:
# CLI flag
python main.py --tickers AAPL --verbose
# Check logs for details
# Logs include: API calls, cache hits/misses, timing, errorsIf you encounter issues:
- Check this troubleshooting section
- Review the error message carefully
- Enable
--verbosemode for detailed logs - Check the Issues section
- Verify your configuration with:
pytest tests/test_env_loading.py -v
Contributions are welcome! This project values:
- Clean, maintainable code
- Comprehensive testing
- Security-first approach
- Clear documentation
# 1. Fork and clone
git clone https://github.com/skanga/financial_reporting_agent.git
cd financial_reporting_agent
# 2. Create virtual environment
python -m venv venv
source venv/bin/activate # or venv\Scripts\activate on Windows
# 3. Install dependencies
pip install -r requirements.txt
# 4. Create .env for testing
cp .env.example .env
# Add your API key
# 5. Run tests
pytest tests/ -v- Follow PEP 8 guidelines
- Use type hints
- Write docstrings for all functions
- Add tests for new features
- Keep functions focused and small
- Use meaningful variable names
- Create a feature branch:
git checkout -b feature/amazing-feature - Make your changes with clear commits
- Run all tests and ensure they pass
- Update documentation as needed
- Submit PR with description of changes
- Additional technical indicators
- More chart types
- Additional LLM providers
- Performance optimizations
- Documentation improvements
- Bug fixes
This project is licensed under the MIT License.
MIT License
Copyright (c) 2024
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
- yfinance: Market data retrieval
- pandas/numpy: Data processing
- matplotlib: Visualization
- LangChain: LLM integration
- python-dotenv: Configuration management
- Documentation: This README and inline code comments
- Issues: GitHub Issues
- Questions: Open a discussion or issue
- HTML report generation with professional styling
- Chart embedding in reports (markdown + HTML)
- Auto-launch reports in browser
- Responsive design for mobile/tablet/desktop
- Options Analytics (Greeks, IV, strategies, P&L modeling, portfolio hedging)
- Dual-format caching (Parquet + Pickle)
- Stochastic oscillator indicator
- LLM quality review system
- Additional Data Sources (not only yfinance)
- Real-time data streaming
- Advanced portfolio optimization (Markowitz, Black-Litterman)
- Sector and industry analysis
- Backtesting framework
- Web interface (Flask/FastAPI)
- Database persistence (PostgreSQL/SQLite)
- Additional chart types (candlesticks, volume analysis)
- Interactive charts (Plotly integration)
- News sentiment integration
- PDF report generation
- Multi-currency support
- ESG metrics integration
- Dark mode for HTML reports
- More options strategies (ratio spreads, box spreads, synthetic positions)
- Historical IV percentile tracking
- Earnings calendar integration for options
- American options pricing (binomial trees)
Built with β€οΈ in the SF Bay Area