refactor(analytics): initialize optional capabilities lazily (CL35)
This commit is contained in:
parent
b4589d5af1
commit
7ae6ac21c4
9 changed files with 701 additions and 387 deletions
|
|
@ -1,79 +1,63 @@
|
|||
from fastapi import FastAPI, HTTPException
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from contextlib import asynccontextmanager
|
||||
import logging
|
||||
from typing import Dict, Any
|
||||
|
||||
from .endpoints import optimization, analytics, models
|
||||
from ..analytics.performance import PerformanceAnalyzer
|
||||
from ..analytics.regime import RegimeDetector
|
||||
from ..optimization.portfolio_optimizer import PortfolioOptimizer
|
||||
|
||||
# Configure logging
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Global instances
|
||||
performance_analyzer = PerformanceAnalyzer()
|
||||
regime_detector = RegimeDetector()
|
||||
portfolio_optimizer = PortfolioOptimizer()
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
# Startup
|
||||
logger.info("Starting Trading Analytics Service...")
|
||||
# Initialize connections, load models, etc.
|
||||
yield
|
||||
# Shutdown
|
||||
logger.info("Shutting down Trading Analytics Service...")
|
||||
|
||||
# Create FastAPI app
|
||||
app = FastAPI(
|
||||
title="Trading Analytics Service",
|
||||
description="Complex analytics, optimization, and ML inference for trading",
|
||||
version="0.1.0",
|
||||
lifespan=lifespan
|
||||
)
|
||||
|
||||
# Configure CORS
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"], # Configure appropriately for production
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# Include routers
|
||||
app.include_router(optimization.router, prefix="/optimize", tags=["optimization"])
|
||||
app.include_router(analytics.router, prefix="/analytics", tags=["analytics"])
|
||||
app.include_router(models.router, prefix="/models", tags=["models"])
|
||||
|
||||
@app.get("/")
|
||||
async def root():
|
||||
return {
|
||||
"service": "Trading Analytics",
|
||||
"status": "operational",
|
||||
"version": "0.1.0"
|
||||
}
|
||||
|
||||
@app.get("/health")
|
||||
async def health_check():
|
||||
return {
|
||||
"status": "healthy",
|
||||
"components": {
|
||||
"performance_analyzer": "operational",
|
||||
"regime_detector": "operational",
|
||||
"portfolio_optimizer": "operational"
|
||||
}
|
||||
}
|
||||
|
||||
# Dependency injection
|
||||
def get_performance_analyzer():
|
||||
return performance_analyzer
|
||||
|
||||
def get_regime_detector():
|
||||
return regime_detector
|
||||
|
||||
def get_portfolio_optimizer():
|
||||
return portfolio_optimizer
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from contextlib import asynccontextmanager
|
||||
import logging
|
||||
|
||||
from .endpoints import optimization, analytics, models
|
||||
from . import capabilities
|
||||
|
||||
# Configure logging
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
# Startup
|
||||
logger.info("Starting Trading Analytics Service...")
|
||||
# Initialize connections, load models, etc.
|
||||
yield
|
||||
# Shutdown
|
||||
logger.info("Shutting down Trading Analytics Service...")
|
||||
|
||||
# Create FastAPI app
|
||||
app = FastAPI(
|
||||
title="Trading Analytics Service",
|
||||
description="Complex analytics, optimization, and ML inference for trading",
|
||||
version="0.1.0",
|
||||
lifespan=lifespan
|
||||
)
|
||||
|
||||
# Configure CORS
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"], # Configure appropriately for production
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# Include routers
|
||||
app.include_router(optimization.router, prefix="/optimize", tags=["optimization"])
|
||||
app.include_router(analytics.router, prefix="/analytics", tags=["analytics"])
|
||||
app.include_router(models.router, prefix="/models", tags=["models"])
|
||||
|
||||
@app.get("/")
|
||||
async def root():
|
||||
return {
|
||||
"service": "Trading Analytics",
|
||||
"status": "available",
|
||||
"version": "0.1.0"
|
||||
}
|
||||
|
||||
@app.get("/health")
|
||||
async def health_check():
|
||||
return {
|
||||
"status": "degraded",
|
||||
"components": {
|
||||
"performance_analyzer": {"status": "unavailable", "reason": "observed_data_not_integrated"},
|
||||
"regime_detector": {"status": "unavailable", "reason": "observed_data_not_integrated"},
|
||||
"portfolio_optimizer": capabilities.portfolio_optimizer.status(),
|
||||
"model_runtime": capabilities.model_runtime.status(),
|
||||
"model_upload": capabilities.model_upload.status(),
|
||||
}
|
||||
}
|
||||
|
|
|
|||
88
apps/stock/analytics/src/api/capabilities.py
Normal file
88
apps/stock/analytics/src/api/capabilities.py
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
"""Optional runtimes are loaded on first use, independently of app/router imports."""
|
||||
from dataclasses import dataclass
|
||||
import logging
|
||||
from threading import Lock
|
||||
from typing import Any, Callable
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class LazyCapability:
|
||||
def __init__(self, name: str, load: Callable[[], Any]):
|
||||
self.name = name
|
||||
self.load = load
|
||||
self._lock = Lock()
|
||||
self._value = None
|
||||
self._state = "uninitialized"
|
||||
self._failure = None
|
||||
|
||||
def get(self):
|
||||
with self._lock:
|
||||
if self._state == "uninitialized":
|
||||
try:
|
||||
self._value = self.load()
|
||||
self._state = "ready"
|
||||
except Exception as error:
|
||||
logger.exception("Optional capability %s could not initialize", self.name)
|
||||
self._state = "unavailable"
|
||||
self._failure = {
|
||||
"code": "analytics_capability_unavailable",
|
||||
"capability": self.name,
|
||||
"reason": "missing_dependency" if isinstance(error, ImportError) else "initialization_failed",
|
||||
"message": f"Optional analytics capability '{self.name}' is unavailable",
|
||||
}
|
||||
if isinstance(error, ImportError) and error.name:
|
||||
self._failure["dependency"] = error.name
|
||||
if self._failure is not None:
|
||||
raise HTTPException(status_code=503, detail=dict(self._failure))
|
||||
return self._value
|
||||
|
||||
def status(self):
|
||||
# Health observes state; it must not load scientific runtimes as a side effect.
|
||||
with self._lock:
|
||||
return {"status": self._state, **(self._failure or {})}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OptimizationRuntime:
|
||||
numpy: Any
|
||||
optimizer: Any
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ModelRuntime:
|
||||
numpy: Any
|
||||
onnx: Any
|
||||
|
||||
|
||||
def _load_optimizer():
|
||||
import numpy
|
||||
from ..optimization.portfolio_optimizer import PortfolioOptimizer
|
||||
return OptimizationRuntime(numpy, PortfolioOptimizer())
|
||||
|
||||
|
||||
def _load_models():
|
||||
import numpy
|
||||
import onnxruntime
|
||||
return ModelRuntime(numpy, onnxruntime)
|
||||
|
||||
|
||||
def _load_multipart():
|
||||
# FastAPI's File(...) would demand this package while registering the route.
|
||||
from multipart.multipart import parse_options_header
|
||||
return parse_options_header
|
||||
|
||||
|
||||
portfolio_optimizer = LazyCapability("portfolio_optimizer", _load_optimizer)
|
||||
model_runtime = LazyCapability("model_runtime", _load_models)
|
||||
model_upload = LazyCapability("model_upload", _load_multipart)
|
||||
|
||||
|
||||
def get_optimization_runtime():
|
||||
return portfolio_optimizer.get()
|
||||
|
||||
|
||||
def get_model_runtime():
|
||||
return model_runtime.get()
|
||||
|
|
@ -1,182 +1,211 @@
|
|||
from fastapi import APIRouter, HTTPException, UploadFile, File
|
||||
from pydantic import BaseModel
|
||||
from typing import Dict, Any, List, Optional
|
||||
import numpy as np
|
||||
import onnxruntime as ort
|
||||
import json
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
# In-memory model storage (in production, use proper model registry)
|
||||
loaded_models = {}
|
||||
|
||||
class PredictionRequest(BaseModel):
|
||||
model_id: str
|
||||
features: Dict[str, float]
|
||||
|
||||
class PredictionResponse(BaseModel):
|
||||
model_id: str
|
||||
prediction: float
|
||||
probability: Optional[Dict[str, float]] = None
|
||||
metadata: Optional[Dict[str, Any]] = None
|
||||
|
||||
class ModelInfo(BaseModel):
|
||||
model_id: str
|
||||
name: str
|
||||
version: str
|
||||
type: str
|
||||
input_features: List[str]
|
||||
output_shape: List[int]
|
||||
metadata: Dict[str, Any]
|
||||
|
||||
@router.post("/predict", response_model=PredictionResponse)
|
||||
async def predict(request: PredictionRequest):
|
||||
"""
|
||||
Run inference on a loaded model
|
||||
"""
|
||||
try:
|
||||
if request.model_id not in loaded_models:
|
||||
raise HTTPException(status_code=404, detail=f"Model {request.model_id} not found")
|
||||
|
||||
model_info = loaded_models[request.model_id]
|
||||
session = model_info['session']
|
||||
|
||||
# Prepare input
|
||||
input_features = model_info['input_features']
|
||||
input_array = np.array([[request.features.get(f, 0.0) for f in input_features]], dtype=np.float32)
|
||||
|
||||
# Run inference
|
||||
input_name = session.get_inputs()[0].name
|
||||
output = session.run(None, {input_name: input_array})
|
||||
|
||||
# Process output
|
||||
prediction = float(output[0][0])
|
||||
|
||||
# For classification models, get probabilities
|
||||
probability = None
|
||||
if model_info['type'] == 'classification' and len(output[0][0]) > 1:
|
||||
probability = {
|
||||
f"class_{i}": float(p)
|
||||
for i, p in enumerate(output[0][0])
|
||||
}
|
||||
|
||||
return PredictionResponse(
|
||||
model_id=request.model_id,
|
||||
prediction=prediction,
|
||||
probability=probability,
|
||||
metadata={
|
||||
"model_version": model_info['version'],
|
||||
"timestamp": np.datetime64('now').tolist()
|
||||
}
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Prediction failed: {str(e)}")
|
||||
raise HTTPException(status_code=500, detail=f"Prediction failed: {str(e)}")
|
||||
|
||||
@router.post("/load")
|
||||
async def load_model(
|
||||
model_id: str,
|
||||
model_file: UploadFile = File(...),
|
||||
metadata: str = None
|
||||
):
|
||||
"""
|
||||
Load an ONNX model for inference
|
||||
"""
|
||||
try:
|
||||
# Read model file
|
||||
content = await model_file.read()
|
||||
|
||||
# Create ONNX session
|
||||
session = ort.InferenceSession(content)
|
||||
|
||||
# Parse metadata
|
||||
model_metadata = json.loads(metadata) if metadata else {}
|
||||
|
||||
# Extract model info
|
||||
input_features = [inp.name for inp in session.get_inputs()]
|
||||
output_shape = [out.shape for out in session.get_outputs()]
|
||||
|
||||
# Store model
|
||||
loaded_models[model_id] = {
|
||||
'session': session,
|
||||
'input_features': model_metadata.get('feature_names', input_features),
|
||||
'type': model_metadata.get('model_type', 'regression'),
|
||||
'version': model_metadata.get('version', '1.0'),
|
||||
'metadata': model_metadata
|
||||
}
|
||||
|
||||
return {
|
||||
"message": f"Model {model_id} loaded successfully",
|
||||
"input_features": input_features,
|
||||
"output_shape": output_shape
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to load model: {str(e)}")
|
||||
raise HTTPException(status_code=500, detail=f"Failed to load model: {str(e)}")
|
||||
|
||||
@router.get("/list", response_model=List[ModelInfo])
|
||||
async def list_models():
|
||||
"""
|
||||
List all loaded models
|
||||
"""
|
||||
models = []
|
||||
|
||||
for model_id, info in loaded_models.items():
|
||||
session = info['session']
|
||||
models.append(ModelInfo(
|
||||
model_id=model_id,
|
||||
name=info['metadata'].get('name', model_id),
|
||||
version=info['version'],
|
||||
type=info['type'],
|
||||
input_features=info['input_features'],
|
||||
output_shape=[out.shape for out in session.get_outputs()],
|
||||
metadata=info['metadata']
|
||||
))
|
||||
|
||||
return models
|
||||
|
||||
@router.delete("/{model_id}")
|
||||
async def unload_model(model_id: str):
|
||||
"""
|
||||
Unload a model from memory
|
||||
"""
|
||||
if model_id not in loaded_models:
|
||||
raise HTTPException(status_code=404, detail=f"Model {model_id} not found")
|
||||
|
||||
del loaded_models[model_id]
|
||||
|
||||
return {"message": f"Model {model_id} unloaded successfully"}
|
||||
|
||||
@router.post("/batch_predict")
|
||||
async def batch_predict(
|
||||
model_id: str,
|
||||
features: List[Dict[str, float]]
|
||||
):
|
||||
"""
|
||||
Run batch predictions
|
||||
"""
|
||||
try:
|
||||
if model_id not in loaded_models:
|
||||
raise HTTPException(status_code=404, detail=f"Model {model_id} not found")
|
||||
|
||||
predictions = []
|
||||
|
||||
for feature_set in features:
|
||||
request = PredictionRequest(model_id=model_id, features=feature_set)
|
||||
result = await predict(request)
|
||||
predictions.append(result.dict())
|
||||
|
||||
return {
|
||||
"model_id": model_id,
|
||||
"predictions": predictions,
|
||||
"count": len(predictions)
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Batch prediction failed: {str(e)}")
|
||||
raise HTTPException(status_code=500, detail=f"Batch prediction failed: {str(e)}")
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from starlette.datastructures import UploadFile
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
from pydantic import BaseModel
|
||||
from typing import Dict, Any, List, Optional, Union
|
||||
import json
|
||||
import logging
|
||||
|
||||
from ..capabilities import get_model_runtime, model_upload
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
# In-memory model storage (in production, use proper model registry)
|
||||
loaded_models = {}
|
||||
|
||||
class PredictionRequest(BaseModel):
|
||||
model_id: str
|
||||
features: Dict[str, float]
|
||||
|
||||
class PredictionResponse(BaseModel):
|
||||
model_id: str
|
||||
prediction: float
|
||||
probability: Optional[Dict[str, float]] = None
|
||||
metadata: Optional[Dict[str, Any]] = None
|
||||
|
||||
class ModelInfo(BaseModel):
|
||||
model_id: str
|
||||
name: str
|
||||
version: str
|
||||
type: str
|
||||
input_features: List[str]
|
||||
# One shape per ONNX output; dimensions may be symbolic or unspecified.
|
||||
output_shape: List[List[Union[int, str, None]]]
|
||||
metadata: Dict[str, Any]
|
||||
|
||||
@router.post("/predict", response_model=PredictionResponse)
|
||||
async def predict(request: PredictionRequest):
|
||||
"""
|
||||
Run inference on a loaded model
|
||||
"""
|
||||
try:
|
||||
if request.model_id not in loaded_models:
|
||||
raise HTTPException(status_code=404, detail=f"Model {request.model_id} not found")
|
||||
np = get_model_runtime().numpy
|
||||
|
||||
model_info = loaded_models[request.model_id]
|
||||
session = model_info['session']
|
||||
|
||||
# Prepare input
|
||||
input_features = model_info['input_features']
|
||||
input_array = np.array([[request.features.get(f, 0.0) for f in input_features]], dtype=np.float32)
|
||||
|
||||
# Run inference
|
||||
input_name = session.get_inputs()[0].name
|
||||
output = session.run(None, {input_name: input_array})
|
||||
|
||||
# Process output
|
||||
prediction = float(output[0][0])
|
||||
|
||||
# For classification models, get probabilities
|
||||
probability = None
|
||||
if model_info['type'] == 'classification' and len(output[0][0]) > 1:
|
||||
probability = {
|
||||
f"class_{i}": float(p)
|
||||
for i, p in enumerate(output[0][0])
|
||||
}
|
||||
|
||||
return PredictionResponse(
|
||||
model_id=request.model_id,
|
||||
prediction=prediction,
|
||||
probability=probability,
|
||||
metadata={
|
||||
"model_version": model_info['version'],
|
||||
"timestamp": np.datetime64('now').tolist()
|
||||
}
|
||||
)
|
||||
|
||||
except StarletteHTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Prediction failed: {str(e)}")
|
||||
raise HTTPException(status_code=500, detail=f"Prediction failed: {str(e)}")
|
||||
|
||||
@router.post("/load", openapi_extra={
|
||||
"requestBody": {
|
||||
"required": True,
|
||||
"content": {"multipart/form-data": {"schema": {
|
||||
"type": "object",
|
||||
"required": ["model_file"],
|
||||
"properties": {"model_file": {"type": "string", "format": "binary"}},
|
||||
}}},
|
||||
},
|
||||
})
|
||||
async def load_model(
|
||||
model_id: str,
|
||||
request: Request,
|
||||
metadata: str = None
|
||||
):
|
||||
"""
|
||||
Load an ONNX model for inference
|
||||
"""
|
||||
try:
|
||||
runtime = get_model_runtime()
|
||||
model_upload.get()
|
||||
# Parse only on upload, so an absent multipart package cannot block app startup.
|
||||
async with request.form() as form:
|
||||
model_file = form.get('model_file')
|
||||
if not isinstance(model_file, UploadFile):
|
||||
raise HTTPException(status_code=422, detail=[{
|
||||
"loc": ["body", "model_file"],
|
||||
"msg": "A model_file upload is required",
|
||||
"type": "value_error.missing",
|
||||
}])
|
||||
content = await model_file.read()
|
||||
|
||||
# Create ONNX session
|
||||
session = runtime.onnx.InferenceSession(content)
|
||||
|
||||
# Parse metadata
|
||||
model_metadata = json.loads(metadata) if metadata else {}
|
||||
|
||||
# Extract model info
|
||||
input_features = [inp.name for inp in session.get_inputs()]
|
||||
output_shape = [out.shape for out in session.get_outputs()]
|
||||
|
||||
# Store model
|
||||
loaded_models[model_id] = {
|
||||
'session': session,
|
||||
'input_features': model_metadata.get('feature_names', input_features),
|
||||
'type': model_metadata.get('model_type', 'regression'),
|
||||
'version': model_metadata.get('version', '1.0'),
|
||||
'metadata': model_metadata
|
||||
}
|
||||
|
||||
return {
|
||||
"message": f"Model {model_id} loaded successfully",
|
||||
"input_features": input_features,
|
||||
"output_shape": output_shape
|
||||
}
|
||||
|
||||
except StarletteHTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to load model: {str(e)}")
|
||||
raise HTTPException(status_code=500, detail=f"Failed to load model: {str(e)}")
|
||||
|
||||
@router.get("/list", response_model=List[ModelInfo])
|
||||
async def list_models():
|
||||
"""
|
||||
List all loaded models
|
||||
"""
|
||||
models = []
|
||||
|
||||
for model_id, info in loaded_models.items():
|
||||
session = info['session']
|
||||
models.append(ModelInfo(
|
||||
model_id=model_id,
|
||||
name=info['metadata'].get('name', model_id),
|
||||
version=info['version'],
|
||||
type=info['type'],
|
||||
input_features=info['input_features'],
|
||||
output_shape=[out.shape for out in session.get_outputs()],
|
||||
metadata=info['metadata']
|
||||
))
|
||||
|
||||
return models
|
||||
|
||||
@router.delete("/{model_id}")
|
||||
async def unload_model(model_id: str):
|
||||
"""
|
||||
Unload a model from memory
|
||||
"""
|
||||
if model_id not in loaded_models:
|
||||
raise HTTPException(status_code=404, detail=f"Model {model_id} not found")
|
||||
|
||||
del loaded_models[model_id]
|
||||
|
||||
return {"message": f"Model {model_id} unloaded successfully"}
|
||||
|
||||
@router.post("/batch_predict")
|
||||
async def batch_predict(
|
||||
model_id: str,
|
||||
features: List[Dict[str, float]]
|
||||
):
|
||||
"""
|
||||
Run batch predictions
|
||||
"""
|
||||
try:
|
||||
if model_id not in loaded_models:
|
||||
raise HTTPException(status_code=404, detail=f"Model {model_id} not found")
|
||||
|
||||
predictions = []
|
||||
|
||||
for feature_set in features:
|
||||
request = PredictionRequest(model_id=model_id, features=feature_set)
|
||||
result = await predict(request)
|
||||
predictions.append(result.dict())
|
||||
|
||||
return {
|
||||
"model_id": model_id,
|
||||
"predictions": predictions,
|
||||
"count": len(predictions)
|
||||
}
|
||||
|
||||
except StarletteHTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Batch prediction failed: {str(e)}")
|
||||
raise HTTPException(status_code=500, detail=f"Batch prediction failed: {str(e)}")
|
||||
|
|
|
|||
|
|
@ -1,120 +1,120 @@
|
|||
from fastapi import APIRouter, HTTPException, Depends
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import List, Optional, Dict
|
||||
import numpy as np
|
||||
|
||||
from ...optimization.portfolio_optimizer import PortfolioOptimizer
|
||||
from ..app import get_portfolio_optimizer
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
class OptimizationConstraints(BaseModel):
|
||||
min_weight: Optional[float] = Field(0.0, ge=0.0, le=1.0)
|
||||
max_weight: Optional[float] = Field(1.0, ge=0.0, le=1.0)
|
||||
target_return: Optional[float] = None
|
||||
max_risk: Optional[float] = None
|
||||
|
||||
class PortfolioOptimizationRequest(BaseModel):
|
||||
symbols: List[str]
|
||||
returns: List[List[float]]
|
||||
constraints: Optional[OptimizationConstraints] = None
|
||||
method: str = Field("mean_variance", pattern="^(mean_variance|min_variance|max_sharpe|risk_parity|black_litterman)$")
|
||||
|
||||
class PortfolioWeights(BaseModel):
|
||||
symbols: List[str]
|
||||
weights: List[float]
|
||||
expected_return: float
|
||||
expected_risk: float
|
||||
sharpe_ratio: float
|
||||
|
||||
@router.post("/portfolio", response_model=PortfolioWeights)
|
||||
async def optimize_portfolio(
|
||||
request: PortfolioOptimizationRequest,
|
||||
optimizer: PortfolioOptimizer = Depends(get_portfolio_optimizer)
|
||||
):
|
||||
"""
|
||||
Optimize portfolio weights using various methods
|
||||
"""
|
||||
try:
|
||||
# Convert returns to numpy array
|
||||
returns_array = np.array(request.returns)
|
||||
|
||||
# Validate dimensions
|
||||
if len(request.symbols) != returns_array.shape[1]:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Number of symbols must match number of return columns"
|
||||
)
|
||||
|
||||
# Run optimization
|
||||
result = optimizer.optimize(
|
||||
returns=returns_array,
|
||||
method=request.method,
|
||||
constraints=request.constraints.dict() if request.constraints else None
|
||||
)
|
||||
|
||||
return PortfolioWeights(
|
||||
symbols=request.symbols,
|
||||
weights=result['weights'].tolist(),
|
||||
expected_return=float(result['expected_return']),
|
||||
expected_risk=float(result['expected_risk']),
|
||||
sharpe_ratio=float(result['sharpe_ratio'])
|
||||
)
|
||||
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"Optimization failed: {str(e)}")
|
||||
|
||||
@router.post("/efficient_frontier")
|
||||
async def calculate_efficient_frontier(
|
||||
request: PortfolioOptimizationRequest,
|
||||
num_portfolios: int = 100,
|
||||
optimizer: PortfolioOptimizer = Depends(get_portfolio_optimizer)
|
||||
):
|
||||
"""
|
||||
Calculate the efficient frontier for a set of assets
|
||||
"""
|
||||
try:
|
||||
returns_array = np.array(request.returns)
|
||||
|
||||
frontier = optimizer.calculate_efficient_frontier(
|
||||
returns=returns_array,
|
||||
num_portfolios=num_portfolios
|
||||
)
|
||||
|
||||
return {
|
||||
"symbols": request.symbols,
|
||||
"frontier": frontier
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"Failed to calculate efficient frontier: {str(e)}")
|
||||
|
||||
@router.post("/rebalance")
|
||||
async def suggest_rebalance(
|
||||
current_weights: Dict[str, float],
|
||||
target_weights: Dict[str, float],
|
||||
constraints: Optional[Dict[str, float]] = None
|
||||
):
|
||||
"""
|
||||
Suggest trades to rebalance portfolio from current to target weights
|
||||
"""
|
||||
try:
|
||||
# Calculate differences
|
||||
trades = {}
|
||||
for symbol in target_weights:
|
||||
current = current_weights.get(symbol, 0.0)
|
||||
target = target_weights[symbol]
|
||||
diff = target - current
|
||||
|
||||
if abs(diff) > 0.001: # Ignore tiny differences
|
||||
trades[symbol] = diff
|
||||
|
||||
return {
|
||||
"trades": trades,
|
||||
"total_turnover": sum(abs(t) for t in trades.values())
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"Rebalance calculation failed: {str(e)}")
|
||||
from fastapi import APIRouter, HTTPException, Depends
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import List, Optional, Dict
|
||||
|
||||
from ..capabilities import OptimizationRuntime, get_optimization_runtime
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
class OptimizationConstraints(BaseModel):
|
||||
min_weight: Optional[float] = Field(0.0, ge=0.0, le=1.0)
|
||||
max_weight: Optional[float] = Field(1.0, ge=0.0, le=1.0)
|
||||
target_return: Optional[float] = None
|
||||
max_risk: Optional[float] = None
|
||||
|
||||
class PortfolioOptimizationRequest(BaseModel):
|
||||
symbols: List[str]
|
||||
returns: List[List[float]]
|
||||
constraints: Optional[OptimizationConstraints] = None
|
||||
method: str = Field("mean_variance", pattern="^(mean_variance|min_variance|max_sharpe|risk_parity|black_litterman)$")
|
||||
|
||||
class PortfolioWeights(BaseModel):
|
||||
symbols: List[str]
|
||||
weights: List[float]
|
||||
expected_return: float
|
||||
expected_risk: float
|
||||
sharpe_ratio: float
|
||||
|
||||
@router.post("/portfolio", response_model=PortfolioWeights)
|
||||
async def optimize_portfolio(
|
||||
request: PortfolioOptimizationRequest,
|
||||
runtime: OptimizationRuntime = Depends(get_optimization_runtime)
|
||||
):
|
||||
"""
|
||||
Optimize portfolio weights using various methods
|
||||
"""
|
||||
try:
|
||||
# Convert returns to numpy array
|
||||
returns_array = runtime.numpy.array(request.returns)
|
||||
|
||||
# Validate dimensions
|
||||
if len(request.symbols) != returns_array.shape[1]:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Number of symbols must match number of return columns"
|
||||
)
|
||||
|
||||
# Run optimization
|
||||
result = runtime.optimizer.optimize(
|
||||
returns=returns_array,
|
||||
method=request.method,
|
||||
constraints=request.constraints.dict() if request.constraints else None
|
||||
)
|
||||
|
||||
return PortfolioWeights(
|
||||
symbols=request.symbols,
|
||||
weights=result['weights'].tolist(),
|
||||
expected_return=float(result['expected_return']),
|
||||
expected_risk=float(result['expected_risk']),
|
||||
sharpe_ratio=float(result['sharpe_ratio'])
|
||||
)
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"Optimization failed: {str(e)}")
|
||||
|
||||
@router.post("/efficient_frontier")
|
||||
async def calculate_efficient_frontier(
|
||||
request: PortfolioOptimizationRequest,
|
||||
num_portfolios: int = 100,
|
||||
runtime: OptimizationRuntime = Depends(get_optimization_runtime)
|
||||
):
|
||||
"""
|
||||
Calculate the efficient frontier for a set of assets
|
||||
"""
|
||||
try:
|
||||
returns_array = runtime.numpy.array(request.returns)
|
||||
|
||||
frontier = runtime.optimizer.calculate_efficient_frontier(
|
||||
returns=returns_array,
|
||||
num_portfolios=num_portfolios
|
||||
)
|
||||
|
||||
return {
|
||||
"symbols": request.symbols,
|
||||
"frontier": frontier
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"Failed to calculate efficient frontier: {str(e)}")
|
||||
|
||||
@router.post("/rebalance")
|
||||
async def suggest_rebalance(
|
||||
current_weights: Dict[str, float],
|
||||
target_weights: Dict[str, float],
|
||||
constraints: Optional[Dict[str, float]] = None
|
||||
):
|
||||
"""
|
||||
Suggest trades to rebalance portfolio from current to target weights
|
||||
"""
|
||||
try:
|
||||
# Calculate differences
|
||||
trades = {}
|
||||
for symbol in target_weights:
|
||||
current = current_weights.get(symbol, 0.0)
|
||||
target = target_weights[symbol]
|
||||
diff = target - current
|
||||
|
||||
if abs(diff) > 0.001: # Ignore tiny differences
|
||||
trades[symbol] = diff
|
||||
|
||||
return {
|
||||
"trades": trades,
|
||||
"total_turnover": sum(abs(t) for t in trades.values())
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"Rebalance calculation failed: {str(e)}")
|
||||
|
|
|
|||
205
apps/stock/analytics/test/test_app_composition.py
Normal file
205
apps/stock/analytics/test/test_app_composition.py
Normal file
|
|
@ -0,0 +1,205 @@
|
|||
"""Import the actual service with optional scientific dependencies unavailable."""
|
||||
import importlib
|
||||
from io import BytesIO
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import unittest
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from starlette.datastructures import FormData, UploadFile
|
||||
from starlette.exceptions import HTTPException
|
||||
|
||||
|
||||
class UploadForm:
|
||||
def __init__(self, values):
|
||||
self.form = FormData(values)
|
||||
|
||||
async def __aenter__(self):
|
||||
return self.form
|
||||
|
||||
async def __aexit__(self, *_):
|
||||
await self.form.close()
|
||||
|
||||
|
||||
class AnalyticsAppComposition(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.path = str(Path(__file__).parents[1])
|
||||
sys.path.insert(0, self.path)
|
||||
self.addCleanup(lambda: sys.path.remove(self.path))
|
||||
for name in list(sys.modules):
|
||||
if name == "src" or name.startswith("src."):
|
||||
del sys.modules[name]
|
||||
missing = {name: None for name in (
|
||||
"numpy", "pandas", "scipy", "sklearn", "cvxpy", "onnxruntime", "multipart",
|
||||
)}
|
||||
self.dependencies = patch.dict(sys.modules, missing)
|
||||
self.dependencies.start()
|
||||
self.addCleanup(self.dependencies.stop)
|
||||
self.module = importlib.import_module("src.api.app")
|
||||
self.capabilities = importlib.import_module("src.api.capabilities")
|
||||
self.client = self.enterContext(TestClient(self.module.app))
|
||||
|
||||
def test_actual_app_starts_without_optional_dependencies(self):
|
||||
self.assertEqual(self.client.get("/").status_code, 200)
|
||||
self.assertEqual(self.client.get("/models/list").json(), [])
|
||||
self.assertEqual(self.client.get("/analytics/risk/P").status_code, 503)
|
||||
response = self.client.post("/optimize/rebalance", json={
|
||||
"current_weights": {"A.US": 0.25},
|
||||
"target_weights": {"A.US": 0.5},
|
||||
})
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response.json(), {"trades": {"A.US": 0.25}, "total_turnover": 0.25})
|
||||
|
||||
def test_health_observes_uninitialized_capabilities_without_loading_them(self):
|
||||
response = self.client.get("/health")
|
||||
self.assertEqual(response.status_code, 200)
|
||||
health = response.json()
|
||||
self.assertEqual(health["status"], "degraded")
|
||||
for name in ("portfolio_optimizer", "model_runtime", "model_upload"):
|
||||
self.assertEqual(health["components"][name], {"status": "uninitialized"})
|
||||
for name in ("performance_analyzer", "regime_detector"):
|
||||
self.assertEqual(health["components"][name], {
|
||||
"status": "unavailable", "reason": "observed_data_not_integrated",
|
||||
})
|
||||
for name in ("src.analytics.performance", "src.analytics.regime", "src.optimization.portfolio_optimizer"):
|
||||
self.assertNotIn(name, sys.modules)
|
||||
schema = self.client.get("/openapi.json").json()
|
||||
upload = schema["paths"]["/models/load"]["post"]["requestBody"]
|
||||
self.assertTrue(upload["required"])
|
||||
self.assertEqual(upload["content"]["multipart/form-data"]["schema"]["required"], ["model_file"])
|
||||
|
||||
def test_missing_optimizer_is_503_with_diagnostic_and_independent_health(self):
|
||||
request = {"symbols": ["A.US", "B.US"], "returns": [[0.01, 0.02]]}
|
||||
loader = Mock(wraps=self.capabilities.portfolio_optimizer.load)
|
||||
self.capabilities.portfolio_optimizer.load = loader
|
||||
for path in ("portfolio", "efficient_frontier", "portfolio"):
|
||||
response = self.client.post("/optimize/" + path, json=request)
|
||||
self.assertEqual(response.status_code, 503)
|
||||
self.assertEqual(response.json()["detail"], {
|
||||
"code": "analytics_capability_unavailable",
|
||||
"capability": "portfolio_optimizer",
|
||||
"reason": "missing_dependency",
|
||||
"message": "Optional analytics capability 'portfolio_optimizer' is unavailable",
|
||||
"dependency": "numpy",
|
||||
})
|
||||
loader.assert_called_once()
|
||||
health = self.client.get("/health").json()["components"]
|
||||
self.assertEqual(health["portfolio_optimizer"]["status"], "unavailable")
|
||||
self.assertEqual(health["model_runtime"]["status"], "uninitialized")
|
||||
self.assertEqual(self.client.get("/models/list").json(), [])
|
||||
|
||||
def test_optimizer_success_is_lazy_reused_and_preserves_input_and_output(self):
|
||||
arrays = SimpleNamespace(array=Mock(return_value=SimpleNamespace(shape=(2, 2))))
|
||||
optimizer = SimpleNamespace(
|
||||
optimize=Mock(return_value={
|
||||
"weights": SimpleNamespace(tolist=lambda: [0.25, 0.75]),
|
||||
"expected_return": 0.1,
|
||||
"expected_risk": 0.2,
|
||||
"sharpe_ratio": 0.5,
|
||||
}),
|
||||
calculate_efficient_frontier=Mock(return_value=[{"risk": 0.2, "return": 0.1}]),
|
||||
)
|
||||
loader = Mock(return_value=self.capabilities.OptimizationRuntime(arrays, optimizer))
|
||||
self.capabilities.portfolio_optimizer.load = loader
|
||||
self.client.get("/health")
|
||||
loader.assert_not_called()
|
||||
request = {"symbols": ["A.US", "B.US"], "returns": [[0.01, 0.02], [0.03, -0.01]]}
|
||||
response = self.client.post("/optimize/portfolio", json=request)
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response.json(), {
|
||||
"symbols": request["symbols"], "weights": [0.25, 0.75],
|
||||
"expected_return": 0.1, "expected_risk": 0.2, "sharpe_ratio": 0.5,
|
||||
})
|
||||
arrays.array.assert_called_once_with(request["returns"])
|
||||
optimizer.optimize.assert_called_once_with(
|
||||
returns=arrays.array.return_value, method="mean_variance", constraints=None,
|
||||
)
|
||||
response = self.client.post("/optimize/efficient_frontier?num_portfolios=7", json=request)
|
||||
self.assertEqual(response.status_code, 200)
|
||||
optimizer.calculate_efficient_frontier.assert_called_once_with(
|
||||
returns=arrays.array.return_value, num_portfolios=7,
|
||||
)
|
||||
loader.assert_called_once()
|
||||
self.assertEqual(self.client.get("/health").json()["components"]["portfolio_optimizer"], {"status": "ready"})
|
||||
request["symbols"] = ["A.US"]
|
||||
self.assertEqual(self.client.post("/optimize/portfolio", json=request).status_code, 400)
|
||||
|
||||
def test_failed_runtime_initialization_is_not_reported_ready(self):
|
||||
self.capabilities.portfolio_optimizer.load = Mock(side_effect=RuntimeError("fixture failure"))
|
||||
response = self.client.post("/optimize/portfolio", json={
|
||||
"symbols": ["A.US"], "returns": [[0.01]],
|
||||
})
|
||||
self.assertEqual(response.status_code, 503)
|
||||
self.assertEqual(response.json()["detail"]["reason"], "initialization_failed")
|
||||
self.assertEqual(self.client.get("/health").json()["components"]["portfolio_optimizer"]["status"], "unavailable")
|
||||
|
||||
def test_model_absence_and_optional_model_dependencies_have_distinct_statuses(self):
|
||||
self.assertEqual(self.client.post("/models/predict", json={"model_id": "missing", "features": {}}).status_code, 404)
|
||||
self.assertEqual(self.client.post("/models/batch_predict?model_id=missing", json=[]).status_code, 404)
|
||||
self.assertEqual(self.client.delete("/models/missing").status_code, 404)
|
||||
response = self.client.post("/models/load?model_id=fixture", files={"model_file": ("model.onnx", b"fixture")})
|
||||
self.assertEqual(response.status_code, 503)
|
||||
self.assertEqual(response.json()["detail"]["capability"], "model_runtime")
|
||||
self.assertEqual(self.client.get("/health").json()["components"]["model_runtime"]["status"], "unavailable")
|
||||
|
||||
def test_missing_multipart_only_disables_model_upload(self):
|
||||
self.capabilities.model_runtime.load = Mock(return_value=self.capabilities.ModelRuntime(None, None))
|
||||
response = self.client.post("/models/load?model_id=fixture", files={"model_file": ("model.onnx", b"fixture")})
|
||||
self.assertEqual(response.status_code, 503)
|
||||
self.assertEqual(response.json()["detail"]["capability"], "model_upload")
|
||||
self.assertEqual(response.json()["detail"]["reason"], "missing_dependency")
|
||||
self.assertEqual(self.client.get("/models/list").json(), [])
|
||||
|
||||
def test_model_upload_and_prediction_keep_the_existing_contract_with_runtime_stubs(self):
|
||||
session = SimpleNamespace(
|
||||
get_inputs=lambda: [SimpleNamespace(name="input")],
|
||||
get_outputs=lambda: [SimpleNamespace(shape=["batch", 1, None])],
|
||||
run=Mock(return_value=[[1.5]]),
|
||||
)
|
||||
arrays = SimpleNamespace(
|
||||
array=Mock(return_value="feature-array"),
|
||||
float32="float32",
|
||||
datetime64=lambda _: SimpleNamespace(tolist=lambda: "2024-01-01T00:00:00"),
|
||||
)
|
||||
onnx = SimpleNamespace(InferenceSession=Mock(return_value=session))
|
||||
loader = Mock(return_value=self.capabilities.ModelRuntime(arrays, onnx))
|
||||
self.capabilities.model_runtime.load = loader
|
||||
self.capabilities.model_upload.load = Mock(return_value=True)
|
||||
file = UploadFile(filename="model.onnx", file=BytesIO(b"fixture"))
|
||||
with patch("starlette.requests.Request.form", return_value=UploadForm({"model_file": file})):
|
||||
response = self.client.post("/models/load", params={
|
||||
"model_id": "fixture",
|
||||
"metadata": json.dumps({"feature_names": ["trend", "volatility"], "version": "2"}),
|
||||
})
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertTrue(file.file.closed)
|
||||
onnx.InferenceSession.assert_called_once_with(b"fixture")
|
||||
listed = self.client.get("/models/list")
|
||||
self.assertEqual(listed.status_code, 200)
|
||||
self.assertEqual(listed.json()[0]["output_shape"], [["batch", 1, None]])
|
||||
self.assertEqual(listed.json()[0]["model_id"], "fixture")
|
||||
response = self.client.post("/models/predict", json={
|
||||
"model_id": "fixture", "features": {"trend": 0.4},
|
||||
})
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response.json()["prediction"], 1.5)
|
||||
self.assertEqual(response.json()["metadata"]["model_version"], "2")
|
||||
arrays.array.assert_called_once_with([[0.4, 0.0]], dtype="float32")
|
||||
session.run.assert_called_once_with(None, {"input": "feature-array"})
|
||||
loader.assert_called_once()
|
||||
response = self.client.post("/models/batch_predict?model_id=fixture", json=[{"trend": 0.1}])
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response.json()["count"], 1)
|
||||
self.assertEqual(self.client.delete("/models/fixture").status_code, 200)
|
||||
self.assertEqual(self.client.get("/models/list").json(), [])
|
||||
with patch("starlette.requests.Request.form", return_value=UploadForm({})):
|
||||
self.assertEqual(self.client.post("/models/load?model_id=fixture").status_code, 422)
|
||||
with patch("starlette.requests.Request.form", side_effect=HTTPException(400, "Malformed form")):
|
||||
self.assertEqual(self.client.post("/models/load?model_id=fixture").status_code, 400)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
@ -23,3 +23,5 @@ Agents use root-reserved disjoint files in the integration worktree. Root alone
|
|||
- **CL32:** Independent pure projection/runtime suite 4 passed, 22 assertions; disposable PostgreSQL paper-runtime suite 22 passed, 143 assertions. Verified atomic expiry latch, rollback on storage failure, no implicit reactivation, stale generation and restart recovery. Scoped lint/format passed.
|
||||
|
||||
- **CL26:** Moved existing shared server helpers to explicit trading-runtime subpaths, shared financial wire contracts to config, split metadata verifier from executable loader, and made artifact paths lazy. Config/runtime/API/orchestrator builds and full source typecheck passed. Architecture/Turbo/browser gates: 30 passed (7363 assertions); shared admission/storage/feed tests passed; isolated retained worker final15 passed after preserving rejection diagnostics. Native finance unchanged.
|
||||
|
||||
- **CL35:** Actual FastAPI app/lifespan and optional capability tests: 11 passed. Missing scientific/multipart dependencies do not prevent unrelated routes; unavailable initialization returns503, health observes state. Successful optimizer/model paths tested with stubs; load-to-list output shape corrected and covered. No heavy scientific packages installed.
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Canonical development backlog
|
||||
|
||||
**Active: E13 architecture cleanup, CL22–CL35 (8/14 complete).** Owner authorized all October 28 audit recommendations and a commit per validated task. Earlier completion counts below are historical. [Execution record](../architecture-cleanup-execution.md).
|
||||
**Active: E13 architecture cleanup, CL22–CL35 (9/14 complete).** Owner authorized all October 28 audit recommendations and a commit per validated task. Earlier completion counts below are historical. [Execution record](../architecture-cleanup-execution.md).
|
||||
|
||||
**Current scheduled backlog: 99/99 complete.** The owner resumed performance and authorized review of all seven conditions. P08 and O02 are implemented; five optional extensions remain deliberately deferred, and four merged IDs are redirects. This is not a claim that all 108 retained IDs were implemented. [Decisions, measurements and validation](../conditional-review.md).
|
||||
|
||||
|
|
|
|||
|
|
@ -3837,7 +3837,7 @@
|
|||
"complexity": "M",
|
||||
"assignment": null,
|
||||
"write_locks": ["CL26"],
|
||||
"completed_commit": null,
|
||||
"completed_commit": "b4589d5af1c4b78026ef4fad484a8f493bc98786",
|
||||
"blocker": null,
|
||||
"release_gates": [],
|
||||
"completion_evidence": "architecture-cleanup-execution.md",
|
||||
|
|
@ -4000,7 +4000,7 @@
|
|||
"epic": "E13",
|
||||
"priority": "P2",
|
||||
"severity": "Medium",
|
||||
"status": "ready",
|
||||
"status": "done",
|
||||
"dependencies": [],
|
||||
"decision_dependencies": [],
|
||||
"task_file": "backlog/tasks/CL35.md",
|
||||
|
|
@ -4010,7 +4010,9 @@
|
|||
"completed_commit": null,
|
||||
"blocker": null,
|
||||
"release_gates": [],
|
||||
"completion_evidence": "architecture-cleanup-execution.md"
|
||||
"completion_evidence": "architecture-cleanup-execution.md",
|
||||
"integration_state": "accepted",
|
||||
"validation": "Actual FastAPI app/lifespan and optional capability tests: 11 passed. Missing scientific/multipart dependencies do not prevent unrelated routes; unavailable initialization returns503, health observes state. Successful optimizer/model paths tested with stubs; load-to-list output shape corrected and covered. No heavy scientific packages installed."
|
||||
}
|
||||
],
|
||||
"review_note": "Independent skeptical revision: four superseded tasks retain stable IDs; deferred work is not a dependency of scheduled tasks. Release gates are distinct from implementation prerequisites.",
|
||||
|
|
@ -10397,7 +10399,7 @@
|
|||
],
|
||||
"work_policy": "Root integrates/commits reviewed tasks; agents own disjoint explicit files in the root integration worktree. Only root builds shared outputs and runs combined gates. No isolated native agent build claim.",
|
||||
"first_wave": ["CL22", "CL23", "CL24"],
|
||||
"completed": 8,
|
||||
"last_verification": "Moved existing shared server helpers to explicit trading-runtime subpaths, shared financial wire contracts to config, split metadata verifier from executable loader, and made artifact paths lazy. Config/runtime/API/orchestrator builds and full source typecheck passed. Architecture/Turbo/browser gates: 30 passed (7363 assertions); shared admission/storage/feed tests passed; isolated retained worker final15 passed after preserving rejection diagnostics. Native finance unchanged."
|
||||
"completed": 9,
|
||||
"last_verification": "Actual FastAPI app/lifespan and optional capability tests: 11 passed. Missing scientific/multipart dependencies do not prevent unrelated routes; unavailable initialization returns503, health observes state. Successful optimizer/model paths tested with stubs; load-to-list output shape corrected and covered. No heavy scientific packages installed."
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,3 +18,7 @@ Actual app import/startup and existing analytics API tests; missing dependency d
|
|||
|
||||
No new service/framework, financial simulator, real trading activation, external research execution, push/PR or .env changes. D04/P03/P05/P06/CL21 remain deferred. Root owns shared outputs, task state and commits; agents own disjoint files in the integration worktree.
|
||||
|
||||
|
||||
## Accepted verification
|
||||
|
||||
Actual FastAPI app/lifespan and optional capability tests: 11 passed. Missing scientific/multipart dependencies do not prevent unrelated routes; unavailable initialization returns503, health observes state. Successful optimizer/model paths tested with stubs; load-to-list output shape corrected and covered. No heavy scientific packages installed.
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue