Skip to content

RajendharAre/SentXStock

Repository files navigation

πŸ“ˆ SentXStock β€” Sentiment Trading Agent

AI-powered trading advisor that reads the market mood and tells you what to do with your money.

Python Streamlit FinBERT Gemini License


🧠 What is SentXStock?

SentXStock is an autonomous sentiment-driven trading agent that monitors real-time news and social media, analyzes market sentiment using a 3-tier AI pipeline, and generates actionable buy/sell/hold recommendations for a mock portfolio.

No manual stock picking. The AI reads 100+ news articles & social posts, judges the market mood, adjusts risk, and tells you exactly what to trade.


✨ Key Features

Feature Description
πŸ€– 3-Tier AI Pipeline FinBERT (local ML) β†’ Gemini (LLM) β†’ VADER (fallback)
πŸ“° Real-Time News Finnhub + NewsAPI (80,000+ sources)
πŸ’¬ Social Media Analysis Reddit (r/wallstreetbets, r/stocks, r/investing)
πŸ“Š Mock Portfolio Virtual portfolio with live Yahoo Finance prices
βš–οΈ Dynamic Risk Engine Auto-adjusts risk level based on market sentiment
πŸ“ Order Drafting BUY / SELL / HOLD recommendations with AI reasoning
πŸ’¬ AI Chatbot Ask questions like "Should I buy Tesla?" β€” get data-backed answers
πŸ”„ API Key Rotation Multiple Gemini keys with auto-rotation on quota limits
🎯 User Interaction Custom tickers, portfolio size, and risk preference

πŸ—οΈ Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                    STREAMLIT FRONTEND                         β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚  β”‚  Sentiment  β”‚ β”‚   Portfolio   β”‚ β”‚    AI Chatbot          β”‚ β”‚
β”‚  β”‚   Gauge     β”‚ β”‚   Pie Chart   β”‚ β”‚  "Should I buy TSLA?"  β”‚ β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
          β”‚               β”‚                    β”‚
          β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                          β”‚
                    β”Œβ”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”
                    β”‚  api.py   β”‚  ← Unified API Layer
                    β””β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”˜
                          β”‚
          β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
          β–Ό               β–Ό               β–Ό
   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
   β”‚  Data Layer  β”‚ β”‚ Sentiment β”‚ β”‚  Portfolio    β”‚
   β”‚  (Fetchers)  β”‚ β”‚ (3-Tier)  β”‚ β”‚  (Risk+Orders)β”‚
   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

3-Tier Sentiment Pipeline

News/Social Posts (100+ items)
        β”‚
        β–Ό
  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
  β”‚   FinBERT    β”‚  ← Tier 1: Local ML model (FREE, unlimited)
  β”‚  (Primary)   β”‚     Handles ~90% of headlines with high confidence
  β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜
         β”‚
    Confident? ──Yes──→ Use FinBERT result
         β”‚
         No (ambiguous)
         β”‚
         β–Ό
  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
  β”‚   Gemini     β”‚  ← Tier 2: LLM (nuanced understanding)
  β”‚  (Premium)   β”‚     Only called for ~10% of items
  β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜
         β”‚
    Available? ──Yes──→ Use Gemini result
         β”‚
         No (quota hit)
         β”‚
         β–Ό
  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
  β”‚    VADER     β”‚  ← Tier 3: Rule-based fallback (always works)
  β”‚  (Fallback)  β”‚
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸ“ Project Structure

