Back to Projects

AltAlpha Lab — Quantitative Trading Platform

Quantitative trading research platform combining sentiment analysis, machine learning predictions, and strategy optimization. Built with Python 3.11+ FastAPI backend featuring 12 API endpoints (price data from yfinance, VADER sentiment analysis, feature engineering, strategy signals with configurable threshold/volatility, backtesting with transaction costs, performance metrics, RandomForest ML prediction, grid-search optimizer, live trading simulation, AI research reports) and React 18 + Vite 5.4 frontend with interactive dashboard (portfolio charts via Recharts, price/sentiment/drawdown/rolling Sharpe visualizations, strategy control panel, asset comparison, AI insights, multi-currency support).

Python 3.11+FastAPIPandasNumPyyfinancescikit-learnVADER SentimentReact 18Vite 5.4Tailwind CSSRechartsjsPDFhtml2canvasGitHub ActionsMakefile

Role

Quantitative Developer & ML Engineer

Team

Solo

Company/Organization

Personal Project (Research & Experimentation)

The Problem

Quantitative traders and researchers needed integrated platform to analyze trading strategies combining sentiment analysis, machine learning...

Commercial trading platforms like Bloomberg Terminal or QuantConnect required expensive subscriptions ($2000+/month or paid API credits), making them...

No unified platform existed for experimenting with sentiment-based trading signalsrequired manual integration of sentiment analysis tools, trading...

Strategy optimization (finding optimal parameters like sentiment threshold, volatility filter) required manual parameter sweeping and result...

Live trading simulation (day-by-day execution with trade logs) was not available in most backtesting toolsonly showed final portfolio value without...

AI-powered research reports and recommendations were unavailable in open-source trading toolsrequired expensive analyst subscriptions or manual...

Multi-asset comparison and correlation analysis required separate tools and manual data alignment across different tickers and time periods.

Most trading platforms required complex setup with multiple paid API keys (Alpha Vantage, Quandl, News APIs)no solution existed using only free data...

The Solution

Built a comprehensive quantitative trading research platform with two main components: Python FastAPI backend and React frontend.

Backend Architecture (Python 3.11+ + FastAPI)

Implemented 12 RESTful API endpoints for complete trading workflow:

GET / — Health check endpoint returning "AltAlpha Lab API is running"

GET /price-data?ticker=AAPL — Historical price data fetching via yfinance (no API key required). Returns OHLCV data with calculated returns...

GET /sentiment?ticker=AAPL — Sentiment time series using VADER sentiment analyzer. Analyzes ticker-related news and social media mentions,...

GET /features?ticker=AAPL — Feature engineering: merges price data and sentiment, calculates rolling averages (returns_avg_5d,...

GET /strategy?ticker=AAPL&sentiment_threshold=0.2&volatility_percentile=50 — Trading signal generation based on sentiment. Configurable...

GET /backtest?ticker=AAPL&initial_capital=10000&sentiment_threshold=0.2&transaction_cost=0.001 — Backtesting engine runs strategy with...

GET /metrics?ticker=AAPL&sentiment_threshold=0.2 — Performance metrics calculation: Sharpe ratio (risk-adjusted returns), max drawdown (largest...

GET /ml-predict?ticker=AAPL — RandomForest ML classifier for next-day direction prediction. Uses features: returns, rolling_sentiment_5d,...

GET /optimize?ticker=AAPL — Strategy optimizer using grid search. Sweeps sentiment_threshold (-0.5 to 0.5 in 0.1 steps) and volatility_percentile...

GET /live-sim?ticker=AAPL&sentiment_threshold=0.2 — Live trading simulation: day-by-day execution from historical data start to today. Trade logs...

GET /ai-report?ticker=AAPL — AI research analyst report: generates concise analysis with key metrics, trend assessment, sentiment summary, risk...

GET /ai-report/comprehensive?ticker=AAPL — Comprehensive AI analysis: detailed report with ratings (1-10 scale), buy/hold/sell recommendation,...

Core Backend Modules

data.py — Price data fetching via yfinance API. No authentication required, free market data for any ticker. Handles errors (invalid tickers,...

sentiment.py — VADER (Valence Aware Dictionary and sEntiment Reasoner) sentiment analysis. Rule-based sentiment scoring optimized for social...

features.py — Feature engineering: rolling averages (SMA 5-day for returns and sentiment), volatility calculation (standard deviation), lag...

strategy.py — Trading signal generation: buy when sentiment > threshold AND volatility < percentile, sell when sentiment < -threshold OR...

backtest.py — Backtesting engine with transaction cost simulation (default 0.1%). Tracks portfolio value, cash, shares, trade history. Handles...

metrics.py — Performance metrics calculation: Sharpe ratio (annualized returns / volatility * sqrt(252)), max drawdown (max peak-to-trough...

ml_model.py — RandomForest classifier (100 trees, max_depth 10). Time-based train/test split (80/20) to prevent data leakage. Cross-validation...

optimizer.py — Grid search optimizer: sweeps parameter grid, runs backtest for each combination, ranks by Sharpe ratio, returns top...

live_simulator.py — Live trading simulator: iterates day-by-day from historical data start to present, executes trades based on strategy signals,...

ai_analyst.py — AI research report generator: analyzes price trends, sentiment patterns, volatility regimes, ML predictions, generates narrative...

Frontend Architecture (React 18 + Vite 5.4 + Tailwind CSS)

Implemented interactive dashboard with modular component architecture:

Dashboard.jsx — Main dashboard view with portfolio overview, key metrics cards (total return, Sharpe ratio, max drawdown, win rate), chart grid.

PriceChart.jsx — Line chart showing historical prices with Recharts. Hover tooltips display date, price, volume.

SentimentChart.jsx — Area chart visualizing sentiment scores over time (-1 to +1 range). Color-coded (green positive, red negative).

PortfolioChart.jsx — Portfolio value chart comparing strategy performance vs buy-and-hold. Dual y-axes for capital and returns percentage.

DrawdownChart.jsx — Drawdown chart showing peak-to-trough declines over time. Highlights max drawdown period.

ComparisonChart.jsx — Multi-asset comparison: overlays price charts for different tickers normalized to 100. Correlation matrix heatmap.

RollingSharpeChart.jsx — Rolling Sharpe ratio chart (30-day window) tracking risk-adjusted returns over time.

Strategy Control Panel — UI for adjusting sentiment_threshold slider (-0.5 to 0.5), volatility_percentile slider (20 to 80), initial_capital...

Asset Comparison Widgets — Add/remove tickers, correlation analysis table, performance comparison table (returns, volatility, Sharpe).

AI Insight Panels — Display comprehensive AI report with ratings visualizations (radial charts), recommendation badges (Buy/Hold/Sell with color...

Multi-Currency Conversion — CurrencyContext provides global currency state (USD, EUR, GBP, JPY, INR). Real-time exchange rate fetching (free API,...

PDF Report Export — jsPDF + html2canvas capture dashboard charts and metrics, generate professional PDF report with logo, date, ticker, all...

Makefile Automation (11 commands)

`make setup`First-time setup: creates Python venv, installs requirements.txt, npm installs frontend, copies .env.example → .env.local

`make install`Install all dependencies (backend pip install + frontend npm install)

`make dev`Run backend (uvicorn on port 8000) and frontend (Vite on port 5173) concurrently in parallel

`make dev-backend`Run backend only (uvicorn main:app --reload --port 8000)

`make dev-frontend`Run frontend only (cd frontend && npm run dev)

`make build`Build frontend for production (cd frontend && npm run build)

`make lint`Lint frontend code (cd frontend && npm run lint)

`make preview`Preview production build (cd frontend && npm run preview)

`make check`Check if backend (curl localhost:8000) and frontend (curl localhost:5173) are running

`make freeze`Freeze Python dependencies to requirements.txt (pip freeze > requirements.txt)

`make clean`Remove venv, node_modules, __pycache__, .next, dist for fresh start

GitHub Actions CI/CD (.github/workflows/ci.yml)

Runs automatically on every push to main and pull requests:

Backend Job:

- Set up Python 3.11

- Install dependencies (pip install -r requirements.txt)

- Verify all module imports (python -c "import module" for each backend file)

- Start FastAPI server in background (uvicorn main:app --port 8000 &)

- Health check (curl http://localhost:8000 returns success)

Frontend Job:

- Set up Node.js 18

- Install npm dependencies (cd frontend && npm ci)

- Run ESLint (npm run lint)

- Build for production (npm run build)

- Verify dist/ directory created

Security Best Practices

No API keys requiredyfinance and exchange rate APIs are free and keyless

No server-side secrets stored anywhere in application

.gitignore blocks: .env, .env.local, .env.*, *.pem, *.key, credentials.json, service-account*.json

CORS configured for localhost:5173 by defaultupdate main.py for production deployment

Environment variable template (.env.example) safe to commit with placeholder values

Deployment Options

Vercel (Frontend) — Connect GitHub repo, set root directory to frontend/, add VITE_API_URL environment variable pointing to backend, deploy

Google Cloud Platform (Backend) — Create Cloud Run service, deploy with uvicorn main:app --host 0.0.0.0 --port $PORT, update CORS in main.py with...

Railway / Render — Both support Python + Node.js. Point backend to root directory, frontend to frontend/ subdirectory

Strategy Configuration

sentiment_threshold (default 0.2, range -0.5 to 0.5): Threshold for buy/sell signals based on sentiment score

volatility_percentile (default 50, range 20 to 80): Filter trades by volatilityonly trade when volatility below this percentile

initial_capital (default 10,000): Starting capital for backtests in selected currency

transaction_cost (default 0.001 = 0.1%): Transaction cost as fraction of trade value

Design Decisions

Chose FastAPI over Flask/DjangoFastAPI provides automatic API documentation (Swagger/OpenAPI), async support for concurrent requests, built-in...

Used yfinance for market data instead of paid APIs (Alpha Vantage, Quandl)yfinance is free, requires no API key, provides comprehensive OHLCV data,...

Implemented VADER sentiment analysis instead of transformer models (BERT, FinBERT)VADER is rule-based (no training required), fast (real-time...

Chose RandomForest over deep learning (LSTM, Transformer)RandomForest provides feature importance analysis, handles missing data well, no GPU...

Built custom backtesting engine instead of using Backtrader/Ziplinecustom engine provides full control over transaction cost modeling, position...

Used time-based train/test split (80/20) instead of random splitprevents data leakage in time series, ensures model only learns from past data,...

Implemented grid search optimizer instead of Bayesian optimizationgrid search is simpler to implement, guarantees exhaustive coverage of parameter...

Chose Recharts over Chart.js/D3.jsRecharts is React-native (declarative components), handles responsive resizing automatically, good performance for...

Added multi-currency support with real-time exchange ratesenables global users to view metrics in their local currency (USD, EUR, GBP, JPY, INR)...

Implemented Makefile for project automationsingle commands (make dev, make build, make clean) simplify development workflow, ensure consistent setup...

Used GitHub Actions for CI/CDfree for public repos, automatic testing on push/PR prevents broken deployments, backend health check + frontend build...

Built modular backend (12 separate modules: data, sentiment, features, strategy, backtest, metrics, ml_model, optimizer, live_simulator,...

Chose Vite over Create React AppVite provides instant HMR (Hot Module Replacement), faster dev server startup, optimized production builds with...

Implemented React Context for currency state instead of Reduxsimpler state management for single global state (currency), avoids Redux boilerplate,...

Added PDF report export (jsPDF + html2canvas)enables sharing analysis results offline, professional report format with charts and metrics, useful...

Tradeoffs & Constraints

Chose free data sources (yfinance, exchange rates) over paid APIsexcellent for research and experimentation, but yfinance can have rate limits (60...

VADER sentiment analysis: Fast and rule-based but less accurate than transformer models (FinBERT, RoBERTa). Trade accuracy for speed and simplicity....

RandomForest ML model: Good interpretability and feature importance but limited to tabular features. Deep learning (LSTM, Transformer) could capture...

Custom backtesting engine: Full control and simplicity but lacks advanced features like slippage modeling, market impact, or options/futures support....

Grid search optimizer: Exhaustive but computationally expensive (n^2 parameter combinations). Bayesian optimization (Optuna, Hyperopt) would be...

Time-based train/test split (80/20): Prevents data leakage but reduces training data for ML. Cross-validation (walk-forward) would use more data but...

Recharts for visualization: Good for standard charts but limited for complex financial visualizations (candlestick, volume profile). Lightweight...

Frontend-only PDF export: Works offline but limited to visible screen area. Server-side PDF generation (Puppeteer, ReportLab) could create multi-page...

Single-ticker analysis: Simplified UI and API but can't compare multiple strategies simultaneously. Multi-strategy comparison would require more...

No real-time data: Uses historical data from yfinance (15-minute delay). Real-time trading requires WebSocket connections to exchanges (Alpaca,...

No paper trading integration: Simulates trades from historical data but can't execute live paper trades. Integration with broker APIs (Alpaca, TD...

Would improve: Add options and futures support, implement slippage and market impact modeling, integrate with broker APIs for paper trading, add...

Outcome & Impact

Production-ready quantitative trading research platform enabling strategy analysis combining sentiment analysis, machine learning, and backtesting...

Comprehensive backend with 12 RESTful API endpoints: health check, price data (yfinance), sentiment analysis (VADER), feature engineering (rolling...

Sentiment-based trading strategy: generates buy/sell signals based on VADER sentiment scores with configurable threshold (-0.5 to 0.5) and volatility...

Backtesting engine with transaction costs: simulates historical trading from strategy signals, applies configurable transaction cost (default 0.1%),...

Performance metrics calculation: Sharpe ratio (annualized risk-adjusted returns), max drawdown (largest peak-to-trough decline), annualized returns,...

RandomForest ML classifier for next-day direction prediction: uses 5 features (returns, rolling_sentiment_5d, volatility_5d, sentiment,...

Strategy optimizer with grid search: sweeps sentiment_threshold (-0.5 to 0.5 in 0.1 increments, 11 values) × volatility_percentile (20 to 80 in 10...

Live trading simulation: day-by-day execution from historical data start to present, logs every trade (date, action, price, shares, capital, reason),...

AI research reports: basic report (key metrics, trend assessment, sentiment summary, risk factors) and comprehensive report (detailed analysis with...

Interactive React 18 dashboard: portfolio charts with Recharts (price, sentiment, portfolio value, drawdown, rolling Sharpe), key metrics cards...

Multi-currency support: USD, EUR, GBP, JPY, INR conversion with real-time exchange rates (free API, no key). CurrencyContext provides global state,...

PDF report export: jsPDF + html2canvas capture dashboard with all charts and metrics, generate professional PDF with logo, date, ticker,...

Makefile automation with 11 commands: make setup (first-time install + env setup), make dev (run backend + frontend concurrently), make build...

GitHub Actions CI/CD: .github/workflows/ci.yml runs on push to main and PRs with backend job (Python 3.11 setup, install deps, verify imports, start...

Security-first approach: no API keys required (yfinance and exchange rates are free), no server-side secrets, comprehensive .gitignore (blocks .env*,...

Flexible deployment: Vercel for frontend (set root to frontend/, add VITE_API_URL env var), Google Cloud Run for backend (uvicorn on $PORT, update...

Clean project structure: backend modules at root (main.py, data.py, sentiment.py, features.py, strategy.py, backtest.py, metrics.py, ml_model.py,...

Comprehensive documentation in README: features overview, quick start, Makefile commands, project structure, manual installation, API endpoints with...

MIT license for open research useenables academic research, personal projects, and commercial applications with attribution.

Tech Stack

Backend: Python 3.11+, FastAPI (web framework), Uvicorn (ASGI server)

Data: Pandas (data manipulation), NumPy (numerical computing), yfinance (market datano API key)

Machine Learning: scikit-learn (RandomForest classifier, metrics, preprocessing)

Sentiment: VADER Sentiment (rule-based sentiment scoring)

Frontend: React 18 (UI library), Vite 5.4 (build tool, dev server)

Styling: Tailwind CSS (utility-first responsive design)

Charts: Recharts (React charting library for financial visualizations)

PDF Export: jsPDF (PDF generation), html2canvas (DOM to canvas capture)

State: React Context (global currency state management)

CI/CD: GitHub Actions (automated testing and builds)

Automation: Makefile (11 commands for dev/build/deploy workflows)

Back to Projects