-
Notifications
You must be signed in to change notification settings - Fork 910
/
VN.py
207 lines (175 loc) · 6.28 KB
/
VN.py
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
#!/usr/bin/env python3
import json
from datetime import datetime, timedelta
from logging import Logger, getLogger
from zoneinfo import ZoneInfo
from requests import Session
from electricitymap.contrib.config import ZoneKey
from electricitymap.contrib.lib.models.event_lists import (
PriceList,
TotalConsumptionList,
)
from parsers.lib.exceptions import ParserException
## Vietnamese National Load Dispatch Center https://www.nldc.evn.vn/
# Access via day, can also parse historical data
tz = ZoneInfo("Asia/Ho_Chi_Minh")
LIVE_DATA = {
"consumption": "https://www.nldc.evn.vn/api/services/app/Pages/GetChartPhuTaiVM",
"price": "https://www.nldc.evn.vn/api/services/app/Pages/GetChartGiaBienVM",
}
HISTORICAL_DATA = "https://www.nldc.evn.vn/api/services/app/Dashboard/GetBieuDoTuongQuanPT" # + dd/mm/yyyy
ZONE_CODE = {
ZoneKey("VN"): "HT",
ZoneKey("VN-N"): "MB",
ZoneKey("VN-C"): "MT",
ZoneKey("VN-S"): "MN",
}
def fetch_live_data(data_type: str, session: Session):
res = session.get(LIVE_DATA[data_type])
if not res.ok:
raise ParserException(
parser="VN.py", message=f"Request failed: {res.status_code}"
)
return json.loads(res.text)["result"]["data"]
def fetch_historical_data(
target_datetime: datetime,
session: Session,
):
res = session.get(
f"{HISTORICAL_DATA}?day={(target_datetime.astimezone(tz)).strftime('%d/%m/%Y')}"
)
if not res.ok:
raise ParserException(
parser="VN.py", message=f"Request failed: {res.status_code}"
)
return json.loads(res.text)["result"]["data"]["phuTai"]
def fetch_live_price(
zone_key: ZoneKey,
session: Session,
logger: Logger = getLogger(__name__),
):
data_list = fetch_live_data("price", session)["giaBiens"]
result_list = PriceList(logger)
for data in data_list:
result_list.append(
datetime=datetime.fromisoformat(data["thoiGian"]).replace(tzinfo=tz)
- timedelta(minutes=30),
price=data[f"giaBien{ZONE_CODE[zone_key]}"],
currency="VND",
zoneKey=zone_key,
source="nldc.evn.vn",
)
return result_list.to_list()
def fetch_live_consumption(
zone_key: ZoneKey,
session: Session,
logger: Logger = getLogger(__name__),
):
data_list = fetch_live_data("consumption", session)["phuTais"]
result_list = TotalConsumptionList(logger)
for data in data_list:
result_list.append(
datetime=datetime.fromisoformat(data["thoiGian"]).replace(tzinfo=tz)
- timedelta(minutes=30),
consumption=data[f"congSuat{ZONE_CODE[zone_key]}"],
zoneKey=zone_key,
source="nldc.evn.vn",
)
return result_list.to_list()
def fetch_historical_price(
target_datetime: datetime,
session: Session,
logger: Logger = getLogger(__name__),
):
data_list = fetch_historical_data(session=session, target_datetime=target_datetime)
result_list = PriceList(logger)
for data in data_list:
result_list.append(
datetime=datetime.fromisoformat(data["thoiGian"]).replace(tzinfo=tz)
- timedelta(minutes=30),
currency="VND",
price=data["giaBan"],
zoneKey=ZoneKey("VN"),
source="nldc.evn.vn",
)
return result_list.to_list()
def fetch_historical_consumption(
target_datetime: datetime,
session: Session,
logger: Logger = getLogger(__name__),
):
data_list = fetch_historical_data(session=session, target_datetime=target_datetime)
result_list = TotalConsumptionList(logger)
for data in data_list:
result_list.append(
datetime=datetime.fromisoformat(data["thoiGian"]).replace(tzinfo=tz)
- timedelta(
minutes=30
), # Substract 30 minutes to convert backwards looking timestamp to forward looking
consumption=data["congSuat"],
zoneKey=ZoneKey("VN"),
source="nldc.evn.vn",
)
return result_list.to_list()
def fetch_price(
zone_key: ZoneKey,
session: Session | None = None,
target_datetime: datetime | None = None,
logger: Logger = getLogger(__name__),
):
session = session or Session()
if target_datetime is None:
live_consumption = fetch_live_price(zone_key, session, logger)
if len(live_consumption) > 0:
return live_consumption
else:
if zone_key is ZoneKey("VN"):
return fetch_historical_price(
datetime.now() - timedelta(days=1), session, logger
)
else:
raise ParserException(
"VN.py",
"No real time data found",
zone_key,
)
elif target_datetime is not None and zone_key is ZoneKey("VN"):
return fetch_historical_price(target_datetime, session, logger)
else:
raise NotImplementedError(
"This parser is not yet able to parse past dates for this zone"
)
def fetch_consumption(
zone_key: ZoneKey,
session: Session | None = None,
target_datetime: datetime | None = None,
logger: Logger = getLogger(__name__),
):
session = session or Session()
if target_datetime is None:
live_consumption = fetch_live_consumption(zone_key, session, logger)
# Live data is empty at 00:00, resort to historical from previous day
if len(live_consumption) > 0:
return live_consumption
else:
if zone_key is ZoneKey("VN"):
return fetch_historical_consumption(
datetime.now() - timedelta(days=1), session, logger
)
else:
raise ParserException(
"VN.py",
"No real time data found",
zone_key,
)
elif target_datetime is not None and zone_key is ZoneKey("VN"):
return fetch_historical_consumption(target_datetime, session, logger)
else:
raise NotImplementedError(
"This parser is not yet able to parse past dates for this zone"
)
if __name__ == "__main__":
print("fetch_consumption() ->")
print(fetch_consumption(ZoneKey("VN")))
print("fetch_price() ->")
print(fetch_price(ZoneKey("VN")))