170 lines
3.7 KiB
Python
170 lines
3.7 KiB
Python
"""
|
|
FastAPI Application Entry Point
|
|
Stock Recommendation System Backend
|
|
"""
|
|
|
|
import asyncio
|
|
import logging
|
|
from contextlib import asynccontextmanager
|
|
from fastapi import FastAPI
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from fastapi.responses import JSONResponse
|
|
|
|
from app.config import get_settings
|
|
from app.database import init_db, health_check
|
|
from app.modules.cache_manager import cache
|
|
from app.routes import recommendations, analysis, backtest, ai_assistant, sentiment_analysis, monitoring
|
|
|
|
# Setup logging
|
|
logging.basicConfig(
|
|
level=logging.INFO,
|
|
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
|
)
|
|
logger = logging.getLogger(__name__)
|
|
|
|
settings = get_settings()
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI):
|
|
"""Lifespan context manager for app startup/shutdown"""
|
|
# Startup
|
|
logger.info("🚀 Starting Stock Recommendation System...")
|
|
|
|
# Check database connection
|
|
if not health_check():
|
|
logger.warning("⚠️ Database connection check failed (non-blocking)")
|
|
|
|
# Check Redis connection
|
|
if not cache.health_check():
|
|
logger.warning("⚠️ Redis connection check failed (non-blocking)")
|
|
|
|
# Initialize database tables
|
|
try:
|
|
init_db()
|
|
except Exception as e:
|
|
logger.warning(f"⚠️ Database initialization warning: {e}")
|
|
|
|
logger.info("✅ All services initialized")
|
|
|
|
yield
|
|
|
|
# Shutdown
|
|
logger.info("🛑 Shutting down Stock Recommendation System...")
|
|
logger.info("✅ Shutdown complete")
|
|
|
|
|
|
# Create FastAPI application
|
|
app = FastAPI(
|
|
title="AI Stock Recommendation System",
|
|
description="Real-time stock recommendations powered by AI",
|
|
version="1.0.0",
|
|
lifespan=lifespan
|
|
)
|
|
|
|
|
|
# CORS Middleware Configuration
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=settings.cors_origins_list,
|
|
allow_credentials=True,
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
|
|
|
|
# Include routers
|
|
app.include_router(
|
|
recommendations.router,
|
|
prefix="/api",
|
|
tags=["Recommendations"]
|
|
)
|
|
|
|
app.include_router(
|
|
analysis.router,
|
|
prefix="/api",
|
|
tags=["Analysis"]
|
|
)
|
|
|
|
app.include_router(
|
|
backtest.router,
|
|
prefix="/api",
|
|
tags=["Backtest"]
|
|
)
|
|
|
|
app.include_router(
|
|
ai_assistant.router,
|
|
tags=["AI Assistant"]
|
|
)
|
|
|
|
app.include_router(
|
|
sentiment_analysis.router,
|
|
tags=["Sentiment Analysis"]
|
|
)
|
|
|
|
app.include_router(
|
|
monitoring.router,
|
|
tags=["Monitoring & Optimization"]
|
|
)
|
|
|
|
|
|
# Root endpoint
|
|
@app.get("/")
|
|
async def root():
|
|
"""Root endpoint"""
|
|
return {
|
|
"service": "AI Stock Recommendation System",
|
|
"version": "1.0.0",
|
|
"status": "operational",
|
|
"docs": "/docs",
|
|
"api_base": "/api"
|
|
}
|
|
|
|
|
|
# Health check endpoint
|
|
@app.get("/health")
|
|
async def health():
|
|
"""Health check endpoint"""
|
|
return {
|
|
"status": "healthy",
|
|
"database": health_check(),
|
|
"cache": cache.health_check()
|
|
}
|
|
|
|
|
|
# Error handlers
|
|
@app.exception_handler(Exception)
|
|
async def general_exception_handler(request, exc):
|
|
"""Global exception handler"""
|
|
logger.error(f"Unhandled exception: {exc}", exc_info=True)
|
|
return JSONResponse(
|
|
status_code=500,
|
|
content={"detail": "Internal server error"}
|
|
)
|
|
|
|
|
|
# Startup event
|
|
@app.on_event("startup")
|
|
async def startup_event():
|
|
"""Startup event handler"""
|
|
logger.info("📊 Stock Recommendation System started")
|
|
|
|
|
|
# Shutdown event
|
|
@app.on_event("shutdown")
|
|
async def shutdown_event():
|
|
"""Shutdown event handler"""
|
|
logger.info("🛑 Stock Recommendation System stopped")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
import uvicorn
|
|
|
|
uvicorn.run(
|
|
app,
|
|
host=settings.api_host,
|
|
port=settings.api_port,
|
|
reload=settings.debug,
|
|
log_level=settings.log_level.lower()
|
|
)
|