SentXStock/
β”œβ”€β”€ api.py                    # Unified API for Streamlit frontend
β”œβ”€β”€ main.py                   # CLI entry point
β”œβ”€β”€ requirements.txt          # Python dependencies
β”œβ”€β”€ .env.example              # Environment variables template
β”‚
β”œβ”€β”€ agent/                    # Core agent logic
β”‚   β”œβ”€β”€ agent.py              # Trading agent orchestrator (5-step pipeline)
β”‚   └── chatbot.py            # AI chatbot for user questions
β”‚
β”œβ”€β”€ config/                   # Configuration
β”‚   └── config.py             # API keys, thresholds, model settings
β”‚
β”œβ”€β”€ data/                     # Data fetching layer
β”‚   β”œβ”€β”€ realtime_news.py      # Finnhub + NewsAPI news fetchers
β”‚   β”œβ”€β”€ realtime_social.py    # Reddit social media fetcher
β”‚   β”œβ”€β”€ scraper.py            # BeautifulSoup web scraper
β”‚   β”œβ”€β”€ mock_news.py          # Mock news data for demo
β”‚   └── mock_social.py        # Mock social data for demo
β”‚
β”œβ”€β”€ sentiment/                # Sentiment analysis engine
β”‚   β”œβ”€β”€ analyzer.py           # Main analyzer (3-tier pipeline)
β”‚   β”œβ”€β”€ finbert.py            # FinBERT local ML model
β”‚   β”œβ”€β”€ scorer.py             # VADER scoring + aggregation
β”‚   └── prompts.py            # LLM prompt templates
β”‚
β”œβ”€β”€ portfolio/                # Portfolio management
β”‚   β”œβ”€β”€ portfolio.py          # Portfolio manager (holdings, live prices)
β”‚   β”œβ”€β”€ risk.py               # Risk engine (dynamic risk adjustment)
β”‚   └── orders.py             # Order drafter (BUY/SELL/HOLD logic)
β”‚
β”œβ”€β”€ streamlit_app.py          # Streamlit entry point (run this)
└── st_pages/                 # Streamlit page modules
    β”œβ”€β”€ dashboard.py          # Sentiment dashboard + orders
    β”œβ”€β”€ chat.py               # AI chatbot page
    └── settings.py           # Tickers, portfolio & risk config

πŸš€ Getting Started

Prerequisites

  • Python 3.11+
  • Git
  • Free API keys (see below)

1. Clone the Repository

git clone https://github.com/RajendharAre/SentXStock.git
cd SentXStock

2. Install Dependencies

pip install -r requirements.txt

Note: First run will download FinBERT model (~438MB). This is cached locally and loads instantly on subsequent runs.

3. Set Up API Keys

Copy the example env file and add your keys:

cp .env.example .env

Edit .env:

# Multiple Gemini keys (comma-separated) for auto-rotation
GEMINI_API_KEYS=your_key_1,your_key_2

# Finnhub (financial news)
FINNHUB_API_KEY=your_finnhub_key

# NewsAPI (80,000+ news sources)
NEWSAPI_KEY=your_newsapi_key

Where to Get Free API Keys

API Free Tier Sign Up
Gemini 1,500 req/day (2.0-flash) ai.google.dev
Finnhub 60 req/min finnhub.io
NewsAPI 100 req/day newsapi.org

4. Run the Agent

# Real-time mode (uses live news + social data)
python main.py --output results.json

# Mock mode (uses demo data β€” great for testing)
python main.py --mock --output results.json

# Custom tickers
python main.py --tickers AAPL,TSLA,NVDA --output results.json

πŸ–₯️ Frontend (Streamlit Dashboard)

Running the Dashboard

streamlit run streamlit_app.py

Dashboard Features

Section What it Shows
Market Sentiment Gauge Overall sentiment score (-1.0 to +1.0) with Bullish/Neutral/Bearish indicator
Risk Level Display Current risk: High / Medium / Low with dynamic adjustment
Order Recommendations BUY / SELL / HOLD cards with AI reasoning
Portfolio Pie Chart Equity / Bonds / Cash allocation breakdown
News Feed Headlines color-coded: 🟒 Bullish, πŸ”΄ Bearish, βšͺ Neutral
AI Chatbot Ask trading questions, get data-backed answers
User Settings Custom tickers, investment amount, risk preference

Frontend API Usage

The Streamlit frontend uses api.py β€” the unified API layer:

from api import TradingAPI

api = TradingAPI()

# ── User Setup ──
api.set_user_tickers(["AAPL", "TSLA", "NVDA"])
api.set_user_portfolio(cash=50000, risk="Moderate")

# ── Run Analysis ──
result = api.run_analysis()            # Real-time
result = api.run_analysis(use_mock=True)  # Mock data

# ── AI Chatbot ──
response = api.chat("Should I buy Tesla?")
print(response["answer"])

# ── Ticker Deep Dive ──
ticker_data = api.analyze_ticker("AAPL")

