# Unified Financial & Demand Forecast API A single FastAPI backend serving both **EWA Demand Forecasting** and **Financial Distress Risk Prediction**. ## Features ✅ **EWA Demand Forecasting** - Exponential Weighted Average model for time series prediction - Support for simple and Holt's double exponential smoothing - Automatic parameter optimization or custom alpha/beta values - Batch prediction support ✅ **Financial Distress Prediction** - Predict financial distress risk based on spending patterns - Risk scores from 0 (no risk) to 1 (highest risk) - Integration with EWA features ✅ **Production Ready** - Docker containerization - Deployed on Render - Comprehensive API documentation - Gradio web interface ## Endpoints ### Health & Information **GET** `/health` - Health check endpoint - Returns: `{status: "ok", version: "2.0.0"}` **GET** `/model-info` - Get model metadata and default parameters - Returns: Model name, version, supported algorithms, defaults **GET** `/docs` (Swagger UI) - Interactive API documentation ### EWA Demand Forecast **POST** `/predict` - Single forecast prediction - Request body: ```json { "history": [10, 12, 15, 14, 16], "horizon": 5, "alpha": 0.3, "beta": 0.1, "confidence_level": 0.95 } ``` - Returns: Forecast values, confidence intervals, parameters used **POST** `/predict/batch` - Multiple forecasts in one request - Request body: Array of forecast requests - Returns: Array of forecast responses ### Financial Distress **POST** `/distress/predict` - Predict financial distress risk for a user - Request body: ```json { "user_id": "user_123", "total_spend": 5000, "txn_count": 50, "total_spend_30d": 1500, "max_daily_spend_30d": 300, "txn_count_30d": 15, "ewa_usage_count": 5, "ewa_total_amount": 500, "ewa_avg_amount": 100, "ewa_max_amount": 200 } ``` - Returns: `{user_id, risk_score, model_type, timestamp}` ## Local Development ### Installation ```bash pip install -r requirements.txt ``` ### Running the Backend ```bash python main.py ``` Server starts at `http://localhost:8000` ### Testing ```bash # In another terminal python test_api.py ``` ## Deployment ### Docker ```bash docker build -t ewa-api . docker run -p 8000:8000 ewa-api ``` ### Render (Production) - Repository: https://github.com/JiainingZhan/ewa-demand-forecast-api - Deployed at: https://ewa-demand-forecast-api.onrender.com - Start Command: `uvicorn main:app --host 0.0.0.0 --port $PORT` ## Gradio Frontend A Gradio interface is available at: - Hugging Face Spaces: (Link TBD) - Or run locally: `python gradio_app.py` ### Features 1. **Tab 1: EWA Demand Forecast** - Input historical data - Set forecast horizon - Customize smoothing parameters - View forecast and confidence intervals 2. **Tab 2: Financial Distress Risk** - Input user spending features - Get risk score with color-coded risk level - Integration with EWA features 3. **Tab 3: API Info** - Endpoint documentation - API base URL configuration ## Architecture ### Single Unified Backend Both models run in the same FastAPI application: - No inter-service communication overhead - Shared configuration and dependencies - Financial Distress model can internally call EWA functions if needed ``` ┌─────────────────────────────────────┐ │ Gradio Frontend (HF Spaces) │ └────────────────┬────────────────────┘ │ HTTP Requests ↓ ┌─────────────────────────────────────┐ │ Unified FastAPI Backend │ ├─────────────────────────────────────┤ │ • /predict (EWA) │ │ • /predict/batch (EWA) │ │ • /distress/predict (Distress) │ │ • /health, /model-info │ └─────────────────────────────────────┘ ``` ## Configuration ### Environment Variables - `API_BASE_URL`: Backend URL for Gradio frontend (default: `http://localhost:8000`) - `EWA_HOST`: FastAPI host (default: `0.0.0.0`) - `EWA_PORT`: FastAPI port (default: `8000`) - `EWA_DEBUG`: Debug mode (default: `false`) ## Project Structure ``` ├── main.py # FastAPI application entry point ├── config.py # Configuration management ├── models/ │ ├── forecast.py # EWA forecast model │ └── distress.py # Financial distress model ├── schemas/ │ ├── request.py # Request Pydantic models │ └── response.py # Response Pydantic models ├── utils/ │ └── validation.py # Input validation utilities ├── gradio_app.py # Gradio web interface ├── requirements.txt # Python dependencies ├── Dockerfile # Docker configuration └── test_api.py # API endpoint tests ``` ## Dependencies - **FastAPI 0.115+**: Web framework - **Uvicorn 0.30+**: ASGI server - **Pydantic 2.6+**: Data validation - **NumPy 1.26+**: Numerical computing - **SciPy 1.12+**: Scientific computing - **Pandas 2.0+**: Data manipulation - **Scikit-learn 1.3+**: Machine learning - **XGBoost 2.0+**: Gradient boosting (optional) - **Gradio 6.0+**: Web UI (for frontend) ## Troubleshooting ### Status 127 on Render - Check that Start Command is: `uvicorn main:app --host 0.0.0.0 --port $PORT` - Verify all dependencies installed: Check `requirements.txt` - Review Render logs for specific errors ### Import Errors - Ensure all dependencies installed: `pip install -r requirements.txt` - Check Python version: Must be 3.9+ ### XGBoost Issues - macOS: `brew install libomp` - Can safely ignore if Financial Distress model uses heuristic fallback ## Support For issues or questions: - GitHub: https://github.com/JiainingZhan/ewa-demand-forecast-api - Issues: Open a GitHub issue with detailed description --- *Last updated: 2024*