from fastapi import APIRouter from models.market import MarketData from gridstatus import ISONE from datetime import datetime, timedelta from typing import List router = APIRouter() # Keeping the scope of this api to just one market right now iso = ISONE() # In-memory cache _cached_day_ahead: List[MarketData] = [] _cache_timestamp: datetime | None = None _cached_real_time: List[MarketData] = [] _cache_real_time_timestamp: datetime | None = None # TODO: Error Handling @router.get("/day-ahead", response_model=list[MarketData]) def get_day_ahead_data(): global _cached_day_ahead, _cache_timestamp now = datetime.utcnow() if _cache_timestamp is None or now - _cache_timestamp > timedelta(hours=1): df = iso.get_lmp(date=datetime.now().date(), market="DAY_AHEAD_HOURLY", locations="ALL") grouped = (df.groupby("Interval Start")[["LMP", "Energy", "Congestion", "Loss"]].mean().reset_index()) _cached_day_ahead = [ MarketData( timestamp=row["Interval Start"], lmp=row["LMP"], energy=row["Energy"], congestion=row["Congestion"], loss=row["Loss"], ) for _, row in grouped.iterrows() ] _cache_timestamp = now return _cached_day_ahead @router.get("/real-time", response_model=list[MarketData]) def get_real_time_data(): global _cached_real_time, _cache_real_time_timestamp now = datetime.utcnow() if _cache_real_time_timestamp is None or now - _cache_real_time_timestamp > timedelta(minutes=5): df = iso.get_lmp(date="today", market="REAL_TIME_5_MIN", locations="ALL") grouped = (df.groupby("Interval Start")[["LMP", "Energy", "Congestion", "Loss"]].mean().reset_index()) _cached_real_time = [ MarketData( timestamp=row["Interval Start"], lmp=row["LMP"], energy=row["Energy"], congestion=row["Congestion"], loss=row["Loss"], ) for _, row in grouped.iterrows() ] _cache_real_time_timestamp = now return _cached_real_time