""" app.py — FastAPI Backend for Crude Oil Price Predictor Run: uvicorn app:app --reload --port 8000 """ from fastapi import FastAPI, HTTPException from fastapi.staticfiles import StaticFiles from fastapi.responses import FileResponse from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel import traceback from predictor import ( load_model, load_data, run_walkforward, forecast_future, predict_date, get_historical, ) app = FastAPI(title="Crude Oil Price Predictor", version="1.0.0") # CORS — allow frontend to call backend app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"], ) # Serve frontend app.mount("/static", StaticFiles(directory="frontend"), name="static") # ── Startup: preload model + data ── @app.on_event("startup") async def startup(): print("🚀 Starting up...") load_data() load_model() print("✅ Ready!") # ── Routes ── @app.get("/") def root(): return FileResponse("frontend/index.html") @app.get("/api/health") def health(): return {"status": "ok", "model": "TimesFM 2.5"} @app.get("/api/historical") def historical(): """Return last 300 days of historical prices for chart.""" try: return get_historical() except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @app.get("/api/backtest") def backtest(days: int = 60): """Run walk-forward validation on last N days.""" try: if days < 10 or days > 120: raise HTTPException(400, "days must be between 10 and 120") return run_walkforward(test_days=days) except HTTPException: raise except Exception as e: traceback.print_exc() raise HTTPException(status_code=500, detail=str(e)) @app.get("/api/forecast") def forecast(horizon: int = 60): """Return future forecast for next N business days.""" try: if horizon < 5 or horizon > 90: raise HTTPException(400, "horizon must be between 5 and 90") return forecast_future(horizon=horizon) except HTTPException: raise except Exception as e: traceback.print_exc() raise HTTPException(status_code=500, detail=str(e)) class PredictRequest(BaseModel): date: str # format: YYYY-MM-DD @app.post("/api/predict") def predict(req: PredictRequest): """Predict price for a specific future date.""" try: result = predict_date(req.date) if "error" in result: raise HTTPException(status_code=400, detail=result["error"]) return result except HTTPException: raise except Exception as e: traceback.print_exc() raise HTTPException(status_code=500, detail=str(e)) class ChatRequest(BaseModel): message: str @app.post("/api/chat") def chat(req: ChatRequest): """ Natural language query handler. Parses date from message and returns prediction. """ import re from datetime import datetime, timedelta import pandas as pd msg = req.message.lower().strip() # Try to extract a date (YYYY-MM-DD or common phrases) date_pattern = re.search(r"\d{4}-\d{2}-\d{2}", req.message) today = datetime.today() target_date = None if date_pattern: target_date = date_pattern.group() elif "tomorrow" in msg: target_date = str((today + timedelta(days=1)).date()) elif "next week" in msg: target_date = str((today + timedelta(days=7)).date()) elif "next month" in msg or "1 month" in msg or "one month" in msg: target_date = str((today + timedelta(days=30)).date()) elif "2 week" in msg or "two week" in msg: target_date = str((today + timedelta(days=14)).date()) elif "3 month" in msg or "three month" in msg: target_date = str((today + timedelta(days=90)).date()) elif "6 month" in msg or "six month" in msg: target_date = str((today + timedelta(days=180)).date()) elif any(k in msg for k in ["today", "now", "current", "latest"]): _, dates, data = load_data() from predictor import _series return { "type" : "current", "message" : f"The latest Brent Crude Oil price is " f"${float(data['DCOILBRENTEU'].iloc[-1]):.2f}/barrel " f"as of {str(dates[-1])[:10]}.", } # Month name detection (e.g. "May 2026", "June 2026") if not target_date: months = { "january":1,"february":2,"march":3,"april":4, "may":5,"june":6,"july":7,"august":8, "september":9,"october":10,"november":11,"december":12, } for month_name, month_num in months.items(): if month_name in msg: year_match = re.search(r"\b(202\d)\b", msg) year = int(year_match.group()) if year_match else today.year try: target_date = f"{year}-{month_num:02d}-15" except: pass break if not target_date: return { "type" : "error", "message": ( "I couldn't understand that date. Try asking like:\n" "• 'What will oil cost on 2026-06-01?'\n" "• 'Predict price for next month'\n" "• 'What is the price for May 2026?'" ), } try: result = predict_date(target_date) if "error" in result: return {"type": "error", "message": result["error"]} direction = "📈 UP" if result["change_usd"] >= 0 else "📉 DOWN" conf_map = {"HIGH": "🟢", "MEDIUM": "🟡", "LOW": "🟠", "VERY LOW": "🔴"} conf_icon = conf_map.get(result["confidence"], "⚪") message = ( f"🛢️ **Brent Crude Oil Forecast for {target_date}**\n\n" f"📌 **Predicted Price:** ${result['predicted']:.2f}/barrel\n" f"📉 Low (10%): ${result['lower_10pct']:.2f}\n" f"📈 High (90%): ${result['upper_90pct']:.2f}\n" f"📊 Uncertainty: ±${result['uncertainty']/2:.2f}\n\n" f"{direction} ${abs(result['change_usd']):.2f} ({result['change_pct']:+.1f}%) " f"vs last known ${result['last_known']['price']:.2f}\n\n" f"{conf_icon} Confidence: **{result['confidence']}** " f"({result['days_ahead']} business days ahead)\n\n" f"_Based on TimesFM 2.5 | Walk-Forward MAE ~$3.66_" ) return { "type" : "prediction", "message": message, "data" : result, } except Exception as e: return {"type": "error", "message": str(e)}