"""Unified Financial & Demand Forecast API – FastAPI application entry point.
Supports both:
- EWA Demand Forecast predictions
- Financial Distress Risk predictions
"""
from fastapi import FastAPI, HTTPException
from fastapi.responses import HTMLResponse
from pydantic import BaseModel
from typing import Optional
from config import settings
from models.forecast import EWAForecastModel
from models.distress import predict_distress
from schemas.request import BatchForecastRequest, ForecastRequest
from schemas.response import (
BatchForecastResponse,
ConfidenceInterval,
ForecastResponse,
HealthResponse,
ModelInfoResponse,
)
from utils.validation import validate_history
app = FastAPI(
title="Unified Financial & Demand Forecast API",
description="Combined API for EWA demand forecasting and financial distress prediction",
version="2.0.0",
docs_url="/docs",
redoc_url="/redoc",
)
@app.get("/", include_in_schema=False, response_class=HTMLResponse)
def root() -> HTMLResponse:
"""Show a small landing page with direct links to the useful endpoints."""
return HTMLResponse(
"""
Unified Financial & Demand Forecast API
"""
)
# ---------------------------------------------------------------------------
# Request/Response Models for Distress
# ---------------------------------------------------------------------------
class DistressRequest(BaseModel):
"""Request model for financial distress prediction."""
user_id: Optional[str] = None
total_spend: float
txn_count: float
total_spend_30d: float
max_daily_spend_30d: float
txn_count_30d: float
ewa_usage_count: float = 0
ewa_total_amount: float = 0
ewa_avg_amount: float = 0
ewa_max_amount: float = 0
class DistressResponse(BaseModel):
"""Response model for distress prediction."""
user_id: Optional[str] = None
risk_score: float
timestamp: str
model_type: str
# ---------------------------------------------------------------------------
# Health check
# ---------------------------------------------------------------------------
@app.get(
"/health",
response_model=HealthResponse,
summary="Health check",
tags=["Operations"],
)
def health() -> HealthResponse:
"""Return the current health status of the service."""
return HealthResponse(status="ok", version=settings.app_version)
# ---------------------------------------------------------------------------
# Model information
# ---------------------------------------------------------------------------
@app.get(
"/model-info",
response_model=ModelInfoResponse,
summary="Model information",
tags=["Operations"],
)
def model_info() -> ModelInfoResponse:
"""Return metadata and default parameters of the forecast model."""
return ModelInfoResponse(
name="EWA Demand Forecast Model",
version=settings.app_version,
description=(
"Exponential Weighted Average (EWA) demand forecasting model. "
"Supports simple (level only) and Holt's double (level + trend) "
"exponential smoothing with automatic parameter optimisation."
),
supported_models=["simple", "double"],
default_alpha=settings.default_alpha,
default_beta=settings.default_beta,
default_horizon=settings.default_horizon,
default_confidence_level=settings.default_confidence_level,
min_history_length=settings.min_history_length,
)
# ---------------------------------------------------------------------------
# Single prediction
# ---------------------------------------------------------------------------
@app.post(
"/predict",
response_model=ForecastResponse,
summary="Generate a demand forecast",
tags=["Forecast"],
)
def predict(request: ForecastRequest) -> ForecastResponse:
"""Fit an EWA model on the supplied history and return a forecast.
* If **alpha** / **beta** are omitted the parameters are automatically
optimised to minimise in-sample squared error.
* Supplying only **alpha** enables simple exponential smoothing.
* Supplying both **alpha** and **beta** enables Holt's double
exponential smoothing with the given parameters.
"""
validate_history(request.history, min_length=settings.min_history_length)
model = EWAForecastModel(alpha=request.alpha, beta=request.beta)
try:
forecast_vals, intervals, alpha_used, beta_used, model_type, rmse = (
model.fit_predict(
history=request.history,
horizon=request.horizon,
confidence_level=request.confidence_level,
)
)
except Exception as exc: # pragma: no cover
raise HTTPException(status_code=500, detail=str(exc)) from exc
return ForecastResponse(
forecast=forecast_vals,
confidence_intervals=[
ConfidenceInterval(lower=lo, upper=hi) for lo, hi in intervals
],
confidence_level=request.confidence_level,
alpha=alpha_used,
beta=beta_used,
model_type=model_type,
rmse=rmse,
)
# ---------------------------------------------------------------------------
# Batch prediction
# ---------------------------------------------------------------------------
@app.post(
"/predict/batch",
response_model=BatchForecastResponse,
summary="Generate a batch of demand forecasts",
tags=["Forecast"],
)
def predict_batch(request: BatchForecastRequest) -> BatchForecastResponse:
"""Run forecasts for multiple time series in a single request (max 100)."""
results = []
for item in request.items:
validate_history(item.history, min_length=settings.min_history_length)
model = EWAForecastModel(alpha=item.alpha, beta=item.beta)
try:
forecast_vals, intervals, alpha_used, beta_used, model_type, rmse = (
model.fit_predict(
history=item.history,
horizon=item.horizon,
confidence_level=item.confidence_level,
)
)
except Exception as exc: # pragma: no cover
raise HTTPException(status_code=500, detail=str(exc)) from exc
results.append(
ForecastResponse(
forecast=forecast_vals,
confidence_intervals=[
ConfidenceInterval(lower=lo, upper=hi) for lo, hi in intervals
],
confidence_level=item.confidence_level,
alpha=alpha_used,
beta=beta_used,
model_type=model_type,
rmse=rmse,
)
)
return BatchForecastResponse(results=results, total=len(results))
# ---------------------------------------------------------------------------
# Financial Distress endpoints
# ---------------------------------------------------------------------------
@app.post(
"/distress/predict",
response_model=DistressResponse,
summary="Predict financial distress risk",
tags=["Financial Distress"],
)
def predict_financial_distress(request: DistressRequest) -> DistressResponse:
"""Predict financial distress risk for a user based on spending patterns.
Takes engineered features about user spending, transaction count, and EWA usage
and returns a risk score between 0 and 1 where 1 = highest risk.
"""
try:
# Convert request to dict for internal model
features = request.dict()
result = predict_distress(features)
return DistressResponse(**result)
except Exception as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
# ---------------------------------------------------------------------------
# Entry point (local development)
# ---------------------------------------------------------------------------
if __name__ == "__main__": # pragma: no cover
import uvicorn
uvicorn.run(
"main:app",
host=settings.host,
port=settings.port,
reload=settings.debug,
)