Building NancyBot: An AI-Powered Congressional Stock Trade Monitoring Agent
How to build an intelligent agent that tracks Nancy Pelosi's stock trades using xAI's Grok-4
Members of Congress are required by law to publicly disclose their stock trades under the STOCK Act. While this information is public, staying on top of new disclosures can be tedious. Enter NancyBot - an AI-powered monitoring agent that automatically tracks these trades and provides intelligent analysis of their significance.
In this post, I’ll walk you through everything you need to know about NancyBot, from what it does to how to deploy it as a background service on your own infrastructure.
What is NancyBot?
NancyBot is a Python application that continuously monitors Nancy Pelosi’s stock trades and notifies you when new trades are disclosed. But it’s more than just a notification system - it uses xAI’s Grok-4 model to provide contextual analysis of each trade, including:
What the company does
Recent news and developments
The potential significance of the trade timing
Think of it as your personal financial disclosure analyst that never sleeps.
Key Features
🔍 Automated Monitoring - Runs continuously, checking for new trades at configurable intervals
🤖 AI-Powered Analysis - Uses xAI’s Grok-4 to provide intelligent insights on each trade
📊 Smart Tracking - Maintains a history of seen trades to avoid duplicate notifications
🔔 Real-time Alerts - Notifies you immediately when new trades are detected
💾 Persistent Storage - Remembers previously seen trades across restarts
⚙️ Highly Configurable - Customize check intervals, notifications, and more
How It Works
The architecture is elegantly simple:
Data Collection: NancyBot uses xAI’s Grok-4 to search for Nancy Pelosi’s recent stock trades from public disclosure data
Change Detection: It compares new results against a local JSON file of previously seen trades
AI Analysis: When a new trade is detected, Grok-4 analyzes its significance
Notification: You receive an alert with trade details and AI-generated insights
Persistence: The trade is saved to avoid duplicate notifications
┌─────────────┐
│ NancyBot │
│ Monitor │
└──────┬──────┘
│
├─► xAI API (Grok-4) ──► Search for trades
│
├─► Compare with known trades
│
├─► New trade? ──► Analyze with AI
│
└─► Notify user + Save to historyGetting Started
Prerequisites
Before you begin, you’ll need:
Python 3.8 or higher installed on your system
An xAI API key (get one at console.x.ai)
Basic familiarity with the command line
Installation
The installation process is straightforward:
Step 1: Clone the Repository
git clone https://github.com/rod-trent/JunkDrawer.git
cd JunkDrawer/NancyBotStep 2: Install Dependencies
pip install -r requirements.txtThis installs just two lightweight dependencies:
requests- For making HTTP requests to the xAI APIpython-dotenv- For loading environment variables from a.envfile
Step 3: Configure Your API Key
Create a .env file from the example:
cp .env.example .envEdit .env and add your xAI API key:
XAI_API_KEY=xai-your_actual_api_key_hereImportant: Keep your .env file secure and never commit it to version control!
Step 4: Test Your Setup
Before running the full bot, verify your API connection:
python test_xai_api.pyYou should see:
✓ API Key loaded: xai-...
Testing xAI API connection...
Endpoint: https://api.x.ai/v1/chat/completions
Model: grok-4
Status Code: 200
✅ SUCCESS! API is working correctly.
Response:
Hello from NancyBot test!
✓ NancyBot should work correctly now!If you see this, you’re ready to go!
Running NancyBot
Basic Usage
Start the bot with default settings (checks every hour):
python nancybot.pyYou’ll see output like this:
🤖 NancyBot Starting...
Check interval: 1.0 hours
Press Ctrl+C to stop
[2026-01-27 15:30:00] Checking for new trades...
No new trades since last check.
💤 Sleeping for 1.0 hours...When a New Trade is Detected
When NancyBot finds a new trade, you’ll receive a detailed notification:
🆕 New trade detected!
============================================================
🚨 NEW TRADE ALERT - Nancy Pelosi
============================================================
Date: 2026-01-15
Stock: NVDA - NVIDIA Corporation
Type: BUY
Amount: $1,000 - $15,000
AI Analysis:
NVIDIA Corporation is a leading technology company specializing in
graphics processing units (GPUs) and AI computing. Recent developments
include strong AI chip demand and data center growth. This trade timing
coincides with the company's latest earnings announcement showing
record revenue in AI segments.
============================================================
✅ Found 1 new trade(s)Customizing Check Intervals
You can adjust how frequently NancyBot checks for new trades by editing the main() function in nancybot.py:
def main():
try:
bot = NancyBot()
# Check every 30 minutes (for active monitoring)
bot.run(check_interval=1800)
# Check every 6 hours (for passive monitoring)
# bot.run(check_interval=21600)
# Check once daily (for casual monitoring)
# bot.run(check_interval=86400)
except Exception as e:
print(f"❌ Error starting NancyBot: {e}")Deployment Options
Running NancyBot manually is fine for testing, but for production use, you’ll want it running as a background service.
Option 1: Linux/Mac with systemd
Create a systemd service file:
sudo nano /etc/systemd/system/nancybot.serviceAdd the following configuration:
[Unit]
Description=NancyBot Stock Trade Monitor
After=network.target
[Service]
Type=simple
User=yourusername
WorkingDirectory=/path/to/NancyBot
Environment="PATH=/usr/bin:/usr/local/bin"
ExecStart=/usr/bin/python3 /path/to/NancyBot/nancybot.py
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.targetEnable and start the service:
sudo systemctl daemon-reload
sudo systemctl enable nancybot
sudo systemctl start nancybot
sudo systemctl status nancybotView logs:
sudo journalctl -u nancybot -fOption 2: Windows Task Scheduler
Open Task Scheduler
Create Basic Task
Name: “NancyBot Stock Monitor”
Trigger: “When the computer starts”
Action: “Start a program”
Program:
C:\Python39\python.exeArguments:
C:\path\to\NancyBot\nancybot.pyFinish and test the task
Option 3: Docker Container
Create a Dockerfile:
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["python", "nancybot.py"]Build and run:
docker build -t nancybot .
docker run -d --name nancybot --restart unless-stopped -v $(pwd)/.env:/app/.env nancybotOption 4: Cloud Deployment
AWS EC2:
Launch a t2.micro instance (free tier eligible)
SSH into the instance
Follow the Linux installation steps
Set up systemd service
Azure VM:
Create an Ubuntu VM
Follow the Linux installation steps
Configure systemd service
Heroku:
Add a
Procfile:worker: python nancybot.pyDeploy:
git push heroku main
DigitalOcean Droplet:
Create a $5/month droplet
Follow Linux installation steps
Set up systemd service
Extending NancyBot
Adding Email Notifications
Modify the notify_new_trade() method:
import smtplib
from email.mime.text import MIMEText
def notify_new_trade(self, trade: Dict[str, Any], analysis: str):
# Console output (keep existing)
print(f"🚨 NEW TRADE ALERT...")
# Add email notification
msg = MIMEText(f"New trade detected:\n\n{trade}\n\n{analysis}")
msg['Subject'] = f"🚨 Pelosi Trade: {trade.get('ticker')}"
msg['From'] = 'nancybot@yourdomain.com'
msg['To'] = 'your@email.com'
with smtplib.SMTP('smtp.gmail.com', 587) as server:
server.starttls()
server.login('your@email.com', 'your_app_password')
server.send_message(msg)Adding Discord Notifications
def send_discord_notification(self, trade: Dict[str, Any], analysis: str):
webhook_url = os.getenv('DISCORD_WEBHOOK_URL')
data = {
'embeds': [{
'title': f"🚨 New Pelosi Trade: {trade.get('ticker')}",
'description': analysis,
'fields': [
{'name': 'Date', 'value': trade.get('date'), 'inline': True},
{'name': 'Type', 'value': trade.get('type'), 'inline': True},
{'name': 'Amount', 'value': trade.get('amount'), 'inline': True},
],
'color': 0xFF5733
}]
}
requests.post(webhook_url, json=data)Tracking Multiple Politicians
Extend the bot to monitor other members of Congress:
class CongressTradeBot:
def __init__(self, politician_name: str):
self.politician_name = politician_name
# ... rest of init
def fetch_trades(self):
prompt = f"""
Search for recent stock trades by {self.politician_name}...
"""
# ... rest of method
# Create multiple bots
pelosi_bot = CongressTradeBot("Nancy Pelosi")
mcconnell_bot = CongressTradeBot("Mitch McConnell")Integrating Real Data Sources
For production use, consider integrating with dedicated APIs:
Capitol Trades API Example:
def fetch_pelosi_trades(self) -> List[Dict[str, Any]]:
api_key = os.getenv('CAPITOL_TRADES_API_KEY')
response = requests.get(
'https://api.capitoltrades.com/v1/trades',
params={
'politician': 'nancy-pelosi',
'limit': 50
},
headers={'Authorization': f'Bearer {api_key}'}
)
return response.json()['trades']Understanding the Code
Let’s break down the key components:
The NancyBot Class
class NancyBot:
def __init__(self):
load_dotenv()
self.xai_api_key = os.getenv('XAI_API_KEY')
self.xai_api_base = os.getenv('XAI_API_BASE', 'https://api.x.ai')
self.trades_file = 'trades_history.json'
self.known_trades = self.load_known_trades()The constructor loads environment variables and initializes the trade history.
Querying xAI
def query_xai(self, prompt: str) -> str:
headers = {
'Authorization': f'Bearer {self.xai_api_key}',
'Content-Type': 'application/json'
}
data = {
'messages': [
{'role': 'system', 'content': 'You are a financial analyst...'},
{'role': 'user', 'content': prompt}
],
'model': 'grok-4',
'stream': False,
'temperature': 0
}
response = requests.post(
f'{self.xai_api_base}/v1/chat/completions',
headers=headers,
json=data,
timeout=3600
)
return response.json()['choices'][0]['message']['content']This method handles all communication with the xAI API using OpenAI-compatible endpoints.
Trade Detection Logic
def check_for_new_trades(self):
trades = self.fetch_pelosi_trades()
for trade in trades:
trade_id = self.generate_trade_id(trade)
if trade_id not in self.known_trades:
# New trade detected!
analysis = self.analyze_trade(trade)
self.notify_new_trade(trade, analysis)
self.known_trades.add(trade_id)
self.save_known_trades()This is the heart of the bot - it compares new trades against known ones and triggers analysis and notifications.
Troubleshooting Common Issues
404 Not Found Error
Problem: 404 Client Error: Not Found for url: https://api.x.ai/v1/chat/completions
Solution: This was fixed in v1.1. Make sure you’re using model name grok-4 (not grok-beta or grok-2-latest).
XAI_API_KEY Not Found
Problem: ValueError: XAI_API_KEY not found in .env file
Solution:
Ensure
.envfile exists in the same directory asnancybot.pyVerify the format:
XAI_API_KEY=xai-your_key_here(no quotes)Check for typos in the variable name
No Trades Detected
Problem: Bot runs but reports “No trades found”
Solution:
This is actually normal! Nancy Pelosi may not have recent trades
The bot will continue checking on schedule
Try reducing the check interval for testing purposes
The bot relies on xAI’s knowledge, which may have limitations
Rate Limiting
Problem: API requests are being throttled
Solution:
Increase the check interval:
bot.run(check_interval=7200)(2 hours)Add exponential backoff for retries
Monitor your API usage in the xAI console
Performance and Cost Considerations
API Usage
Each check cycle makes approximately 2-3 API calls:
One to search for recent trades
One to analyze each new trade found
At a 1-hour check interval (24 checks/day):
Minimum: 48 API calls/day (if no new trades)
Maximum: 72+ API calls/day (if multiple trades found)
xAI Pricing
As of January 2026, xAI’s Grok-4 pricing:
Input: $2.50 per 1M tokens
Output: $10.00 per 1M tokens
Estimated monthly cost with default settings:
Low activity: $5-10/month (few new trades)
High activity: $15-25/month (many new trades)
Resource Requirements
Minimum Hardware:
256MB RAM
1 CPU core
100MB disk space
Recommended Hardware:
512MB RAM (for comfort)
1 CPU core
500MB disk space (for logs)
This means NancyBot can run on the smallest cloud instances:
AWS t2.micro (free tier)
Azure B1s
DigitalOcean $5/month droplet
Raspberry Pi 3 or newer
Security Best Practices
Protecting Your API Key
Never commit
.envto version controlAdd
.envto.gitignoreUse
.env.examplefor templates
Use environment-specific keys
Development key for testing
Production key for deployment
Rotate keys regularly
Generate new keys quarterly
Revoke old keys immediately after rotation
Limit key permissions
Only enable Chat Completions endpoint
Use separate keys for different projects
Running Securely
Use non-root user (Linux/Mac)
Enable firewall on cloud instances
Keep Python and dependencies updated
Monitor logs for suspicious activity
Set resource limits to prevent runaway processes
Legal and Ethical Considerations
Is This Legal?
Yes! NancyBot tracks publicly disclosed information that members of Congress are required to report under the STOCK Act (Stop Trading on Congressional Knowledge Act of 2012).
Key points:
All trade data is public record
Congressional members must disclose trades within 45 days
This information is available on official House and Senate websites
No proprietary or insider information is used
Is This Ethical?
This is a matter of perspective:
Arguments for:
Promotes transparency in government
Holds elected officials accountable
Levels the playing field for retail investors
Uses only public information
Arguments against:
Could be seen as targeting specific individuals
May contribute to market speculation
Personal financial decisions, even of public figures, deserve some privacy
My take: Congressional stock trading is a controversial topic, but this tool simply automates access to information that’s already public. Make your own informed decisions about both the tool and the underlying practice.
Important Disclaimer
NancyBot is for informational purposes only. It is not financial advice.
Do your own research before making any investment decisions
Past performance doesn’t indicate future results
Congressional trades don’t necessarily signal good or bad investments
Consult with a qualified financial advisor
Real-World Use Cases
For Retail Investors
Stay informed about trades made by one of the most successful Congressional traders. Some investors use this information as one data point among many in their research.
For Journalists
Automate the tedious process of monitoring Congressional disclosures for potential stories about conflicts of interest or unusual trading patterns.
For Researchers
Gather data for academic or policy research on Congressional trading patterns, market timing, and regulatory effectiveness.
For Watchdog Organizations
Monitor compliance with trading disclosure requirements and flag potential violations for further investigation.
Project Repository
The complete source code for NancyBot is available on GitHub:
Repository: https://github.com/rod-trent/JunkDrawer/tree/main/NancyBot
What’s Included
nancybot.py- Main application codetest_xai_api.py- API connection test scriptrequirements.txt- Python dependencies.env.example- Environment variable templateREADME.md- Complete documentationQUICKSTART.md- 5-minute setup guideTROUBLESHOOTING.md- Detailed error solutionsCHANGELOG.md- Version history
Contributing
Found a bug? Have an improvement? Contributions are welcome!
Fork the repository
Create a feature branch
Make your changes
Submit a pull request
Future Roadmap
Here’s what’s planned for future versions:
Version 1.2 (Coming Soon)
Integration with Capitol Trades API
Email notification support
Discord webhook integration
Configuration file support
Version 2.0 (Future)
Multi-politician tracking
Web dashboard interface
Historical trade analysis
Database storage (SQLite/PostgreSQL)
Mobile app
Version 3.0 (Long-term)
Real-time WebSocket notifications
Machine learning trade pattern analysis
Portfolio tracking features
Trade correlation analysis
Advanced analytics dashboard
Conclusion
NancyBot demonstrates the power of combining public data, AI analysis, and automation to create useful monitoring tools. In just a few hundred lines of Python, we’ve built an intelligent agent that:
Continuously monitors public disclosures
Provides contextual analysis using AI
Alerts users to new information
Runs reliably as a background service
Whether you’re a developer learning about AI agents, an investor researching Congressional trades, or a citizen interested in government transparency, NancyBot provides a practical example of how modern AI tools can be applied to real-world problems.
The beauty of this project is its simplicity and extensibility. The core concepts - periodic checking, change detection, AI analysis, and notifications - can be applied to countless other monitoring scenarios:
SEC filings
Patent applications
Real estate transactions
Corporate executive trades
Government contract awards
I encourage you to not only use NancyBot but also modify it for your own purposes. The code is intentionally straightforward and well-commented to make customization easy.
Get Started Today
Ready to deploy your own NancyBot?
Clone the repo:
git clone https://github.com/rod-trent/JunkDrawer.gitNavigate to NancyBot:
cd JunkDrawer/NancyBotFollow QUICKSTART.md: Get running in 5 minutes
Customize: Make it your own!
Resources
GitHub Repository: https://github.com/rod-trent/JunkDrawer/tree/main/NancyBot
xAI Documentation: https://docs.x.ai
xAI Console: https://console.x.ai
STOCK Act Information: https://ethics.house.gov/stock-act
House Financial Disclosures: https://disclosures-clerk.house.gov
Have questions or feedback? Found NancyBot useful? Let me know in the comments below or open an issue on GitHub!



