-
Notifications
You must be signed in to change notification settings - Fork 924
/
NZ.py
140 lines (117 loc) · 4.79 KB
/
NZ.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
#!/usr/bin/env python3
# The datetime library is used to handle datetimes
import json
from datetime import datetime, timezone
from logging import Logger, getLogger
from bs4 import BeautifulSoup
# The request library is used to fetch content through HTTP
from requests import Session
time_zone = "Pacific/Auckland"
NZ_PRICE_REGIONS = set(range(1, 14))
PRODUCTION_URL = "https://www.transpower.co.nz/system-operator/live-system-and-market-data/consolidated-live-data"
PRICE_URL = "https://api.em6.co.nz/ords/em6/data_api/region/price/"
def fetch(session: Session | None = None):
r = session or Session()
url = PRODUCTION_URL
response = r.get(url)
soup = BeautifulSoup(response.text, "html.parser")
for item in soup.find_all("script"):
if item.attrs.get("data-drupal-selector"):
body = item.contents[0]
obj = json.loads(body)
return obj
def fetch_price(
zone_key: str = "NZ",
session: Session | None = None,
target_datetime: datetime | None = None,
logger: Logger = getLogger(__name__),
) -> dict:
"""
Requests the current price of electricity based on the zone key.
Note that since EM6 breaks the electricity price down into regions,
the regions are averaged out for each island.
"""
if target_datetime:
raise NotImplementedError(
"This parser is not able to retrieve data for past dates"
)
r = session or Session()
url = PRICE_URL
response = r.get(url, verify=False)
obj = response.json()
region_prices = []
regions = NZ_PRICE_REGIONS
for item in obj.get("items"):
region = item.get("grid_zone_id")
if region in regions:
time = item.get("timestamp")
price = float(item.get("price"))
region_prices.append(price)
avg_price = sum(region_prices) / len(region_prices)
date_time = datetime.strptime(time, "%Y-%m-%dT%H:%M:%SZ").replace(
tzinfo=timezone.utc
)
return {
"datetime": date_time,
"price": avg_price,
"currency": "NZD",
"source": "api.em6.co.nz",
"zoneKey": zone_key,
}
def fetch_production(
zone_key: str = "NZ",
session: Session | None = None,
target_datetime: datetime | None = None,
logger: Logger = getLogger(__name__),
) -> dict:
"""Requests the last known production mix (in MW) of a given zone."""
if target_datetime:
raise NotImplementedError(
"This parser is not able to retrieve data for past dates"
)
obj = fetch(session)
date_time = datetime.fromtimestamp(obj["soPgenGraph"]["timestamp"], tz=timezone.utc)
region_key = "New Zealand"
productions = obj["soPgenGraph"]["data"][region_key]
data = {
"zoneKey": zone_key,
"datetime": date_time,
"production": {
"coal": productions.get("Coal", {"generation": None})["generation"],
"oil": productions.get("Diesel/Oil", {"generation": None})["generation"],
"gas": productions.get("Gas", {"generation": None})["generation"],
"geothermal": productions.get("Geothermal", {"generation": None})[
"generation"
],
"wind": productions.get("Wind", {"generation": None})["generation"],
"hydro": productions.get("Hydro", {"generation": None})["generation"],
"solar": productions.get("Solar", {"generation": None})["generation"],
"unknown": productions.get("Co-Gen", {"generation": None})["generation"],
"nuclear": 0, # famous issue in NZ politics
},
"capacity": {
"coal": productions.get("Coal", {"capacity": None})["capacity"],
"oil": productions.get("Diesel/Oil", {"capacity": None})["capacity"],
"gas": productions.get("Gas", {"capacity": None})["capacity"],
"geothermal": productions.get("Geothermal", {"capacity": None})["capacity"],
"wind": productions.get("Wind", {"capacity": None})["capacity"],
"hydro": productions.get("Hydro", {"capacity": None})["capacity"],
"solar": productions.get("Solar", {"capacity": None})["capacity"],
"battery storage": productions.get("Battery", {"capacity": None})[
"capacity"
],
"unknown": productions.get("Co-Gen", {"capacity": None})["capacity"],
"nuclear": 0, # famous issue in NZ politics
},
"storage": {
"battery": productions.get("Battery", {"generation": None})["generation"],
},
"source": "transpower.co.nz",
}
return data
if __name__ == "__main__":
"""Main method, never used by the Electricity Map backend, but handy for testing."""
print("fetch_price(NZ) ->")
print(fetch_price("NZ"))
print("fetch_production(NZ) ->")
print(fetch_production("NZ"))