File size: 4,575 Bytes
72fc0ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
"""
REST API: FastAPI routers for all suites with auth middleware.

Week 11: API Layer - Main FastAPI application with all routers.
"""

from contextlib import asynccontextmanager

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware

from quantlib_pro.api.health import router as health_router
from quantlib_pro.api.optimizations import startup_optimizations, shutdown_optimizations
from quantlib_pro.api.routers import (
    all_routers,
    macro_router,
    options_router,
    portfolio_router,
    regime_router,
    risk_router,
    volatility_router,
)

# =============================================================================
# Application Lifespan Management
# =============================================================================

@asynccontextmanager
async def lifespan(app: FastAPI):
    """Manage application startup and shutdown."""
    # Startup
    await startup_optimizations()
    yield
    # Shutdown
    await shutdown_optimizations()

# =============================================================================
# FastAPI Application
# =============================================================================

app = FastAPI(
    title="QuantLib Pro API",
    description="Enterprise quantitative finance platform with sub-500ms performance, "
                "Redis caching, async database pools, and real-time monitoring",
    version="2.1.0",
    docs_url="/docs",
    redoc_url="/redoc",
    openapi_url="/openapi.json",
    lifespan=lifespan,  # Add performance optimization lifecycle
)

# =============================================================================
# Middleware
# =============================================================================

# CORS middleware for cross-origin requests
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # In production: restrict to specific origins
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# GZip compression for responses
app.add_middleware(GZipMiddleware, minimum_size=1000)

# =============================================================================
# Register Routers
# =============================================================================

# Health check endpoints
app.include_router(health_router)

# Core API routers
app.include_router(portfolio_router, prefix="/api/v1")
app.include_router(options_router, prefix="/api/v1")
app.include_router(risk_router, prefix="/api/v1")
app.include_router(regime_router, prefix="/api/v1")
app.include_router(volatility_router, prefix="/api/v1")
app.include_router(macro_router, prefix="/api/v1")

# =============================================================================
# Root Endpoints
# =============================================================================

@app.get("/", tags=["root"])
async def root():
    """Root endpoint with API information."""
    return {
        "name": "QuantLib Pro API",
        "version": "2.1.0",
        "status": "running",
        "performance": "optimized",
        "features": [
            "Redis caching (<50ms)",
            "Async database pools",
            "Sub-500ms SLA",
            "Connection pooling"
        ],
        "docs": "/docs",
        "health": "/health",
        "metrics": "/metrics",
    }

@app.get("/metrics", tags=["monitoring"])
async def performance_metrics():
    """Get API performance metrics."""
    from quantlib_pro.api.optimizations import performance_monitor
    
    report = performance_monitor.get_performance_report()
    
    return {
        "performance_report": report,
        "sla_target": "500ms",
        "optimization_status": "active",
        "cache_layers": ["L1: In-Memory", "L2: Redis", "L3: Database"],
        "monitoring": {
            "prometheus_enabled": True,
            "grafana_dashboard": True,
            "alerts_configured": True
        }
    }


@app.get("/version", tags=["root"])
async def version():
    """Get API version information."""
    return {
        "version": "1.0.0",
        "api_version": "v1",
        "build": "production",
    }


# =============================================================================
# Exports
# =============================================================================

__all__ = [
    # FastAPI app
    "app",
    
    # Routers
    "health_router",
    "portfolio_router",
    "options_router",
    "risk_router",
    "regime_router",
    "volatility_router",
    "macro_router",
    "all_routers",
]