POTE/scripts/daily_fetch.sh
ilia 0d8d85adc1 Add complete automation, reporting, and CI/CD system
Features Added:
==============

📧 EMAIL REPORTING SYSTEM:
- EmailReporter: Send reports via SMTP (Gmail, SendGrid, custom)
- ReportGenerator: Generate daily/weekly summaries with HTML/text formatting
- Configurable via .env (SMTP_HOST, SMTP_PORT, etc.)
- Scripts: send_daily_report.py, send_weekly_report.py

🤖 AUTOMATED RUNS:
- automated_daily_run.sh: Full daily ETL pipeline + reporting
- automated_weekly_run.sh: Weekly pattern analysis + reports
- setup_cron.sh: Interactive cron job setup (5-minute setup)
- Logs saved to ~/logs/ with automatic cleanup

🔍 HEALTH CHECKS:
- health_check.py: System health monitoring
- Checks: DB connection, data freshness, counts, recent alerts
- JSON output for programmatic use
- Exit codes for monitoring integration

🚀 CI/CD PIPELINE:
- .github/workflows/ci.yml: Full CI/CD pipeline
- GitHub Actions / Gitea Actions compatible
- Jobs: lint & test, security scan, dependency scan, Docker build
- PostgreSQL service for integration tests
- 93 tests passing in CI

📚 COMPREHENSIVE DOCUMENTATION:
- AUTOMATION_QUICKSTART.md: 5-minute email setup guide
- docs/12_automation_and_reporting.md: Full automation guide
- Updated README.md with automation links
- Deployment → Production workflow guide

🛠️ IMPROVEMENTS:
- All shell scripts made executable
- Environment variable examples in .env.example
- Report logs saved with timestamps
- 30-day log retention with auto-cleanup
- Health checks can be scheduled via cron

WHAT THIS ENABLES:
==================
After deployment, users can:
1. Set up automated daily/weekly email reports (5 min)
2. Receive HTML+text emails with:
   - New trades, market alerts, suspicious timing
   - Weekly patterns, rankings, repeat offenders
3. Monitor system health automatically
4. Run full CI/CD pipeline on every commit
5. Deploy with confidence (tests + security scans)

USAGE:
======
# One-time setup (on deployed server)
./scripts/setup_cron.sh

# Or manually send reports
python scripts/send_daily_report.py --to user@example.com
python scripts/send_weekly_report.py --to user@example.com

# Check system health
python scripts/health_check.py

See AUTOMATION_QUICKSTART.md for full instructions.

93 tests passing | Full CI/CD | Email reports ready
2025-12-15 15:34:31 -05:00

120 lines
3.3 KiB
Bash
Executable File

#!/bin/bash
# Daily POTE Data Update Script
# Run this once per day to fetch new trades and prices
# Recommended: 7 AM daily (after markets close and disclosures are filed)
set -e # Exit on error
# --- Configuration ---
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
LOG_DIR="${PROJECT_DIR}/logs"
LOG_FILE="${LOG_DIR}/daily_fetch_$(date +%Y%m%d).log"
# Ensure log directory exists
mkdir -p "$LOG_DIR"
# Redirect all output to log file
exec > >(tee -a "$LOG_FILE") 2>&1
echo "=========================================="
echo " POTE Daily Data Fetch"
echo " $(date)"
echo "=========================================="
# Activate virtual environment
cd "$PROJECT_DIR"
source venv/bin/activate
# --- Step 1: Fetch Congressional Trades ---
echo ""
echo "--- Step 1: Fetching Congressional Trades ---"
# Fetch last 7 days (to catch any late filings)
python scripts/fetch_congressional_trades.py --days 7
TRADES_EXIT=$?
if [ $TRADES_EXIT -ne 0 ]; then
echo "⚠️ WARNING: Failed to fetch congressional trades"
echo " This is likely because House Stock Watcher API is down"
echo " Continuing with other steps..."
fi
# --- Step 2: Enrich Securities ---
echo ""
echo "--- Step 2: Enriching Securities ---"
# Add company names, sectors, industries for any new tickers
python scripts/enrich_securities.py
ENRICH_EXIT=$?
if [ $ENRICH_EXIT -ne 0 ]; then
echo "⚠️ WARNING: Failed to enrich securities"
fi
# --- Step 3: Fetch Price Data ---
echo ""
echo "--- Step 3: Fetching Price Data ---"
# Fetch prices for all securities
python scripts/fetch_sample_prices.py
PRICES_EXIT=$?
if [ $PRICES_EXIT -ne 0 ]; then
echo "⚠️ WARNING: Failed to fetch price data"
fi
# --- Step 4: Calculate Returns (Optional) ---
echo ""
echo "--- Step 4: Calculating Returns ---"
python scripts/calculate_all_returns.py --window 90 --limit 100
CALC_EXIT=$?
if [ $CALC_EXIT -ne 0 ]; then
echo "⚠️ WARNING: Failed to calculate returns"
fi
# --- Summary ---
echo ""
echo "=========================================="
echo " Daily Fetch Complete"
echo " $(date)"
echo "=========================================="
# Show quick stats
python << 'PYEOF'
from sqlalchemy import text
from pote.db import engine
from datetime import datetime
print("\n📊 Current Database Stats:")
with engine.connect() as conn:
officials = conn.execute(text("SELECT COUNT(*) FROM officials")).scalar()
trades = conn.execute(text("SELECT COUNT(*) FROM trades")).scalar()
securities = conn.execute(text("SELECT COUNT(*) FROM securities")).scalar()
prices = conn.execute(text("SELECT COUNT(*) FROM prices")).scalar()
print(f" Officials: {officials:,}")
print(f" Securities: {securities:,}")
print(f" Trades: {trades:,}")
print(f" Prices: {prices:,}")
# Show most recent trade
result = conn.execute(text("""
SELECT o.name, s.ticker, t.side, t.transaction_date
FROM trades t
JOIN officials o ON t.official_id = o.id
JOIN securities s ON t.security_id = s.id
ORDER BY t.transaction_date DESC
LIMIT 1
""")).fetchone()
if result:
print(f"\n📈 Most Recent Trade:")
print(f" {result[0]} - {result[2].upper()} {result[1]} on {result[3]}")
print()
PYEOF
# Exit with success (even if some steps warned)
exit 0