bvmac-data 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- bvmac/__init__.py +66 -0
- bvmac/cli.py +30 -0
- bvmac/config.py +9 -0
- bvmac/database.py +213 -0
- bvmac/download.py +137 -0
- bvmac/extract.py +923 -0
- bvmac/pipeline.py +114 -0
- bvmac_data-0.1.0.dist-info/METADATA +216 -0
- bvmac_data-0.1.0.dist-info/RECORD +13 -0
- bvmac_data-0.1.0.dist-info/WHEEL +5 -0
- bvmac_data-0.1.0.dist-info/entry_points.txt +2 -0
- bvmac_data-0.1.0.dist-info/licenses/LICENSE +201 -0
- bvmac_data-0.1.0.dist-info/top_level.txt +1 -0
bvmac/__init__.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Python data access for daily BVMAC market bulletins."""
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
from .database import (
|
|
5
|
+
load_bond_issues, load_bonds, load_equities, load_funds, load_index,
|
|
6
|
+
load_issuer_snapshots, load_prices,
|
|
7
|
+
)
|
|
8
|
+
from . import extract as _extract
|
|
9
|
+
from .config import DEFAULT_DB, DEFAULT_FOLDER
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def update(start=None, end=None, folder=DEFAULT_FOLDER, db_path=DEFAULT_DB, force=False):
|
|
13
|
+
"""Download and process local bulletins for a date range."""
|
|
14
|
+
from .pipeline import update as _update
|
|
15
|
+
return _update(start=start, end=end, folder=folder, db_path=db_path, force=force)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def history(symbol, start, end=None, *, db_path=DEFAULT_DB, folder=DEFAULT_FOLDER):
|
|
19
|
+
"""Fetch/process the requested period if needed, then return share prices.
|
|
20
|
+
|
|
21
|
+
Example: ``bvmac.history("SOCAP", start="2026-01-01")``.
|
|
22
|
+
On first use, the package downloads available official bulletins into its
|
|
23
|
+
private local cache and creates its SQLite database automatically.
|
|
24
|
+
"""
|
|
25
|
+
update(start=start, end=end, folder=folder, db_path=db_path)
|
|
26
|
+
return load_prices(symbol, start=start, end=end, db_path=db_path)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def read_bulletin(pdf_path):
|
|
30
|
+
"""Read one bulletin PDF directly and return its datasets as DataFrames.
|
|
31
|
+
|
|
32
|
+
This does not download files or create a database. For example::
|
|
33
|
+
|
|
34
|
+
bulletin = bvmac.read_bulletin(r"C:\\data\\BOC-20261118.pdf")
|
|
35
|
+
shares = bulletin["equities"]
|
|
36
|
+
"""
|
|
37
|
+
path = Path(pdf_path).expanduser()
|
|
38
|
+
if not path.is_file():
|
|
39
|
+
raise FileNotFoundError(
|
|
40
|
+
f"Bulletin PDF not found at {path}. Check the file path or download the bulletin first."
|
|
41
|
+
)
|
|
42
|
+
import pdfplumber
|
|
43
|
+
|
|
44
|
+
with pdfplumber.open(path) as pdf:
|
|
45
|
+
result = _extract.extract_bulletin(pdf)
|
|
46
|
+
result["date"] = _extract.bulletin_date(pdf, path.name)
|
|
47
|
+
return result
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def download_data(start=None, end=None, *, db_path=DEFAULT_DB, folder=DEFAULT_FOLDER):
|
|
51
|
+
"""Download available bulletins for a date range and build/update the cache.
|
|
52
|
+
|
|
53
|
+
Supply ``start`` for the first historical download. Later calls can omit
|
|
54
|
+
it to continue from the newest date already in the local database.
|
|
55
|
+
Returns the path to the local SQLite database.
|
|
56
|
+
"""
|
|
57
|
+
update(start=start, end=end, db_path=db_path, folder=folder)
|
|
58
|
+
return Path(db_path)
|
|
59
|
+
|
|
60
|
+
__all__ = [
|
|
61
|
+
"load_bond_issues", "load_bonds", "load_equities", "load_funds", "load_index",
|
|
62
|
+
"load_issuer_snapshots", "load_prices",
|
|
63
|
+
"download_data", "history", "read_bulletin", "update",
|
|
64
|
+
]
|
|
65
|
+
__version__ = "0.1.0"
|
|
66
|
+
|
bvmac/cli.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
|
|
3
|
+
from .config import DEFAULT_DB, DEFAULT_FOLDER
|
|
4
|
+
from .pipeline import process_folder, update
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def main():
|
|
8
|
+
parser = argparse.ArgumentParser(description="Download and process BVMAC daily bulletins")
|
|
9
|
+
parser.add_argument("--start", help="first bulletin date YYYY-MM-DD (initial history)")
|
|
10
|
+
parser.add_argument("--end", help="last bulletin date YYYY-MM-DD; defaults to today")
|
|
11
|
+
parser.add_argument("--folder", default=str(DEFAULT_FOLDER), help="where bulletin PDFs are stored")
|
|
12
|
+
parser.add_argument("--db", default=str(DEFAULT_DB), help="SQLite database path")
|
|
13
|
+
parser.add_argument("--no-download", action="store_true", help="process only PDFs already in --folder")
|
|
14
|
+
parser.add_argument("--force", action="store_true", help="reprocess dates already in the database")
|
|
15
|
+
args = parser.parse_args()
|
|
16
|
+
if args.no_download:
|
|
17
|
+
if args.start or args.end:
|
|
18
|
+
parser.error("--start and --end cannot be used with --no-download")
|
|
19
|
+
summary = process_folder(args.folder, args.db, args.force)
|
|
20
|
+
return 1 if summary["failed"] else 0
|
|
21
|
+
else:
|
|
22
|
+
summary = update(args.start, args.end, args.folder, args.db, args.force)
|
|
23
|
+
if summary["processing"]["failed"] or summary["downloads"]["errors"]:
|
|
24
|
+
return 1
|
|
25
|
+
return 0
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
if __name__ == "__main__":
|
|
29
|
+
raise SystemExit(main())
|
|
30
|
+
|
bvmac/config.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
# Keep the cache out of the user's project so they can start from any folder.
|
|
5
|
+
DATA_HOME = Path(os.environ.get("LOCALAPPDATA", Path.home())) / "bvmac-data"
|
|
6
|
+
DEFAULT_DB = DATA_HOME / "bvmac.db"
|
|
7
|
+
DEFAULT_FOLDER = DATA_HOME / "bulletins"
|
|
8
|
+
BASE_URL = "https://www.bvm-ac.org/wp-content/uploads"
|
|
9
|
+
|
bvmac/database.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"""SQLite storage and DataFrame loaders for the standalone BVMAC package."""
|
|
2
|
+
import sqlite3
|
|
3
|
+
from contextlib import closing
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from datetime import datetime
|
|
6
|
+
|
|
7
|
+
import pandas as pd
|
|
8
|
+
|
|
9
|
+
from .config import DEFAULT_DB
|
|
10
|
+
from .extract import BOND_COLUMNS, EQUITY_COLUMNS, FUND_COLUMNS, ISSUER_COLUMNS, QUOTE_COLUMNS
|
|
11
|
+
|
|
12
|
+
DATASETS = {
|
|
13
|
+
"equities": EQUITY_COLUMNS,
|
|
14
|
+
"bond_quotes": QUOTE_COLUMNS,
|
|
15
|
+
"bond_issues": BOND_COLUMNS,
|
|
16
|
+
"funds": FUND_COLUMNS,
|
|
17
|
+
"issuer_snapshots": ISSUER_COLUMNS,
|
|
18
|
+
"index": ["index_name", "value", "change_pct"],
|
|
19
|
+
}
|
|
20
|
+
KEYS = {
|
|
21
|
+
"equities": ["date", "mnemo"], "bond_quotes": ["date", "mnemo"],
|
|
22
|
+
"bond_issues": ["date", "mnemo"],
|
|
23
|
+
"funds": ["date", "management_company", "custodian", "fund_name", "frequency", "nav_current_date"],
|
|
24
|
+
"issuer_snapshots": ["date", "mnemo"], "index": ["date", "index_name"],
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def connect(db_path=DEFAULT_DB):
|
|
29
|
+
db_path = str(db_path)
|
|
30
|
+
if db_path != ":memory:":
|
|
31
|
+
Path(db_path).expanduser().parent.mkdir(parents=True, exist_ok=True)
|
|
32
|
+
con = sqlite3.connect(db_path, timeout=30)
|
|
33
|
+
con.execute("PRAGMA busy_timeout=30000")
|
|
34
|
+
if db_path != ":memory:":
|
|
35
|
+
con.execute("PRAGMA journal_mode=WAL")
|
|
36
|
+
con.execute("PRAGMA synchronous=NORMAL")
|
|
37
|
+
if db_path != ":memory:" and Path(db_path).is_file():
|
|
38
|
+
tables = {row[0] for row in con.execute("SELECT name FROM sqlite_master WHERE type='table'")}
|
|
39
|
+
needs_migration = False
|
|
40
|
+
for table, columns in DATASETS.items():
|
|
41
|
+
if table not in tables:
|
|
42
|
+
continue
|
|
43
|
+
info = con.execute(f'PRAGMA table_info("{table}")').fetchall()
|
|
44
|
+
existing = {row[1] for row in info}
|
|
45
|
+
primary = {row[1] for row in info if row[5]}
|
|
46
|
+
if any(column not in existing for column in columns) or (table == "funds" and "frequency" not in primary):
|
|
47
|
+
needs_migration = True
|
|
48
|
+
break
|
|
49
|
+
if needs_migration:
|
|
50
|
+
backup = Path(db_path).with_name(
|
|
51
|
+
f"{Path(db_path).stem}.pre-migration-{datetime.now():%Y%m%d-%H%M%S}.bak"
|
|
52
|
+
)
|
|
53
|
+
with closing(sqlite3.connect(backup)) as backup_con:
|
|
54
|
+
con.backup(backup_con)
|
|
55
|
+
for table, columns in DATASETS.items():
|
|
56
|
+
defs = ["date TEXT NOT NULL"]
|
|
57
|
+
for col in columns:
|
|
58
|
+
if col in KEYS[table][1:]:
|
|
59
|
+
typ = "TEXT NOT NULL"
|
|
60
|
+
elif col in {"source_page", "transactions"}:
|
|
61
|
+
typ = "INTEGER"
|
|
62
|
+
elif col in {"issuer", "title", "isin", "mnemo", "short_name", "fund_name",
|
|
63
|
+
"management_company", "custodian", "category", "frequency", "status",
|
|
64
|
+
"asset_class", "repayment_type", "coupon_frequency", "previous_date",
|
|
65
|
+
"first_listing_date", "previous_coupon_date", "next_coupon_date",
|
|
66
|
+
"nav_previous_date", "nav_current_date", "inception_date", "dividend_date",
|
|
67
|
+
"dividend_year", "index_name"}:
|
|
68
|
+
typ = "TEXT"
|
|
69
|
+
else:
|
|
70
|
+
typ = "REAL"
|
|
71
|
+
defs.append(f'"{col}" {typ}')
|
|
72
|
+
defs.append("source_file TEXT")
|
|
73
|
+
primary = ", ".join(f'"{key}"' for key in KEYS[table])
|
|
74
|
+
con.execute(f'CREATE TABLE IF NOT EXISTS "{table}" ({", ".join(defs)}, PRIMARY KEY ({primary}))')
|
|
75
|
+
existing = {row[1] for row in con.execute(f'PRAGMA table_info("{table}")')}
|
|
76
|
+
for col in columns:
|
|
77
|
+
if col not in existing:
|
|
78
|
+
typ = "INTEGER" if col in {"source_page", "transactions"} else "REAL"
|
|
79
|
+
if col in {"issuer", "title", "isin", "mnemo", "short_name", "fund_name",
|
|
80
|
+
"management_company", "custodian", "category", "frequency", "status",
|
|
81
|
+
"asset_class", "repayment_type", "coupon_frequency", "previous_date",
|
|
82
|
+
"first_listing_date", "previous_coupon_date", "next_coupon_date",
|
|
83
|
+
"nav_previous_date", "nav_current_date", "inception_date", "dividend_date",
|
|
84
|
+
"dividend_year", "index_name"}:
|
|
85
|
+
typ = "TEXT"
|
|
86
|
+
con.execute(f'ALTER TABLE "{table}" ADD COLUMN "{col}" {typ}')
|
|
87
|
+
_migrate_fund_key(con)
|
|
88
|
+
con.execute("PRAGMA user_version=2")
|
|
89
|
+
return con
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _migrate_fund_key(con):
|
|
93
|
+
"""Add frequency to the fund key after connect() has made a backup."""
|
|
94
|
+
info = con.execute('PRAGMA table_info("funds")').fetchall()
|
|
95
|
+
primary = {row[1] for row in info if row[5]}
|
|
96
|
+
if "frequency" in primary:
|
|
97
|
+
return
|
|
98
|
+
cols = ["date", *FUND_COLUMNS, "source_file"]
|
|
99
|
+
definitions = []
|
|
100
|
+
text_columns = {"date", "management_company", "custodian", "fund_name", "frequency",
|
|
101
|
+
"category", "nav_previous_date", "nav_current_date", "inception_date", "source_file"}
|
|
102
|
+
for col in cols:
|
|
103
|
+
definitions.append(f'"{col}" {"TEXT" if col in text_columns else "REAL"}')
|
|
104
|
+
primary = ', '.join(f'"{key}"' for key in KEYS["funds"])
|
|
105
|
+
con.execute(f'CREATE TABLE funds_migrating ({", ".join(definitions)}, PRIMARY KEY ({primary}))')
|
|
106
|
+
quoted_cols = ", ".join('"' + col + '"' for col in cols)
|
|
107
|
+
con.execute(f'INSERT OR IGNORE INTO funds_migrating ({quoted_cols}) '
|
|
108
|
+
f'SELECT {quoted_cols} FROM funds')
|
|
109
|
+
con.execute('DROP TABLE funds')
|
|
110
|
+
con.execute('ALTER TABLE funds_migrating RENAME TO funds')
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def save_bulletin(con, datasets, day, source_file):
|
|
114
|
+
try:
|
|
115
|
+
for table, columns in DATASETS.items():
|
|
116
|
+
frame = datasets[table].copy()
|
|
117
|
+
if frame.empty:
|
|
118
|
+
continue
|
|
119
|
+
frame = frame.reindex(columns=columns)
|
|
120
|
+
required = KEYS[table][1:]
|
|
121
|
+
before = len(frame)
|
|
122
|
+
frame = frame.dropna(subset=required)
|
|
123
|
+
skipped = before - len(frame)
|
|
124
|
+
if skipped:
|
|
125
|
+
print(f"WARNING {source_file}: skipped {skipped} {table} row(s) missing database key fields")
|
|
126
|
+
if frame.empty:
|
|
127
|
+
continue
|
|
128
|
+
con.execute(f'DELETE FROM "{table}" WHERE date = ?', (day,))
|
|
129
|
+
frame.insert(0, "date", day)
|
|
130
|
+
frame["source_file"] = source_file
|
|
131
|
+
sql_columns = ["date"] + columns + ["source_file"]
|
|
132
|
+
marks = ",".join("?" for _ in sql_columns)
|
|
133
|
+
records = frame[sql_columns].astype(object).where(pd.notna(frame[sql_columns]), None).values.tolist()
|
|
134
|
+
con.executemany(
|
|
135
|
+
f'INSERT OR REPLACE INTO "{table}" ({", ".join(sql_columns)}) VALUES ({marks})', records)
|
|
136
|
+
con.commit()
|
|
137
|
+
except Exception:
|
|
138
|
+
con.rollback()
|
|
139
|
+
raise
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _load(table, start=None, end=None, db_path=DEFAULT_DB, symbol=None):
|
|
143
|
+
if str(db_path) != ":memory:" and not Path(db_path).expanduser().is_file():
|
|
144
|
+
raise FileNotFoundError(
|
|
145
|
+
f"BVMAC database not found at {Path(db_path).expanduser()}. "
|
|
146
|
+
"Build it once with bvmac.download_data(start='YYYY-MM-DD'), "
|
|
147
|
+
"or run bvmac-update with a start date."
|
|
148
|
+
)
|
|
149
|
+
con = connect(db_path)
|
|
150
|
+
conditions, values = [], []
|
|
151
|
+
if start:
|
|
152
|
+
conditions.append("date >= ?")
|
|
153
|
+
values.append(pd.Timestamp(start).date().isoformat())
|
|
154
|
+
if end:
|
|
155
|
+
conditions.append("date <= ?")
|
|
156
|
+
values.append(pd.Timestamp(end).date().isoformat())
|
|
157
|
+
if symbol:
|
|
158
|
+
conditions.append("(mnemo = ? OR isin = ?)")
|
|
159
|
+
values.extend([symbol.upper(), symbol.upper()])
|
|
160
|
+
where = " WHERE " + " AND ".join(conditions) if conditions else ""
|
|
161
|
+
tie_breakers = ", ".join(f'"{key}"' for key in KEYS[table][1:])
|
|
162
|
+
ordering = f' ORDER BY date, {tie_breakers}' if tie_breakers else ' ORDER BY date'
|
|
163
|
+
try:
|
|
164
|
+
df = pd.read_sql_query(f'SELECT * FROM "{table}"{where}{ordering}', con, params=values)
|
|
165
|
+
finally:
|
|
166
|
+
con.close()
|
|
167
|
+
if "date" in df:
|
|
168
|
+
df["date"] = pd.to_datetime(df["date"])
|
|
169
|
+
return df
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def load_equities(symbol=None, start=None, end=None, db_path=DEFAULT_DB):
|
|
173
|
+
"""Load daily BVMAC share market observations; filter by Mnemo or ISIN."""
|
|
174
|
+
return _load("equities", start, end, db_path, symbol)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def load_prices(symbol, start=None, end=None, db_path=DEFAULT_DB):
|
|
178
|
+
"""Return a price history; BVMAC daily bulletins do not publish daily high/low."""
|
|
179
|
+
df = load_equities(symbol, start, end, db_path)
|
|
180
|
+
if df.empty:
|
|
181
|
+
result = pd.DataFrame(columns=["Open", "Close", "Volume", "Value", "Change %", "Year High", "Year Low"])
|
|
182
|
+
result.index.name = "Date"
|
|
183
|
+
return result
|
|
184
|
+
result = df.set_index("date")[["open", "close", "volume", "value_fcfa", "change_pct", "year_high", "year_low"]]
|
|
185
|
+
result.columns = ["Open", "Close", "Volume", "Value", "Change %", "Year High", "Year Low"]
|
|
186
|
+
result.index.name = "Date"
|
|
187
|
+
return result
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def load_index(start=None, end=None, db_path=DEFAULT_DB):
|
|
191
|
+
return _load("index", start, end, db_path)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def load_bonds(symbol=None, start=None, end=None, db_path=DEFAULT_DB):
|
|
195
|
+
"""Load daily bond quotes. The symbol can be the bond Mnemo or ISIN."""
|
|
196
|
+
return _load("bond_quotes", start, end, db_path, symbol)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def load_bond_issues(symbol=None, start=None, end=None, db_path=DEFAULT_DB):
|
|
200
|
+
"""Load issue terms such as coupon, maturity, and outstanding amount."""
|
|
201
|
+
return _load("bond_issues", start, end, db_path, symbol)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def load_funds(name=None, start=None, end=None, db_path=DEFAULT_DB):
|
|
205
|
+
df = _load("funds", start, end, db_path)
|
|
206
|
+
if name and not df.empty:
|
|
207
|
+
df = df[df["fund_name"].str.contains(name, case=False, na=False)]
|
|
208
|
+
return df
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def load_issuer_snapshots(symbol=None, start=None, end=None, db_path=DEFAULT_DB):
|
|
212
|
+
return _load("issuer_snapshots", start, end, db_path, symbol)
|
|
213
|
+
|
bvmac/download.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""Download dated BVMAC official bulletins."""
|
|
2
|
+
from datetime import date, datetime, timedelta
|
|
3
|
+
import os
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from urllib.parse import urlparse
|
|
6
|
+
|
|
7
|
+
import requests
|
|
8
|
+
from requests.adapters import HTTPAdapter
|
|
9
|
+
from urllib3.util.retry import Retry
|
|
10
|
+
|
|
11
|
+
from .config import BASE_URL, DEFAULT_FOLDER
|
|
12
|
+
|
|
13
|
+
_SESSION = requests.Session()
|
|
14
|
+
_SESSION.headers.update({"User-Agent": "bvmac-data/0.1 (+https://github.com/)"})
|
|
15
|
+
_SESSION.mount("https://", HTTPAdapter(max_retries=Retry(
|
|
16
|
+
total=3, connect=3, read=3, backoff_factor=0.5,
|
|
17
|
+
status_forcelist=(429, 500, 502, 503, 504), allowed_methods=("GET",))))
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def to_date(value):
|
|
21
|
+
if isinstance(value, datetime):
|
|
22
|
+
return value.date()
|
|
23
|
+
if isinstance(value, date):
|
|
24
|
+
return value
|
|
25
|
+
return date.fromisoformat(str(value))
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def bulletin_url(day):
|
|
29
|
+
"""Return the most likely official URL for a bulletin date."""
|
|
30
|
+
day = to_date(day)
|
|
31
|
+
return bulletin_url_candidates(day)[0]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def bulletin_url_candidates(day):
|
|
35
|
+
"""Try the date-specific naming variants used in BVMAC's PDF archive.
|
|
36
|
+
|
|
37
|
+
Through early 2023, examples use ``BOC-BVMAC-DD-MM-YYYY.pdf``. Later
|
|
38
|
+
bulletins use ``BOC-YYYYMMDD.pdf``. The second candidate covers the
|
|
39
|
+
transition period and occasional archive exceptions.
|
|
40
|
+
"""
|
|
41
|
+
day = to_date(day)
|
|
42
|
+
compact = f"BOC-{day:%Y%m%d}.pdf"
|
|
43
|
+
legacy = f"BOC-BVMAC-{day:%d-%m-%Y}.pdf"
|
|
44
|
+
names = [legacy, compact] if day < date(2023, 6, 1) else [compact, legacy]
|
|
45
|
+
return [f"{BASE_URL}/{day:%Y/%m}/{name}" for name in names]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def bulletin_filenames(day):
|
|
49
|
+
return [Path(urlparse(url).path).name for url in bulletin_url_candidates(day)]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _looks_like_complete_pdf(path):
|
|
53
|
+
if not path.is_file() or path.stat().st_size < 20:
|
|
54
|
+
return False
|
|
55
|
+
with path.open("rb") as local_pdf:
|
|
56
|
+
if local_pdf.read(5) != b"%PDF-":
|
|
57
|
+
return False
|
|
58
|
+
local_pdf.seek(max(0, path.stat().st_size - 2048))
|
|
59
|
+
return b"%%EOF" in local_pdf.read()
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def download_day(day, folder=DEFAULT_FOLDER, timeout=30, force=False):
|
|
63
|
+
"""Download one bulletin. Return its path, or None when no file is published."""
|
|
64
|
+
day = to_date(day)
|
|
65
|
+
folder = Path(folder)
|
|
66
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
67
|
+
for filename in bulletin_filenames(day):
|
|
68
|
+
path = folder / filename
|
|
69
|
+
if not force and _looks_like_complete_pdf(path):
|
|
70
|
+
return path
|
|
71
|
+
errors = []
|
|
72
|
+
for url in bulletin_url_candidates(day):
|
|
73
|
+
try:
|
|
74
|
+
response = _SESSION.get(url, timeout=timeout)
|
|
75
|
+
if response.status_code == 404:
|
|
76
|
+
continue
|
|
77
|
+
if not 200 <= response.status_code < 300:
|
|
78
|
+
errors.append(f"{url}: HTTP {response.status_code}")
|
|
79
|
+
continue
|
|
80
|
+
if not response.content.startswith(b"%PDF"):
|
|
81
|
+
errors.append(f"{url}: response was not a PDF")
|
|
82
|
+
continue
|
|
83
|
+
path = folder / Path(urlparse(url).path).name
|
|
84
|
+
temporary = path.with_suffix(path.suffix + ".part")
|
|
85
|
+
try:
|
|
86
|
+
temporary.write_bytes(response.content)
|
|
87
|
+
os.replace(temporary, path)
|
|
88
|
+
finally:
|
|
89
|
+
if temporary.exists():
|
|
90
|
+
temporary.unlink()
|
|
91
|
+
return path
|
|
92
|
+
except requests.RequestException as exc:
|
|
93
|
+
errors.append(f"{url}: {exc}")
|
|
94
|
+
continue
|
|
95
|
+
if errors:
|
|
96
|
+
raise RuntimeError("No bulletin URL succeeded: " + "; ".join(errors))
|
|
97
|
+
return None
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def download_range(start, end, folder=DEFAULT_FOLDER, force=False, verbose=True):
|
|
101
|
+
"""Try each weekday in an inclusive range, skipping unpublished bulletins."""
|
|
102
|
+
start, end = to_date(start), to_date(end)
|
|
103
|
+
if end < start:
|
|
104
|
+
raise ValueError("end must be on or after start")
|
|
105
|
+
result = {"saved": 0, "already": 0, "missing": 0, "errors": []}
|
|
106
|
+
day = start
|
|
107
|
+
while day <= end:
|
|
108
|
+
legacy_schedule = day.year < 2023 and day.weekday() in {1, 3}
|
|
109
|
+
if day.weekday() < 5 and not legacy_schedule:
|
|
110
|
+
existed = any(
|
|
111
|
+
_looks_like_complete_pdf(Path(folder) / name)
|
|
112
|
+
for name in bulletin_filenames(day)
|
|
113
|
+
)
|
|
114
|
+
try:
|
|
115
|
+
found = download_day(day, folder, force=force)
|
|
116
|
+
if found is None:
|
|
117
|
+
result["missing"] += 1
|
|
118
|
+
if verbose:
|
|
119
|
+
print(f"NO FILE {day:%Y-%m-%d}")
|
|
120
|
+
elif existed and not force:
|
|
121
|
+
result["already"] += 1
|
|
122
|
+
if verbose:
|
|
123
|
+
print(f"ALREADY IN FOLDER {found.name}")
|
|
124
|
+
else:
|
|
125
|
+
result["saved"] += 1
|
|
126
|
+
if verbose:
|
|
127
|
+
print(f"DOWNLOADED {found.name}")
|
|
128
|
+
except Exception as exc:
|
|
129
|
+
result["errors"].append((day.isoformat(), str(exc)))
|
|
130
|
+
if verbose:
|
|
131
|
+
print(f"ERROR {day:%Y-%m-%d}: {exc}")
|
|
132
|
+
day += timedelta(days=1)
|
|
133
|
+
summary = {key: value for key, value in result.items() if key != "errors"}
|
|
134
|
+
summary["errors"] = len(result["errors"])
|
|
135
|
+
print("Download finished: " + ", ".join(f"{v} {k}" for k, v in summary.items()))
|
|
136
|
+
return result
|
|
137
|
+
|