from fastapi import FastAPI from pydantic import BaseModel import numpy as np import joblib # load model model = joblib.load("credit_risk_xgb.pkl") scaler = joblib.load("credit_risk_scaler.pkl") app = FastAPI() class CreditRiskInput(BaseModel): age: int income: float loan_amount: float credit_score: int years_employed: int missed_payments: int @app.get("/") def home(): return {"message": "API is running"} @app.post("/predict") def predict(data: CreditRiskInput): arr = np.array([[ data.age, data.income, data.loan_amount, data.credit_score, data.years_employed, data.missed_payments ]]) arr_scaled = scaler.transform(arr) prob = float(model.predict(arr_scaled)[0]) pred = 1 if prob > 0.5 else 0 return { "prediction": pred, "risk_label": "High Risk" if pred == 1 else "Low Risk", "default_probability": round(prob, 4) } # ----------------------------- # Health check endpoint # ----------------------------- @app.get("/") def home(): return { "message": "Credit Risk Prediction API is running" } @app.get("/health") def health(): return { "status": "ok", "model_loaded": True } # ----------------------------- # Prediction endpoint # ----------------------------- @app.post("/predict") def predict_risk(data: CreditRiskInput): input_data = np.array([[ data.age, data.income, data.loan_amount, data.credit_score, data.years_employed, data.missed_payments ]]) input_scaled = scaler.transform(input_data) probability = float(model.predict_proba(input_scaled)[0][1]) prediction = int(model.predict(input_scaled)[0]) risk_label = "High Risk" if prediction == 1 else "Low Risk" return { "prediction": prediction, "risk_label": risk_label, "default_probability": round(probability, 4) }