aboutsummaryrefslogtreecommitdiff
path: root/server/api/market.py
blob: 5102f032c325c4545667ef16fd56cc47d502f84c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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