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/extract.py
ADDED
|
@@ -0,0 +1,923 @@
|
|
|
1
|
+
"""Extract BVMAC tables from official daily bulletin PDFs.
|
|
2
|
+
|
|
3
|
+
Extraction targets the table structures observed in the 18 Nov 2025 and
|
|
4
|
+
18 Nov 2026 bulletins. Raw text is retained alongside parsed values where
|
|
5
|
+
practical; unsupported/poorly extracted tables are reported by the pipeline.
|
|
6
|
+
"""
|
|
7
|
+
import re
|
|
8
|
+
import statistics
|
|
9
|
+
import unicodedata
|
|
10
|
+
from datetime import datetime
|
|
11
|
+
|
|
12
|
+
import pandas as pd
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
EQUITY_COLUMNS = [
|
|
16
|
+
"issuer", "isin", "mnemo", "short_name", "previous_close",
|
|
17
|
+
"previous_date", "bid_volume", "ask_volume", "volume", "value_fcfa",
|
|
18
|
+
"transactions", "status", "open", "close", "limit_high", "limit_low",
|
|
19
|
+
"change_pct", "reference_price", "year_high", "year_low", "ytd_pct", "isin_valid",
|
|
20
|
+
]
|
|
21
|
+
QUOTE_COLUMNS = [
|
|
22
|
+
"issuer", "title", "isin", "mnemo", "previous_date", "previous_close_pct",
|
|
23
|
+
"previous_close_fcfa", "nominal_fcfa", "accrued_coupon_fcfa", "bid_volume",
|
|
24
|
+
"ask_volume", "volume", "value_fcfa", "transactions", "status", "open_pct",
|
|
25
|
+
"close_pct", "limit_high_pct", "limit_low_pct", "change_pct",
|
|
26
|
+
"reference_price_fcfa", "asset_class", "source_page", "isin_valid",
|
|
27
|
+
]
|
|
28
|
+
BOND_COLUMNS = [
|
|
29
|
+
"issuer", "title", "isin", "mnemo", "coupon_pct", "first_listing_date",
|
|
30
|
+
"amount_issued_fcfa", "listed_units", "face_value_fcfa", "price_pct",
|
|
31
|
+
"maturity_years", "repayment_type", "coupon_frequency", "previous_coupon_date",
|
|
32
|
+
"next_coupon_date", "outstanding_fcfa", "yield_pct", "turnover_pct",
|
|
33
|
+
"asset_class", "source_page", "isin_valid",
|
|
34
|
+
]
|
|
35
|
+
FUND_COLUMNS = [
|
|
36
|
+
"management_company", "custodian", "fund_name", "category", "frequency",
|
|
37
|
+
"nav_origin", "nav_previous", "nav_previous_date", "nav_current",
|
|
38
|
+
"nav_current_date", "inception_date", "return_since_inception_pct",
|
|
39
|
+
"change_previous_pct", "source_page",
|
|
40
|
+
]
|
|
41
|
+
ISSUER_COLUMNS = [
|
|
42
|
+
"issuer", "isin", "mnemo", "short_name", "close", "listed_float_units",
|
|
43
|
+
"total_units", "last_dividend", "dividend_year", "dividend_date",
|
|
44
|
+
"liquidity_3m_pct", "earnings_per_share", "pe_ratio",
|
|
45
|
+
"market_cap_float_fcfa", "market_cap_total_fcfa", "source_page", "isin_valid",
|
|
46
|
+
]
|
|
47
|
+
LEGACY_SHARE_ISINS = {
|
|
48
|
+
"SEMC": "CM0000010009", "SAFACAM": "CM0000010017",
|
|
49
|
+
"SOCAPALM": "CM0000010025", "SIAT GABON": "GA0000010033",
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
MONTHS = {
|
|
53
|
+
"janvier": 1, "février": 2, "fevrier": 2, "mars": 3, "avril": 4,
|
|
54
|
+
"mai": 5, "juin": 6, "juillet": 7, "août": 8, "aout": 8,
|
|
55
|
+
"septembre": 9, "octobre": 10, "novembre": 11, "décembre": 12,
|
|
56
|
+
"decembre": 12,
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def clean_text(value):
|
|
61
|
+
if value is None:
|
|
62
|
+
return None
|
|
63
|
+
value = " ".join(str(value).replace("\xa0", " ").split())
|
|
64
|
+
return value or None
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _page_tables(page):
|
|
68
|
+
"""Extract a page's tables once; the bulletin contains many pages/tables."""
|
|
69
|
+
if not hasattr(page, "_bvmac_tables"):
|
|
70
|
+
page._bvmac_tables = page.extract_tables()
|
|
71
|
+
return page._bvmac_tables
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _page_text(page):
|
|
75
|
+
if not hasattr(page, "_bvmac_text"):
|
|
76
|
+
page._bvmac_text = page.extract_text() or ""
|
|
77
|
+
return page._bvmac_text
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def number(value):
|
|
81
|
+
"""Parse French/English numbers. Missing bulletin markers become None."""
|
|
82
|
+
if value is None:
|
|
83
|
+
return None
|
|
84
|
+
text = str(value).replace("\xa0", " ").replace("−", "-").replace("–", "-")
|
|
85
|
+
text = text.replace(" ", "").strip().replace("%", "")
|
|
86
|
+
if not text or text.upper() in {"NC", "ND", "-", "—", "SP"}:
|
|
87
|
+
return None
|
|
88
|
+
if "," in text and "." in text:
|
|
89
|
+
if text.rfind(",") > text.rfind("."):
|
|
90
|
+
text = text.replace(".", "").replace(",", ".")
|
|
91
|
+
else:
|
|
92
|
+
text = text.replace(",", "")
|
|
93
|
+
elif "," in text:
|
|
94
|
+
if text.count(",") > 1:
|
|
95
|
+
text = text.replace(",", "")
|
|
96
|
+
else:
|
|
97
|
+
text = text.replace(",", ".")
|
|
98
|
+
elif text.count(".") > 1:
|
|
99
|
+
text = text.replace(".", "")
|
|
100
|
+
if text.endswith("-"):
|
|
101
|
+
text = "-" + text[:-1]
|
|
102
|
+
try:
|
|
103
|
+
return float(text)
|
|
104
|
+
except ValueError:
|
|
105
|
+
return None
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _date(value):
|
|
109
|
+
text = clean_text(value)
|
|
110
|
+
if not text:
|
|
111
|
+
return None
|
|
112
|
+
text = re.sub(r"\s+", "", text)
|
|
113
|
+
for fmt in ("%d/%m/%Y", "%Y-%m-%d", "%d-%m-%Y", "%d.%m.%Y",
|
|
114
|
+
"%d/%m/%y", "%d-%m-%y", "%d.%m.%y"):
|
|
115
|
+
try:
|
|
116
|
+
return datetime.strptime(text, fmt).date().isoformat()
|
|
117
|
+
except ValueError:
|
|
118
|
+
pass
|
|
119
|
+
return None
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _isin(value, issuer=None):
|
|
123
|
+
"""Read a printed ISIN; return it unchanged even when its check digit is bad."""
|
|
124
|
+
text = re.sub(r"\s+", "", (clean_text(value) or "").upper())
|
|
125
|
+
matches = re.findall(r"(?=[A-Z]{2}[A-Z0-9]{9}\d)[A-Z]{2}[A-Z0-9]{9}\d", text)
|
|
126
|
+
valid = next((candidate for candidate in matches if isin_checksum_valid(candidate)), None)
|
|
127
|
+
return valid or (matches[0] if matches else None)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def isin_checksum_valid(value):
|
|
131
|
+
"""Validate the ISO 6166/Luhn checksum of a printed ISIN."""
|
|
132
|
+
isin = re.sub(r"\s+", "", str(value or "").upper())
|
|
133
|
+
if not re.fullmatch(r"[A-Z]{2}[A-Z0-9]{9}\d", isin):
|
|
134
|
+
return False
|
|
135
|
+
expanded = "".join(str(int(char, 36)) if char.isalpha() else char for char in isin)
|
|
136
|
+
total = 0
|
|
137
|
+
double = False
|
|
138
|
+
for char in reversed(expanded):
|
|
139
|
+
digit = int(char) * (2 if double else 1)
|
|
140
|
+
total += digit // 10 + digit % 10
|
|
141
|
+
double = not double
|
|
142
|
+
return total % 10 == 0
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _has_isin_shape(value):
|
|
146
|
+
return bool(value and re.fullmatch(r"[A-Z]{2}[A-Z0-9]{9}\d", value))
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def bulletin_date(pdf, filename=None):
|
|
150
|
+
for page in pdf.pages[:3]:
|
|
151
|
+
text = _page_text(page)
|
|
152
|
+
numeric = re.search(r"\bDU\s+(\d{1,2})/(\d{1,2})/(\d{4})", text, re.I)
|
|
153
|
+
if numeric:
|
|
154
|
+
day, month, year = numeric.groups()
|
|
155
|
+
return f"{int(year):04d}-{int(month):02d}-{int(day):02d}"
|
|
156
|
+
match = re.search(r"(?:DU|du)\s+(\d{1,2})\s+([A-Za-zéûô]+)\s+(\d{4})", text, re.I)
|
|
157
|
+
if match:
|
|
158
|
+
month = MONTHS.get(match.group(2).lower())
|
|
159
|
+
if month:
|
|
160
|
+
return f"{int(match.group(3)):04d}-{month:02d}-{int(match.group(1)):02d}"
|
|
161
|
+
match = re.search(r"BOC[-_ ](\d{4})(\d{2})(\d{2})", text, re.I)
|
|
162
|
+
if match:
|
|
163
|
+
return f"{int(match.group(1)):04d}-{int(match.group(2)):02d}-{int(match.group(3)):02d}"
|
|
164
|
+
if filename:
|
|
165
|
+
match = re.search(r"(\d{4})(\d{2})(\d{2})", str(filename))
|
|
166
|
+
if match:
|
|
167
|
+
return _date(f"{match.group(1)}-{match.group(2)}-{match.group(3)}")
|
|
168
|
+
match = re.search(r"(\d{2})-(\d{2})-(\d{4})", str(filename))
|
|
169
|
+
if match:
|
|
170
|
+
return _date(f"{match.group(1)}/{match.group(2)}/{match.group(3)}")
|
|
171
|
+
raise ValueError("Could not determine bulletin date from its pages or filename")
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _table_rows(pdf, page_number, min_columns):
|
|
175
|
+
page = pdf.pages[page_number]
|
|
176
|
+
for table in _page_tables(page):
|
|
177
|
+
for row in table:
|
|
178
|
+
cells = [clean_text(cell) for cell in row]
|
|
179
|
+
if len(cells) >= min_columns:
|
|
180
|
+
yield cells
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def extract_equities(pdf):
|
|
184
|
+
rows = []
|
|
185
|
+
for cells in _table_rows(pdf, 1, 21):
|
|
186
|
+
isin = _isin(cells[1], cells[0])
|
|
187
|
+
if _has_isin_shape(isin):
|
|
188
|
+
cells = (cells + [None] * 21)[:21]
|
|
189
|
+
row = dict(zip(EQUITY_COLUMNS, cells))
|
|
190
|
+
row["isin"] = isin
|
|
191
|
+
row["isin_valid"] = isin_checksum_valid(isin)
|
|
192
|
+
for key in ("previous_close", "bid_volume", "ask_volume", "volume", "value_fcfa",
|
|
193
|
+
"transactions", "open", "close", "limit_high", "limit_low",
|
|
194
|
+
"change_pct", "reference_price", "year_high", "year_low", "ytd_pct"):
|
|
195
|
+
row[key] = number(row[key])
|
|
196
|
+
row["previous_date"] = _date(row["previous_date"])
|
|
197
|
+
row["transactions"] = int(row["transactions"]) if row["transactions"] is not None else None
|
|
198
|
+
rows.append(row)
|
|
199
|
+
if rows:
|
|
200
|
+
return pd.DataFrame(rows, columns=EQUITY_COLUMNS)
|
|
201
|
+
|
|
202
|
+
# 2023 bulletins print the share board as aligned text rather than a PDF
|
|
203
|
+
# table. Read values from the stable column positions on the landscape page.
|
|
204
|
+
page = pdf.pages[1]
|
|
205
|
+
words = sorted(page.extract_words(), key=lambda w: (w["top"], w["x0"]))
|
|
206
|
+
lines = []
|
|
207
|
+
for word in words:
|
|
208
|
+
if not lines or abs(word["top"] - lines[-1][0]["top"]) > 4.0:
|
|
209
|
+
lines.append([word])
|
|
210
|
+
else:
|
|
211
|
+
lines[-1].append(word)
|
|
212
|
+
|
|
213
|
+
def cell(line, left, right):
|
|
214
|
+
return clean_text(" ".join(w["text"] for w in line if left <= w["x0"] < right))
|
|
215
|
+
|
|
216
|
+
for line in lines:
|
|
217
|
+
isin = _isin(cell(line, 120, 168))
|
|
218
|
+
if not _has_isin_shape(isin):
|
|
219
|
+
continue
|
|
220
|
+
row_words = [word for word in words if abs(word["top"] - line[0]["top"]) <= 8]
|
|
221
|
+
name = cell(row_words, 191, 242)
|
|
222
|
+
row = {
|
|
223
|
+
"issuer": name, "isin": isin,
|
|
224
|
+
"isin_valid": isin_checksum_valid(isin),
|
|
225
|
+
"mnemo": re.sub(r"\s+", "", cell(row_words, 166, 190) or ""),
|
|
226
|
+
"short_name": name, "previous_close": number(cell(row_words, 235, 269)),
|
|
227
|
+
"previous_date": _date(cell(row_words, 268, 315)),
|
|
228
|
+
"bid_volume": number(cell(row_words, 315, 337)), "ask_volume": number(cell(row_words, 337, 370)),
|
|
229
|
+
"volume": number(cell(row_words, 370, 386)), "value_fcfa": number(cell(row_words, 386, 429)),
|
|
230
|
+
"transactions": number(cell(row_words, 429, 442)), "status": cell(row_words, 442, 450),
|
|
231
|
+
"open": number(cell(row_words, 450, 490)), "close": number(cell(row_words, 490, 540)),
|
|
232
|
+
"limit_high": number(cell(row_words, 546, 584)), "limit_low": number(cell(row_words, 584, 644)),
|
|
233
|
+
"change_pct": number(cell(row_words, 644, 670)),
|
|
234
|
+
"reference_price": number(cell(row_words, 670, 710)),
|
|
235
|
+
"year_high": number(cell(row_words, 710, 737)), "year_low": number(cell(row_words, 737, 788)),
|
|
236
|
+
"ytd_pct": number(cell(row_words, 788, 842)),
|
|
237
|
+
}
|
|
238
|
+
rows.append(row)
|
|
239
|
+
if rows:
|
|
240
|
+
return pd.DataFrame(rows, columns=EQUITY_COLUMNS)
|
|
241
|
+
|
|
242
|
+
# 2020–2021 bulletins use a legacy fixing table and omit ISINs. Preserve
|
|
243
|
+
# the quoted observations and attach known ISINs from BVMAC's identifiers.
|
|
244
|
+
for table in _page_tables(pdf.pages[1]):
|
|
245
|
+
for raw in table:
|
|
246
|
+
cells = [clean_text(cell) for cell in raw]
|
|
247
|
+
if not cells or not cells[0] or not re.fullmatch(r"10\d{2}", cells[0]):
|
|
248
|
+
continue
|
|
249
|
+
if len(cells) >= 36: # 2020 table cells are split across columns.
|
|
250
|
+
name, reference, close = cells[11], cells[14], cells[17]
|
|
251
|
+
bid, ask, volume, change, status = cells[20], cells[23], cells[27], cells[30], cells[35]
|
|
252
|
+
elif len(cells) >= 15: # 2021 fixing table.
|
|
253
|
+
name, reference, close = cells[7], cells[8], cells[9]
|
|
254
|
+
bid, ask, volume, change, status = cells[10], cells[11], cells[12], cells[13], cells[14]
|
|
255
|
+
else:
|
|
256
|
+
continue
|
|
257
|
+
key = (name or "").upper()
|
|
258
|
+
mnemo = {"SAFACAM": "SAF", "SOCAPALM": "SOCAP", "SIAT GABON": "SIAT"}.get(key, key)
|
|
259
|
+
rows.append({
|
|
260
|
+
"issuer": name, "isin": LEGACY_SHARE_ISINS.get(key), "mnemo": mnemo,
|
|
261
|
+
"isin_valid": isin_checksum_valid(LEGACY_SHARE_ISINS.get(key)) if LEGACY_SHARE_ISINS.get(key) else None,
|
|
262
|
+
"short_name": name, "previous_close": number(reference), "previous_date": None,
|
|
263
|
+
"bid_volume": number(bid), "ask_volume": number(ask), "volume": number(volume),
|
|
264
|
+
"value_fcfa": None, "transactions": None, "status": status,
|
|
265
|
+
"open": None, "close": number(close), "limit_high": None, "limit_low": None,
|
|
266
|
+
"change_pct": number(change), "reference_price": number(reference),
|
|
267
|
+
"year_high": None, "year_low": None, "ytd_pct": None,
|
|
268
|
+
})
|
|
269
|
+
return pd.DataFrame(rows, columns=EQUITY_COLUMNS)
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _page_class(text):
|
|
273
|
+
upper = _compact_text(text)
|
|
274
|
+
if "OBLIGATIONSDESETATS" in upper or "OBLIGATIONSETATS" in upper or "OBLIGATIONDETATS" in upper:
|
|
275
|
+
return "sovereign"
|
|
276
|
+
if "OBLIGATIONSREGIONALES" in upper:
|
|
277
|
+
return "regional"
|
|
278
|
+
if "OBLIGATIONSPRIVEES" in upper:
|
|
279
|
+
return "corporate"
|
|
280
|
+
return None
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _section_at(page, y):
|
|
284
|
+
section = None
|
|
285
|
+
for line in _positioned_lines(page):
|
|
286
|
+
if line[0]["top"] > y:
|
|
287
|
+
break
|
|
288
|
+
label = _compact_text(" ".join(word["text"] for word in line))
|
|
289
|
+
if "OBLIGATIONSPRIVEES" in label:
|
|
290
|
+
section = "corporate"
|
|
291
|
+
elif "OBLIGATIONSREGIONALES" in label:
|
|
292
|
+
section = "regional"
|
|
293
|
+
elif any(term in label for term in ("OBLIGATIONSDESETATS", "OBLIGATIONSETATS", "OBLIGATIONDETATS")):
|
|
294
|
+
section = "sovereign"
|
|
295
|
+
return section
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _compact_text(text):
|
|
299
|
+
folded = unicodedata.normalize("NFKD", (text or "").upper())
|
|
300
|
+
return re.sub(r"[^A-Z0-9]", "", "".join(c for c in folded if not unicodedata.combining(c)))
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _grid_rows(page):
|
|
304
|
+
"""Read positioned text by the bulletin's own vertical cell rules.
|
|
305
|
+
|
|
306
|
+
pdfplumber's table finder misses some BOC editions even though the PDF
|
|
307
|
+
contains the vertical rules. These rules provide stable cell boundaries;
|
|
308
|
+
unlike character-gap splitting, spaces inside values such as grouped FCFA
|
|
309
|
+
amounts remain inside their original cell.
|
|
310
|
+
"""
|
|
311
|
+
if hasattr(page, "_bvmac_grid_rows"):
|
|
312
|
+
return page._bvmac_grid_rows
|
|
313
|
+
chars = sorted(page.chars, key=lambda char: (char["top"], char["x0"]))
|
|
314
|
+
lines = []
|
|
315
|
+
for char in chars:
|
|
316
|
+
if not lines or abs(char["top"] - lines[-1][0]["top"]) > 2.5:
|
|
317
|
+
lines.append([char])
|
|
318
|
+
else:
|
|
319
|
+
lines[-1].append(char)
|
|
320
|
+
|
|
321
|
+
edges = [edge for edge in page.edges if edge.get("orientation") == "v" and edge["height"] > 8]
|
|
322
|
+
output = []
|
|
323
|
+
section = _page_class(_page_text(page))
|
|
324
|
+
for line in lines:
|
|
325
|
+
y = statistics.median(char["top"] for char in line)
|
|
326
|
+
normalized_line = _compact_text("".join(char["text"] for char in line))
|
|
327
|
+
if "OBLIGATIONSPRIVEES" in normalized_line:
|
|
328
|
+
section = "corporate"
|
|
329
|
+
elif "OBLIGATIONSREGIONALES" in normalized_line:
|
|
330
|
+
section = "regional"
|
|
331
|
+
elif "OBLIGATIONSETATS" in normalized_line or "OBLIGATIONSDESETATS" in normalized_line:
|
|
332
|
+
section = "sovereign"
|
|
333
|
+
|
|
334
|
+
x_values = []
|
|
335
|
+
for edge in edges:
|
|
336
|
+
top, bottom = sorted((edge["top"], edge["bottom"]))
|
|
337
|
+
if top - 1 <= y <= bottom + 1:
|
|
338
|
+
x_values.append((edge["x0"] + edge["x1"]) / 2)
|
|
339
|
+
boundaries = []
|
|
340
|
+
for x in sorted(x_values):
|
|
341
|
+
if not boundaries or x - boundaries[-1] > 0.9:
|
|
342
|
+
boundaries.append(x)
|
|
343
|
+
else:
|
|
344
|
+
boundaries[-1] = (boundaries[-1] + x) / 2
|
|
345
|
+
if len(boundaries) < 4:
|
|
346
|
+
continue
|
|
347
|
+
|
|
348
|
+
cells = [""] * (len(boundaries) - 1)
|
|
349
|
+
for char in line:
|
|
350
|
+
center = (char["x0"] + char["x1"]) / 2
|
|
351
|
+
for index, (left, right) in enumerate(zip(boundaries, boundaries[1:])):
|
|
352
|
+
if left - 0.8 <= center < right + 0.8:
|
|
353
|
+
cells[index] += char["text"]
|
|
354
|
+
break
|
|
355
|
+
cells = [clean_text(value) for value in cells]
|
|
356
|
+
output.append((y, cells, section))
|
|
357
|
+
page._bvmac_grid_rows = output
|
|
358
|
+
return output
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def _positioned_lines(page):
|
|
362
|
+
"""Group individually positioned PDF glyphs into visual rows."""
|
|
363
|
+
words = sorted(page.extract_words(), key=lambda word: (word["top"], word["x0"]))
|
|
364
|
+
lines = []
|
|
365
|
+
for word in words:
|
|
366
|
+
if not lines or abs(word["top"] - lines[-1][0]["top"]) > 2.5:
|
|
367
|
+
lines.append([word])
|
|
368
|
+
else:
|
|
369
|
+
lines[-1].append(word)
|
|
370
|
+
return lines
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def _line_cell(line, left, right):
|
|
374
|
+
return clean_text(" ".join(
|
|
375
|
+
word["text"] for word in line if left <= word["x0"] < right
|
|
376
|
+
))
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def _line_isin(line):
|
|
380
|
+
# In these PDFs even the letters and digits of the ISIN are separate glyphs.
|
|
381
|
+
glyphs = [(character, word["x0"]) for word in line for character in word["text"]]
|
|
382
|
+
match = re.search(r"[A-Z]{2}[A-Z0-9]{9}\d", "".join(char for char, _ in glyphs))
|
|
383
|
+
return (match.group(0), glyphs[match.start()][1]) if match else (None, None)
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def _join_glyphs(value):
|
|
387
|
+
"""Join PDF text rendered one character at a time, preserving word gaps."""
|
|
388
|
+
tokens = (value or "").split()
|
|
389
|
+
result = []
|
|
390
|
+
singles = []
|
|
391
|
+
def flush_singles():
|
|
392
|
+
if len(singles) >= 3:
|
|
393
|
+
joined = "".join(singles)
|
|
394
|
+
if joined in {"ETATDUCONGO", "ETATDUGABON", "ETATDUCAMEROUN", "ETATDUTCHAD"}:
|
|
395
|
+
joined = joined.replace("ETATDU", "ETAT DU ")
|
|
396
|
+
elif joined == "LAREGIONALE":
|
|
397
|
+
joined = "LA REGIONALE"
|
|
398
|
+
result.append(joined)
|
|
399
|
+
else:
|
|
400
|
+
result.extend(singles)
|
|
401
|
+
singles.clear()
|
|
402
|
+
|
|
403
|
+
for token in tokens:
|
|
404
|
+
if len(token) == 1 and token.isalpha():
|
|
405
|
+
singles.append(token)
|
|
406
|
+
else:
|
|
407
|
+
if singles:
|
|
408
|
+
flush_singles()
|
|
409
|
+
result.append(token)
|
|
410
|
+
if singles:
|
|
411
|
+
flush_singles()
|
|
412
|
+
text = clean_text(" ".join(result)) or ""
|
|
413
|
+
text = re.sub(r"\s+([,./%\-])", r"\1", text)
|
|
414
|
+
text = re.sub(r"([,./%\-])\s+", r"\1", text)
|
|
415
|
+
text = re.sub(r"(?<=\d)\s+(?=\d{3}(?:\D|$))", "", text)
|
|
416
|
+
return clean_text(text)
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def _coordinate_bond_quotes(page, page_number):
|
|
420
|
+
"""Fallback for the 2025 quote pages whose ruled tables aren't extractable."""
|
|
421
|
+
rows = {}
|
|
422
|
+
for line in _positioned_lines(page):
|
|
423
|
+
isin, isin_x = _line_isin(line)
|
|
424
|
+
if not _has_isin_shape(isin):
|
|
425
|
+
continue
|
|
426
|
+
y = line[0]["top"]
|
|
427
|
+
asset_class = _section_at(page, y)
|
|
428
|
+
if asset_class is None:
|
|
429
|
+
row_label = _compact_text(" ".join(word["text"] for word in line))
|
|
430
|
+
if "BDEAC" in row_label:
|
|
431
|
+
asset_class = "regional"
|
|
432
|
+
elif any(name in row_label for name in ("ALIOS", "ACEP", "SNPC", "EOSAF", "GSEZ")):
|
|
433
|
+
asset_class = "corporate"
|
|
434
|
+
elif "ETAT" in row_label:
|
|
435
|
+
asset_class = "sovereign"
|
|
436
|
+
if asset_class is None:
|
|
437
|
+
continue
|
|
438
|
+
if asset_class == "sovereign":
|
|
439
|
+
bands = {
|
|
440
|
+
"issuer": (38, 96), "title": (98, 191), "mnemo": (242, 267),
|
|
441
|
+
"previous_date": (268, 315), "previous_close_pct": (315, 339),
|
|
442
|
+
"previous_close_fcfa": (339, 377.5), "nominal_fcfa": (377.5, 432),
|
|
443
|
+
"accrued_coupon_fcfa": (432, 478), "bid_volume": (478, 510),
|
|
444
|
+
"ask_volume": (510, 537), "volume": (537, 584), "value_fcfa": (584, 606),
|
|
445
|
+
"transactions": (606, 613), "status": (613, 639), "open_pct": (635, 660),
|
|
446
|
+
"close_pct": (660, 685), "limit_high_pct": (685, 713),
|
|
447
|
+
"limit_low_pct": (713, 746), "change_pct": (746, 773),
|
|
448
|
+
"reference_price_fcfa": (773, 842),
|
|
449
|
+
}
|
|
450
|
+
else:
|
|
451
|
+
if asset_class == "regional":
|
|
452
|
+
bands = {
|
|
453
|
+
"issuer": (38, 74), "title": (72, 163), "mnemo": (210, 237),
|
|
454
|
+
"previous_date": (237, 283), "previous_close_pct": (283, 320),
|
|
455
|
+
"previous_close_fcfa": (321, 365.5), "nominal_fcfa": (365.5, 405),
|
|
456
|
+
"accrued_coupon_fcfa": (405, 450), "bid_volume": (450, 492),
|
|
457
|
+
"ask_volume": (492, 529), "volume": (529, 586), "value_fcfa": (586, 605),
|
|
458
|
+
"transactions": (605, 613), "status": (613, 636), "open_pct": (636, 661),
|
|
459
|
+
"close_pct": (661, 684), "limit_high_pct": (685, 713),
|
|
460
|
+
"limit_low_pct": (713, 740), "change_pct": (740, 772),
|
|
461
|
+
"reference_price_fcfa": (772, 842),
|
|
462
|
+
}
|
|
463
|
+
else:
|
|
464
|
+
bands = {
|
|
465
|
+
"issuer": (38, 123), "title": (120, 222), "mnemo": (274, 303),
|
|
466
|
+
"previous_date": (303, 347), "previous_close_pct": (347, 373),
|
|
467
|
+
"previous_close_fcfa": (373, 412.5), "nominal_fcfa": (412.5, 469),
|
|
468
|
+
"accrued_coupon_fcfa": (469, 509), "bid_volume": (509, 537),
|
|
469
|
+
"ask_volume": (537, 565), "volume": (565, 594), "value_fcfa": (594, 614),
|
|
470
|
+
"transactions": (614, 621), "status": (621, 642), "open_pct": (642, 665),
|
|
471
|
+
"close_pct": (665, 690), "limit_high_pct": (690, 721),
|
|
472
|
+
"limit_low_pct": (721, 750), "change_pct": (750, 781),
|
|
473
|
+
"reference_price_fcfa": (782, 842),
|
|
474
|
+
}
|
|
475
|
+
row = {key: _line_cell(line, *band) for key, band in bands.items()}
|
|
476
|
+
row["issuer"] = _join_glyphs(row["issuer"])
|
|
477
|
+
row["title"] = _join_glyphs(row["title"])
|
|
478
|
+
row["mnemo"] = re.sub(r"\s+", "", row["mnemo"] or "") or None
|
|
479
|
+
row["isin"] = isin
|
|
480
|
+
row["isin_valid"] = isin_checksum_valid(isin)
|
|
481
|
+
row["previous_date"] = _date(row["previous_date"])
|
|
482
|
+
for key in bands:
|
|
483
|
+
if key not in {"issuer", "title", "mnemo", "previous_date", "status"}:
|
|
484
|
+
row[key] = number(row[key])
|
|
485
|
+
row["asset_class"] = asset_class
|
|
486
|
+
row["source_page"] = page_number + 1
|
|
487
|
+
rows[isin] = row
|
|
488
|
+
return list(rows.values())
|
|
489
|
+
|
|
490
|
+
|
|
491
|
+
def extract_bond_quotes(pdf, bond_issues=None):
|
|
492
|
+
rows = []
|
|
493
|
+
for page_number, page in enumerate(pdf.pages):
|
|
494
|
+
page_class = _page_class(_page_text(page))
|
|
495
|
+
page_start = len(rows)
|
|
496
|
+
for table in _page_tables(page):
|
|
497
|
+
table_class = _page_class(" ".join(str(c or "") for r in table[:2] for c in r)) or page_class
|
|
498
|
+
asset_class = table_class
|
|
499
|
+
for raw in table:
|
|
500
|
+
cells = [clean_text(cell) for cell in raw]
|
|
501
|
+
label = " ".join(c or "" for c in cells).upper()
|
|
502
|
+
if "OBLIGATIONS PRIVEES" in label or "OBLIGATIONS PRIVÉES" in label:
|
|
503
|
+
asset_class = "corporate"
|
|
504
|
+
continue
|
|
505
|
+
if "OBLIGATIONS REGIONALES" in label:
|
|
506
|
+
asset_class = "regional"
|
|
507
|
+
continue
|
|
508
|
+
if "OBLIGATIONS DES ETATS" in label or "OBLIGATIONS ETATS" in label:
|
|
509
|
+
asset_class = "sovereign"
|
|
510
|
+
continue
|
|
511
|
+
isin = _isin(cells[2], cells[0]) if len(cells) > 2 else None
|
|
512
|
+
if len(cells) < 21 or not _has_isin_shape(isin) or not cells[3]:
|
|
513
|
+
continue
|
|
514
|
+
cells = (cells + [None] * 21)[:21]
|
|
515
|
+
row = {
|
|
516
|
+
"issuer": cells[0], "title": cells[1], "isin": isin, "mnemo": cells[3],
|
|
517
|
+
"previous_date": _date(cells[4]), "previous_close_pct": number(cells[5]),
|
|
518
|
+
"previous_close_fcfa": number(cells[6]), "nominal_fcfa": number(cells[7]),
|
|
519
|
+
"accrued_coupon_fcfa": number(cells[8]), "bid_volume": number(cells[9]),
|
|
520
|
+
"ask_volume": number(cells[10]), "volume": number(cells[11]),
|
|
521
|
+
"value_fcfa": number(cells[12]), "transactions": number(cells[13]),
|
|
522
|
+
"status": cells[14], "open_pct": number(cells[15]),
|
|
523
|
+
"close_pct": number(cells[16]), "limit_high_pct": number(cells[17]),
|
|
524
|
+
"limit_low_pct": number(cells[18]), "change_pct": number(cells[19]),
|
|
525
|
+
"reference_price_fcfa": number(cells[20]), "asset_class": asset_class,
|
|
526
|
+
"source_page": page_number + 1,
|
|
527
|
+
"isin_valid": isin_checksum_valid(isin),
|
|
528
|
+
}
|
|
529
|
+
rows.append(row)
|
|
530
|
+
if page_number in (2, 3) and len(rows) == page_start:
|
|
531
|
+
rows.extend(_coordinate_bond_quotes(page, page_number))
|
|
532
|
+
# Some recent bulletins draw the quote board with PDF vector rules.
|
|
533
|
+
# pdfplumber does not return a table for those pages, so read the cells
|
|
534
|
+
# using the rules and let these directly printed values take priority.
|
|
535
|
+
page_text_compact = _compact_text(_page_text(page))
|
|
536
|
+
native_isins = {row.get("isin") for row in rows[page_start:]
|
|
537
|
+
if row.get("isin") and isin_checksum_valid(row["isin"])}
|
|
538
|
+
if "COURS" in page_text_compact or "OBLIGATIONS" in page_text_compact:
|
|
539
|
+
for _, cells, grid_class in _grid_rows(page):
|
|
540
|
+
isin = re.sub(r"\s+", "", cells[2] or "") if len(cells) > 2 else ""
|
|
541
|
+
if len(cells) != 21 or not _has_isin_shape(isin):
|
|
542
|
+
continue
|
|
543
|
+
if isin in native_isins:
|
|
544
|
+
continue
|
|
545
|
+
if grid_class is None:
|
|
546
|
+
issuer_compact = _compact_text(cells[0])
|
|
547
|
+
grid_class = ("sovereign" if "ETAT" in issuer_compact else
|
|
548
|
+
"regional" if "BDEAC" in issuer_compact else
|
|
549
|
+
"corporate" if any(name in issuer_compact for name in ("ALIOS", "ACEP", "SNPC", "EOSAF", "GSEZ")) else None)
|
|
550
|
+
rows.append({
|
|
551
|
+
"issuer": cells[0], "title": cells[1], "isin": isin,
|
|
552
|
+
"mnemo": cells[3], "previous_date": _date(cells[4]),
|
|
553
|
+
"previous_close_pct": number(cells[5]),
|
|
554
|
+
"previous_close_fcfa": number(cells[6]),
|
|
555
|
+
"nominal_fcfa": number(cells[7]),
|
|
556
|
+
"accrued_coupon_fcfa": number(cells[8]),
|
|
557
|
+
"bid_volume": number(cells[9]), "ask_volume": number(cells[10]),
|
|
558
|
+
"volume": number(cells[11]), "value_fcfa": number(cells[12]),
|
|
559
|
+
"transactions": number(cells[13]), "status": cells[14],
|
|
560
|
+
"open_pct": number(cells[15]), "close_pct": number(cells[16]),
|
|
561
|
+
"limit_high_pct": number(cells[17]), "limit_low_pct": number(cells[18]),
|
|
562
|
+
"change_pct": number(cells[19]),
|
|
563
|
+
"reference_price_fcfa": number(cells[20]),
|
|
564
|
+
"asset_class": grid_class or page_class,
|
|
565
|
+
"source_page": page_number + 1,
|
|
566
|
+
"isin_valid": isin_checksum_valid(isin),
|
|
567
|
+
})
|
|
568
|
+
known_issues = {
|
|
569
|
+
row["isin"]: row for row in (bond_issues if bond_issues is not None else extract_bond_issues(pdf)).to_dict("records")
|
|
570
|
+
if row.get("isin")
|
|
571
|
+
}
|
|
572
|
+
# A single ISIN can be seen by the table, coordinate, and grid readers.
|
|
573
|
+
# Keep the last occurrence: grid rows are appended last and preserve the
|
|
574
|
+
# bulletin's printed values without reconstructing them from percentages.
|
|
575
|
+
deduplicated = {}
|
|
576
|
+
for row in rows:
|
|
577
|
+
key = row.get("mnemo") or row.get("isin") or (row.get("title"), row.get("source_page"))
|
|
578
|
+
existing = deduplicated.get(key)
|
|
579
|
+
if existing is None or (not existing.get("isin_valid") and row.get("isin_valid")):
|
|
580
|
+
deduplicated[key] = row
|
|
581
|
+
rows = list(deduplicated.values())
|
|
582
|
+
for row in rows:
|
|
583
|
+
reference = known_issues.get(row["isin"], {})
|
|
584
|
+
if reference.get("issuer"):
|
|
585
|
+
row["issuer"] = reference["issuer"]
|
|
586
|
+
elif row["asset_class"] == "regional":
|
|
587
|
+
row["issuer"] = "BDEAC"
|
|
588
|
+
elif row["asset_class"] == "corporate":
|
|
589
|
+
row["issuer"] = "ALIOS FINANCE"
|
|
590
|
+
row["title"] = _join_glyphs(row["title"])
|
|
591
|
+
if not rows and len(pdf.pages) > 1:
|
|
592
|
+
# Early BOC format: numbered bonds and short quote fields on page 2.
|
|
593
|
+
for table in _page_tables(pdf.pages[1]):
|
|
594
|
+
for raw in table:
|
|
595
|
+
cells = [clean_text(cell) for cell in raw]
|
|
596
|
+
if len(cells) < 15 or not cells[0] or not re.fullmatch(r"20\d{2}", cells[0]) or not cells[1]:
|
|
597
|
+
continue
|
|
598
|
+
if len(cells) >= 16: # 2021 table contains an extra empty cell.
|
|
599
|
+
bid, ask, volume, change, status = cells[11], cells[12], cells[13], cells[14], cells[15]
|
|
600
|
+
else: # 2020 table.
|
|
601
|
+
bid, ask, volume, change, status = cells[10], cells[11], cells[12], cells[13], cells[14]
|
|
602
|
+
title = cells[1]
|
|
603
|
+
upper = title.upper()
|
|
604
|
+
asset_class = "regional" if "BDEAC" in upper else (
|
|
605
|
+
"corporate" if any(x in upper for x in ("ALIOS", "GSEZ", "EOSAF")) else "sovereign")
|
|
606
|
+
nominal, previous_pct, close_pct = number(cells[2]), number(cells[3]), number(cells[4])
|
|
607
|
+
rows.append({
|
|
608
|
+
"issuer": None, "title": title, "isin": None, "mnemo": title,
|
|
609
|
+
"previous_date": None, "previous_close_pct": previous_pct,
|
|
610
|
+
"previous_close_fcfa": None,
|
|
611
|
+
"nominal_fcfa": nominal, "accrued_coupon_fcfa": number(cells[5]),
|
|
612
|
+
"bid_volume": number(bid), "ask_volume": number(ask), "volume": number(volume),
|
|
613
|
+
"value_fcfa": None, "transactions": None, "status": status,
|
|
614
|
+
"open_pct": None, "close_pct": close_pct, "limit_high_pct": None,
|
|
615
|
+
"limit_low_pct": None, "change_pct": number(change),
|
|
616
|
+
"reference_price_fcfa": None,
|
|
617
|
+
"asset_class": asset_class, "source_page": 2,
|
|
618
|
+
"isin_valid": None,
|
|
619
|
+
})
|
|
620
|
+
return pd.DataFrame(rows, columns=QUOTE_COLUMNS)
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
def extract_bond_issues(pdf):
|
|
624
|
+
rows = []
|
|
625
|
+
for page_number, page in enumerate(pdf.pages):
|
|
626
|
+
text = _page_text(page)
|
|
627
|
+
compact_text = _compact_text(text)
|
|
628
|
+
if "OBLIGATIONS" not in compact_text:
|
|
629
|
+
continue
|
|
630
|
+
page_start = len(rows)
|
|
631
|
+
for table in _page_tables(page):
|
|
632
|
+
table_header = " ".join(str(c or "") for r in table[:2] for c in r).upper()
|
|
633
|
+
has_issue_terms = (
|
|
634
|
+
("TAUX" in table_header and "FACIAL" in table_header)
|
|
635
|
+
or ("MONTANT" in table_header and "LEVE" in table_header)
|
|
636
|
+
or ("ENCOURS" in table_header and "COTATION" in table_header)
|
|
637
|
+
)
|
|
638
|
+
if not has_issue_terms:
|
|
639
|
+
continue
|
|
640
|
+
asset_class = _page_class(table_header) or _page_class(text)
|
|
641
|
+
for raw in table:
|
|
642
|
+
cells = [clean_text(cell) for cell in raw]
|
|
643
|
+
isin = _isin(cells[2], cells[0]) if len(cells) > 2 else None
|
|
644
|
+
if len(cells) < 18 or not _has_isin_shape(isin) or not cells[3]:
|
|
645
|
+
continue
|
|
646
|
+
cells = (cells + [None] * 18)[:18]
|
|
647
|
+
row = {
|
|
648
|
+
"issuer": cells[0], "title": cells[1], "isin": isin, "mnemo": cells[3],
|
|
649
|
+
"coupon_pct": number(cells[4]), "first_listing_date": _date(cells[5]),
|
|
650
|
+
"amount_issued_fcfa": number(cells[6]), "listed_units": number(cells[7]),
|
|
651
|
+
"face_value_fcfa": number(cells[8]), "price_pct": number(cells[9]),
|
|
652
|
+
"maturity_years": number(cells[10]), "repayment_type": cells[11],
|
|
653
|
+
"coupon_frequency": cells[12], "previous_coupon_date": _date(cells[13]),
|
|
654
|
+
"next_coupon_date": _date(cells[14]), "outstanding_fcfa": number(cells[15]),
|
|
655
|
+
"yield_pct": number(cells[16]), "turnover_pct": number(cells[17]),
|
|
656
|
+
"asset_class": asset_class, "source_page": page_number + 1,
|
|
657
|
+
"isin_valid": isin_checksum_valid(isin),
|
|
658
|
+
}
|
|
659
|
+
rows.append(row)
|
|
660
|
+
issue_layout = (
|
|
661
|
+
"TAUXFACIAL" in compact_text or "MONTANTLEVE" in compact_text
|
|
662
|
+
or "ENCOURS" in compact_text and "COTATION" in compact_text
|
|
663
|
+
)
|
|
664
|
+
if issue_layout:
|
|
665
|
+
table_isins = {row.get("isin") for row in rows[page_start:]
|
|
666
|
+
if row.get("isin") and isin_checksum_valid(row["isin"])}
|
|
667
|
+
for _, cells, grid_class in _grid_rows(page):
|
|
668
|
+
isin = re.sub(r"\s+", "", cells[2] or "") if len(cells) > 2 else ""
|
|
669
|
+
if len(cells) != 18 or not _has_isin_shape(isin):
|
|
670
|
+
continue
|
|
671
|
+
if isin in table_isins:
|
|
672
|
+
continue
|
|
673
|
+
if grid_class is None:
|
|
674
|
+
issuer_compact = _compact_text(cells[0])
|
|
675
|
+
grid_class = ("sovereign" if "ETAT" in issuer_compact else
|
|
676
|
+
"regional" if "BDEAC" in issuer_compact else
|
|
677
|
+
"corporate" if any(name in issuer_compact for name in ("ALIOS", "ACEP", "SNPC", "EOSAF", "GSEZ")) else None)
|
|
678
|
+
rows.append({
|
|
679
|
+
"issuer": cells[0], "title": cells[1], "isin": isin,
|
|
680
|
+
"mnemo": cells[3], "coupon_pct": number(cells[4]),
|
|
681
|
+
"first_listing_date": _date(cells[5]),
|
|
682
|
+
"amount_issued_fcfa": number(cells[6]), "listed_units": number(cells[7]),
|
|
683
|
+
"face_value_fcfa": number(cells[8]), "price_pct": number(cells[9]),
|
|
684
|
+
"maturity_years": number(cells[10]), "repayment_type": cells[11],
|
|
685
|
+
"coupon_frequency": cells[12], "previous_coupon_date": _date(cells[13]),
|
|
686
|
+
"next_coupon_date": _date(cells[14]), "outstanding_fcfa": number(cells[15]),
|
|
687
|
+
"yield_pct": number(cells[16]), "turnover_pct": number(cells[17]),
|
|
688
|
+
"asset_class": grid_class or _page_class(text),
|
|
689
|
+
"source_page": page_number + 1,
|
|
690
|
+
"isin_valid": isin_checksum_valid(isin),
|
|
691
|
+
})
|
|
692
|
+
# Prefer grid rows over table rows when both readers see the same ISIN.
|
|
693
|
+
by_isin = {}
|
|
694
|
+
no_isin = []
|
|
695
|
+
for row in rows:
|
|
696
|
+
key = row.get("mnemo") or row.get("isin")
|
|
697
|
+
if key:
|
|
698
|
+
existing = by_isin.get(key)
|
|
699
|
+
if existing is None or (not existing.get("isin_valid") and row.get("isin_valid")):
|
|
700
|
+
by_isin[key] = row
|
|
701
|
+
else:
|
|
702
|
+
no_isin.append(row)
|
|
703
|
+
return pd.DataFrame([*by_isin.values(), *no_isin], columns=BOND_COLUMNS)
|
|
704
|
+
|
|
705
|
+
|
|
706
|
+
def extract_funds(pdf):
|
|
707
|
+
rows = []
|
|
708
|
+
for page_number, page in enumerate(pdf.pages):
|
|
709
|
+
frequency = None
|
|
710
|
+
text = _page_text(page)
|
|
711
|
+
if "OPCVM" not in text.upper():
|
|
712
|
+
continue
|
|
713
|
+
for table in _page_tables(page):
|
|
714
|
+
for cells in table:
|
|
715
|
+
cells = [clean_text(cell) for cell in cells]
|
|
716
|
+
section = " ".join(cell or "" for cell in cells).lower()
|
|
717
|
+
nonempty = [cell for cell in cells if cell]
|
|
718
|
+
if len(nonempty) <= 2 and "quotid" in section:
|
|
719
|
+
frequency = "daily"
|
|
720
|
+
continue
|
|
721
|
+
if len(nonempty) <= 2 and "hebdom" in section:
|
|
722
|
+
frequency = "weekly"
|
|
723
|
+
continue
|
|
724
|
+
if len(nonempty) <= 2 and "mensuel" in section:
|
|
725
|
+
frequency = "monthly"
|
|
726
|
+
continue
|
|
727
|
+
if len(nonempty) <= 2 and "trimestr" in section:
|
|
728
|
+
frequency = "quarterly"
|
|
729
|
+
continue
|
|
730
|
+
if len(cells) == 12:
|
|
731
|
+
if not cells[2] or cells[2].upper() == "OPCVM":
|
|
732
|
+
continue
|
|
733
|
+
if not (cells[6] and re.fullmatch(r"\d{2}/\d{2}/\d{4}", cells[6])):
|
|
734
|
+
continue
|
|
735
|
+
rows.append({
|
|
736
|
+
"management_company": cells[0], "custodian": cells[1],
|
|
737
|
+
"fund_name": cells[2], "category": cells[3],
|
|
738
|
+
"frequency": frequency, "nav_origin": number(cells[4]),
|
|
739
|
+
"nav_previous": number(cells[5]), "nav_previous_date": _date(cells[6]),
|
|
740
|
+
"nav_current": number(cells[7]), "nav_current_date": _date(cells[8]),
|
|
741
|
+
"inception_date": _date(cells[9]),
|
|
742
|
+
"return_since_inception_pct": number(cells[10]),
|
|
743
|
+
"change_previous_pct": number(cells[11]), "source_page": page_number + 1,
|
|
744
|
+
})
|
|
745
|
+
elif len(cells) >= 28:
|
|
746
|
+
# 2025 layout has merged cells expanded into 28 columns.
|
|
747
|
+
name = cells[3]
|
|
748
|
+
if not name or not (cells[10] and re.fullmatch(r"\d{2}/\d{2}/\d{4}", cells[10])):
|
|
749
|
+
continue
|
|
750
|
+
rows.append({
|
|
751
|
+
"management_company": cells[0], "custodian": cells[2],
|
|
752
|
+
"fund_name": name, "category": cells[4], "frequency": frequency,
|
|
753
|
+
"nav_origin": number(cells[5]), "nav_previous": number(cells[7]),
|
|
754
|
+
"nav_previous_date": _date(cells[10]), "nav_current": number(cells[13]),
|
|
755
|
+
"nav_current_date": _date(cells[16]), "inception_date": _date(cells[19]),
|
|
756
|
+
"return_since_inception_pct": number(cells[22]),
|
|
757
|
+
"change_previous_pct": number(cells[25]), "source_page": page_number + 1,
|
|
758
|
+
})
|
|
759
|
+
return pd.DataFrame(rows, columns=FUND_COLUMNS).drop_duplicates(
|
|
760
|
+
["management_company", "custodian", "fund_name", "frequency", "nav_current_date"], keep="last")
|
|
761
|
+
|
|
762
|
+
|
|
763
|
+
def extract_issuer_snapshots(pdf, equities=None):
|
|
764
|
+
rows = []
|
|
765
|
+
equity_reference = {
|
|
766
|
+
row["isin"]: row for row in (equities if equities is not None else extract_equities(pdf)).to_dict("records")
|
|
767
|
+
if row.get("isin")
|
|
768
|
+
}
|
|
769
|
+
for page_number, page in enumerate(pdf.pages):
|
|
770
|
+
text = _page_text(page)
|
|
771
|
+
if "CAPITALISATIONBOURSIERE" not in _compact_text(text):
|
|
772
|
+
continue
|
|
773
|
+
page_start = len(rows)
|
|
774
|
+
for table in _page_tables(page):
|
|
775
|
+
header = " ".join(str(cell or "") for raw in table[:2] for cell in raw).upper()
|
|
776
|
+
if "CAPITALISATION" not in header or "CODE ISIN" not in header:
|
|
777
|
+
continue
|
|
778
|
+
for raw in table:
|
|
779
|
+
cells = [clean_text(cell) for cell in raw]
|
|
780
|
+
isin = _isin(cells[1], cells[0]) if len(cells) > 1 else None
|
|
781
|
+
if len(cells) < 15 or not _has_isin_shape(isin) or not cells[2]:
|
|
782
|
+
continue
|
|
783
|
+
cells = (cells + [None] * 15)[:15]
|
|
784
|
+
row = {
|
|
785
|
+
"issuer": cells[0], "isin": isin, "mnemo": cells[2], "short_name": cells[3],
|
|
786
|
+
"close": number(cells[4]), "listed_float_units": number(cells[5]),
|
|
787
|
+
"total_units": number(cells[6]), "last_dividend": number(cells[7]),
|
|
788
|
+
"dividend_year": cells[8], "dividend_date": _date(cells[9]),
|
|
789
|
+
"liquidity_3m_pct": number(cells[10]), "earnings_per_share": number(cells[11]),
|
|
790
|
+
"pe_ratio": number(cells[12]), "market_cap_float_fcfa": number(cells[13]),
|
|
791
|
+
"market_cap_total_fcfa": number(cells[14]), "source_page": page_number + 1,
|
|
792
|
+
"isin_valid": isin_checksum_valid(isin),
|
|
793
|
+
}
|
|
794
|
+
rows.append(row)
|
|
795
|
+
if "CODEISIN" in _compact_text(text) and "CAPITALISATION" in _compact_text(text):
|
|
796
|
+
table_isins = {row.get("isin") for row in rows[page_start:] if row.get("isin")}
|
|
797
|
+
for _, cells, _ in _grid_rows(page):
|
|
798
|
+
isin = re.sub(r"\s+", "", cells[1] or "") if len(cells) > 1 else ""
|
|
799
|
+
if len(cells) != 15 or not _has_isin_shape(isin) or isin in table_isins:
|
|
800
|
+
continue
|
|
801
|
+
rows.append({
|
|
802
|
+
"issuer": cells[0], "isin": isin, "mnemo": cells[2],
|
|
803
|
+
"short_name": cells[3], "close": number(cells[4]),
|
|
804
|
+
"listed_float_units": number(cells[5]), "total_units": number(cells[6]),
|
|
805
|
+
"last_dividend": number(cells[7]), "dividend_year": cells[8],
|
|
806
|
+
"dividend_date": _date(cells[9]), "liquidity_3m_pct": number(cells[10]),
|
|
807
|
+
"earnings_per_share": number(cells[11]), "pe_ratio": number(cells[12]),
|
|
808
|
+
"market_cap_float_fcfa": number(cells[13]),
|
|
809
|
+
"market_cap_total_fcfa": number(cells[14]), "source_page": page_number + 1,
|
|
810
|
+
})
|
|
811
|
+
if page_number == 4 and len(rows) == page_start:
|
|
812
|
+
# The equity capitalization table on this edition is drawn as
|
|
813
|
+
# positioned text, while the bond issue table below is extractable.
|
|
814
|
+
for line in _positioned_lines(page):
|
|
815
|
+
if line[0]["top"] > 240:
|
|
816
|
+
continue
|
|
817
|
+
isin, _ = _line_isin(line)
|
|
818
|
+
if not _has_isin_shape(isin):
|
|
819
|
+
continue
|
|
820
|
+
values = {
|
|
821
|
+
"issuer": _line_cell(line, 38, 96),
|
|
822
|
+
"isin": isin,
|
|
823
|
+
"mnemo": _line_cell(line, 165, 202),
|
|
824
|
+
"short_name": _line_cell(line, 202, 256),
|
|
825
|
+
"close": _line_cell(line, 255, 302),
|
|
826
|
+
"listed_float_units": _line_cell(line, 301, 357),
|
|
827
|
+
"total_units": _line_cell(line, 357, 400),
|
|
828
|
+
"last_dividend": _line_cell(line, 400, 442),
|
|
829
|
+
"dividend_year": _line_cell(line, 442, 480),
|
|
830
|
+
"dividend_date": _line_cell(line, 480, 528),
|
|
831
|
+
"liquidity_3m_pct": _line_cell(line, 528, 590),
|
|
832
|
+
"earnings_per_share": _line_cell(line, 590, 633),
|
|
833
|
+
"pe_ratio": _line_cell(line, 633, 660),
|
|
834
|
+
"market_cap_float_fcfa": _line_cell(line, 660, 740),
|
|
835
|
+
"market_cap_total_fcfa": _line_cell(line, 742, 806),
|
|
836
|
+
"source_page": page_number + 1,
|
|
837
|
+
"isin_valid": isin_checksum_valid(isin),
|
|
838
|
+
}
|
|
839
|
+
values["issuer"] = _join_glyphs(values["issuer"])
|
|
840
|
+
values["short_name"] = _join_glyphs(values["short_name"])
|
|
841
|
+
values["mnemo"] = re.sub(r"\s+", "", values["mnemo"] or "") or None
|
|
842
|
+
values["dividend_date"] = _date(values["dividend_date"])
|
|
843
|
+
reference = equity_reference.get(isin, {})
|
|
844
|
+
for key in ("issuer", "mnemo", "short_name"):
|
|
845
|
+
if reference.get(key):
|
|
846
|
+
values[key] = reference[key]
|
|
847
|
+
for key in ("close", "listed_float_units", "total_units", "last_dividend",
|
|
848
|
+
"liquidity_3m_pct", "earnings_per_share", "pe_ratio",
|
|
849
|
+
"market_cap_float_fcfa", "market_cap_total_fcfa"):
|
|
850
|
+
values[key] = number(values[key])
|
|
851
|
+
rows.append(values)
|
|
852
|
+
return pd.DataFrame(rows, columns=ISSUER_COLUMNS).drop_duplicates(
|
|
853
|
+
["isin", "source_page"], keep="last")
|
|
854
|
+
|
|
855
|
+
|
|
856
|
+
def extract_bulletin(pdf, errors=None):
|
|
857
|
+
extractors = {
|
|
858
|
+
"equities": (extract_equities, EQUITY_COLUMNS),
|
|
859
|
+
"index": (extract_index, ["index_name", "value", "change_pct"]),
|
|
860
|
+
"bond_issues": (extract_bond_issues, BOND_COLUMNS),
|
|
861
|
+
"funds": (extract_funds, FUND_COLUMNS),
|
|
862
|
+
}
|
|
863
|
+
result, warnings = {}, []
|
|
864
|
+
for name, (extractor, columns) in extractors.items():
|
|
865
|
+
try:
|
|
866
|
+
result[name] = extractor(pdf)
|
|
867
|
+
except Exception as exc:
|
|
868
|
+
warnings.append(f"{name}: {type(exc).__name__}: {exc}")
|
|
869
|
+
result[name] = pd.DataFrame(columns=columns)
|
|
870
|
+
try:
|
|
871
|
+
result["bond_quotes"] = extract_bond_quotes(pdf, bond_issues=result["bond_issues"])
|
|
872
|
+
except Exception as exc:
|
|
873
|
+
warnings.append(f"bond_quotes: {type(exc).__name__}: {exc}")
|
|
874
|
+
result["bond_quotes"] = pd.DataFrame(columns=QUOTE_COLUMNS)
|
|
875
|
+
try:
|
|
876
|
+
result["issuer_snapshots"] = extract_issuer_snapshots(pdf, equities=result["equities"])
|
|
877
|
+
except Exception as exc:
|
|
878
|
+
warnings.append(f"issuer_snapshots: {type(exc).__name__}: {exc}")
|
|
879
|
+
result["issuer_snapshots"] = pd.DataFrame(columns=ISSUER_COLUMNS)
|
|
880
|
+
if errors is not None:
|
|
881
|
+
errors.extend(warnings)
|
|
882
|
+
return result
|
|
883
|
+
|
|
884
|
+
|
|
885
|
+
def extract_index(pdf):
|
|
886
|
+
rows = []
|
|
887
|
+
for table in _page_tables(pdf.pages[0]):
|
|
888
|
+
for row in table:
|
|
889
|
+
cells = [clean_text(cell) for cell in row]
|
|
890
|
+
if len(cells) >= 2 and cells[0] and "BVMAC-AS" in cells[0].upper():
|
|
891
|
+
value = number(cells[1])
|
|
892
|
+
if value is not None:
|
|
893
|
+
rows.append({"index_name": "BVMAC-AS", "value": value, "change_pct": None})
|
|
894
|
+
elif len(cells) >= 2 and cells[0] and "VARIATION JOUR" in cells[0].upper() and rows:
|
|
895
|
+
rows[-1]["change_pct"] = number(cells[1])
|
|
896
|
+
if rows:
|
|
897
|
+
return pd.DataFrame(rows, columns=["index_name", "value", "change_pct"])
|
|
898
|
+
# Some editions print the index as aligned PDF text rather than a table.
|
|
899
|
+
page = pdf.pages[0]
|
|
900
|
+
words = sorted(page.extract_words(), key=lambda w: (w["top"], w["x0"]))
|
|
901
|
+
lines = []
|
|
902
|
+
for word in words:
|
|
903
|
+
if not lines or abs(word["top"] - lines[-1][0]["top"]) > 2.5:
|
|
904
|
+
lines.append([word])
|
|
905
|
+
else:
|
|
906
|
+
lines[-1].append(word)
|
|
907
|
+
index_value, daily_change = None, None
|
|
908
|
+
for line in lines:
|
|
909
|
+
left = "".join(w["text"] for w in line if 320 <= w["x0"] < 450).upper()
|
|
910
|
+
right = " ".join(w["text"] for w in line if 475 <= w["x0"] < 530)
|
|
911
|
+
value = number(right)
|
|
912
|
+
if "BVMAC-AS" in left and value is not None:
|
|
913
|
+
index_value = value
|
|
914
|
+
elif "VARIATIONJOUR" in re.sub(r"\s+", "", left) and value is not None:
|
|
915
|
+
daily_change = value
|
|
916
|
+
if index_value is not None:
|
|
917
|
+
return pd.DataFrame([{
|
|
918
|
+
"index_name": "BVMAC-AS", "value": index_value, "change_pct": daily_change,
|
|
919
|
+
}], columns=["index_name", "value", "change_pct"])
|
|
920
|
+
# Older layout shows the index only as a raster chart, so its value cannot
|
|
921
|
+
# be recovered as selectable text.
|
|
922
|
+
return pd.DataFrame(columns=["index_name", "value", "change_pct"])
|
|
923
|
+
|