Skip to content
/ finLG Public

AI Powered Stock Analysis and Forecasting CLI

Notifications You must be signed in to change notification settings

knid/finLG

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

4 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ“Š FinLG - Stock Analysis and Forecasting CLI

A production-quality CLI application for stock analysis and probabilistic forecasting using AI-powered news analysis and Monte Carlo simulation.

Features

  • News Analysis: Fetches and analyzes recent news from Google News RSS and optionally Alpaca News API
  • AI-Powered Insights: Uses OpenRouter (supports Claude, GPT-4, Gemini, Llama, etc.) to extract events, sentiment, and generate bull/bear cases with citations
  • Quantile Forecasting: LightGBM-based quantile regression for p10/p50/p90 return predictions
  • Monte Carlo Simulation: Student-t distributed path simulation for intra-month risk metrics
  • Rich Terminal Output: Beautiful, user-friendly terminal output with tables and colors
  • Multiple Output Formats: Terminal display, JSON export, Markdown reports, and PNG plots

Installation

Prerequisites

  • Python 3.11 or higher
  • An OpenRouter API key (required)
  • Alpaca API credentials (optional, for additional news sources)

Setup

  1. Clone or download the project:
cd finlg
  1. Create and activate a virtual environment:
python -m venv .venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate
  1. Install dependencies:
pip install -r requirements.txt
  1. Create a .env file with your API keys:
# Required - Get your key at https://openrouter.ai/
OPENROUTER_API_KEY=your_openrouter_api_key_here

# Optional - Choose your model (default: anthropic/claude-sonnet-4-20250514)
OPENROUTER_MODEL=anthropic/claude-sonnet-4-20250514

# Optional - for additional news sources
ALPACA_API_KEY=your_alpaca_key_here
ALPACA_API_SECRET=your_alpaca_secret_here

# Optional - customize directories
FINBOT_CACHE_DIR=.cache
FINBOT_OUT_DIR=./out

Supported Models

You can use any model available on OpenRouter by setting OPENROUTER_MODEL:

  • anthropic/claude-sonnet-4-20250514 (default)
  • anthropic/claude-3-opus
  • openai/gpt-4-turbo
  • openai/gpt-4o
  • google/gemini-pro
  • meta-llama/llama-3-70b-instruct
  • And many more at https://openrouter.ai/models

Usage

Quick Start

# Run the interactive wizard
python -m finlg wizard

# Quick forecast for a stock
python -m finlg forecast GOOGL

# Generate full report with plots
python -m finlg report GOOGL --out ./reports/googl

Commands

analyze - News Analysis

Analyze news and market context for a stock:

python -m finlg analyze GOOGL --news-days 30
python -m finlg analyze AAPL --news-days 14 --json
python -m finlg analyze GOOGL --lang tr  # Turkish output

Options:

  • --news-days, -n: Days of news to analyze (default: 30)
  • --lang, -l: Output language: en (English) or tr (Turkish) (default: en)
  • --json, -j: Output as JSON
  • --verbose, -v: Enable verbose logging

forecast - Generate Forecast

Generate probabilistic forecast with Monte Carlo simulation:

python -m finlg forecast GOOGL
python -m finlg forecast MSFT --horizon 21 --paths 10000
python -m finlg forecast TSLA --json
python -m finlg forecast GOOGL --lang tr  # Turkish output

Options:

  • --horizon, -h: Forecast horizon in trading days (default: 21)
  • --paths, -p: Number of Monte Carlo simulation paths (default: 10000)
  • --news-days, -n: Days of news to analyze (default: 30)
  • --lang, -l: Output language: en (English) or tr (Turkish) (default: en)
  • --json, -j: Output as JSON
  • --verbose, -v: Enable verbose logging

report - Full Report

Generate complete report with plots and save to files:

python -m finlg report GOOGL --out ./out
python -m finlg report NVDA --horizon 42 --out ./reports/nvda
python -m finlg report GOOGL --lang tr --out ./out  # Turkish report

Options:

  • --out, -o: Output directory (default: ./out)
  • --horizon, -h: Forecast horizon in trading days (default: 21)
  • --paths, -p: Number of Monte Carlo simulation paths (default: 10000)
  • --news-days, -n: Days of news to analyze (default: 30)
  • --lang, -l: Output language: en (English) or tr (Turkish) (default: en)
  • --json, -j: Output as JSON
  • --verbose, -v: Enable verbose logging

Output files:

  • summary.md: Markdown report with citations
  • forecast.json: Machine-readable forecast data
  • plots/price_forecast.png: Price chart with forecast band
  • plots/return_distribution.png: End-of-period return histogram
  • plots/drawdown_distribution.png: Max drawdown distribution
  • plots/news_timeline.png: News intensity and sentiment timeline

wizard - Interactive Mode

Guided wizard for step-by-step configuration:

python -m finlg wizard
python -m finlg wizard --lang tr  # Turkish prompts

Options:

  • --lang, -l: Output language: en (English) or tr (Turkish) (default: en)

The wizard will prompt you for:

  • Language selection
  • Stock ticker
  • News analysis period
  • Forecast horizon
  • Number of simulation paths
  • Output directory
  • Output format preferences

Multilingual Support

Finbot supports multiple languages for terminal output and markdown reports:

  • English (en): Default language
  • Turkish (tr): Full Turkish translation
# Turkish forecast
python -m finlg forecast GOOGL --lang tr

# Turkish report with plots
python -m finlg report GOOGL --lang tr --out ./out

# Interactive wizard in Turkish
python -m finlg wizard --lang tr

Note: JSON output keys remain in English for API stability, regardless of the --lang setting.