# ── Dashboard Data (everything in one call) ──
dashboard = api.get_dashboard_data()

πŸ“Š Sample Output

{
  "timestamp": "2026-02-27 15:33:33",
  "overall_sentiment": "Neutral",
  "sentiment_score": -0.0838,
  "risk_adjustment": "Maintain Medium risk β€” sentiment supports current allocation",
  "new_risk_level": "Medium",
  "portfolio_action": "Maintain balanced allocation with selective adjustments",
  "orders": [
    {
      "action": "SELL",
      "asset": "AAPL",
      "reason": "Risk trim on AAPL β€” strong negative sentiment (score: -0.67)"
    },
    {
      "action": "BUY",
      "asset": "GOOGL",
      "reason": "Opportunistic buy on GOOGL β€” strong positive sentiment (score: 0.92)"
    }
  ],
  "analysis_details": {
    "total_items_analyzed": 122,
    "bullish_count": 28,
    "bearish_count": 46,
    "neutral_count": 48
  },
  "portfolio_snapshot": {
    "total_value": 114834.90,
    "equity_pct": 51.74,
    "bonds_pct": 4.72,
    "cash_pct": 43.54,
    "risk_level": "Medium"
  }
}

πŸ”§ Tech Stack

Component Technology
Language Python 3.11+
ML Model FinBERT (ProsusAI/finbert) β€” financial sentiment BERT
LLM Google Gemini 2.0-flash
NLP Fallback VADER Sentiment
Web Scraping BeautifulSoup4
News APIs Finnhub, NewsAPI
Social Data Reddit JSON API
Stock Prices Yahoo Finance (yfinance)
Frontend Streamlit
Deep Learning PyTorch + HuggingFace Transformers

βš™οΈ How It Works

1. Data Collection

  • Fetches 50+ news headlines from Finnhub (general + company-specific)
  • Fetches 35+ headlines from NewsAPI (business + technology)
  • Scrapes 24+ posts from Reddit (wallstreetbets, stocks, investing)
  • Deduplicates overlapping headlines across sources

2. Sentiment Analysis (3-Tier Pipeline)

  • FinBERT (primary): Local BERT model fine-tuned on financial text. Processes all 100+ items in ~2 seconds. Handles ~90% with high confidence.
  • Gemini (premium): Only called for ambiguous items (~10%). Provides nuanced understanding.
  • VADER (fallback): Rule-based scorer. Always available, no API limits.

3. Risk Engine

Sentiment Score Risk Level Allocation
> 0.5 High (aggressive) 70% equity, 15% bonds, 15% cash
-0.3 to 0.5 Medium (balanced) 50% equity, 30% bonds, 20% cash
< -0.3 Low (defensive) 25% equity, 35% bonds, 40% cash

4. Order Drafting

The agent generates BUY/SELL/HOLD orders based on:

  • Individual ticker sentiment scores
  • Overall market mood
  • Current portfolio allocation vs target
  • Risk level recommendations

5. AI Chatbot

Users can ask natural language questions. The chatbot:

  • Injects real-time sentiment data into the prompt
  • Uses Gemini for conversational responses
  • Falls back to template-based answers if Gemini is unavailable

πŸ”‘ API Key Rotation

SentXStock supports multiple Gemini API keys with automatic rotation:

GEMINI_API_KEYS=key1,key2,key3,key4,key5
  • When one key hits the daily quota β†’ automatically rotates to the next
  • All keys exhausted β†’ falls back to FinBERT + VADER (no interruption)
  • Each free-tier key provides 1,500 requests/day on gemini-2.0-flash

πŸ“œ License

This project is built for the NAAC Hackathon 2026.


πŸ‘₯ Team

  • Backend & AI Pipeline β€” Sentiment analysis, portfolio engine, API layer
  • Frontend β€” Streamlit dashboard, visualizations, user interface

Built with ❀️ for the NAAC Hackathon 2026

About

Sentiment-Driven Trading Agent is a Python-based system that analyzes mock news and social media using LLM-powered sentiment analysis to adjust portfolio risk dynamically. It generates buy/sell recommendations and visualizes performance through a Streamlit dashboard, demonstrating autonomous, sentiment-based trading logic.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors