Newer
Older
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
#! /usr/bin/env python3
# entsoe-fetcher -- Download and convert data from ENTSOE
# By: DBnomics team <contact@nomics.world>
#
# Copyright (C) 2020 Cepremap
# https://git.nomics.world/dbnomics-fetchers/entsoe-fetcher
#
# entsoe-fetcher is free software; you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# entsoe-fetcher is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Download data from ENTSOE, write it in a target directory.
See also `.gitlab-ci.yml` in which data is committed to a Git repository of source data.
"""
import argparse
import http.client
import logging
import os
import sys
from datetime import datetime
from pathlib import Path
from typing import List
import pandas as pd
import entsoe
API_KEY_NAME = "WEB_SECURITY_TOKEN"
log = logging.getLogger(__name__)
COUNTRY_CODES = ["FR", "IT", "DE"]
def download_actual_generation_per_type_daily_per_country_year(
client, country_code, year
):
# date interval
start = pd.Timestamp(f"{year}01010000", tz="Europe/Brussels")
end = pd.Timestamp(f"{year}12312359", tz="Europe/Brussels")
# query
df = client.query_generation(country_code, start=start, end=end)
# resample hourly data to daily data
return df.resample("D").sum()
def download_actual_generation_per_type_daily(
api_key, country_code_list: List[str], year_interval: List[int], target_dir: Path
):
target_dir.mkdir(exist_ok=True)
client = entsoe.EntsoePandasClient(api_key=api_key)
for country_code in country_code_list:
for year in year_interval:
log.info("Download data for %s (%d)", country_code, year)
csv_filepath = target_dir / f"AGPT_{country_code}_{year}.csv"
if not csv_filepath.exists():
df = download_actual_generation_per_type_daily_per_country_year(
client, country_code, year
)
df.to_csv(csv_filepath, date_format="%Y-%m-%d")
log = logging.getLogger(__name__)
def main():
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument("target_dir", type=Path, help="path of target directory")
parser.add_argument(
"--start-year", type=int, help="start year if different from current year"
)
parser.add_argument(
"--debug-http", action="store_true", help="display http.client debug messages"
)
parser.add_argument("--log", default="WARNING", help="level of logging messages")
args = parser.parse_args()
numeric_level = getattr(logging, args.log.upper(), None)
if not isinstance(numeric_level, int):
raise ValueError("Invalid log level: {}".format(args.log))
logging.basicConfig(
format="%(levelname)s:%(name)s:%(asctime)s:%(message)s",
level=numeric_level,
stream=sys.stdout, # Use stderr if script outputs data to stdout.
)
logging.getLogger("urllib3").setLevel(
logging.DEBUG if args.debug_http else logging.WARNING
)
if args.debug_http:
http.client.HTTPConnection.debuglevel = 1
target_dir = args.target_dir
if not target_dir.exists():
parser.error("Target dir %r not found", target_dir)
current_year = datetime.today().year
start_year = (
args.start_year
if args.start_year and args.start_year < current_year
else current_year
)
year_interval = list(range(start_year, current_year + 1))
# Get API token
api_key = os.environ.get(API_KEY_NAME)
if not api_key:
log.error("Please define %r env variable", API_KEY_NAME)
sys.exit(1)
# download actual generation per type
log.info("Processing [AGPT]")
download_actual_generation_per_type_daily(
api_key, COUNTRY_CODES, year_interval, target_dir / "AGPT"
)
return 0
if __name__ == "__main__":
sys.exit(main())