Example Output

πŸ“Š FINBOT FORECAST: GOOGL
╔══════════════════════════════════════════════════════════════════╗

As of:          2024-01-15 14:30
Last Price:     $175.42
Horizon:        21 trading days
News analyzed:  45 articles (30 days)

πŸ“ˆ End-of-Period Return Forecast
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Percentile     β”‚ Return  β”‚ Price Target β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ p10 (bearish)  β”‚ -5.2%   β”‚ $166.30      β”‚
β”‚ p50 (median)   β”‚ +2.1%   β”‚ $179.10      β”‚
β”‚ p90 (bullish)  β”‚ +8.7%   β”‚ $190.68      β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸ“‰ Intra-Period Risk Metrics
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Metric       β”‚ p50    β”‚ p90 (worst case) β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Max Drawdown β”‚ -3.2%  β”‚ -8.5%            β”‚
β”‚ Lowest Point β”‚ -2.1%  β”‚ -6.8%            β”‚
β”‚ Highest Pointβ”‚ +4.5%  β”‚ +9.2%            β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸ‚ Bull Case
  1. Strong Q4 earnings beat expectations with cloud revenue growth
  2. AI product launches gaining market traction
  3. Cost optimization measures showing results
  4. Positive analyst upgrades from major firms
  5. Search market share remains dominant

🐻 Bear Case
  1. Regulatory scrutiny increasing in multiple jurisdictions
  2. Competition in AI space intensifying
  3. Advertising revenue growth slowing
  4. Antitrust concerns may limit acquisitions
  5. Macro headwinds affecting ad spending

⚠️ Unknowns & Risks
  β€’ Pending DOJ antitrust case outcome
  β€’ AI investment ROI timeline uncertain

🎯 Upcoming Catalysts
  β€’ Q4 earnings report (late January)
  β€’ Google I/O developer conference

⚠️ DISCLAIMER: This is not financial advice. Forecasts are probabilistic
estimates based on historical data and news analysis. Past performance
does not guarantee future results. Always do your own research.

Environment Variables

Variable Required Default Description
OPENROUTER_API_KEY Yes - OpenRouter API key for LLM
OPENROUTER_MODEL No anthropic/claude-sonnet-4.5 Model to use
ALPACA_API_KEY No - Alpaca API key for news
ALPACA_API_SECRET No - Alpaca API secret
FINBOT_CACHE_DIR No .cache Cache directory
FINBOT_OUT_DIR No ./out Default output directory

Architecture

finlg/
β”œβ”€β”€ __init__.py          # Package initialization
β”œβ”€β”€ __main__.py          # Entry point for python -m finlg
β”œβ”€β”€ cli.py               # Typer CLI application
β”œβ”€β”€ config.py            # Environment and settings
β”œβ”€β”€ features.py          # Feature engineering
β”œβ”€β”€ data/
β”‚   β”œβ”€β”€ prices.py        # yfinance price fetching
β”‚   └── news.py          # Google RSS + Alpaca news
β”œβ”€β”€ nlp/
β”‚   └── events.py        # OpenRouter LLM integration
β”œβ”€β”€ models/
β”‚   └── quantile.py      # LightGBM quantile regression
β”œβ”€β”€ sim/
β”‚   └── path_sim.py      # Monte Carlo simulation
β”œβ”€β”€ reporting/
β”‚   β”œβ”€β”€ plots.py         # Matplotlib visualizations
β”‚   └── render.py        # Rich terminal + Markdown output
└── utils/
    └── cache.py         # Disk caching utilities

Methodology

Forecasting Model

  1. Feature Engineering: Calculates momentum (5/20/60-day returns), volatility (20/60-day), drawdown, volume z-score, benchmark relative strength, and news-derived features (event counts, sentiment scores)

  2. Quantile Regression: Uses LightGBM to predict p10/p50/p90 quantiles of forward returns over the specified horizon

  3. Monte Carlo Simulation: Generates price paths using:

    • EWMA volatility estimation
    • Student-t distributed returns (df=5) for heavy tails
    • Drift derived from the quantile model's median prediction

News Analysis

  1. Data Collection: Fetches news from Google News RSS (primary) and Alpaca News API (optional)

  2. Event Extraction: Uses LLM via OpenRouter to classify each article by:

    • Event type (earnings, guidance, regulation, etc.)
    • Direction (bullish, bearish, mixed, unknown)
    • Time horizon (0-2d, 3-10d, 11-30d, 31-90d)
    • Confidence score (0-1)
  3. Analysis Generation: Synthesizes bull/bear cases with citations from the analyzed articles

Caching

Finbot caches:

  • Price data (1 hour TTL)
  • News fetches (30 minutes TTL)
  • LLM responses (24 hours TTL)

Cache is stored in .cache/ by default. Clear cache by deleting this directory.

Limitations

  • Not Financial Advice: This tool is for informational purposes only
  • Historical Data: Forecasts are based on historical patterns which may not repeat
  • News Coverage: Google News RSS may not capture all relevant news
  • Model Uncertainty: Quantile predictions have inherent uncertainty

License

MIT License - See LICENSE file for details.

Contributing

Contributions are welcome! Please ensure:

  • Code follows existing style (type hints, docstrings)
  • Tests pass (when added)
  • Documentation is updated

Disclaimer

⚠️ This software is not financial advice. All forecasts are probabilistic estimates based on historical data and news analysis. Past performance does not guarantee future results. The creators and contributors are not responsible for any financial decisions made based on this tool's output. Always conduct your own research and consult with qualified financial advisors before making investment decisions.

About

AI Powered Stock Analysis and Forecasting CLI

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages