A production-grade dashboard backend for real-time portfolio management and analytics, seamlessly integrated into the existing QuantResearch project.
β
Real-time Portfolio Analytics - Track portfolio value, P/L, and returns with live market data
β
Risk Metrics Engine - Sharpe ratio, max drawdown, volatility, beta, alpha calculations
β
Live Market Data Integration - Finnhub API with intelligent caching (1min quotes, 24hr profiles)
β
Position Management - Track open positions with unrealized P/L and sector allocation
β
Trade History - Complete trade log with realized P/L tracking
β
Company Intelligence - Logos, sector data, market cap, and company profiles
β
JWT Authentication - Secure user authentication integrated with existing auth system
β
Performance Optimizations - Async/await, connection pooling, batch operations, smart caching
βββββββββββββββββββ ββββββββββββββββββββ βββββββββββββββββββ
β React Frontend β βββ> β FastAPI Backend β βββ> β PostgreSQL DB β
β (Port 3004) β β (Port 8000) β β (Aiven) β
βββββββββββββββββββ ββββββββββββββββββββ βββββββββββββββββββ
β β
β β
βΌ βΌ
ββββββββββββ βββββββββββββββββββ
β Redis β β Finnhub API β
β (Valkey) β β (Live Prices) β
ββββββββββββ βββββββββββββββββββ
- FastAPI - Async Python web framework
- SQLAlchemy 2.0 - Async ORM with PostgreSQL
- Pydantic - Data validation and schemas
- JWT - Token-based authentication
- Finnhub.io - Real-time stock quotes and company data
- PostgreSQL 17.7 - Primary database (Aiven cloud)
- Redis/Valkey 8.1.4 - Caching and pub/sub
# One command setup (creates tables + seeds data)
python scripts/setup_dashboard.pyThis creates:
- β All database tables (users, portfolios, positions, trades, stock_quotes, company_profiles)
- β
Demo user account (
demo/demo123) - β 5 sample stock positions (AAPL, MSFT, GOOGL, TSLA, NVDA)
- β Trade history with P/L examples
cd src/quant_research_starter
uvicorn api.main:app --reload --host 0.0.0.0 --port 8000Backend available at:
- API: http://localhost:8000
- Swagger UI: http://localhost:8000/docs
- Health Check: http://localhost:8000/api/health
- Open http://localhost:8000/docs
- Click "Authorize" button (top right)
- Enter credentials:
- Username:
demo - Password:
demo123
- Username:
- Click "Authorize" β "Close"
- Test any endpoint (they're now authenticated)
# 1. Login to get JWT token
$loginResponse = Invoke-RestMethod -Uri "http://localhost:8000/api/auth/token" `
-Method POST `
-ContentType "application/x-www-form-urlencoded" `
-Body "username=demo&password=demo123"
$token = $loginResponse.access_token
# 2. Get portfolio overview
Invoke-RestMethod -Uri "http://localhost:8000/api/dashboard/overview" `
-Headers @{ Authorization = "Bearer $token" } | ConvertTo-Json -Depth 10
# 3. Get all positions with live prices
Invoke-RestMethod -Uri "http://localhost:8000/api/dashboard/positions" `
-Headers @{ Authorization = "Bearer $token" } | ConvertTo-Json -Depth 10
# 4. Get trade history
Invoke-RestMethod -Uri "http://localhost:8000/api/dashboard/trades?limit=10" `
-Headers @{ Authorization = "Bearer $token" } | ConvertTo-Json -Depth 10
# 5. Get live quote for AAPL
Invoke-RestMethod -Uri "http://localhost:8000/api/dashboard/quote/AAPL" `
-Headers @{ Authorization = "Bearer $token" } | ConvertTo-Json -Depth 10All endpoints require JWT authentication via Authorization: Bearer <token> header.
GET /api/dashboard/overviewResponse:
{
"status": "success",
"data": {
"total_value": 142850.00,
"cash": 57937.50,
"invested": 84912.50,
"market_value": 95107.20,
"unrealized_pnl": 10194.70,
"total_return_percent": 12.00,
"sharpe_ratio": 1.85,
"max_drawdown": 8.45,
"volatility": 18.32,
"win_rate": 100.00
}
}GET /api/dashboard/positionsResponse:
{
"status": "success",
"data": [
{
"symbol": "AAPL",
"company_name": "Apple Inc.",
"quantity": 50,
"average_cost": 175.50,
"current_price": 196.56,
"market_value": 9828.00,
"unrealized_pnl": 1053.00,
"unrealized_pnl_pct": 12.00,
"logo": "https://static2.finnhub.io/file/publicdatany/finnhubimage/stock_logo/AAPL.png",
"sector": "Technology"
}
]
}GET /api/dashboard/trades?limit=50Response:
{
"status": "success",
"data": [
{
"id": 1,
"symbol": "AMZN",
"trade_type": "sell",
"quantity": 10,
"price": 158.50,
"commission": 1.50,
"trade_date": "2024-01-10T00:00:00",
"realized_pnl": 200.00
}
]
}GET /api/dashboard/quote/{symbol}Response:
{
"status": "success",
"data": {
"symbol": "AAPL",
"current_price": 196.56,
"change": 2.34,
"percent_change": 1.20,
"high": 197.80,
"low": 195.20,
"open": 195.50,
"previous_close": 194.22,
"updated_at": "2024-01-15T10:30:00"
}
}GET /api/dashboard/profile/{symbol}Response:
{
"status": "success",
"data": {
"symbol": "MSFT",
"name": "Microsoft Corporation",
"country": "US",
"currency": "USD",
"exchange": "NASDAQ",
"ipo": "1986-03-13",
"market_cap": 2800000000000,
"industry": "Technology",
"logo": "https://static2.finnhub.io/file/publicdatany/finnhubimage/stock_logo/MSFT.png",
"website": "https://www.microsoft.com"
}
}GET /api/dashboard/performance?days=30Response:
{
"status": "success",
"data": [
{
"date": "2024-01-15",
"total_value": 142850.00,
"return_pct": 12.00,
"sharpe_ratio": 1.85
}
]
}Portfolio - Portfolio snapshots with performance metrics
total_value,cash,investedsharpe_ratio,max_drawdown,volatility- Tracks performance over time
Position - Open stock positions
symbol,quantity,average_costcurrent_price,unrealized_pnl- Links to
stock_quotesandcompany_profiles
Trade - Complete trade history
symbol,trade_type(buy/sell),quantity,pricerealized_pnl,commission,trade_date
StockQuote - Cached live market data
symbol,current_price,change,percent_changeupdated_atfor cache expiration (60 second TTL)
CompanyProfile - Company metadata
name,logo,sector,industry,market_capupdated_atfor cache expiration (24 hour TTL)
users (1) ββββ (many) portfolios
users (1) ββββ (many) positions
users (1) ββββ (many) trades
positions (many) ββββ (1) stock_quotes (via symbol)
positions (many) ββββ (1) company_profiles (via symbol)
src/quant_research_starter/api/services/__init__.pysrc/quant_research_starter/api/services/finnhub.py- Finnhub API clientsrc/quant_research_starter/api/services/dashboard.py- Business logic
src/quant_research_starter/api/routers/dashboard.py- 6 API endpoints
src/quant_research_starter/api/models.py- Added 5 new modelssrc/quant_research_starter/api/main.py- Imported dashboard router
scripts/setup_dashboard.py- Complete setup (tables + data)scripts/seed_dashboard.py- Data seeding onlyscripts/test_dashboard.py- Verification testsscripts/create_tables.py- Table creation only
DASHBOARD_WORKING.md- Quick start guide (this file)TECHNICAL_DOCS.md- Architecture and implementation details
β
Password Hashing - bcrypt with automatic salt generation
β
JWT Tokens - Secure authentication with expiration
β
SQL Injection Protection - SQLAlchemy ORM (no raw SQL)
β
CORS Configuration - Controlled cross-origin access
β
SSL/TLS - Encrypted database and Redis connections
β
Input Validation - Pydantic schemas for all requests
β
Async/Await - Non-blocking I/O throughout
β
Connection Pooling - SQLAlchemy async pools
β
Smart Caching - Database-backed cache with TTL
β
Batch Operations - Multiple API calls in single batch
β
Rate Limiting - Finnhub API throttling (30 req/sec)
β
Database Indexes - Optimized queries
Stock Quotes:
- Cache duration: 60 seconds
- Reason: Real-time trading data needs to be fresh
- Storage:
stock_quotestable
Company Profiles:
- Cache duration: 24 hours
- Reason: Static data rarely changes
- Storage:
company_profilestable
# Run comprehensive tests
python scripts/test_dashboard.py- Open http://localhost:8000/docs
- Authorize with demo/demo123
- Test each endpoint interactively
- View request/response schemas
- Username:
demo - Password:
demo123 - ID: 1
| Symbol | Shares | Avg Cost | Current Price* | Unrealized P/L* |
|---|---|---|---|---|
| AAPL | 50 | $175.50 | Live | Live |
| MSFT | 30 | $380.25 | Live | Live |
| GOOGL | 25 | $142.30 | Live | Live |
| TSLA | 20 | $245.80 | Live | Live |
| NVDA | 15 | $495.60 | Live | Live |
*Live prices fetched from Finnhub API
- AMZN: Bought 10 @ $144.00, Sold 10 @ $158.50 β Profit: $200 (+13.79%)
- Check
.envfile has correctDATABASE_URL - Verify firewall allows connection to Aiven
- Confirm SSL mode is set to
require
- Verify
FINNHUB_API_KEYis set in.env - Check you haven't exceeded rate limit (60 calls/min free tier)
- Visit https://finnhub.io to check API status
- Get new JWT token (tokens expire after 30 minutes)
- Verify username/password are correct
- Check
JWT_SECRETis set in.env
- Check Finnhub API key is valid
- Verify internet connectivity
- Check
stock_quotestable has recent data
- Swagger UI: http://localhost:8000/docs - Interactive API testing
- ReDoc: http://localhost:8000/redoc - Beautiful API documentation
- Health Check: http://localhost:8000/api/health - Backend status
- Technical Docs: TECHNICAL_DOCS.md - Architecture details
- Main README: README.md - Full project overview
- Build React components to consume dashboard API
- Display portfolio cards with live data
- Create position table with real-time updates
- Add trade history timeline
- Implement charts for performance visualization
- WebSocket real-time price streaming
- Trade execution simulation
- Alert/notification system
- Watchlist functionality
- Portfolio optimization
- More factor models
- Cryptocurrency support
This dashboard backend is part of the QuantResearch open source project. Contributions welcome!
- Fork the repository
- Create feature branch (
git checkout -b feature/AmazingFeature) - Commit changes (
git commit -m 'Add AmazingFeature') - Push to branch (
git push origin feature/AmazingFeature) - Open Pull Request
Built with β€οΈ using FastAPI, SQLAlchemy, and modern async Python