FrenchCastle commited on
Commit
cbd273f
·
verified ·
1 Parent(s): ee3c628

ISORA FY2014-FY2024 v1.0.0: observations, indicators, indicator_history, jurisdictions, coverage, revisions + card, license, pipeline

Browse files
LICENSE ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ LICENSE AND TERMS OF USE
2
+ ========================
3
+
4
+ This Hugging Face dataset is an UNOFFICIAL, restructured redistribution of data from the
5
+ International Survey on Revenue Administration (ISORA). ISORA is a collaborative product of the
6
+ Asian Development Bank (ADB), the Inter-American Center of Tax Administrations (CIAT), the
7
+ International Monetary Fund (IMF), the Intra-European Organisation of Tax Administrations (IOTA)
8
+ and the Organisation for Economic Co-operation and Development (OECD). The IMF publishes the data
9
+ on behalf of the partner organizations through the ISORA Data Portal (https://isoradata.org,
10
+ hosted at https://data.imf.org).
11
+
12
+ The redistributor is not affiliated with, and this dataset is not endorsed by, the IMF, ADB, CIAT,
13
+ IOTA, the OECD or any participating tax administration.
14
+
15
+ 1. THE DATA
16
+ -----------
17
+ The data (every value in the `observations`, `coverage`, `revisions`, `indicators`,
18
+ `indicator_history` and `jurisdictions` tables, and the source metadata files) remain subject to
19
+ the ISORA Data Portal Terms and Conditions of Data Access and Use and to the IMF Copyright and
20
+ Usage policy. By downloading or using this dataset you accept those terms, reproduced below, in
21
+ addition to anything stated here. In particular (clause A of the ISORA terms) you may publish
22
+ ISORA data provided that the publication source is appropriately acknowledged, and (IMF policy)
23
+ if you materially transform the data you must say so explicitly next to the required source
24
+ citation.
25
+
26
+ The `LICENSE` metadata on the Hugging Face Hub is therefore declared as "other" with the name
27
+ "isora-data-portal-terms". This is NOT an open-source or Creative Commons licence.
28
+
29
+ Required acknowledgement (from the source metadata, adapt the access date):
30
+
31
+ The International Survey on Revenue Administration (ISORA). http://isoradata.org.
32
+ Accessed on [date].
33
+
34
+ Full source citation (from the source metadata):
35
+
36
+ The Asian Development Bank (ADB), the Inter-American Center of Tax Administrations (CIAT);
37
+ the International Monetary Fund (IMF); the Intra-European Organisation of Tax Administrations
38
+ (IOTA); and the Organisation for Economic Co-operation and Development (OECD), International
39
+ Survey on Revenue Administration: https://ISORADATA.ORG
40
+
41
+ Transformation notice: the values in this dataset are those published through the IMF SDMX API,
42
+ reorganised into long-format tables, typed (numeric / text / missing-status), with jurisdiction
43
+ codes harmonised to the alpha-3 codes used by the IMF, monetary amounts additionally expressed in
44
+ base local-currency units, text answers cleaned of HTML fragments and encoding glitches, and
45
+ enriched with metadata (indicator definitions, question evolution, revisions between releases).
46
+ The original published strings are preserved verbatim in the `value_raw` column. See the dataset
47
+ card for the full list of transformations.
48
+
49
+ 2. ISORA DATA PORTAL - TERMS AND CONDITIONS OF DATA ACCESS AND USE
50
+ --------------------------------------------------------------------
51
+ Source: https://data.imf.org/en/Datasets/RAFIT-Consolidated/Terms-and-Conditions
52
+ (retrieved 2026-09-20; the URL is the LICENSE attribute published with every ISORA dataflow
53
+ in the IMF SDMX API). Reproduced verbatim:
54
+
55
+ The data set forth in the ISORA Data Portal (the "Portal") has been supplied by tax
56
+ administrations in accordance with the terms and conditions for participation in ISORA.
57
+ Based on those terms partner organizations (i.e. the Asian Development Bank (ADB), the
58
+ Inter-American Center for Tax Administration [CIAT]; the International Monetary Fund [IMF];
59
+ the Intra-European Organization of Tax Administrations [IOTA]; the Organization for Economic
60
+ Co-operation and Development [OECD]), users are granted access to such data under certain
61
+ conditions. As a User of the portal 1, you agree to the following terms and conditions, as
62
+ may be amended from time to time, with respect to the treatment, dissemination and
63
+ publication of data and information contained on the Portal:
64
+
65
+ A. Users may publish ISORA data, provided that the publication source is appropriately
66
+ acknowledged.
67
+
68
+ B. Users indemnify and hold harmless the ADB, CIAT, the IMF, IOTA, and the OECD from and
69
+ against any and all third party claims concerning the unauthorized use or disclosure of
70
+ information by any Partner Organization, or Participating Revenue Administration, its
71
+ employees, contractors and agents.
72
+
73
+ C. The data on the Portal are provided "as is" and without warranty of any kind, either
74
+ express or implied, including without limitation, warranties of merchantability, fitness for
75
+ a particular purpose, and non-infringement. The IMF disclaims all responsibility for ensuring
76
+ the accuracy, completeness and reliability of data and Information made available on the
77
+ Portal. Reliance on any such data and Information shall be at the User's own risk.
78
+
79
+ D. As administrator of the Portal, the IMF disclaims all responsibility for use of such data
80
+ and information by the users or any associated dissemination tools.
81
+
82
+ E. Use of the Portal is at your own risk. It may not be compatible with all computer systems,
83
+ and the Partner Organizations and the ADB cannot guarantee that data stored on the Portal
84
+ will not be lost.
85
+
86
+ Preservation of Immunities
87
+
88
+ All Partner Organizations, their property, and their assets, are immune from every form of
89
+ judicial process. Nothing herein shall constitute a limitation upon or a waiver of these and
90
+ other privileges and immunities of the Partner Organizations or the ADB, which are
91
+ specifically reserved.
92
+
93
+ These terms and conditions constitute the entire agreement between the parties with respect
94
+ to the subject matter hereof. No waiver or amendment of these terms and conditions shall be
95
+ binding upon the Partner Organizations unless in writing and signed by its duly authorized
96
+ representative.
97
+
98
+ By using the Portal, you agree to these terms and conditions of use, as may be amended from
99
+ time to time.
100
+
101
+ 1 Users are persons issued with access to the Portal and the ability to download data from
102
+ the public ISORA databases.
103
+
104
+ 3. ISORA DATA PORTAL - DISCLAIMER
105
+ ---------------------------------
106
+ Source: https://data.imf.org/en/Datasets/RAFIT-Consolidated/Disclaimer (retrieved 2026-09-20).
107
+ Reproduced verbatim:
108
+
109
+ The data on the ISORA Data Portal ("the Portal") are provided "as is" and without warranty
110
+ of any kind, either express or implied, including without limitation, warranties of
111
+ merchantability, fitness for a particular purposes, and non-infringement. The International
112
+ Monetary Fund (IMF), the Asian Development Bank (ADB), the Inter-American Center of Tax
113
+ Administration, the Intra-European Organisation of Tax Administrations and the Organisation
114
+ for Economic Cooperation and Development disclaim all responsibility for ensuring the
115
+ accuracy, completeness or reliability of data and information made available on the Portal.
116
+ Reliance upon any such data and information shall be at the user's own risk. The user bears
117
+ all responsibility in determining whether these data are fit for the user's intended use.
118
+ The information contained in these data is dynamic and may change over time. These data are
119
+ neither official records, nor legal documents and must not be used as such. Data may be
120
+ updated without notification. Names of countries and territories, as well as any depiction
121
+ of the same, follow IMF practices. Further, any data and map shown on this portal are without
122
+ prejudice to the status of or sovereignty over any territory, to the delimitation of
123
+ international frontiers and boundaries and to the name of any territory, city or area.
124
+
125
+ 4. IMF COPYRIGHT AND USAGE POLICY
126
+ ---------------------------------
127
+ https://www.imf.org/en/about/copyright-and-terms - applies to all IMF data. Key points as
128
+ published there: IMF data may be freely accessed and reused with source citation; any material
129
+ transformation must be stated explicitly along with the source citation; for potential commercial
130
+ reuse of IMF data, email copyright@imf.org to request permission; the data are provided "as is"
131
+ without warranty. Contact copyright@imf.org for any question about these terms.
132
+
133
+ 5. JURISDICTION NAMES
134
+ ---------------------
135
+ Jurisdiction names and codes are reproduced exactly as published in the IMF codelists and follow
136
+ IMF practice. They are without prejudice to the status of or sovereignty over any territory.
137
+
138
+ 6. PIPELINE CODE
139
+ ----------------
140
+ The Python code that builds this dataset (not the data) is released under the MIT License by the
141
+ redistributor. It is shipped separately from the data files.
142
+
143
+ 7. TAKEDOWN
144
+ -----------
145
+ If you represent a partner organization or a participating tax administration and believe any
146
+ part of this redistribution is not permitted, open a discussion on the dataset's Hugging Face
147
+ page and the content will be reviewed promptly.
README.md ADDED
@@ -0,0 +1,512 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pretty_name: ISORA — International Survey on Revenue Administration (FY2014–FY2024)
3
+ license: other
4
+ license_name: isora-data-portal-terms
5
+ license_link: LICENSE
6
+ language:
7
+ - en
8
+ tags:
9
+ - isora
10
+ - international-survey-on-revenue-administration
11
+ - tax-administration
12
+ - revenue-administration
13
+ - tax-authority
14
+ - taxation
15
+ - tax
16
+ - tax-policy
17
+ - tax-compliance
18
+ - tax-collection
19
+ - vat
20
+ - corporate-income-tax
21
+ - personal-income-tax
22
+ - public-finance
23
+ - fiscal-policy
24
+ - government-revenue
25
+ - revenue-statistics
26
+ - economics
27
+ - macroeconomics
28
+ - development-economics
29
+ - public-sector
30
+ - government
31
+ - e-government
32
+ - digitalization
33
+ - imf
34
+ - international-monetary-fund
35
+ - oecd
36
+ - adb
37
+ - ciat
38
+ - iota
39
+ - ra-fit
40
+ - cross-country
41
+ - comparative
42
+ - panel-data
43
+ - time-series
44
+ - survey-data
45
+ - open-government-data
46
+ - sdmx
47
+ annotations_creators:
48
+ - expert-generated
49
+ multilinguality:
50
+ - monolingual
51
+ source_datasets:
52
+ - original
53
+ size_categories:
54
+ - 100K<n<1M
55
+ task_categories:
56
+ - tabular-classification
57
+ - tabular-regression
58
+ configs:
59
+ - config_name: observations
60
+ default: true
61
+ data_files:
62
+ - split: train
63
+ path: data/observations/*.parquet
64
+ - config_name: indicators
65
+ data_files:
66
+ - split: train
67
+ path: data/indicators.parquet
68
+ - config_name: indicator_history
69
+ data_files:
70
+ - split: train
71
+ path: data/indicator_history.parquet
72
+ - config_name: jurisdictions
73
+ data_files:
74
+ - split: train
75
+ path: data/jurisdictions.parquet
76
+ - config_name: coverage
77
+ data_files:
78
+ - split: train
79
+ path: data/coverage.parquet
80
+ - config_name: revisions
81
+ data_files:
82
+ - split: train
83
+ path: data/revisions.parquet
84
+ ---
85
+
86
+ # ISORA — International Survey on Revenue Administration, FY2014–FY2024
87
+
88
+ **Every published answer of every ISORA survey round, in one clean long-format panel**, with the
89
+ metadata you need to use it responsibly: what each question means in each questionnaire
90
+ generation, which questions changed wording (or meaning) between rounds, which jurisdictions
91
+ answered which question in which year, and how published values were revised between releases.
92
+
93
+ ISORA is the joint survey of national tax administrations run by the **Asian Development Bank
94
+ (ADB), the Inter-American Center of Tax Administrations (CIAT), the International Monetary Fund
95
+ (IMF), the Intra-European Organisation of Tax Administrations (IOTA) and the OECD**. It covers
96
+ revenue collections, budgets and staffing, registration, filing and payment, arrears, audit and
97
+ compliance risk management, dispute resolution, taxpayer services, digitalisation, governance and
98
+ institutional arrangements. The IMF publishes the data through the ISORA Data Portal
99
+ ([isoradata.org](https://isoradata.org)), and this dataset is built from the IMF SDMX API that
100
+ sits behind that portal.
101
+
102
+ > **Unofficial redistribution.** This dataset is not produced or endorsed by the IMF, ADB, CIAT,
103
+ > IOTA, the OECD or any tax administration. The data remain subject to the
104
+ > [ISORA Data Portal Terms and Conditions](https://data.imf.org/en/Datasets/RAFIT-Consolidated/Terms-and-Conditions)
105
+ > and the [IMF Copyright and Usage policy](https://www.imf.org/en/about/copyright-and-terms) —
106
+ > read the [`LICENSE`](LICENSE) file. You may publish ISORA data provided the source is
107
+ > acknowledged; see [Citation](#citation-and-acknowledgement).
108
+
109
+ | | |
110
+ |---|---|
111
+ | Observations | **796,601** (`observations` table) |
112
+ | Jurisdictions | **182** tax administrations (alpha-3 codes, IMF practice) |
113
+ | Indicator codes | **1,868** distinct question/answer codes with data |
114
+ | Fiscal years | **FY2014 – FY2024** (eight survey rounds: ISORA 2016 → ISORA 2025) |
115
+ | Tables | `observations` · `indicators` · `indicator_history` · `jurisdictions` · `coverage` · `revisions` |
116
+ | Formats | Parquet (`data/`), gzip CSV copies (`csv/`), build metadata (`metadata/`) |
117
+ | Source snapshot | IMF SDMX API, retrieved 2026-09-20T04:42:35Z |
118
+ | Keywords | ISORA, RA-FIT, tax administration, revenue administration, tax authority, tax agency, IMF Fiscal Affairs Department, OECD Tax Administration Series, CIAT, IOTA, ADB, tax compliance, tax collection, VAT, CIT, PIT, PAYE, tax arrears, tax audit, taxpayer registration, e-filing, e-payment, tax administration staffing, tax administration budget, TADAT, public finance, government revenue, panel data, cross-country comparison |
119
+
120
+ ## Quick start
121
+
122
+ ```python
123
+ from datasets import load_dataset
124
+
125
+ obs = load_dataset("FrenchCastle/isora-tax-administration", "observations", split="train").to_pandas()
126
+ ind = load_dataset("FrenchCastle/isora-tax-administration", "indicators", split="train").to_pandas()
127
+ hist = load_dataset("FrenchCastle/isora-tax-administration", "indicator_history", split="train").to_pandas()
128
+ ```
129
+
130
+ ```python
131
+ import pandas as pd
132
+
133
+ # 1. Pick a question and look at its history across questionnaire generations first.
134
+ hist.set_index("indicator_code").loc["80040_3", ["label_2016", "label_2018", "label_2020plus", "comparability_flag"]]
135
+
136
+ # 2. Build a country × year panel of one indicator (values already in base local-currency units).
137
+ net_revenue = (
138
+ obs[obs.indicator_code == "80040_3"]
139
+ .pivot(index="jurisdiction_code", columns="fiscal_year", values="value_local_currency_units")
140
+ )
141
+
142
+ # 3. Wide table of every numeric indicator for one jurisdiction-year.
143
+ fra_2023 = obs[(obs.jurisdiction_code == "FRA") & (obs.fiscal_year == 2023) & (obs.value_status == "value")]
144
+ fra_2023.pivot(index="indicator_code", columns="fiscal_year", values="value_numeric")
145
+
146
+ # 4. Categorical answers: the closed list of options is in indicators.answer_categories.
147
+ ind.loc[ind.indicator_code == "80700", ["questionnaire_generation", "label", "answer_categories"]]
148
+ ```
149
+
150
+ DuckDB works directly on the Parquet files:
151
+
152
+ ```sql
153
+ SELECT jurisdiction_name, fiscal_year, value_numeric
154
+ FROM 'data/observations/*.parquet'
155
+ WHERE indicator_code = '337_001' -- net revenue collected as % of GDP (derived by ISORA)
156
+ ORDER BY 1, 2;
157
+ ```
158
+
159
+ ## About ISORA
160
+
161
+ ISORA collects tax administration data from national or federal tax administrations through an
162
+ online platform administered by the IMF, using common questions and definitions agreed by the five
163
+ partner organisations. Participation is voluntary; after collection the partners review the data
164
+ for accuracy, completeness and consistency, then publish the finalised round. Participants in
165
+ ISORA 2020 and later rounds agree in advance that all data they provide can be placed in the
166
+ public domain; every row in this dataset carries the source flag `PUBLIC_DATA = true`.
167
+
168
+ | Survey round | Collected in | Fiscal years covered | Participating administrations (as published) |
169
+ |---|---|---|---|
170
+ | ISORA 2016 | 2016 | 2014, 2015 | 135 |
171
+ | ISORA 2018 | 2018 | 2016, 2017 | 159 |
172
+ | ISORA 2020 | 2020 | 2018, 2019 | 156 |
173
+ | ISORA 2021 | 2021 | 2020 | 156 |
174
+ | ISORA 2022 | 2022 | 2021 | 165 |
175
+ | ISORA 2023 | 2023 | 2022 | 166 |
176
+ | ISORA 2024 | 2024 | 2023 | 164 |
177
+ | ISORA 2025 | 2025 | 2024 | 166 |
178
+
179
+ Until 2021 the survey ran every two years and collected two fiscal years at a time. After ISORA
180
+ 2018 the questionnaire was redesigned: a smaller **annual** core is asked every year and a larger
181
+ **periodic** module (governance, human resources, compliance risk management, taxpayer services,
182
+ tax operations) is asked every four years — it was included in ISORA 2023 (FY2022), which is why
183
+ that year has roughly twice as many indicators as its neighbours.
184
+
185
+ The IMF exposes the published data as three SDMX dataflows, one per **questionnaire generation**.
186
+ This dataset keeps that distinction because the question codes and wording differ between them:
187
+
188
+ | Questionnaire generation | Source dataflow | Fiscal years | Rows | Jurisdictions | Indicator codes |
189
+ |---|---|---|---|---|---|
190
+ | ISORA 2016 | `ISORA_2016_DATA_PUB` v2.0.0 | FY2014–FY2015 | 185,360 | 131 | 1,000 |
191
+ | ISORA 2018 | `ISORA_2018_DATA_PUB` v2.0.0 | FY2016–FY2017 | 254,942 | 155 | 1,072 |
192
+ | ISORA 2020+ | `ISORA_LATEST_DATA_PUB` v5.0.0 | FY2018–FY2024 | 356,299 | 182 | 701 |
193
+
194
+ Coverage by fiscal year:
195
+
196
+ | Fiscal year | Collected in | Jurisdictions | Indicator codes | Rows |
197
+ |---|---|---|---|---|
198
+ | 2014 | ISORA 2016 | 131 | 1000 | 92,679 |
199
+ | 2015 | ISORA 2016 | 131 | 999 | 92,681 |
200
+ | 2016 | ISORA 2018 | 155 | 1072 | 127,395 |
201
+ | 2017 | ISORA 2018 | 155 | 1072 | 127,547 |
202
+ | 2018 | ISORA 2020 | 157 | 302 | 40,898 |
203
+ | 2019 | ISORA 2020 | 157 | 304 | 41,306 |
204
+ | 2020 | ISORA 2021 | 165 | 312 | 41,571 |
205
+ | 2021 | ISORA 2022 | 174 | 314 | 43,580 |
206
+ | 2022 | ISORA 2023 | 174 | 675 | 92,313 |
207
+ | 2023 | ISORA 2024 | 164 | 353 | 48,181 |
208
+ | 2024 | ISORA 2025 | 167 | 349 | 48,450 |
209
+
210
+ ## The six tables
211
+
212
+ ### `observations` (default config)
213
+
214
+ One row per *jurisdiction × indicator × fiscal year*. Keys are unique within each questionnaire
215
+ generation and, because fiscal years do not overlap between generations, unique overall.
216
+
217
+ | Column | Type | Description |
218
+ |---|---|---|
219
+ | `jurisdiction_code` | string | Alpha-3 code as used in the IMF ISORA codelists (ISO 3166-1 alpha-3 except `KOS` for Kosovo). ISORA 2016/2018 published numeric IMF codes; they were mapped through the ISO annotation of the IMF codelist. |
220
+ | `jurisdiction_name` | string | Name exactly as published by the IMF (IMF naming practice, without prejudice to the status of any territory). |
221
+ | `fiscal_year` | int16 | Fiscal year the answer refers to. Fiscal-year definitions differ by jurisdiction. |
222
+ | `survey_round` | string | Round in which that fiscal year was first collected (`ISORA 2016` … `ISORA 2025`). Values for earlier years may have been revised in later rounds. |
223
+ | `questionnaire_generation` | string | `ISORA 2016`, `ISORA 2018` or `ISORA 2020+` — which codelist / questionnaire family the `indicator_code` belongs to. **Join to `indicators` on both this and `indicator_code`.** |
224
+ | `indicator_code` | string | Source code of the question or answer cell (e.g. `80040_3`, `337_001`, `PARTICIPATION_RATE`). Codes are reused across generations, sometimes with different wording. |
225
+ | `indicator_label` | string | Label of the code **in that generation's codelist** (denormalised for convenience). |
226
+ | `indicator_value_kind` | string | What this indicator's answers look like in the data: `numeric`, `binary`, `categorical`, `free_text`, `mixed`, `no_values` (inferred from the published values, see below). |
227
+ | `value_raw` | string | The published value, verbatim (before any cleaning). |
228
+ | `value_numeric` | float64 | Parsed number when the published value is numeric, else null. Stored exactly as published (see [Units](#units-and-currency)). |
229
+ | `value_text` | string | Cleaned text answer (HTML fragments removed, encoding glitches repaired, whitespace collapsed), else null. |
230
+ | `value_status` | string | `value`, `not_available`, `not_applicable`, `empty`, `unrecognized_code` (table below). |
231
+ | `unit_multiplier` | int8 | The source `SCALE` attribute (`0` or `3`). |
232
+ | `monetary_unit` | string | `thousands of local currency` (ISORA 2016/2018 money questions), `local currency units` (ISORA 2020+ money questions, i.e. every row with `unit_multiplier = 3`), or null for non-monetary indicators. |
233
+ | `value_local_currency_units` | float64 | **Harmonised money amount in base units of the jurisdiction's currency** (2016/2018 values × 1 000; 2020+ values unchanged). Null for non-monetary indicators. Not converted across currencies. |
234
+ | `form_status` | string | Source workflow flag on the observation (`CERTIFY`, `EDIT`, `REEDIT`) or null. |
235
+ | `footnote` | string | Free-text note published with the observation (cleaned), or null. |
236
+ | `source_dataflow`, `source_dataflow_version` | string | Provenance: which IMF dataflow version the row came from. |
237
+
238
+ | `value_status` | Rows | Share | Meaning |
239
+ |---|---|---|---|
240
+ | `value` | 664,349 | 83.4% | a numeric or text answer is present |
241
+ | `not_available` | 113,785 | 14.3% | the administration answered `D` (data not available) to a numeric question |
242
+ | `not_applicable` | 9,203 | 1.2% | the administration answered *Not Applicable* |
243
+ | `empty` | 7,738 | 1.0% | the cell was published empty |
244
+ | `unrecognized_code` | 1,526 | 0.2% | the published value is the undocumented code `P` (ISORA 2016 only) |
245
+
246
+ | `indicator_value_kind` | Rows | What it means |
247
+ |---|---|---|
248
+ | `numeric` | 455,528 | every published answer is a number |
249
+ | `binary` | 253,326 | answers are Yes / No |
250
+ | `categorical` | 82,533 | answers come from a closed list (≤ 25 distinct values) |
251
+ | `mixed` | 2,856 | numbers and text both occur (usually a category plus a numeric ‘other’) |
252
+ | `no_values` | 2,358 | only `D`, empty or not-applicable cells were published |
253
+
254
+ ### `indicators`
255
+
256
+ One row per *questionnaire generation × indicator code* (3,569 rows), i.e. the three
257
+ source codelists flattened with every annotation the IMF attaches to a code, plus statistics
258
+ computed from the observations. Key columns: `label`, `display_label`, `description` (rarely
259
+ filled at source), `form_code` / `form_name` (the survey form, e.g. *Form F. Operational metrics*),
260
+ `question_ref` (e.g. *Form D - Q2*, ISORA 2020+ only), `section`, `topic_group` / `topic_subgroup`
261
+ (the IMF *Indicators by Topic* hierarchy, ISORA 2020+ only), `report_table_index` /
262
+ `report_table_title` (where the code appears in the IMF review tables), `indicator_type` (the
263
+ source's declared type: binary, count, currency, percent, nominal, ordinal, text, date,
264
+ unspecified — unreliable, see caveats), `observed_value_kind` (inferred from data),
265
+ `answer_categories` (the closed list of answers actually observed, most frequent first),
266
+ `is_derived` / `formula` / `numerator` / `denominator` / `legend` (ISORA-computed ratios such as
267
+ `337_001` *net revenue as % of GDP*), `is_monetary`, `is_local_currency`,
268
+ `label_mentions_thousands`, `is_periodic` (periodic-module question), `is_review_indicator`,
269
+ `n_observations`, `n_observations_with_value`, `n_jurisdictions`, `fiscal_years_with_data`,
270
+ `has_observations` (codelists contain codes that were never published with data).
271
+
272
+ ### `indicator_history`
273
+
274
+ One row per indicator code (2,551 codes) describing how the code appears across the three
275
+ questionnaire generations: `in_2016` / `in_2018` / `in_2020plus`, the label in each generation,
276
+ `label_changed_2016_to_2018`, `label_changed_2018_to_2020plus`, similarity scores of the normalised
277
+ labels (0–1), `n_generations`, `fiscal_years_with_data`, observation counts and a
278
+ `comparability_flag`:
279
+
280
+ | `comparability_flag` | Codes | Meaning |
281
+ |---|---|---|
282
+ | `single_generation` | 1,759 | The code exists in only one questionnaire generation. |
283
+ | `label_stable` | 439 | Present in two or three generations with the same wording (after normalising case, punctuation and spacing). |
284
+ | `label_changed` | 353 | Present in more than one generation **with different wording** — check whether the meaning changed before stitching a time series. |
285
+
286
+ 226 codes exist in all three generations, 566 in two, 1,759 in one.
287
+ 183 codes changed wording between ISORA 2016 and ISORA 2018, 215
288
+ between ISORA 2018 and ISORA 2020+.
289
+
290
+ ### `jurisdictions`
291
+
292
+ One row per jurisdiction with data (182 rows): `jurisdiction_code`, `jurisdiction_name`,
293
+ `imf_numeric_code`, IMF region / sub-region / regional technical-assistance centre, World Bank
294
+ region and **FY2015** income group (a snapshot carried in the IMF codelist, not current), WEO
295
+ group, fragile / small-developing-state flags, membership flags (ADB, CIAT, IOTA, OECD, OECD
296
+ Forum on Tax Administration, EU, G20, G7, WCO, WAEMU) as recorded in the IMF codelist, and
297
+ participation computed from the data (`fiscal_years_with_data`, `survey_rounds_with_data`,
298
+ `in_isora_2016` / `in_isora_2018` / `in_isora_2020plus`, `n_observations`).
299
+
300
+ ### `coverage`
301
+
302
+ One row per *generation × indicator × fiscal year* (6,752 rows) counting how many
303
+ jurisdictions were published for that question in that year, split by `value_status`
304
+ (`n_value`, `n_not_available`, `n_not_applicable`, `n_empty`, `n_unrecognized_code`,
305
+ `n_jurisdictions_reporting`). This is the questionnaire matrix: it tells you which questions were
306
+ asked (or at least published) in which year, and how well they were answered.
307
+
308
+ ### `revisions`
309
+
310
+ The IMF API still serves earlier published versions of the consolidated FY2018+ dataflow. Each
311
+ version is the dataset as released after a survey round, so differences between versions are
312
+ **revisions of previously published answers**. Three vintages were compared on every
313
+ *jurisdiction × indicator × fiscal year* key they share (359,777 keys):
314
+
315
+ | Vintage | Content |
316
+ |---|---|
317
+ | `ISORA_LATEST_DATA_PUB` v2.0.0 | ISORA 2023 release, FY2018–FY2022 |
318
+ | `ISORA_LATEST_DATA_PUB` v4.0.0 | ISORA 2024 release, FY2018–FY2023 |
319
+ | `ISORA_LATEST_DATA_PUB` v5.0.0 | ISORA 2025 release, FY2018–FY2024 (the vintage used for `observations`) |
320
+
321
+ The table lists, in long format (one row per key × vintage), only the keys where something
322
+ meaningful changed (42,552 keys), with a `change_type`:
323
+
324
+ | `change_type` | Keys | Meaning |
325
+ |---|---|---|
326
+ | `value_revised` | 2,787 | A number was replaced by a different number (beyond published precision) or by a sentinel. |
327
+ | `text_revised` | 47 | A categorical/text answer changed. |
328
+ | `scale_convention_change` | 20,114 | The number changed by exactly ×1 000: the 2023 release published money in thousands, later releases in base units (see [Units](#units-and-currency)). Not a revision of the answer. |
329
+ | `added_in_later_release` | 16,189 | The key was absent from an earlier release covering that year (question added, back-filled or late submission). |
330
+ | `removed_in_later_release` | 3,415 | The key was present in an earlier release and dropped later (question withdrawn or answer removed). |
331
+
332
+ Differences that are only formatting (thousands separators, float precision, rounding to the
333
+ coarser published precision, encoding glitches, letter case) are **not** listed. Example of a
334
+ real revision: Australia's `337_084` (on-time filing rate, CIT) for FY2022 was published as
335
+ 72.88 in the 2023 and 2024 releases and as 68.68 in the 2025 release — the latter equals the
336
+ FY2021 value of the earlier releases. Users who need "the value as first published" can rebuild
337
+ it from this table; users who need "the latest view" should simply use `observations`.
338
+
339
+ ## Working with questions that changed over time
340
+
341
+ ISORA question codes are **not** stable identifiers of meaning across the three questionnaire
342
+ generations. Three patterns occur:
343
+
344
+ 1. **Same code, same question, new wording.** `80250_3` is *Non-tax revenue - Net* in 2016 and 2018
345
+ and *Net revenue collected by the tax administration (in thousands in local currency)-Non-tax
346
+ revenue* in 2020+. Comparable.
347
+ 2. **Same code, narrower or broader question.** `88360` is *Administration pre-fills returns or
348
+ assessments* (2016, 2018) but *Administration pre-fills PIT returns or assessments* (2020+).
349
+ `85710_268` is *Other verification interventions - Total additional assessments…* (2016),
350
+ *Automated audits - Total additional assessments…* (2018) and *Value of additional assessments
351
+ raised from audits and verification actions… - Electronic compliance checks* (2020+).
352
+ Comparability is a judgement call.
353
+ 3. **Same code, unrelated question.** `92670` is *Categories of third party information used to
354
+ pre-fill returns - Other income - description* (2018) and *Description of tax deductible
355
+ expenses that are prefilled in PIT tax returns and assessments* (2020+). Not comparable.
356
+
357
+ Recommended workflow:
358
+
359
+ - Start from `indicator_history`; filter `comparability_flag == "label_stable"` for series that
360
+ can be stitched with little risk, and read both labels for `label_changed` codes.
361
+ - Join `observations` to `indicators` on `(questionnaire_generation, indicator_code)` so each
362
+ value carries the definition that applied when it was collected. Never join on the code alone.
363
+ - Use `coverage` to see in which years a question was actually asked; the periodic module
364
+ (`indicators.is_periodic`) only has data for FY2022 within the consolidated generation.
365
+ - Within ISORA 2020+ the questionnaire is stable across FY2018–FY2024 (the same codelist
366
+ version is published for all seven years); the `revisions` table shows which earlier answers
367
+ were revised in later rounds.
368
+ - The ISORA 2016 → ISORA 2018 transition is smoother (605 shared codes, mostly same questions)
369
+ than ISORA 2018 → ISORA 2020+ (a redesigned, much shorter questionnaire).
370
+
371
+ ## Units and currency
372
+
373
+ - **Money is in the jurisdiction's own currency** and is not converted. `indicators.is_local_currency`
374
+ marks national-currency questions. Derived ratios (`337_*`, `398_*`, `111_*`) are unit-free.
375
+ - The three generations publish money differently. ISORA 2016 and 2018 published amounts **in
376
+ thousands** (as asked on the form) with `SCALE = 0`. The consolidated ISORA 2020+ dataflow
377
+ publishes the same questions already multiplied out to **base currency units** and marks them
378
+ with `SCALE = 3` (verified against GDP: France's `398_001` for FY2022 is published as
379
+ 2 638 008 000 000 with `SCALE = 3`, i.e. EUR 2.64 trillion; the ISORA 2023 release had
380
+ published 2 638 008 000, in thousands). **Do not multiply ISORA 2020+ values by 1 000.**
381
+ - `value_local_currency_units` removes the ambiguity: it is always base units
382
+ (41,020 rows converted from thousands, 39,451 rows taken
383
+ as published). `value_numeric` stays exactly as published for traceability.
384
+ - Counts (staff, taxpayers, returns), percentages and ratios are published as-is.
385
+
386
+ ## What was changed relative to the source (transformation notice)
387
+
388
+ Values were **not** altered. The following was done, and is reversible through `value_raw`:
389
+
390
+ 1. Three SDMX dataflows were stacked into one long table with a common schema; the dataset-level
391
+ and series-level attribute rows of the SDMX-CSV were dropped.
392
+ 2. Numeric IMF jurisdiction codes (ISORA 2016/2018) were mapped to the alpha-3 codes used by the
393
+ consolidated dataflow, via the `ISO` annotation of the IMF codelist (Kosovo: `967` → `KOS`,
394
+ the IMF's current code; the 2018 codelist annotated it `UVK`).
395
+ 3. The mixed-type `OBSERVATION` string was split into `value_numeric` / `value_text` /
396
+ `value_status`. `D` → `not_available`; *Not Applicable* / `N/A` → `not_applicable`; `P` →
397
+ `unrecognized_code`; digit strings with space grouping (`163 310 020`) → number.
398
+ 4. Text answers and footnotes: HTML fragments such as `<br/>` and entities removed, whitespace
399
+ collapsed, and 64 values plus 141 footnotes with double-encoded UTF-8
400
+ (`‘` → `‘`, `Türkiye` → `Türkiye`) repaired.
401
+ 5. Monetary harmonisation (`monetary_unit`, `value_local_currency_units`) as described above.
402
+ 6. Indicator metadata flattened from SDMX annotations; declared types normalised (`Counting` →
403
+ `count`, trailing spaces removed); observed value kinds, answer categories, coverage,
404
+ cross-generation history and inter-release revisions computed.
405
+ 7. Jurisdiction attributes taken from the IMF `CL_ISORA_ISO_COUNTRY` codelist; `Yes/No` flags
406
+ converted to booleans.
407
+
408
+ Nothing was imputed, interpolated, deduplicated or filtered out.
409
+
410
+ ## Caveats and known issues in the source
411
+
412
+ - **Self-reported, voluntary.** Answers are provided by the administrations and reviewed by the
413
+ partners, but definitions are applied locally; read the ISORA guide before comparing countries.
414
+ - **`D` and `P`.** 113,785 cells are `D` — the ISORA convention for *no data
415
+ available* on a numeric question, distinct from a question that was skipped. 1,526
416
+ ISORA 2016 cells contain `P`, a code that does not appear in the surviving documentation; it
417
+ occurs only on numeric questions and is treated as missing (`unrecognized_code`).
418
+ - **Declared types are unreliable.** In the 2020+ codelist 817 of 1 098 codes have no declared
419
+ type and several count questions (*Total number of returns received - CIT*) are typed
420
+ `currency`. Use `indicator_value_kind` / `observed_value_kind`, which are inferred from data.
421
+ - **Scale attribute inconsistency** between generations (see Units). The `label_mentions_thousands`
422
+ flag exists because in ISORA 2016/2018 the unit is only stated in some labels.
423
+ - **Categorical answers are not fully harmonised at source**: `InPlace` and `In Place`,
424
+ `Implmenting` and `Implementing`, `option a)` with a stray `<br/>`, leading spaces in ISORA
425
+ 2016 answers. Cleaning removed markup and whitespace but did not merge spellings.
426
+ - **Codelists include codes without data** (283 in 2016, 116 in 2018, 397 in 2020+): questions
427
+ suppressed from publication or never asked. `indicators.has_observations` flags them.
428
+ - **Fiscal years** are the administrations' own fiscal years and do not align across countries.
429
+ - **Combined tax-and-customs administrations** sometimes report total staff or expenditure for
430
+ both functions (the IMF notes this on the staff tables).
431
+ - **World Bank income groups** in `jurisdictions` are the FY2015 classification stored in the IMF
432
+ codelist. Join current classifications yourself if you need them.
433
+ - **Revisions**: the `observations` table is the latest published view (ISORA 2025 release). If
434
+ you compare with figures quoted in older IMF/OECD publications, consult `revisions`.
435
+ - **Territorial names** follow IMF practice (e.g. *China, P.R.: Hong Kong*, *Taiwan*, *Kosovo,
436
+ Republic of*, *Türkiye, Rep of*) and are without prejudice to the status of any territory.
437
+
438
+ ## Provenance and reproducibility
439
+
440
+ Everything comes from the public IMF SDMX API (`https://api.imf.org/external/sdmx/3.0`, agency
441
+ `ISORA`), retrieved on 2026-09-20T04:42:35Z:
442
+
443
+ | Dataflow | Version | Data structure | Last updated at source | Used here |
444
+ |---|---|---|---|---|
445
+ | `ISORA_2016_DATA_PUB` | 1.0.0 | `ISORA:DSD_ISORA_PUBLISHED(1.0+.0)` | 2025-03-31T14:48:21.329477Z | no |
446
+ | `ISORA_2016_DATA_PUB` | 2.0.0 | `ISORA:DSD_ISORA_PUBLISHED(1.0+.0)` | 2025-06-19T04:06:43.477036Z | observations |
447
+ | `ISORA_2018_DATA_PUB` | 1.0.0 | `ISORA:DSD_ISORA_PUBLISHED(2.0+.0)` | 2025-03-31T14:48:21.358333Z | no |
448
+ | `ISORA_2018_DATA_PUB` | 2.0.0 | `ISORA:DSD_ISORA_PUBLISHED(2.0+.0)` | 2025-06-19T04:06:43.532576Z | observations |
449
+ | `ISORA_LATEST_DATA_PUB` | 2.0.0 | `ISORA:DSD_ISORA_PUBLISHED(4.0+.0)` | 2025-03-28T16:08:59.158309Z | revisions |
450
+ | `ISORA_LATEST_DATA_PUB` | 4.0.0 | `ISORA:DSD_ISORA_PUBLISHED(5.0+.0)` | 2025-07-04T18:22:18.692447Z | revisions |
451
+ | `ISORA_LATEST_DATA_PUB` | 5.0.0 | `ISORA:DSD_ISORA_PUBLISHED(6.0+.0)` | 2026-06-15T17:13:23.041621Z | observations |
452
+
453
+ Structures used: `DSD_ISORA_PUBLISHED` 1.0.0 / 2.0.0 / 6.0.0 with their codelists (`CL_INDICATOR`
454
+ 1.0.2, `CL_ISORA_TAX` 1.0.3 and 6.0.6, `CL_COUNTRY`, `CL_JURISDICTION` 4.8.4,
455
+ `CL_ISORA_ISO_COUNTRY` 2.0.1), the hierarchies `H_CL_INDICATORS_BY_TOPIC` 2.2.0,
456
+ `H_CL_PERIODIC_INDICATORS` 2.0.0, `H_CL_DERIVED_INDICATORS` 2.0.0, `H_CL_REVIEW_INDICATORS`
457
+ 2.1.0 and the label codelist `CL_RAFIT_LABELS`. Dataset-level attributes (license URL,
458
+ citations, publication dates) were read from the SDMX 2.1 CSV endpoint and are stored in
459
+ `metadata/build_summary.json`.
460
+
461
+ The full pipeline (download, transformation rules, unit tests, this card's template) is in
462
+ [`pipeline/`](pipeline/) and is MIT-licensed; `python -m isora_hf.sdmx_client && python -m
463
+ isora_hf.build && python -m isora_hf.card` rebuilds the dataset from scratch. Re-running it after
464
+ the next ISORA release (expected mid-2027 for FY2025) is how this dataset will be updated.
465
+
466
+ Official documentation — questionnaires, completion guides, review and derived tables per round —
467
+ is in the ISORA [Documents Catalog](https://data.imf.org/en/Documents#f:Datasets=[International%20Survey%20on%20Revenue%20Administration%20(ISORA)])
468
+ (the files are served through the portal's download buttons and are not mirrored here). The IMF
469
+ also publishes analytical reports on each round (*ISORA 2016: Understanding Revenue
470
+ Administration*, 2019; *ISORA 2018: Understanding Revenue Administration*, 2021; *ISORA 2023: Tax
471
+ Administration: Performance and Practices*, 2026), and the OECD's annual *Tax Administration*
472
+ series is built on the same data for 58 jurisdictions.
473
+
474
+ ## Citation and acknowledgement
475
+
476
+ Any publication using these data must acknowledge the source. The citation requested by the
477
+ publisher (from the source metadata) is:
478
+
479
+ > The International Survey on Revenue Administration (ISORA). http://isoradata.org. Accessed on [date].
480
+
481
+ Full source citation:
482
+
483
+ > The Asian Development Bank (ADB), the Inter-American Center of Tax Administrations (CIAT); the
484
+ > International Monetary Fund (IMF); the Intra-European Organisation of Tax Administrations
485
+ > (IOTA); and the Organisation for Economic Co-operation and Development (OECD), International
486
+ > Survey on Revenue Administration: https://ISORADATA.ORG
487
+
488
+ If you also want to credit this cleaned redistribution:
489
+
490
+ ```bibtex
491
+ @misc{isora_hf_2026,
492
+ title = {ISORA -- International Survey on Revenue Administration, FY2014--FY2024 (cleaned redistribution)},
493
+ howpublished = {Hugging Face dataset \url{https://huggingface.co/datasets/FrenchCastle/isora-tax-administration}},
494
+ year = {2026},
495
+ note = {Unofficial restructuring of data published by the IMF on behalf of ADB, CIAT, IMF, IOTA and OECD through the ISORA Data Portal (https://isoradata.org). Data subject to the ISORA Data Portal Terms and Conditions.}
496
+ }
497
+ ```
498
+
499
+ ## Licence
500
+
501
+ `license: other` — **ISORA Data Portal Terms and Conditions of Data Access and Use** plus the IMF
502
+ Copyright and Usage policy, reproduced in [`LICENSE`](LICENSE). In short: you may use and publish
503
+ the data with appropriate acknowledgement of the source; the data are provided as is, without
504
+ warranty; you indemnify the partner organisations against third-party claims arising from your
505
+ use; the partner organisations' immunities are preserved; contact copyright@imf.org for commercial
506
+ reuse questions. The pipeline code is MIT-licensed.
507
+
508
+ ## Dataset version
509
+
510
+ - **1.0.0** (2026-09-20): first release, built from `ISORA_2016_DATA_PUB` 2.0.0,
511
+ `ISORA_2018_DATA_PUB` 2.0.0 and `ISORA_LATEST_DATA_PUB` 5.0.0 (ISORA 2025 release, FY2024
512
+ data published June 2026).
csv/coverage.csv.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e61c619e56a840d7a25accb8317a9546074c2d94b5a0132c0bf86b068ef9f4db
3
+ size 37366
csv/indicator_history.csv.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3f2bacc517687589d96b1d8a1d0fb3cf51819a6315823c296cdc44d051eeb7ea
3
+ size 56531
csv/indicators.csv.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0c92594a281c05230be15aa250b0053b68d889d710eb1b3434573ac5441178ee
3
+ size 116796
csv/isora_2016.csv.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a4b7aca22bb094bdb90fb56abd97dffd2657a0fea8f7aa647d01cb1b186c9910
3
+ size 2642200
csv/isora_2018.csv.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a3d468a80812c8d0010b43b6c8c63f7576a7b2a03d7cc2934356b2436f5d8519
3
+ size 3809681
csv/isora_2020plus.csv.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6e5f1991271b77ab33f9b80b276f5f6322677054a813a2bc1c4acee62f095273
3
+ size 5237782
csv/jurisdictions.csv.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6da1ea0a6108bf7c8c75db465a88bbeee4df06d3d8c1f074ce800ec183a1b6ba
3
+ size 4999
csv/revisions.csv.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:75baf16e43c9c0f5db682c3dad753384f8ab3a2f320ab16eb0540573c96bfae1
3
+ size 805453
data/coverage.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:969cbbbfd3304aeae07cf1d6313c9328061b2d85bf862ce34a9cc95e506a8471
3
+ size 33948
data/indicator_history.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:de687776d06aa23dc4fe46b253ad1e383df8dc2157a07c323d492cc6c684c29c
3
+ size 93180
data/indicators.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9e2961674d5900c175fb950a8e8e5cef763946e51f9534caa5674931cfdbac09
3
+ size 156989
data/jurisdictions.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c09be2b3dec1529403f17f7e1b05dc9a25f46412c5b10491a874d9904aad5f8b
3
+ size 21568
data/observations/isora_2016.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fc25759dbaabe8d4540b78383a66a5326da71f8840ec54bed5de02ef7506e55a
3
+ size 793671
data/observations/isora_2018.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3a2b3edd71310a9b90bb839e822a67c255ef64594bb9afb39eb26da382485927
3
+ size 1478649
data/observations/isora_2020plus.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:39b12e5681563c641aa34b32f1a77e385bbaf75ef0ffcc97e82f2a7f55153221
3
+ size 3124025
data/revisions.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d3a9c68a5af530bba3a1cb1ba0fe5413d50314f090ae2f1905af9b558a9fcde6
3
+ size 491075
metadata/build_summary.json ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "retrieved_at_utc": "2026-09-20T04:42:35Z",
3
+ "dataflows_used": [
4
+ {
5
+ "id": "ISORA_2016_DATA_PUB",
6
+ "version": "2.0.0",
7
+ "dsd_version": "1.0.0",
8
+ "generation": "ISORA 2016"
9
+ },
10
+ {
11
+ "id": "ISORA_2018_DATA_PUB",
12
+ "version": "2.0.0",
13
+ "dsd_version": "2.0.0",
14
+ "generation": "ISORA 2018"
15
+ },
16
+ {
17
+ "id": "ISORA_LATEST_DATA_PUB",
18
+ "version": "5.0.0",
19
+ "dsd_version": "6.0.0",
20
+ "generation": "ISORA 2020+"
21
+ }
22
+ ],
23
+ "dataflow_versions_at_source": [
24
+ {
25
+ "dataflow_id": "ISORA_LATEST_DATA_PUB",
26
+ "version": "4.0.0",
27
+ "description": "ISORA data beginning FY2018 to current",
28
+ "data_structure": "ISORA:DSD_ISORA_PUBLISHED(5.0+.0)",
29
+ "last_updated_at_source": "2025-07-04T18:22:18.692447Z"
30
+ },
31
+ {
32
+ "dataflow_id": "ISORA_2016_DATA_PUB",
33
+ "version": "2.0.0",
34
+ "description": "ISORA data for FY2014 and FY2015",
35
+ "data_structure": "ISORA:DSD_ISORA_PUBLISHED(1.0+.0)",
36
+ "last_updated_at_source": "2025-06-19T04:06:43.477036Z"
37
+ },
38
+ {
39
+ "dataflow_id": "ISORA_2018_DATA_PUB",
40
+ "version": "1.0.0",
41
+ "description": "ISORA data for FY2016 and FY2017",
42
+ "data_structure": "ISORA:DSD_ISORA_PUBLISHED(2.0+.0)",
43
+ "last_updated_at_source": "2025-03-31T14:48:21.358333Z"
44
+ },
45
+ {
46
+ "dataflow_id": "ISORA_2016_DATA_PUB",
47
+ "version": "1.0.0",
48
+ "description": "ISORA data for FY2014 and FY2015",
49
+ "data_structure": "ISORA:DSD_ISORA_PUBLISHED(1.0+.0)",
50
+ "last_updated_at_source": "2025-03-31T14:48:21.329477Z"
51
+ },
52
+ {
53
+ "dataflow_id": "ISORA_LATEST_DATA_PUB",
54
+ "version": "2.0.0",
55
+ "description": "ISORA data beginning FY2018 to current",
56
+ "data_structure": "ISORA:DSD_ISORA_PUBLISHED(4.0+.0)",
57
+ "last_updated_at_source": "2025-03-28T16:08:59.158309Z"
58
+ },
59
+ {
60
+ "dataflow_id": "ISORA_2018_DATA_PUB",
61
+ "version": "2.0.0",
62
+ "description": "ISORA data for FY2016 and FY2017",
63
+ "data_structure": "ISORA:DSD_ISORA_PUBLISHED(2.0+.0)",
64
+ "last_updated_at_source": "2025-06-19T04:06:43.532576Z"
65
+ },
66
+ {
67
+ "dataflow_id": "ISORA_LATEST_DATA_PUB",
68
+ "version": "5.0.0",
69
+ "description": "ISORA data beginning FY2018 to current - For report year 2024 (ISORA2025)",
70
+ "data_structure": "ISORA:DSD_ISORA_PUBLISHED(6.0+.0)",
71
+ "last_updated_at_source": "2026-06-15T17:13:23.041621Z"
72
+ }
73
+ ],
74
+ "dataset_attributes": {
75
+ "ISORA_2016_DATA_PUB": {
76
+ "DATAFLOW": "ISORA:ISORA_2016_DATA_PUB(2.0.0)",
77
+ "FULL_DESCRIPTION": "Historical 2016 ISORA Data. The International Survey on Revenue Administration (ISORA) collects tax administration data from national or federal tax administrations. In 2016 data was collected on tax administrations' operations and other characteristics in Fiscal Years 2014 and 2015 using common questions and definitions agreed by four international organizations: the Inter-American Center of Tax Administrations (CIAT); the International Monetary Fund (IMF); the Intra-European Organisation of Tax Administrations (IOTA); and the Organisation for Economic Co-operation and Development (OECD). These four Parties signed a Memorandum of Understanding (MOU) governing the administration and management of this worldwide survey. ",
78
+ "PUBLISHER": "ISORA",
79
+ "DEPARTMENT": "FAD",
80
+ "CONTACT_POINT": "fadrafit@imf.org",
81
+ "PUBLICATION_DATE": "2017-12-17T05:00:00Z",
82
+ "UPDATE_DATE": "2017-12-17T05:00:00Z",
83
+ "ACCESS_SHARING_LEVEL": "PUBLIC_AGREEMENT_REQUIRED",
84
+ "SECURITY_CLASSIFICATION": "PUB",
85
+ "SHORT_SOURCE_CITATION": "CIAT, IMF, IOTA and OECD, International Survey on Revenue Administration FY2014 and FY2015, http://ISORADATA.ORG",
86
+ "FULL_SOURCE_CITATION": "The Inter-American Center of Tax Administrations (CIAT); the International Monetary Fund (IMF); the Intra-European Organisation of Tax Administrations (IOTA); and the Organisation for Economic Co-operation and Development (OECD), International Survey on Revenue Administration FY2014 and FY2015, http://ISORADATA.ORG",
87
+ "LICENSE": "https://data.imf.org/en/Datasets/RAFIT-Consolidated/Terms-and-Conditions",
88
+ "SUGGESTED_CITATION": "The International Survey on Revenue Administration (ISORA). http://isoradata.org. Accessed on [current date].",
89
+ "KEYWORDS_DATASET": "International Survey on Revenue Administration; ISORA; Revenue administration; Tax administration; Tax; ISORA data"
90
+ },
91
+ "ISORA_2018_DATA_PUB": {
92
+ "DATAFLOW": "ISORA:ISORA_2018_DATA_PUB(2.0.0)",
93
+ "FULL_DESCRIPTION": "",
94
+ "PUBLISHER": "ISORA",
95
+ "DEPARTMENT": "FAD",
96
+ "CONTACT_POINT": "fadrafit@imf.org",
97
+ "PUBLICATION_DATE": "2023-11-19T05:00:00Z",
98
+ "UPDATE_DATE": "2023-11-19T05:00:00Z",
99
+ "ACCESS_SHARING_LEVEL": "PUBLIC_AGREEMENT_REQUIRED",
100
+ "SECURITY_CLASSIFICATION": "PUB",
101
+ "SHORT_SOURCE_CITATION": "",
102
+ "FULL_SOURCE_CITATION": "",
103
+ "LICENSE": "",
104
+ "SUGGESTED_CITATION": "",
105
+ "KEYWORDS_DATASET": ""
106
+ },
107
+ "ISORA_LATEST_DATA_PUB": {
108
+ "DATAFLOW": "ISORA:ISORA_LATEST_DATA_PUB(5.0.0)",
109
+ "FULL_DESCRIPTION": "The International Survey on Revenue Administration (ISORA) collects data annually on tax administrations through an on-line survey completed by tax administrations. ISORA includes data on tax collections, tax administration operations, expenditures, and other structural characteristics of tax administrations. ISORA is the collaborative product of five international organizations: the Asian Development Bank (ADB), the Inter-American Center of Tax Administrations (CIAT); the International Monetary Fund (IMF); the Intra-European Organisation of Tax Administrations (IOTA); and the Organisation for Economic Co-operation and Development (OECD). ",
110
+ "PUBLISHER": "ISORA",
111
+ "DEPARTMENT": "FAD",
112
+ "CONTACT_POINT": "fadrafit@imf.org",
113
+ "PUBLICATION_DATE": "2025-07-10T04:00:00Z",
114
+ "UPDATE_DATE": "2025-07-10T04:00:00Z",
115
+ "ACCESS_SHARING_LEVEL": "PUBLIC_AGREEMENT_REQUIRED",
116
+ "SECURITY_CLASSIFICATION": "PUB",
117
+ "SHORT_SOURCE_CITATION": "ADB, CIAT, IMF, IOTA and OECD, International Survey on Revenue Administration: http://ISORADATA.ORG",
118
+ "FULL_SOURCE_CITATION": "The Asian Development Bank (ADB), the Inter-American Center of Tax Administrations (CIAT); the International Monetary Fund (IMF); the Intra-European Organisation of Tax Administrations (IOTA); and the Organisation for Economic Co-operation and Development (OECD), International Survey on Revenue Administration: https://ISORADATA.ORG",
119
+ "LICENSE": "https://data.imf.org/en/Datasets/RAFIT-Consolidated/Terms-and-Conditions",
120
+ "SUGGESTED_CITATION": "The International Survey on Revenue Administration (ISORA). http://isoradata.org. Accessed on [current date].",
121
+ "KEYWORDS_DATASET": ""
122
+ }
123
+ },
124
+ "hierarchy_versions": {
125
+ "H_CL_INDICATORS_BY_TOPIC": "2.2.0",
126
+ "H_CL_PERIODIC_INDICATORS": "2.0.0",
127
+ "H_CL_DERIVED_INDICATORS": "2.0.0",
128
+ "H_CL_REVIEW_INDICATORS": "2.1.0"
129
+ },
130
+ "observations": {
131
+ "rows": 796601,
132
+ "jurisdictions": 182,
133
+ "indicator_codes": 1868,
134
+ "fiscal_years": [
135
+ 2014,
136
+ 2015,
137
+ 2016,
138
+ 2017,
139
+ 2018,
140
+ 2019,
141
+ 2020,
142
+ 2021,
143
+ 2022,
144
+ 2023,
145
+ 2024
146
+ ],
147
+ "by_generation": {
148
+ "ISORA 2016": {
149
+ "rows": 185360,
150
+ "jurisdictions": 131,
151
+ "indicators": 1000,
152
+ "fiscal_years": [
153
+ 2014,
154
+ 2015
155
+ ],
156
+ "value_status": {
157
+ "value": 152404,
158
+ "not_available": 25590,
159
+ "empty": 3745,
160
+ "not_applicable": 2095,
161
+ "unrecognized_code": 1526
162
+ },
163
+ "numeric_values": 55006,
164
+ "footnotes": 1343
165
+ },
166
+ "ISORA 2018": {
167
+ "rows": 254942,
168
+ "jurisdictions": 155,
169
+ "indicators": 1072,
170
+ "fiscal_years": [
171
+ 2016,
172
+ 2017
173
+ ],
174
+ "value_status": {
175
+ "value": 209809,
176
+ "not_available": 43626,
177
+ "not_applicable": 1429,
178
+ "empty": 78
179
+ },
180
+ "numeric_values": 74854,
181
+ "footnotes": 22003
182
+ },
183
+ "ISORA 2020+": {
184
+ "rows": 356299,
185
+ "jurisdictions": 182,
186
+ "indicators": 701,
187
+ "fiscal_years": [
188
+ 2018,
189
+ 2019,
190
+ 2020,
191
+ 2021,
192
+ 2022,
193
+ 2023,
194
+ 2024
195
+ ],
196
+ "value_status": {
197
+ "value": 302136,
198
+ "not_available": 44569,
199
+ "not_applicable": 5679,
200
+ "empty": 3915
201
+ },
202
+ "numeric_values": 209850,
203
+ "footnotes": 1908
204
+ }
205
+ },
206
+ "by_fiscal_year": {
207
+ "2014": {
208
+ "jurisdictions": 131,
209
+ "indicators": 1000,
210
+ "rows": 92679
211
+ },
212
+ "2015": {
213
+ "jurisdictions": 131,
214
+ "indicators": 999,
215
+ "rows": 92681
216
+ },
217
+ "2016": {
218
+ "jurisdictions": 155,
219
+ "indicators": 1072,
220
+ "rows": 127395
221
+ },
222
+ "2017": {
223
+ "jurisdictions": 155,
224
+ "indicators": 1072,
225
+ "rows": 127547
226
+ },
227
+ "2018": {
228
+ "jurisdictions": 157,
229
+ "indicators": 302,
230
+ "rows": 40898
231
+ },
232
+ "2019": {
233
+ "jurisdictions": 157,
234
+ "indicators": 304,
235
+ "rows": 41306
236
+ },
237
+ "2020": {
238
+ "jurisdictions": 165,
239
+ "indicators": 312,
240
+ "rows": 41571
241
+ },
242
+ "2021": {
243
+ "jurisdictions": 174,
244
+ "indicators": 314,
245
+ "rows": 43580
246
+ },
247
+ "2022": {
248
+ "jurisdictions": 174,
249
+ "indicators": 675,
250
+ "rows": 92313
251
+ },
252
+ "2023": {
253
+ "jurisdictions": 164,
254
+ "indicators": 353,
255
+ "rows": 48181
256
+ },
257
+ "2024": {
258
+ "jurisdictions": 167,
259
+ "indicators": 349,
260
+ "rows": 48450
261
+ }
262
+ },
263
+ "value_status": {
264
+ "value": 664349,
265
+ "not_available": 113785,
266
+ "not_applicable": 9203,
267
+ "empty": 7738,
268
+ "unrecognized_code": 1526
269
+ },
270
+ "unit_multiplier": {
271
+ "0": 757150,
272
+ "3": 39451
273
+ },
274
+ "monetary_unit": {
275
+ "thousands of local currency": 41020,
276
+ "local currency units": 39451
277
+ },
278
+ "indicator_value_kind": {
279
+ "numeric": 455528,
280
+ "binary": 253326,
281
+ "categorical": 82533,
282
+ "mixed": 2856,
283
+ "no_values": 2358
284
+ },
285
+ "encoding_repairs": {
286
+ "values": 64,
287
+ "footnotes_with_turkiye_or_quotes": 180
288
+ }
289
+ },
290
+ "indicators": {
291
+ "rows": 3569,
292
+ "by_generation": {
293
+ "ISORA 2016": 1283,
294
+ "ISORA 2018": 1188,
295
+ "ISORA 2020+": 1098
296
+ }
297
+ },
298
+ "indicator_history": {
299
+ "indicator_codes": 2551,
300
+ "in_all_three_generations": 226,
301
+ "in_two_generations": 566,
302
+ "single_generation": 1759,
303
+ "comparability_flag": {
304
+ "single_generation": 1759,
305
+ "label_stable": 439,
306
+ "label_changed": 353
307
+ },
308
+ "label_changed_2016_to_2018": 183,
309
+ "label_changed_2018_to_2020plus": 215
310
+ },
311
+ "jurisdictions": {
312
+ "rows": 182
313
+ },
314
+ "coverage": {
315
+ "rows": 6752
316
+ },
317
+ "revisions": {
318
+ "vintages": [
319
+ {
320
+ "version": "2.0.0",
321
+ "label": "ISORA 2023 release (FY2018-FY2022)",
322
+ "rows": 246281
323
+ },
324
+ {
325
+ "version": "4.0.0",
326
+ "label": "ISORA 2024 release (FY2018-FY2023)",
327
+ "rows": 310696
328
+ },
329
+ {
330
+ "version": "5.0.0",
331
+ "label": "ISORA 2025 release (FY2018-FY2024)",
332
+ "rows": 356299
333
+ }
334
+ ],
335
+ "keys_compared": 359777,
336
+ "keys_with_changes": 42552,
337
+ "change_types": {
338
+ "scale_convention_change": 20114,
339
+ "added_in_later_release": 16189,
340
+ "removed_in_later_release": 3415,
341
+ "value_revised": 2787,
342
+ "text_revised": 47
343
+ },
344
+ "keys_with_changes_by_fiscal_year": {
345
+ "2018": 7615,
346
+ "2019": 7649,
347
+ "2020": 7656,
348
+ "2021": 8556,
349
+ "2022": 10361,
350
+ "2023": 715
351
+ }
352
+ }
353
+ }
pipeline/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 the isora-hf contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
6
+ associated documentation files (the "Software"), to deal in the Software without restriction,
7
+ including without limitation the rights to use, copy, modify, merge, publish, distribute,
8
+ sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
9
+ furnished to do so, subject to the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be included in all copies or
12
+ substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
15
+ NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
16
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
17
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
18
+ OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
19
+
20
+ This licence covers the pipeline code only. The ISORA data it processes are subject to the ISORA
21
+ Data Portal Terms and Conditions and IMF Copyright and Usage policy (see hf_dataset/LICENSE).
pipeline/README.md ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # isora-hf
2
+
3
+ Reproducible pipeline that turns the IMF's ISORA (International Survey on Revenue Administration)
4
+ SDMX API into a clean, documented Hugging Face dataset. The dataset card lives in
5
+ `hf_dataset/README.md`; the legal notice in `hf_dataset/LICENSE`.
6
+
7
+ ## What it does
8
+
9
+ 1. `python -m isora_hf.sdmx_client` downloads every artifact from `https://api.imf.org/external/sdmx/3.0`
10
+ into `raw/` (dataflows, data structure definitions with codelists, hierarchies, the three
11
+ published dataflows and two older release vintages, dataset-level attributes).
12
+ 2. `python -m isora_hf.build` turns `raw/` into `hf_dataset/data/*.parquet` (plus gzip CSV copies
13
+ in `hf_dataset/csv/`) and `hf_dataset/metadata/build_summary.json`.
14
+ 3. `python -m isora_hf.card` renders `hf_dataset/README.md` from `card_template.md` and the build summary.
15
+
16
+ ```bash
17
+ uv venv --python 3.12 .venv && uv pip install --python .venv/bin/python -e ".[dev]"
18
+ .venv/bin/python -m isora_hf.sdmx_client # ~1 GB of API traffic the first time, cached after
19
+ .venv/bin/python -m isora_hf.build # ~10 s
20
+ .venv/bin/python -m isora_hf.card --repo-id <namespace>/<dataset-name>
21
+ .venv/bin/python -m pytest -q
22
+ ```
23
+
24
+ Publishing (only after reviewing `hf_dataset/`):
25
+
26
+ ```bash
27
+ hf upload <namespace>/<dataset-name> hf_dataset . --repo-type dataset
28
+ ```
29
+
30
+ ## Layout
31
+
32
+ ```
33
+ src/isora_hf/
34
+ config.py dataflows, rounds, sentinel codes, paths
35
+ sdmx_client.py cached HTTP client for the IMF SDMX 3.0 / 2.1 API
36
+ structures.py codelists -> indicators / jurisdictions / hierarchies / dataset attributes
37
+ observations.py value parsing, encoding repair, monetary harmonisation, observed value kinds
38
+ crosswalk.py indicator_history: how each code appears across questionnaire generations
39
+ revisions.py differences between published release vintages
40
+ build.py orchestration + summary statistics
41
+ card.py dataset card renderer
42
+ tests/ unit tests for every transformation rule
43
+ card_template.md dataset card with $placeholders
44
+ hf_dataset/ what gets uploaded (README.md, LICENSE, data/, csv/, metadata/)
45
+ ```
46
+
47
+ The pipeline code is MIT licensed. The data are not: see `hf_dataset/LICENSE`.
pipeline/card_template.md ADDED
@@ -0,0 +1,476 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pretty_name: ISORA — International Survey on Revenue Administration (FY2014–FY2024)
3
+ license: other
4
+ license_name: isora-data-portal-terms
5
+ license_link: LICENSE
6
+ language:
7
+ - en
8
+ tags:
9
+ - isora
10
+ - international-survey-on-revenue-administration
11
+ - tax-administration
12
+ - revenue-administration
13
+ - tax-authority
14
+ - taxation
15
+ - tax
16
+ - tax-policy
17
+ - tax-compliance
18
+ - tax-collection
19
+ - vat
20
+ - corporate-income-tax
21
+ - personal-income-tax
22
+ - public-finance
23
+ - fiscal-policy
24
+ - government-revenue
25
+ - revenue-statistics
26
+ - economics
27
+ - macroeconomics
28
+ - development-economics
29
+ - public-sector
30
+ - government
31
+ - e-government
32
+ - digitalization
33
+ - imf
34
+ - international-monetary-fund
35
+ - oecd
36
+ - adb
37
+ - ciat
38
+ - iota
39
+ - ra-fit
40
+ - cross-country
41
+ - comparative
42
+ - panel-data
43
+ - time-series
44
+ - survey-data
45
+ - open-government-data
46
+ - sdmx
47
+ annotations_creators:
48
+ - expert-generated
49
+ multilinguality:
50
+ - monolingual
51
+ source_datasets:
52
+ - original
53
+ size_categories:
54
+ - 100K<n<1M
55
+ task_categories:
56
+ - tabular-classification
57
+ - tabular-regression
58
+ configs:
59
+ - config_name: observations
60
+ default: true
61
+ data_files:
62
+ - split: train
63
+ path: data/observations/*.parquet
64
+ - config_name: indicators
65
+ data_files:
66
+ - split: train
67
+ path: data/indicators.parquet
68
+ - config_name: indicator_history
69
+ data_files:
70
+ - split: train
71
+ path: data/indicator_history.parquet
72
+ - config_name: jurisdictions
73
+ data_files:
74
+ - split: train
75
+ path: data/jurisdictions.parquet
76
+ - config_name: coverage
77
+ data_files:
78
+ - split: train
79
+ path: data/coverage.parquet
80
+ - config_name: revisions
81
+ data_files:
82
+ - split: train
83
+ path: data/revisions.parquet
84
+ ---
85
+
86
+ # ISORA — International Survey on Revenue Administration, FY$fy_min–FY$fy_max
87
+
88
+ **Every published answer of every ISORA survey round, in one clean long-format panel**, with the
89
+ metadata you need to use it responsibly: what each question means in each questionnaire
90
+ generation, which questions changed wording (or meaning) between rounds, which jurisdictions
91
+ answered which question in which year, and how published values were revised between releases.
92
+
93
+ ISORA is the joint survey of national tax administrations run by the **Asian Development Bank
94
+ (ADB), the Inter-American Center of Tax Administrations (CIAT), the International Monetary Fund
95
+ (IMF), the Intra-European Organisation of Tax Administrations (IOTA) and the OECD**. It covers
96
+ revenue collections, budgets and staffing, registration, filing and payment, arrears, audit and
97
+ compliance risk management, dispute resolution, taxpayer services, digitalisation, governance and
98
+ institutional arrangements. The IMF publishes the data through the ISORA Data Portal
99
+ ([isoradata.org](https://isoradata.org)), and this dataset is built from the IMF SDMX API that
100
+ sits behind that portal.
101
+
102
+ > **Unofficial redistribution.** This dataset is not produced or endorsed by the IMF, ADB, CIAT,
103
+ > IOTA, the OECD or any tax administration. The data remain subject to the
104
+ > [ISORA Data Portal Terms and Conditions](https://data.imf.org/en/Datasets/RAFIT-Consolidated/Terms-and-Conditions)
105
+ > and the [IMF Copyright and Usage policy](https://www.imf.org/en/about/copyright-and-terms) —
106
+ > read the [`LICENSE`](LICENSE) file. You may publish ISORA data provided the source is
107
+ > acknowledged; see [Citation](#citation-and-acknowledgement).
108
+
109
+ | | |
110
+ |---|---|
111
+ | Observations | **$obs_rows** (`observations` table) |
112
+ | Jurisdictions | **$n_jur** tax administrations (alpha-3 codes, IMF practice) |
113
+ | Indicator codes | **$n_codes** distinct question/answer codes with data |
114
+ | Fiscal years | **FY$fy_min – FY$fy_max** (eight survey rounds: ISORA 2016 → ISORA 2025) |
115
+ | Tables | `observations` · `indicators` · `indicator_history` · `jurisdictions` · `coverage` · `revisions` |
116
+ | Formats | Parquet (`data/`), gzip CSV copies (`csv/`), build metadata (`metadata/`) |
117
+ | Source snapshot | IMF SDMX API, retrieved $retrieved_at |
118
+ | Keywords | ISORA, RA-FIT, tax administration, revenue administration, tax authority, tax agency, IMF Fiscal Affairs Department, OECD Tax Administration Series, CIAT, IOTA, ADB, tax compliance, tax collection, VAT, CIT, PIT, PAYE, tax arrears, tax audit, taxpayer registration, e-filing, e-payment, tax administration staffing, tax administration budget, TADAT, public finance, government revenue, panel data, cross-country comparison |
119
+
120
+ ## Quick start
121
+
122
+ ```python
123
+ from datasets import load_dataset
124
+
125
+ obs = load_dataset("$repo_id", "observations", split="train").to_pandas()
126
+ ind = load_dataset("$repo_id", "indicators", split="train").to_pandas()
127
+ hist = load_dataset("$repo_id", "indicator_history", split="train").to_pandas()
128
+ ```
129
+
130
+ ```python
131
+ import pandas as pd
132
+
133
+ # 1. Pick a question and look at its history across questionnaire generations first.
134
+ hist.set_index("indicator_code").loc["80040_3", ["label_2016", "label_2018", "label_2020plus", "comparability_flag"]]
135
+
136
+ # 2. Build a country × year panel of one indicator (values already in base local-currency units).
137
+ net_revenue = (
138
+ obs[obs.indicator_code == "80040_3"]
139
+ .pivot(index="jurisdiction_code", columns="fiscal_year", values="value_local_currency_units")
140
+ )
141
+
142
+ # 3. Wide table of every numeric indicator for one jurisdiction-year.
143
+ fra_2023 = obs[(obs.jurisdiction_code == "FRA") & (obs.fiscal_year == 2023) & (obs.value_status == "value")]
144
+ fra_2023.pivot(index="indicator_code", columns="fiscal_year", values="value_numeric")
145
+
146
+ # 4. Categorical answers: the closed list of options is in indicators.answer_categories.
147
+ ind.loc[ind.indicator_code == "80700", ["questionnaire_generation", "label", "answer_categories"]]
148
+ ```
149
+
150
+ DuckDB works directly on the Parquet files:
151
+
152
+ ```sql
153
+ SELECT jurisdiction_name, fiscal_year, value_numeric
154
+ FROM 'data/observations/*.parquet'
155
+ WHERE indicator_code = '337_001' -- net revenue collected as % of GDP (derived by ISORA)
156
+ ORDER BY 1, 2;
157
+ ```
158
+
159
+ ## About ISORA
160
+
161
+ ISORA collects tax administration data from national or federal tax administrations through an
162
+ online platform administered by the IMF, using common questions and definitions agreed by the five
163
+ partner organisations. Participation is voluntary; after collection the partners review the data
164
+ for accuracy, completeness and consistency, then publish the finalised round. Participants in
165
+ ISORA 2020 and later rounds agree in advance that all data they provide can be placed in the
166
+ public domain; every row in this dataset carries the source flag `PUBLIC_DATA = true`.
167
+
168
+ | Survey round | Collected in | Fiscal years covered | Participating administrations (as published) |
169
+ |---|---|---|---|
170
+ | ISORA 2016 | 2016 | 2014, 2015 | 135 |
171
+ | ISORA 2018 | 2018 | 2016, 2017 | 159 |
172
+ | ISORA 2020 | 2020 | 2018, 2019 | 156 |
173
+ | ISORA 2021 | 2021 | 2020 | 156 |
174
+ | ISORA 2022 | 2022 | 2021 | 165 |
175
+ | ISORA 2023 | 2023 | 2022 | 166 |
176
+ | ISORA 2024 | 2024 | 2023 | 164 |
177
+ | ISORA 2025 | 2025 | 2024 | 166 |
178
+
179
+ Until 2021 the survey ran every two years and collected two fiscal years at a time. After ISORA
180
+ 2018 the questionnaire was redesigned: a smaller **annual** core is asked every year and a larger
181
+ **periodic** module (governance, human resources, compliance risk management, taxpayer services,
182
+ tax operations) is asked every four years — it was included in ISORA 2023 (FY2022), which is why
183
+ that year has roughly twice as many indicators as its neighbours.
184
+
185
+ The IMF exposes the published data as three SDMX dataflows, one per **questionnaire generation**.
186
+ This dataset keeps that distinction because the question codes and wording differ between them:
187
+
188
+ $generation_table
189
+
190
+ Coverage by fiscal year:
191
+
192
+ $fiscal_year_table
193
+
194
+ ## The six tables
195
+
196
+ ### `observations` (default config)
197
+
198
+ One row per *jurisdiction × indicator × fiscal year*. Keys are unique within each questionnaire
199
+ generation and, because fiscal years do not overlap between generations, unique overall.
200
+
201
+ | Column | Type | Description |
202
+ |---|---|---|
203
+ | `jurisdiction_code` | string | Alpha-3 code as used in the IMF ISORA codelists (ISO 3166-1 alpha-3 except `KOS` for Kosovo). ISORA 2016/2018 published numeric IMF codes; they were mapped through the ISO annotation of the IMF codelist. |
204
+ | `jurisdiction_name` | string | Name exactly as published by the IMF (IMF naming practice, without prejudice to the status of any territory). |
205
+ | `fiscal_year` | int16 | Fiscal year the answer refers to. Fiscal-year definitions differ by jurisdiction. |
206
+ | `survey_round` | string | Round in which that fiscal year was first collected (`ISORA 2016` … `ISORA 2025`). Values for earlier years may have been revised in later rounds. |
207
+ | `questionnaire_generation` | string | `ISORA 2016`, `ISORA 2018` or `ISORA 2020+` — which codelist / questionnaire family the `indicator_code` belongs to. **Join to `indicators` on both this and `indicator_code`.** |
208
+ | `indicator_code` | string | Source code of the question or answer cell (e.g. `80040_3`, `337_001`, `PARTICIPATION_RATE`). Codes are reused across generations, sometimes with different wording. |
209
+ | `indicator_label` | string | Label of the code **in that generation's codelist** (denormalised for convenience). |
210
+ | `indicator_value_kind` | string | What this indicator's answers look like in the data: `numeric`, `binary`, `categorical`, `free_text`, `mixed`, `no_values` (inferred from the published values, see below). |
211
+ | `value_raw` | string | The published value, verbatim (before any cleaning). |
212
+ | `value_numeric` | float64 | Parsed number when the published value is numeric, else null. Stored exactly as published (see [Units](#units-and-currency)). |
213
+ | `value_text` | string | Cleaned text answer (HTML fragments removed, encoding glitches repaired, whitespace collapsed), else null. |
214
+ | `value_status` | string | `value`, `not_available`, `not_applicable`, `empty`, `unrecognized_code` (table below). |
215
+ | `unit_multiplier` | int8 | The source `SCALE` attribute (`0` or `3`). |
216
+ | `monetary_unit` | string | `thousands of local currency` (ISORA 2016/2018 money questions), `local currency units` (ISORA 2020+ money questions, i.e. every row with `unit_multiplier = 3`), or null for non-monetary indicators. |
217
+ | `value_local_currency_units` | float64 | **Harmonised money amount in base units of the jurisdiction's currency** (2016/2018 values × 1 000; 2020+ values unchanged). Null for non-monetary indicators. Not converted across currencies. |
218
+ | `form_status` | string | Source workflow flag on the observation (`CERTIFY`, `EDIT`, `REEDIT`) or null. |
219
+ | `footnote` | string | Free-text note published with the observation (cleaned), or null. |
220
+ | `source_dataflow`, `source_dataflow_version` | string | Provenance: which IMF dataflow version the row came from. |
221
+
222
+ $status_table
223
+
224
+ $kind_table
225
+
226
+ ### `indicators`
227
+
228
+ One row per *questionnaire generation × indicator code* ($n_ind_rows rows), i.e. the three
229
+ source codelists flattened with every annotation the IMF attaches to a code, plus statistics
230
+ computed from the observations. Key columns: `label`, `display_label`, `description` (rarely
231
+ filled at source), `form_code` / `form_name` (the survey form, e.g. *Form F. Operational metrics*),
232
+ `question_ref` (e.g. *Form D - Q2*, ISORA 2020+ only), `section`, `topic_group` / `topic_subgroup`
233
+ (the IMF *Indicators by Topic* hierarchy, ISORA 2020+ only), `report_table_index` /
234
+ `report_table_title` (where the code appears in the IMF review tables), `indicator_type` (the
235
+ source's declared type: binary, count, currency, percent, nominal, ordinal, text, date,
236
+ unspecified — unreliable, see caveats), `observed_value_kind` (inferred from data),
237
+ `answer_categories` (the closed list of answers actually observed, most frequent first),
238
+ `is_derived` / `formula` / `numerator` / `denominator` / `legend` (ISORA-computed ratios such as
239
+ `337_001` *net revenue as % of GDP*), `is_monetary`, `is_local_currency`,
240
+ `label_mentions_thousands`, `is_periodic` (periodic-module question), `is_review_indicator`,
241
+ `n_observations`, `n_observations_with_value`, `n_jurisdictions`, `fiscal_years_with_data`,
242
+ `has_observations` (codelists contain codes that were never published with data).
243
+
244
+ ### `indicator_history`
245
+
246
+ One row per indicator code ($n_hist_rows codes) describing how the code appears across the three
247
+ questionnaire generations: `in_2016` / `in_2018` / `in_2020plus`, the label in each generation,
248
+ `label_changed_2016_to_2018`, `label_changed_2018_to_2020plus`, similarity scores of the normalised
249
+ labels (0–1), `n_generations`, `fiscal_years_with_data`, observation counts and a
250
+ `comparability_flag`:
251
+
252
+ | `comparability_flag` | Codes | Meaning |
253
+ |---|---|---|
254
+ | `single_generation` | $hist_single | The code exists in only one questionnaire generation. |
255
+ | `label_stable` | $hist_label_stable | Present in two or three generations with the same wording (after normalising case, punctuation and spacing). |
256
+ | `label_changed` | $hist_label_changed | Present in more than one generation **with different wording** — check whether the meaning changed before stitching a time series. |
257
+
258
+ $hist_all_three codes exist in all three generations, $hist_two in two, $hist_single in one.
259
+ $hist_changed_16_18 codes changed wording between ISORA 2016 and ISORA 2018, $hist_changed_18_20
260
+ between ISORA 2018 and ISORA 2020+.
261
+
262
+ ### `jurisdictions`
263
+
264
+ One row per jurisdiction with data ($n_jur_rows rows): `jurisdiction_code`, `jurisdiction_name`,
265
+ `imf_numeric_code`, IMF region / sub-region / regional technical-assistance centre, World Bank
266
+ region and **FY2015** income group (a snapshot carried in the IMF codelist, not current), WEO
267
+ group, fragile / small-developing-state flags, membership flags (ADB, CIAT, IOTA, OECD, OECD
268
+ Forum on Tax Administration, EU, G20, G7, WCO, WAEMU) as recorded in the IMF codelist, and
269
+ participation computed from the data (`fiscal_years_with_data`, `survey_rounds_with_data`,
270
+ `in_isora_2016` / `in_isora_2018` / `in_isora_2020plus`, `n_observations`).
271
+
272
+ ### `coverage`
273
+
274
+ One row per *generation × indicator × fiscal year* ($n_cov_rows rows) counting how many
275
+ jurisdictions were published for that question in that year, split by `value_status`
276
+ (`n_value`, `n_not_available`, `n_not_applicable`, `n_empty`, `n_unrecognized_code`,
277
+ `n_jurisdictions_reporting`). This is the questionnaire matrix: it tells you which questions were
278
+ asked (or at least published) in which year, and how well they were answered.
279
+
280
+ ### `revisions`
281
+
282
+ The IMF API still serves earlier published versions of the consolidated FY2018+ dataflow. Each
283
+ version is the dataset as released after a survey round, so differences between versions are
284
+ **revisions of previously published answers**. Three vintages were compared on every
285
+ *jurisdiction × indicator × fiscal year* key they share ($rev_keys_compared keys):
286
+
287
+ | Vintage | Content |
288
+ |---|---|
289
+ | `ISORA_LATEST_DATA_PUB` v2.0.0 | ISORA 2023 release, FY2018–FY2022 |
290
+ | `ISORA_LATEST_DATA_PUB` v4.0.0 | ISORA 2024 release, FY2018–FY2023 |
291
+ | `ISORA_LATEST_DATA_PUB` v5.0.0 | ISORA 2025 release, FY2018–FY2024 (the vintage used for `observations`) |
292
+
293
+ The table lists, in long format (one row per key × vintage), only the keys where something
294
+ meaningful changed ($rev_keys_changed keys), with a `change_type`:
295
+
296
+ | `change_type` | Keys | Meaning |
297
+ |---|---|---|
298
+ | `value_revised` | $rev_value_revised | A number was replaced by a different number (beyond published precision) or by a sentinel. |
299
+ | `text_revised` | $rev_text_revised | A categorical/text answer changed. |
300
+ | `scale_convention_change` | $rev_scale | The number changed by exactly ×1 000: the 2023 release published money in thousands, later releases in base units (see [Units](#units-and-currency)). Not a revision of the answer. |
301
+ | `added_in_later_release` | $rev_added | The key was absent from an earlier release covering that year (question added, back-filled or late submission). |
302
+ | `removed_in_later_release` | $rev_removed | The key was present in an earlier release and dropped later (question withdrawn or answer removed). |
303
+
304
+ Differences that are only formatting (thousands separators, float precision, rounding to the
305
+ coarser published precision, encoding glitches, letter case) are **not** listed. Example of a
306
+ real revision: Australia's `337_084` (on-time filing rate, CIT) for FY2022 was published as
307
+ 72.88 in the 2023 and 2024 releases and as 68.68 in the 2025 release — the latter equals the
308
+ FY2021 value of the earlier releases. Users who need "the value as first published" can rebuild
309
+ it from this table; users who need "the latest view" should simply use `observations`.
310
+
311
+ ## Working with questions that changed over time
312
+
313
+ ISORA question codes are **not** stable identifiers of meaning across the three questionnaire
314
+ generations. Three patterns occur:
315
+
316
+ 1. **Same code, same question, new wording.** `80250_3` is *Non-tax revenue - Net* in 2016 and 2018
317
+ and *Net revenue collected by the tax administration (in thousands in local currency)-Non-tax
318
+ revenue* in 2020+. Comparable.
319
+ 2. **Same code, narrower or broader question.** `88360` is *Administration pre-fills returns or
320
+ assessments* (2016, 2018) but *Administration pre-fills PIT returns or assessments* (2020+).
321
+ `85710_268` is *Other verification interventions - Total additional assessments…* (2016),
322
+ *Automated audits - Total additional assessments…* (2018) and *Value of additional assessments
323
+ raised from audits and verification actions… - Electronic compliance checks* (2020+).
324
+ Comparability is a judgement call.
325
+ 3. **Same code, unrelated question.** `92670` is *Categories of third party information used to
326
+ pre-fill returns - Other income - description* (2018) and *Description of tax deductible
327
+ expenses that are prefilled in PIT tax returns and assessments* (2020+). Not comparable.
328
+
329
+ Recommended workflow:
330
+
331
+ - Start from `indicator_history`; filter `comparability_flag == "label_stable"` for series that
332
+ can be stitched with little risk, and read both labels for `label_changed` codes.
333
+ - Join `observations` to `indicators` on `(questionnaire_generation, indicator_code)` so each
334
+ value carries the definition that applied when it was collected. Never join on the code alone.
335
+ - Use `coverage` to see in which years a question was actually asked; the periodic module
336
+ (`indicators.is_periodic`) only has data for FY2022 within the consolidated generation.
337
+ - Within ISORA 2020+ the questionnaire is stable across FY2018–FY2024 (the same codelist
338
+ version is published for all seven years); the `revisions` table shows which earlier answers
339
+ were revised in later rounds.
340
+ - The ISORA 2016 → ISORA 2018 transition is smoother (605 shared codes, mostly same questions)
341
+ than ISORA 2018 → ISORA 2020+ (a redesigned, much shorter questionnaire).
342
+
343
+ ## Units and currency
344
+
345
+ - **Money is in the jurisdiction's own currency** and is not converted. `indicators.is_local_currency`
346
+ marks national-currency questions. Derived ratios (`337_*`, `398_*`, `111_*`) are unit-free.
347
+ - The three generations publish money differently. ISORA 2016 and 2018 published amounts **in
348
+ thousands** (as asked on the form) with `SCALE = 0`. The consolidated ISORA 2020+ dataflow
349
+ publishes the same questions already multiplied out to **base currency units** and marks them
350
+ with `SCALE = 3` (verified against GDP: France's `398_001` for FY2022 is published as
351
+ 2 638 008 000 000 with `SCALE = 3`, i.e. EUR 2.64 trillion; the ISORA 2023 release had
352
+ published 2 638 008 000, in thousands). **Do not multiply ISORA 2020+ values by 1 000.**
353
+ - `value_local_currency_units` removes the ambiguity: it is always base units
354
+ ($monetary_thousands_rows rows converted from thousands, $monetary_units_rows rows taken
355
+ as published). `value_numeric` stays exactly as published for traceability.
356
+ - Counts (staff, taxpayers, returns), percentages and ratios are published as-is.
357
+
358
+ ## What was changed relative to the source (transformation notice)
359
+
360
+ Values were **not** altered. The following was done, and is reversible through `value_raw`:
361
+
362
+ 1. Three SDMX dataflows were stacked into one long table with a common schema; the dataset-level
363
+ and series-level attribute rows of the SDMX-CSV were dropped.
364
+ 2. Numeric IMF jurisdiction codes (ISORA 2016/2018) were mapped to the alpha-3 codes used by the
365
+ consolidated dataflow, via the `ISO` annotation of the IMF codelist (Kosovo: `967` → `KOS`,
366
+ the IMF's current code; the 2018 codelist annotated it `UVK`).
367
+ 3. The mixed-type `OBSERVATION` string was split into `value_numeric` / `value_text` /
368
+ `value_status`. `D` → `not_available`; *Not Applicable* / `N/A` → `not_applicable`; `P` →
369
+ `unrecognized_code`; digit strings with space grouping (`163 310 020`) → number.
370
+ 4. Text answers and footnotes: HTML fragments such as `<br/>` and entities removed, whitespace
371
+ collapsed, and $mojibake_values values plus 141 footnotes with double-encoded UTF-8
372
+ (`‘` → `‘`, `Türkiye` → `Türkiye`) repaired.
373
+ 5. Monetary harmonisation (`monetary_unit`, `value_local_currency_units`) as described above.
374
+ 6. Indicator metadata flattened from SDMX annotations; declared types normalised (`Counting` →
375
+ `count`, trailing spaces removed); observed value kinds, answer categories, coverage,
376
+ cross-generation history and inter-release revisions computed.
377
+ 7. Jurisdiction attributes taken from the IMF `CL_ISORA_ISO_COUNTRY` codelist; `Yes/No` flags
378
+ converted to booleans.
379
+
380
+ Nothing was imputed, interpolated, deduplicated or filtered out.
381
+
382
+ ## Caveats and known issues in the source
383
+
384
+ - **Self-reported, voluntary.** Answers are provided by the administrations and reviewed by the
385
+ partners, but definitions are applied locally; read the ISORA guide before comparing countries.
386
+ - **`D` and `P`.** $not_available_rows cells are `D` — the ISORA convention for *no data
387
+ available* on a numeric question, distinct from a question that was skipped. $unrecognized_rows
388
+ ISORA 2016 cells contain `P`, a code that does not appear in the surviving documentation; it
389
+ occurs only on numeric questions and is treated as missing (`unrecognized_code`).
390
+ - **Declared types are unreliable.** In the 2020+ codelist 817 of 1 098 codes have no declared
391
+ type and several count questions (*Total number of returns received - CIT*) are typed
392
+ `currency`. Use `indicator_value_kind` / `observed_value_kind`, which are inferred from data.
393
+ - **Scale attribute inconsistency** between generations (see Units). The `label_mentions_thousands`
394
+ flag exists because in ISORA 2016/2018 the unit is only stated in some labels.
395
+ - **Categorical answers are not fully harmonised at source**: `InPlace` and `In Place`,
396
+ `Implmenting` and `Implementing`, `option a)` with a stray `<br/>`, leading spaces in ISORA
397
+ 2016 answers. Cleaning removed markup and whitespace but did not merge spellings.
398
+ - **Codelists include codes without data** (283 in 2016, 116 in 2018, 397 in 2020+): questions
399
+ suppressed from publication or never asked. `indicators.has_observations` flags them.
400
+ - **Fiscal years** are the administrations' own fiscal years and do not align across countries.
401
+ - **Combined tax-and-customs administrations** sometimes report total staff or expenditure for
402
+ both functions (the IMF notes this on the staff tables).
403
+ - **World Bank income groups** in `jurisdictions` are the FY2015 classification stored in the IMF
404
+ codelist. Join current classifications yourself if you need them.
405
+ - **Revisions**: the `observations` table is the latest published view (ISORA 2025 release). If
406
+ you compare with figures quoted in older IMF/OECD publications, consult `revisions`.
407
+ - **Territorial names** follow IMF practice (e.g. *China, P.R.: Hong Kong*, *Taiwan*, *Kosovo,
408
+ Republic of*, *Türkiye, Rep of*) and are without prejudice to the status of any territory.
409
+
410
+ ## Provenance and reproducibility
411
+
412
+ Everything comes from the public IMF SDMX API (`https://api.imf.org/external/sdmx/3.0`, agency
413
+ `ISORA`), retrieved on $retrieved_at:
414
+
415
+ $dataflow_versions_table
416
+
417
+ Structures used: `DSD_ISORA_PUBLISHED` 1.0.0 / 2.0.0 / 6.0.0 with their codelists (`CL_INDICATOR`
418
+ 1.0.2, `CL_ISORA_TAX` 1.0.3 and 6.0.6, `CL_COUNTRY`, `CL_JURISDICTION` 4.8.4,
419
+ `CL_ISORA_ISO_COUNTRY` 2.0.1), the hierarchies `H_CL_INDICATORS_BY_TOPIC` 2.2.0,
420
+ `H_CL_PERIODIC_INDICATORS` 2.0.0, `H_CL_DERIVED_INDICATORS` 2.0.0, `H_CL_REVIEW_INDICATORS`
421
+ 2.1.0 and the label codelist `CL_RAFIT_LABELS`. Dataset-level attributes (license URL,
422
+ citations, publication dates) were read from the SDMX 2.1 CSV endpoint and are stored in
423
+ `metadata/build_summary.json`.
424
+
425
+ The full pipeline (download, transformation rules, unit tests, this card's template) is in
426
+ [`pipeline/`](pipeline/) and is MIT-licensed; `python -m isora_hf.sdmx_client && python -m
427
+ isora_hf.build && python -m isora_hf.card` rebuilds the dataset from scratch. Re-running it after
428
+ the next ISORA release (expected mid-2027 for FY2025) is how this dataset will be updated.
429
+
430
+ Official documentation — questionnaires, completion guides, review and derived tables per round —
431
+ is in the ISORA [Documents Catalog](https://data.imf.org/en/Documents#f:Datasets=[International%20Survey%20on%20Revenue%20Administration%20(ISORA)])
432
+ (the files are served through the portal's download buttons and are not mirrored here). The IMF
433
+ also publishes analytical reports on each round (*ISORA 2016: Understanding Revenue
434
+ Administration*, 2019; *ISORA 2018: Understanding Revenue Administration*, 2021; *ISORA 2023: Tax
435
+ Administration: Performance and Practices*, 2026), and the OECD's annual *Tax Administration*
436
+ series is built on the same data for 58 jurisdictions.
437
+
438
+ ## Citation and acknowledgement
439
+
440
+ Any publication using these data must acknowledge the source. The citation requested by the
441
+ publisher (from the source metadata) is:
442
+
443
+ > The International Survey on Revenue Administration (ISORA). http://isoradata.org. Accessed on [date].
444
+
445
+ Full source citation:
446
+
447
+ > The Asian Development Bank (ADB), the Inter-American Center of Tax Administrations (CIAT); the
448
+ > International Monetary Fund (IMF); the Intra-European Organisation of Tax Administrations
449
+ > (IOTA); and the Organisation for Economic Co-operation and Development (OECD), International
450
+ > Survey on Revenue Administration: https://ISORADATA.ORG
451
+
452
+ If you also want to credit this cleaned redistribution:
453
+
454
+ ```bibtex
455
+ @misc{isora_hf_2026,
456
+ title = {ISORA -- International Survey on Revenue Administration, FY2014--FY2024 (cleaned redistribution)},
457
+ howpublished = {Hugging Face dataset \url{https://huggingface.co/datasets/$repo_id}},
458
+ year = {2026},
459
+ note = {Unofficial restructuring of data published by the IMF on behalf of ADB, CIAT, IMF, IOTA and OECD through the ISORA Data Portal (https://isoradata.org). Data subject to the ISORA Data Portal Terms and Conditions.}
460
+ }
461
+ ```
462
+
463
+ ## Licence
464
+
465
+ `license: other` — **ISORA Data Portal Terms and Conditions of Data Access and Use** plus the IMF
466
+ Copyright and Usage policy, reproduced in [`LICENSE`](LICENSE). In short: you may use and publish
467
+ the data with appropriate acknowledgement of the source; the data are provided as is, without
468
+ warranty; you indemnify the partner organisations against third-party claims arising from your
469
+ use; the partner organisations' immunities are preserved; contact copyright@imf.org for commercial
470
+ reuse questions. The pipeline code is MIT-licensed.
471
+
472
+ ## Dataset version
473
+
474
+ - **1.0.0** ($retrieved_date): first release, built from `ISORA_2016_DATA_PUB` 2.0.0,
475
+ `ISORA_2018_DATA_PUB` 2.0.0 and `ISORA_LATEST_DATA_PUB` 5.0.0 (ISORA 2025 release, FY2024
476
+ data published June 2026).
pipeline/pyproject.toml ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "isora-hf"
3
+ version = "0.1.0"
4
+ description = "Reproducible pipeline that turns the IMF ISORA SDMX API into a clean Hugging Face dataset"
5
+ requires-python = ">=3.12"
6
+ dependencies = ["pandas>=2.2", "pyarrow>=15", "huggingface_hub>=0.30", "requests>=2.31", "pyyaml>=6"]
7
+
8
+ [project.optional-dependencies]
9
+ dev = ["pytest>=8", "ruff>=0.5", "datasets>=2.20"]
10
+
11
+ [tool.setuptools.packages.find]
12
+ where = ["src"]
13
+
14
+ [tool.ruff]
15
+ line-length = 100
16
+ target-version = "py312"
17
+
18
+ [tool.pytest.ini_options]
19
+ pythonpath = ["src"]
20
+ testpaths = ["tests"]
pipeline/src/isora_hf/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """isora-hf: build a clean Hugging Face dataset from the IMF ISORA SDMX API."""
pipeline/src/isora_hf/build.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Orchestrate the build: raw SDMX artifacts -> clean Parquet/CSV tables + metadata for the card."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import gzip
6
+ import json
7
+ import logging
8
+ from pathlib import Path
9
+
10
+ import numpy as np
11
+ import pandas as pd
12
+ import pyarrow as pa
13
+ import pyarrow.parquet as pq
14
+
15
+ from isora_hf import config, structures
16
+ from isora_hf.crosswalk import build_indicator_history
17
+ from isora_hf.observations import MAX_CATEGORIES, OBSERVATION_COLUMNS, clean_observations
18
+ from isora_hf.revisions import build_revisions
19
+
20
+ log = logging.getLogger(__name__)
21
+ LATEST = config.DATAFLOWS[-1]
22
+ FILE_SLUG = {
23
+ "ISORA 2016": "isora_2016",
24
+ "ISORA 2018": "isora_2018",
25
+ "ISORA 2020+": "isora_2020plus",
26
+ }
27
+
28
+
29
+ def _years(series: pd.Series) -> list[int]:
30
+ return sorted({int(y) for y in series})
31
+
32
+
33
+ def _as_list(value) -> list:
34
+ """groupby().agg may hand back numpy arrays or NaN for list-valued aggregations."""
35
+ if isinstance(value, list):
36
+ return value
37
+ if isinstance(value, np.ndarray):
38
+ return value.tolist()
39
+ return []
40
+
41
+
42
+ def _answer_categories(series: pd.Series) -> list[str]:
43
+ """Distinct categorical answers, most frequent first, or empty when the indicator is numeric
44
+ or free text (more than MAX_CATEGORIES distinct answers)."""
45
+ counts = series.dropna().value_counts()
46
+ if counts.empty or len(counts) > MAX_CATEGORIES:
47
+ return []
48
+ return [str(v) for v in counts.index]
49
+
50
+
51
+ def build_indicators(observations: pd.DataFrame) -> pd.DataFrame:
52
+ frames = [structures.indicator_table(flow) for flow in config.DATAFLOWS]
53
+ indicators = pd.concat(frames, ignore_index=True)
54
+
55
+ members = structures.hierarchy_memberships()
56
+ topic = members[members["hierarchy_id"] == "H_CL_INDICATORS_BY_TOPIC"].drop_duplicates(
57
+ "indicator_code"
58
+ )
59
+ topic = topic.set_index("indicator_code")
60
+ sets = {
61
+ h: set(members.loc[members["hierarchy_id"] == h, "indicator_code"])
62
+ for h in members["hierarchy_id"].unique()
63
+ }
64
+ latest = indicators["questionnaire_generation"] == LATEST.generation
65
+ codes = indicators["indicator_code"]
66
+ indicators["topic_group"] = codes.map(topic["group"]).where(latest)
67
+ indicators["topic_subgroup"] = codes.map(topic["subgroup"]).where(latest)
68
+ indicators["is_periodic"] = (
69
+ codes.isin(sets.get("H_CL_PERIODIC_INDICATORS", set())) & latest
70
+ ).where(latest)
71
+ indicators["is_review_indicator"] = (
72
+ codes.isin(sets.get("H_CL_REVIEW_INDICATORS", set())) & latest
73
+ ).where(latest)
74
+ indicators["in_derived_indicators_hierarchy"] = (
75
+ codes.isin(sets.get("H_CL_DERIVED_INDICATORS", set())) & latest
76
+ ).where(latest)
77
+
78
+ key = ["questionnaire_generation", "indicator_code"]
79
+ stats = observations.groupby(key).agg(
80
+ n_observations=("value_raw", "size"),
81
+ n_observations_with_value=("value_status", lambda s: int((s == "value").sum())),
82
+ n_jurisdictions=("jurisdiction_code", "nunique"),
83
+ fiscal_years_with_data=("fiscal_year", _years),
84
+ observed_value_kind=("indicator_value_kind", "first"),
85
+ is_monetary=("monetary_unit", lambda s: bool(s.notna().any())),
86
+ answer_categories=("value_text", _answer_categories),
87
+ )
88
+ indicators = indicators.merge(stats, left_on=key, right_index=True, how="left")
89
+ indicators["n_observations"] = indicators["n_observations"].fillna(0).astype(int)
90
+ indicators["n_observations_with_value"] = (
91
+ indicators["n_observations_with_value"].fillna(0).astype(int)
92
+ )
93
+ indicators["n_jurisdictions"] = indicators["n_jurisdictions"].fillna(0).astype(int)
94
+ for col in ("fiscal_years_with_data", "answer_categories"):
95
+ indicators[col] = indicators[col].apply(_as_list)
96
+ indicators["observed_value_kind"] = indicators["observed_value_kind"].fillna("no_observations")
97
+ indicators["is_monetary"] = indicators["is_monetary"].fillna(False).astype(bool)
98
+ indicators["has_observations"] = indicators["n_observations"] > 0
99
+ return indicators.sort_values(key).reset_index(drop=True)
100
+
101
+
102
+ def build_jurisdictions(observations: pd.DataFrame) -> pd.DataFrame:
103
+ master = structures.jurisdiction_master()
104
+ stats = observations.groupby("jurisdiction_code").agg(
105
+ fiscal_years_with_data=("fiscal_year", _years),
106
+ survey_rounds_with_data=("survey_round", lambda s: sorted(set(s))),
107
+ n_observations=("value_raw", "size"),
108
+ in_isora_2016=("questionnaire_generation", lambda s: bool((s == "ISORA 2016").any())),
109
+ in_isora_2018=("questionnaire_generation", lambda s: bool((s == "ISORA 2018").any())),
110
+ in_isora_2020plus=("questionnaire_generation", lambda s: bool((s == "ISORA 2020+").any())),
111
+ )
112
+ out = master.merge(stats, left_on="jurisdiction_code", right_index=True, how="inner")
113
+ for col in ("fiscal_years_with_data", "survey_rounds_with_data"):
114
+ out[col] = out[col].apply(_as_list)
115
+ missing = set(stats.index) - set(master["jurisdiction_code"])
116
+ if missing:
117
+ raise ValueError(f"jurisdictions in data but not in master codelist: {sorted(missing)}")
118
+ return out.sort_values("jurisdiction_code").reset_index(drop=True)
119
+
120
+
121
+ def build_coverage(observations: pd.DataFrame) -> pd.DataFrame:
122
+ key = ["questionnaire_generation", "indicator_code", "fiscal_year"]
123
+ counts = observations.pivot_table(
124
+ index=key, columns="value_status", values="value_raw", aggfunc="size", fill_value=0
125
+ )
126
+ counts.columns = [f"n_{c}" for c in counts.columns]
127
+ counts["n_jurisdictions_reporting"] = counts.sum(axis=1)
128
+ return counts.reset_index().sort_values(key).reset_index(drop=True)
129
+
130
+
131
+ def write_table(frame: pd.DataFrame, path: Path, csv_dir: Path | None = None) -> None:
132
+ path.parent.mkdir(parents=True, exist_ok=True)
133
+ table = pa.Table.from_pandas(frame, preserve_index=False)
134
+ pq.write_table(table, path, compression="zstd")
135
+ log.info(
136
+ "wrote %s (%d rows, %d cols)",
137
+ path.relative_to(config.OUT_DIR),
138
+ len(frame),
139
+ len(frame.columns),
140
+ )
141
+ if csv_dir is not None:
142
+ csv_dir.mkdir(parents=True, exist_ok=True)
143
+ flat = frame.copy()
144
+ for col in flat.columns:
145
+ if flat[col].map(lambda v: isinstance(v, list)).any():
146
+ flat[col] = flat[col].map(
147
+ lambda v: ";".join(str(x) for x in v) if isinstance(v, list) else v
148
+ )
149
+ with gzip.open(csv_dir / (path.stem + ".csv.gz"), "wt", encoding="utf-8", newline="") as fh:
150
+ flat.to_csv(fh, index=False)
151
+
152
+
153
+ def observation_summary(obs: pd.DataFrame) -> dict:
154
+ per_gen = {}
155
+ for gen, part in obs.groupby("questionnaire_generation"):
156
+ per_gen[gen] = {
157
+ "rows": len(part),
158
+ "jurisdictions": int(part["jurisdiction_code"].nunique()),
159
+ "indicators": int(part["indicator_code"].nunique()),
160
+ "fiscal_years": _years(part["fiscal_year"]),
161
+ "value_status": {k: int(v) for k, v in part["value_status"].value_counts().items()},
162
+ "numeric_values": int(part["value_numeric"].notna().sum()),
163
+ "footnotes": int(part["footnote"].notna().sum()),
164
+ }
165
+ per_year = obs.groupby("fiscal_year").agg(
166
+ jurisdictions=("jurisdiction_code", "nunique"),
167
+ indicators=("indicator_code", "nunique"),
168
+ rows=("value_raw", "size"),
169
+ )
170
+ return {
171
+ "rows": len(obs),
172
+ "jurisdictions": int(obs["jurisdiction_code"].nunique()),
173
+ "indicator_codes": int(obs["indicator_code"].nunique()),
174
+ "fiscal_years": _years(obs["fiscal_year"]),
175
+ "by_generation": per_gen,
176
+ "by_fiscal_year": {
177
+ int(y): {k: int(v) for k, v in r.items()} for y, r in per_year.iterrows()
178
+ },
179
+ "value_status": {k: int(v) for k, v in obs["value_status"].value_counts().items()},
180
+ "unit_multiplier": {
181
+ int(k): int(v) for k, v in obs["unit_multiplier"].value_counts().items()
182
+ },
183
+ "monetary_unit": {str(k): int(v) for k, v in obs["monetary_unit"].value_counts().items()},
184
+ "indicator_value_kind": {
185
+ k: int(v) for k, v in obs["indicator_value_kind"].value_counts().items()
186
+ },
187
+ "encoding_repairs": {
188
+ "values": int(obs["value_raw"].str.contains("Ã|â€", regex=True).sum()),
189
+ "footnotes_with_turkiye_or_quotes": int(
190
+ obs["footnote"].fillna("").str.contains("‘|’|Türkiye", regex=True).sum()
191
+ ),
192
+ },
193
+ }
194
+
195
+
196
+ def history_summary(hist: pd.DataFrame) -> dict:
197
+ return {
198
+ "indicator_codes": len(hist),
199
+ "in_all_three_generations": int((hist["n_generations"] == 3).sum()),
200
+ "in_two_generations": int((hist["n_generations"] == 2).sum()),
201
+ "single_generation": int((hist["n_generations"] == 1).sum()),
202
+ "comparability_flag": {
203
+ k: int(v) for k, v in hist["comparability_flag"].value_counts().items()
204
+ },
205
+ "label_changed_2016_to_2018": int((hist["label_changed_2016_to_2018"] == True).sum()),
206
+ "label_changed_2018_to_2020plus": int(
207
+ (hist["label_changed_2018_to_2020plus"] == True).sum()
208
+ ),
209
+ }
210
+
211
+
212
+ def run() -> dict:
213
+ out = config.OUT_DIR
214
+ data_dir, csv_dir = out / "data", out / "csv"
215
+ n2a = structures.numeric_to_alpha3()
216
+ master = structures.jurisdiction_master()
217
+ names = dict(zip(master["jurisdiction_code"], master["jurisdiction_name"]))
218
+
219
+ base_indicators = pd.concat(
220
+ [structures.indicator_table(f) for f in config.DATAFLOWS], ignore_index=True
221
+ )
222
+ parts = []
223
+ for flow in config.DATAFLOWS:
224
+ ind = base_indicators[base_indicators["questionnaire_generation"] == flow.generation]
225
+ monetary = set() if flow is LATEST else structures.declared_monetary_codes(ind)
226
+ part = clean_observations(flow, ind, n2a, names, monetary)[OBSERVATION_COLUMNS]
227
+ write_table(
228
+ part, data_dir / "observations" / f"{FILE_SLUG[flow.generation]}.parquet", csv_dir
229
+ )
230
+ parts.append(part)
231
+ observations = pd.concat(parts, ignore_index=True)
232
+
233
+ indicators = build_indicators(observations)
234
+ write_table(indicators, data_dir / "indicators.parquet", csv_dir)
235
+ history = build_indicator_history(indicators, observations)
236
+ write_table(history, data_dir / "indicator_history.parquet", csv_dir)
237
+ jurisdictions = build_jurisdictions(observations)
238
+ write_table(jurisdictions, data_dir / "jurisdictions.parquet", csv_dir)
239
+ coverage = build_coverage(observations)
240
+ write_table(coverage, data_dir / "coverage.parquet", csv_dir)
241
+ revisions, rev_summary = build_revisions()
242
+ write_table(revisions, data_dir / "revisions.parquet", csv_dir)
243
+
244
+ summary = {
245
+ "retrieved_at_utc": (config.RAW_DIR / "RETRIEVED_AT.txt").read_text().strip(),
246
+ "dataflows_used": [
247
+ {
248
+ "id": f.id,
249
+ "version": f.version,
250
+ "dsd_version": f.dsd_version,
251
+ "generation": f.generation,
252
+ }
253
+ for f in config.DATAFLOWS
254
+ ],
255
+ "dataflow_versions_at_source": structures.dataflow_versions(),
256
+ "dataset_attributes": {f.id: structures.dataset_metadata(f.id) for f in config.DATAFLOWS},
257
+ "hierarchy_versions": structures.HIERARCHY_VERSIONS,
258
+ "observations": observation_summary(observations),
259
+ "indicators": {
260
+ "rows": len(indicators),
261
+ "by_generation": {
262
+ k: int(v) for k, v in indicators["questionnaire_generation"].value_counts().items()
263
+ },
264
+ },
265
+ "indicator_history": history_summary(history),
266
+ "jurisdictions": {"rows": len(jurisdictions)},
267
+ "coverage": {"rows": len(coverage)},
268
+ "revisions": rev_summary,
269
+ }
270
+ (out / "metadata").mkdir(parents=True, exist_ok=True)
271
+ (out / "metadata" / "build_summary.json").write_text(
272
+ json.dumps(summary, indent=2, ensure_ascii=False), encoding="utf-8"
273
+ )
274
+ log.info("build complete")
275
+ return summary
276
+
277
+
278
+ if __name__ == "__main__":
279
+ logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
280
+ run()
pipeline/src/isora_hf/card.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Render the Hugging Face dataset card from card_template.md and the build summary."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ from string import Template
8
+
9
+ from isora_hf import config
10
+
11
+ TEMPLATE = config.PROJECT_ROOT / "card_template.md"
12
+ OUTPUT = config.OUT_DIR / "README.md"
13
+ SUMMARY = config.OUT_DIR / "metadata" / "build_summary.json"
14
+
15
+
16
+ def fmt(n: float) -> str:
17
+ return f"{int(n):,}"
18
+
19
+
20
+ def generation_table(summary: dict) -> str:
21
+ rows = [
22
+ "| Questionnaire generation | Source dataflow | Fiscal years | Rows | Jurisdictions | Indicator codes |",
23
+ "|---|---|---|---|---|---|",
24
+ ]
25
+ for flow in summary["dataflows_used"]:
26
+ g = summary["observations"]["by_generation"][flow["generation"]]
27
+ years = f"FY{g['fiscal_years'][0]}–FY{g['fiscal_years'][-1]}"
28
+ rows.append(
29
+ f"| {flow['generation']} | `{flow['id']}` v{flow['version']} | {years} | {fmt(g['rows'])} | {g['jurisdictions']} | {fmt(g['indicators'])} |"
30
+ )
31
+ return "\n".join(rows)
32
+
33
+
34
+ def fiscal_year_table(summary: dict) -> str:
35
+ rows = [
36
+ "| Fiscal year | Collected in | Jurisdictions | Indicator codes | Rows |",
37
+ "|---|---|---|---|---|",
38
+ ]
39
+ for year, r in summary["observations"]["by_fiscal_year"].items():
40
+ rnd = config.FISCAL_YEAR_TO_ROUND[int(year)]
41
+ rows.append(
42
+ f"| {year} | {rnd} | {r['jurisdictions']} | {r['indicators']} | {fmt(r['rows'])} |"
43
+ )
44
+ return "\n".join(rows)
45
+
46
+
47
+ def status_table(summary: dict) -> str:
48
+ counts = summary["observations"]["value_status"]
49
+ total = sum(counts.values())
50
+ meaning = {
51
+ "value": "a numeric or text answer is present",
52
+ "not_available": "the administration answered `D` (data not available) to a numeric question",
53
+ "not_applicable": "the administration answered *Not Applicable*",
54
+ "empty": "the cell was published empty",
55
+ "unrecognized_code": "the published value is the undocumented code `P` (ISORA 2016 only)",
56
+ }
57
+ rows = ["| `value_status` | Rows | Share | Meaning |", "|---|---|---|---|"]
58
+ for k in ("value", "not_available", "not_applicable", "empty", "unrecognized_code"):
59
+ n = counts.get(k, 0)
60
+ rows.append(f"| `{k}` | {fmt(n)} | {100 * n / total:.1f}% | {meaning[k]} |")
61
+ return "\n".join(rows)
62
+
63
+
64
+ def dataflow_versions_table(summary: dict) -> str:
65
+ rows = [
66
+ "| Dataflow | Version | Data structure | Last updated at source | Used here |",
67
+ "|---|---|---|---|---|",
68
+ ]
69
+ used = {(f["id"], f["version"]) for f in summary["dataflows_used"]}
70
+ vint = {("ISORA_LATEST_DATA_PUB", v) for v, _, _ in config.VINTAGES}
71
+ for d in sorted(
72
+ summary["dataflow_versions_at_source"], key=lambda x: (x["dataflow_id"], x["version"])
73
+ ):
74
+ key = (d["dataflow_id"], d["version"])
75
+ use = "observations" if key in used else ("revisions" if key in vint else "no")
76
+ rows.append(
77
+ f"| `{d['dataflow_id']}` | {d['version']} | `{d['data_structure']}` | {d['last_updated_at_source'] or '—'} | {use} |"
78
+ )
79
+ return "\n".join(rows)
80
+
81
+
82
+ def kind_table(summary: dict) -> str:
83
+ counts = summary["observations"]["indicator_value_kind"]
84
+ meaning = {
85
+ "numeric": "every published answer is a number",
86
+ "binary": "answers are Yes / No",
87
+ "categorical": "answers come from a closed list (≤ 25 distinct values)",
88
+ "free_text": "more than 25 distinct text answers",
89
+ "mixed": "numbers and text both occur (usually a category plus a numeric ‘other’)",
90
+ "no_values": "only `D`, empty or not-applicable cells were published",
91
+ }
92
+ rows = ["| `indicator_value_kind` | Rows | What it means |", "|---|---|---|"]
93
+ for k, n in sorted(counts.items(), key=lambda kv: -kv[1]):
94
+ rows.append(f"| `{k}` | {fmt(n)} | {meaning.get(k, '')} |")
95
+ return "\n".join(rows)
96
+
97
+
98
+ def build_context(summary: dict, repo_id: str) -> dict[str, str]:
99
+ obs, hist, rev = summary["observations"], summary["indicator_history"], summary["revisions"]
100
+ ct = rev["change_types"]
101
+ return {
102
+ "repo_id": repo_id,
103
+ "retrieved_at": summary["retrieved_at_utc"],
104
+ "retrieved_date": summary["retrieved_at_utc"][:10],
105
+ "obs_rows": fmt(obs["rows"]),
106
+ "n_jur": str(obs["jurisdictions"]),
107
+ "n_codes": fmt(obs["indicator_codes"]),
108
+ "fy_min": str(obs["fiscal_years"][0]),
109
+ "fy_max": str(obs["fiscal_years"][-1]),
110
+ "n_ind_rows": fmt(summary["indicators"]["rows"]),
111
+ "n_hist_rows": fmt(hist["indicator_codes"]),
112
+ "n_cov_rows": fmt(summary["coverage"]["rows"]),
113
+ "n_jur_rows": str(summary["jurisdictions"]["rows"]),
114
+ "hist_all_three": fmt(hist["in_all_three_generations"]),
115
+ "hist_two": fmt(hist["in_two_generations"]),
116
+ "hist_single": fmt(hist["single_generation"]),
117
+ "hist_label_changed": fmt(hist["comparability_flag"].get("label_changed", 0)),
118
+ "hist_label_stable": fmt(hist["comparability_flag"].get("label_stable", 0)),
119
+ "hist_changed_16_18": fmt(hist["label_changed_2016_to_2018"]),
120
+ "hist_changed_18_20": fmt(hist["label_changed_2018_to_2020plus"]),
121
+ "rev_keys_compared": fmt(rev["keys_compared"]),
122
+ "rev_keys_changed": fmt(rev["keys_with_changes"]),
123
+ "rev_value_revised": fmt(ct.get("value_revised", 0)),
124
+ "rev_text_revised": fmt(ct.get("text_revised", 0)),
125
+ "rev_scale": fmt(ct.get("scale_convention_change", 0)),
126
+ "rev_added": fmt(ct.get("added_in_later_release", 0)),
127
+ "rev_removed": fmt(ct.get("removed_in_later_release", 0)),
128
+ "not_available_rows": fmt(obs["value_status"].get("not_available", 0)),
129
+ "unrecognized_rows": fmt(obs["value_status"].get("unrecognized_code", 0)),
130
+ "monetary_thousands_rows": fmt(obs["monetary_unit"].get("thousands of local currency", 0)),
131
+ "monetary_units_rows": fmt(obs["monetary_unit"].get("local currency units", 0)),
132
+ "mojibake_values": fmt(obs["encoding_repairs"]["values"]),
133
+ "generation_table": generation_table(summary),
134
+ "fiscal_year_table": fiscal_year_table(summary),
135
+ "status_table": status_table(summary),
136
+ "dataflow_versions_table": dataflow_versions_table(summary),
137
+ "kind_table": kind_table(summary),
138
+ }
139
+
140
+
141
+ def render(repo_id: str) -> None:
142
+ summary = json.loads(SUMMARY.read_text(encoding="utf-8"))
143
+ text = Template(TEMPLATE.read_text(encoding="utf-8")).substitute(
144
+ build_context(summary, repo_id)
145
+ )
146
+ OUTPUT.write_text(text, encoding="utf-8")
147
+ print(f"wrote {OUTPUT} ({len(text.splitlines())} lines)")
148
+
149
+
150
+ if __name__ == "__main__":
151
+ parser = argparse.ArgumentParser()
152
+ parser.add_argument("--repo-id", default="FrenchCastle/isora-tax-administration")
153
+ render(parser.parse_args().repo_id)
pipeline/src/isora_hf/config.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Constants shared by the pipeline: API endpoints, dataflows, rounds, sentinel codes, paths."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+
8
+ PROJECT_ROOT = Path(__file__).resolve().parents[2]
9
+ RAW_DIR = PROJECT_ROOT / "raw"
10
+ RAW_DATA_DIR = RAW_DIR / "data"
11
+ RAW_STRUCTURES_DIR = RAW_DIR / "structures"
12
+ OUT_DIR = PROJECT_ROOT / "hf_dataset"
13
+
14
+ SDMX3_BASE = "https://api.imf.org/external/sdmx/3.0"
15
+ SDMX21_BASE = "https://api.imf.org/external/sdmx/2.1"
16
+ AGENCY = "ISORA"
17
+ USER_AGENT = "isora-hf/0.1 (+https://huggingface.co; data pipeline; contact via dataset card)"
18
+
19
+ ISORA_PORTAL_URL = "https://data.imf.org/en/datasets/ISORA:ISORA_LATEST_DATA_PUB"
20
+ TERMS_URL = "https://data.imf.org/en/Datasets/RAFIT-Consolidated/Terms-and-Conditions"
21
+ DISCLAIMER_URL = "https://data.imf.org/en/Datasets/RAFIT-Consolidated/Disclaimer"
22
+ ABOUT_URL = "https://data.imf.org/en/Datasets/RAFIT-Consolidated/About-RA-FIT"
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class Dataflow:
27
+ """One published ISORA dataflow (a questionnaire generation)."""
28
+
29
+ id: str
30
+ version: str
31
+ dsd_version: str
32
+ generation: str # human-readable questionnaire generation
33
+ fiscal_years: tuple[int, ...]
34
+ geo_dimension: str # COUNTRY (numeric IMF codes) or JURISDICTION (alpha-3)
35
+ indicator_codelist: str
36
+ form_status_attr: str
37
+
38
+
39
+ DATAFLOWS: tuple[Dataflow, ...] = (
40
+ Dataflow(
41
+ id="ISORA_2016_DATA_PUB",
42
+ version="2.0.0",
43
+ dsd_version="1.0.0",
44
+ generation="ISORA 2016",
45
+ fiscal_years=(2014, 2015),
46
+ geo_dimension="COUNTRY",
47
+ indicator_codelist="CL_INDICATOR",
48
+ form_status_attr="FORM_STATUS",
49
+ ),
50
+ Dataflow(
51
+ id="ISORA_2018_DATA_PUB",
52
+ version="2.0.0",
53
+ dsd_version="2.0.0",
54
+ generation="ISORA 2018",
55
+ fiscal_years=(2016, 2017),
56
+ geo_dimension="JURISDICTION",
57
+ indicator_codelist="CL_ISORA_TAX",
58
+ form_status_attr="FORMSTATUS",
59
+ ),
60
+ Dataflow(
61
+ id="ISORA_LATEST_DATA_PUB",
62
+ version="5.0.0",
63
+ dsd_version="6.0.0",
64
+ generation="ISORA 2020+",
65
+ fiscal_years=(2018, 2019, 2020, 2021, 2022, 2023, 2024),
66
+ geo_dimension="JURISDICTION",
67
+ indicator_codelist="CL_ISORA_TAX",
68
+ form_status_attr="FORMSTATUS",
69
+ ),
70
+ )
71
+
72
+ # Older published versions of the consolidated dataflow, still served by the API.
73
+ # They are earlier release vintages of the same FY2018+ series and let us track revisions.
74
+ VINTAGES: tuple[tuple[str, str, str], ...] = (
75
+ # (dataflow version, release label, fiscal years covered)
76
+ ("2.0.0", "ISORA 2023 release (FY2018-FY2022)", "2018-2022"),
77
+ ("4.0.0", "ISORA 2024 release (FY2018-FY2023)", "2018-2023"),
78
+ ("5.0.0", "ISORA 2025 release (FY2018-FY2024)", "2018-2024"),
79
+ )
80
+
81
+ # Fiscal year -> survey round in which that fiscal year was first collected.
82
+ FISCAL_YEAR_TO_ROUND: dict[int, str] = {
83
+ 2014: "ISORA 2016",
84
+ 2015: "ISORA 2016",
85
+ 2016: "ISORA 2018",
86
+ 2017: "ISORA 2018",
87
+ 2018: "ISORA 2020",
88
+ 2019: "ISORA 2020",
89
+ 2020: "ISORA 2021",
90
+ 2021: "ISORA 2022",
91
+ 2022: "ISORA 2023",
92
+ 2023: "ISORA 2024",
93
+ 2024: "ISORA 2025",
94
+ }
95
+
96
+ # Published participation counts (About ISORA page + ISORA 2025 news item), for the card.
97
+ ROUND_PARTICIPATION: dict[str, int] = {
98
+ "ISORA 2016": 135,
99
+ "ISORA 2018": 159,
100
+ "ISORA 2020": 156,
101
+ "ISORA 2021": 156,
102
+ "ISORA 2022": 165,
103
+ "ISORA 2023": 166,
104
+ "ISORA 2024": 164,
105
+ "ISORA 2025": 166,
106
+ }
107
+
108
+ # Sentinel strings found in the OBSERVATION column.
109
+ NOT_AVAILABLE_CODES = frozenset({"D"})
110
+ NOT_APPLICABLE_STRINGS = frozenset({"not applicable", "n/a", "na"})
111
+ UNRECOGNIZED_CODES = frozenset({"P"}) # ISORA 2016 only; not documented in surviving material
112
+
113
+ # DissemScale annotation -> normalized indicator type
114
+ INDICATOR_TYPE_MAP: dict[str, str] = {
115
+ "binary": "binary",
116
+ "counting": "count",
117
+ "currency": "currency",
118
+ "percent": "percent",
119
+ "nominal": "nominal",
120
+ "ordinal": "ordinal",
121
+ "text": "text",
122
+ "date": "date",
123
+ "na": "unspecified",
124
+ "": "unspecified",
125
+ }
pipeline/src/isora_hf/crosswalk.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Track how each indicator code appears across questionnaire generations.
2
+
3
+ The same code can carry a different question wording (and sometimes meaning) in ISORA 2016,
4
+ ISORA 2018 and the ISORA 2020+ consolidated questionnaire. This module builds the
5
+ `indicator_history` table so users can judge comparability before stitching time series.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from difflib import SequenceMatcher
12
+
13
+ import pandas as pd
14
+
15
+ GENERATIONS = ("ISORA 2016", "ISORA 2018", "ISORA 2020+")
16
+ SUFFIX = {"ISORA 2016": "2016", "ISORA 2018": "2018", "ISORA 2020+": "2020plus"}
17
+ PUNCT_RE = re.compile(r"[^a-z0-9%]+")
18
+
19
+
20
+ def normalize_label(label: str | None) -> str:
21
+ """Lowercase, drop punctuation and repeated whitespace so trivial edits compare equal."""
22
+ if not label:
23
+ return ""
24
+ return PUNCT_RE.sub(" ", label.lower()).strip()
25
+
26
+
27
+ def label_similarity(a: str | None, b: str | None) -> float | None:
28
+ """0..1 similarity of two normalized labels; None when either side is missing."""
29
+ if not a or not b:
30
+ return None
31
+ return round(SequenceMatcher(None, normalize_label(a), normalize_label(b)).ratio(), 3)
32
+
33
+
34
+ def _label_changed(a: str | None, b: str | None) -> bool | None:
35
+ if not a or not b:
36
+ return None
37
+ return normalize_label(a) != normalize_label(b)
38
+
39
+
40
+ def _comparability_flag(row: dict) -> str:
41
+ present = [g for g in GENERATIONS if row[f"in_{SUFFIX[g]}"]]
42
+ if len(present) == 1:
43
+ return "single_generation"
44
+ changes = [
45
+ row.get("label_changed_2016_to_2018"),
46
+ row.get("label_changed_2018_to_2020plus"),
47
+ ]
48
+ if any(c is True for c in changes):
49
+ return "label_changed"
50
+ return "label_stable"
51
+
52
+
53
+ def build_indicator_history(indicators: pd.DataFrame, observations: pd.DataFrame) -> pd.DataFrame:
54
+ by_gen = {
55
+ g: indicators[indicators["questionnaire_generation"] == g].set_index("indicator_code")
56
+ for g in GENERATIONS
57
+ }
58
+ codes = sorted(set(indicators["indicator_code"]))
59
+
60
+ years = (
61
+ observations.groupby("indicator_code")["fiscal_year"]
62
+ .agg(lambda s: sorted({int(y) for y in s}))
63
+ .to_dict()
64
+ )
65
+ n_obs = observations.groupby("indicator_code").size().to_dict()
66
+ n_valued = (
67
+ observations[observations["value_status"] == "value"]
68
+ .groupby("indicator_code")
69
+ .size()
70
+ .to_dict()
71
+ )
72
+
73
+ rows = []
74
+ for code in codes:
75
+ row: dict = {"indicator_code": code}
76
+ for gen in GENERATIONS:
77
+ sfx = SUFFIX[gen]
78
+ present = code in by_gen[gen].index
79
+ row[f"in_{sfx}"] = present
80
+ row[f"label_{sfx}"] = by_gen[gen].at[code, "label"] if present else None
81
+ row[f"indicator_type_{sfx}"] = (
82
+ by_gen[gen].at[code, "indicator_type"] if present else None
83
+ )
84
+ row["label_changed_2016_to_2018"] = _label_changed(row["label_2016"], row["label_2018"])
85
+ row["label_changed_2018_to_2020plus"] = _label_changed(
86
+ row["label_2018"], row["label_2020plus"]
87
+ )
88
+ row["label_similarity_2016_to_2018"] = label_similarity(
89
+ row["label_2016"], row["label_2018"]
90
+ )
91
+ row["label_similarity_2018_to_2020plus"] = label_similarity(
92
+ row["label_2018"], row["label_2020plus"]
93
+ )
94
+ row["n_generations"] = sum(row[f"in_{SUFFIX[g]}"] for g in GENERATIONS)
95
+ row["comparability_flag"] = _comparability_flag(row)
96
+ row["fiscal_years_with_data"] = years.get(code, [])
97
+ row["n_observations"] = int(n_obs.get(code, 0))
98
+ row["n_observations_with_value"] = int(n_valued.get(code, 0))
99
+ rows.append(row)
100
+ return pd.DataFrame(rows)
pipeline/src/isora_hf/observations.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Turn the raw SDMX-CSV observation files into one clean, typed, long-format table."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import html
6
+ import logging
7
+ import re
8
+ from dataclasses import dataclass
9
+
10
+ import pandas as pd
11
+
12
+ from isora_hf import config
13
+ from isora_hf.config import Dataflow
14
+
15
+ log = logging.getLogger(__name__)
16
+
17
+ NUMERIC_RE = re.compile(r"^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$")
18
+ SPACE_GROUPED_RE = re.compile(r"^-?\d{1,3}( \d{3})+$")
19
+ HTML_TAG_RE = re.compile(r"<[^>]+>")
20
+ WS_RE = re.compile(r"\s+")
21
+ MOJIBAKE_RE = re.compile(r"Ã|â€|Â")
22
+
23
+ STATUS_VALUE = "value"
24
+ STATUS_NOT_AVAILABLE = "not_available"
25
+ STATUS_NOT_APPLICABLE = "not_applicable"
26
+ STATUS_EMPTY = "empty"
27
+ STATUS_UNRECOGNIZED = "unrecognized_code"
28
+
29
+ UNIT_LCU = "local currency units"
30
+ UNIT_LCU_THOUSANDS = "thousands of local currency"
31
+ THOUSAND = 1000.0
32
+
33
+ KIND_NUMERIC = "numeric"
34
+ KIND_BINARY = "binary"
35
+ KIND_CATEGORICAL = "categorical"
36
+ KIND_TEXT = "free_text"
37
+ KIND_MIXED = "mixed"
38
+ KIND_NO_VALUES = "no_values"
39
+ MAX_CATEGORIES = 25
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class ParsedValue:
44
+ numeric: float | None
45
+ text: str | None
46
+ status: str
47
+
48
+
49
+ def repair_mojibake(text: str, max_rounds: int = 3) -> str:
50
+ """Undo UTF-8 text that was decoded as cp1252 one or more times (e.g. '‘' -> '‘')."""
51
+ out = text
52
+ for _ in range(max_rounds):
53
+ if not MOJIBAKE_RE.search(out):
54
+ break
55
+ try:
56
+ candidate = out.encode("cp1252").decode("utf-8")
57
+ except (UnicodeEncodeError, UnicodeDecodeError):
58
+ break
59
+ if candidate == out:
60
+ break
61
+ out = candidate
62
+ return out
63
+
64
+
65
+ def clean_text(raw: str) -> str:
66
+ """Strip HTML tags and entities that leak from the survey UI, repair encoding glitches,
67
+ collapse whitespace."""
68
+ no_tags = HTML_TAG_RE.sub(" ", html.unescape(raw))
69
+ return WS_RE.sub(" ", repair_mojibake(no_tags)).strip()
70
+
71
+
72
+ def parse_value(raw: str | None) -> ParsedValue:
73
+ """Split the mixed-type OBSERVATION string into numeric / text / status."""
74
+ stripped = (raw or "").strip()
75
+ if not stripped:
76
+ return ParsedValue(None, None, STATUS_EMPTY)
77
+ if stripped in config.NOT_AVAILABLE_CODES:
78
+ return ParsedValue(None, None, STATUS_NOT_AVAILABLE)
79
+ if stripped in config.UNRECOGNIZED_CODES:
80
+ return ParsedValue(None, stripped, STATUS_UNRECOGNIZED)
81
+ if SPACE_GROUPED_RE.match(stripped):
82
+ stripped = stripped.replace(" ", "")
83
+ if NUMERIC_RE.match(stripped):
84
+ return ParsedValue(float(stripped), None, STATUS_VALUE)
85
+ text = clean_text(stripped)
86
+ if text.lower() in config.NOT_APPLICABLE_STRINGS:
87
+ return ParsedValue(None, text, STATUS_NOT_APPLICABLE)
88
+ return ParsedValue(None, text, STATUS_VALUE)
89
+
90
+
91
+ def observed_value_kind(numeric: pd.Series, text: pd.Series, status: pd.Series) -> str:
92
+ """Infer what kind of answers an indicator actually holds from its parsed values."""
93
+ valued = status == STATUS_VALUE
94
+ n_num = int((valued & numeric.notna()).sum())
95
+ n_txt = int((valued & text.notna()).sum())
96
+ if n_num == 0 and n_txt == 0:
97
+ return KIND_NO_VALUES
98
+ if n_txt == 0:
99
+ return KIND_NUMERIC
100
+ if n_num > 0:
101
+ return KIND_MIXED
102
+ answers = set(text[valued & text.notna()].str.lower())
103
+ if answers <= {"yes", "no"}:
104
+ return KIND_BINARY
105
+ return KIND_CATEGORICAL if len(answers) <= MAX_CATEGORIES else KIND_TEXT
106
+
107
+
108
+ def read_raw(flow_id: str, version: str) -> pd.DataFrame:
109
+ path = config.RAW_DATA_DIR / f"{flow_id}__{version}.csv"
110
+ frame = pd.read_csv(path, dtype=str, keep_default_na=False, encoding="utf-8")
111
+ # Rows without a TIME_PERIOD are dataset/series-level attribute rows, not observations.
112
+ return frame[frame["TIME_PERIOD"] != ""].copy()
113
+
114
+
115
+ def _survey_round(year: int) -> str:
116
+ try:
117
+ return config.FISCAL_YEAR_TO_ROUND[year]
118
+ except KeyError as exc:
119
+ raise ValueError(f"fiscal year {year} has no known ISORA round") from exc
120
+
121
+
122
+ def monetary_columns(
123
+ flow: Dataflow,
124
+ indicator_code: pd.Series,
125
+ unit_multiplier: pd.Series,
126
+ numeric: pd.Series,
127
+ monetary_codes: set[str],
128
+ ) -> tuple[pd.Series, pd.Series]:
129
+ """Harmonize money amounts to base local-currency units.
130
+
131
+ ISORA 2016/2018 published monetary answers in thousands (as asked on the form) with SCALE=0.
132
+ The consolidated FY2018+ dataflow publishes the same questions already multiplied out to base
133
+ units and marks them with SCALE=3 (verified against GDP and revenue magnitudes)."""
134
+ if flow.generation == "ISORA 2020+":
135
+ is_money = unit_multiplier == 3
136
+ unit = pd.Series(pd.NA, index=indicator_code.index, dtype="string").mask(is_money, UNIT_LCU)
137
+ harmonized = numeric.where(is_money)
138
+ else:
139
+ is_money = indicator_code.isin(monetary_codes)
140
+ unit = pd.Series(pd.NA, index=indicator_code.index, dtype="string").mask(
141
+ is_money, UNIT_LCU_THOUSANDS
142
+ )
143
+ harmonized = (numeric * THOUSAND).where(is_money)
144
+ return unit, harmonized
145
+
146
+
147
+ def clean_observations(
148
+ flow: Dataflow,
149
+ indicators: pd.DataFrame,
150
+ numeric_to_alpha3: dict[str, str],
151
+ jurisdiction_names: dict[str, str],
152
+ monetary_codes: set[str],
153
+ ) -> pd.DataFrame:
154
+ raw = read_raw(flow.id, flow.version)
155
+ log.info("%s: %d observation rows", flow.id, len(raw))
156
+ if not (raw["PUBLIC_DATA"].str.lower() == "true").all():
157
+ raise ValueError(f"{flow.id}: found rows not flagged PUBLIC_DATA=true")
158
+
159
+ geo = raw[flow.geo_dimension]
160
+ if geo.str.fullmatch(r"\d+").all():
161
+ unmapped = sorted(set(geo) - set(numeric_to_alpha3))
162
+ if unmapped:
163
+ raise ValueError(f"{flow.id}: numeric jurisdiction codes without alpha-3: {unmapped}")
164
+ jurisdiction_code = geo.map(numeric_to_alpha3)
165
+ else:
166
+ jurisdiction_code = geo
167
+
168
+ parsed = [parse_value(v) for v in raw["OBSERVATION"]]
169
+ labels = indicators.set_index("indicator_code")["label"]
170
+ unknown = sorted(set(raw["INDICATOR"]) - set(labels.index))
171
+ if unknown:
172
+ raise ValueError(f"{flow.id}: indicator codes missing from codelist: {unknown[:10]}")
173
+
174
+ fiscal_year = raw["TIME_PERIOD"].astype(int)
175
+ numeric = pd.Series([p.numeric for p in parsed], index=raw.index, dtype="float64")
176
+ text = pd.Series([p.text for p in parsed], index=raw.index, dtype="string")
177
+ status = pd.Series([p.status for p in parsed], index=raw.index, dtype="string")
178
+ unit_multiplier = raw["SCALE"].replace("", "0").astype(int)
179
+ unit, harmonized = monetary_columns(
180
+ flow, raw["INDICATOR"], unit_multiplier, numeric, monetary_codes
181
+ )
182
+ kinds = (
183
+ pd.DataFrame({"i": raw["INDICATOR"], "n": numeric, "t": text, "s": status})
184
+ .groupby("i")
185
+ .apply(lambda g: observed_value_kind(g["n"], g["t"], g["s"]), include_groups=False)
186
+ )
187
+
188
+ out = pd.DataFrame(
189
+ {
190
+ "jurisdiction_code": jurisdiction_code.values,
191
+ "jurisdiction_name": jurisdiction_code.map(jurisdiction_names).values,
192
+ "fiscal_year": fiscal_year.astype("int16").values,
193
+ "survey_round": [_survey_round(y) for y in fiscal_year],
194
+ "questionnaire_generation": flow.generation,
195
+ "indicator_code": raw["INDICATOR"].values,
196
+ "indicator_label": raw["INDICATOR"].map(labels).values,
197
+ "indicator_value_kind": raw["INDICATOR"].map(kinds).values,
198
+ "value_raw": raw["OBSERVATION"].values,
199
+ "value_numeric": numeric.values,
200
+ "value_text": text.values,
201
+ "value_status": status.values,
202
+ "unit_multiplier": unit_multiplier.astype("int8").values,
203
+ "monetary_unit": unit.values,
204
+ "value_local_currency_units": harmonized.values,
205
+ "form_status": raw[flow.form_status_attr].replace("", None).values,
206
+ "footnote": raw["FOOTNOTE"].map(lambda s: clean_text(s) or None).values,
207
+ "source_dataflow": flow.id,
208
+ "source_dataflow_version": flow.version,
209
+ }
210
+ )
211
+ missing_names = out.loc[out["jurisdiction_name"].isna(), "jurisdiction_code"].unique()
212
+ if len(missing_names):
213
+ raise ValueError(f"{flow.id}: jurisdictions without a name: {sorted(missing_names)}")
214
+ dup = out.duplicated(["jurisdiction_code", "indicator_code", "fiscal_year"]).sum()
215
+ if dup:
216
+ raise ValueError(f"{flow.id}: {dup} duplicate (jurisdiction, indicator, year) keys")
217
+ return out.sort_values(["jurisdiction_code", "indicator_code", "fiscal_year"]).reset_index(
218
+ drop=True
219
+ )
220
+
221
+
222
+ OBSERVATION_COLUMNS = [
223
+ "jurisdiction_code",
224
+ "jurisdiction_name",
225
+ "fiscal_year",
226
+ "survey_round",
227
+ "questionnaire_generation",
228
+ "indicator_code",
229
+ "indicator_label",
230
+ "indicator_value_kind",
231
+ "value_raw",
232
+ "value_numeric",
233
+ "value_text",
234
+ "value_status",
235
+ "unit_multiplier",
236
+ "monetary_unit",
237
+ "value_local_currency_units",
238
+ "form_status",
239
+ "footnote",
240
+ "source_dataflow",
241
+ "source_dataflow_version",
242
+ ]
pipeline/src/isora_hf/revisions.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compare successive published vintages of the consolidated FY2018+ dataflow.
2
+
3
+ The IMF API still serves earlier versions of ISORA_LATEST_DATA_PUB. Each version is the dataset
4
+ as released after a survey round, so differences between versions are revisions (corrections,
5
+ late submissions, withdrawals, indicators added or dropped). Pure formatting differences between
6
+ releases (thousands separators, float precision, encoding glitches) are not revisions and are
7
+ filtered out here.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import logging
13
+ import math
14
+ import re
15
+
16
+ import pandas as pd
17
+
18
+ from isora_hf import config
19
+ from isora_hf.observations import clean_text, read_raw
20
+
21
+ log = logging.getLogger(__name__)
22
+
23
+ KEY = ["jurisdiction_code", "indicator_code", "fiscal_year"]
24
+ GROUPED_NUMBER_RE = re.compile(r"^-?\d{1,3}(,\d{3})+(\.\d+)?$")
25
+ PLAIN_NUMBER_RE = re.compile(r"^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$")
26
+ REL_TOL = 1e-6
27
+ SCALE_FACTOR = 1000.0
28
+
29
+ CHANGE_VALUE = "value_revised"
30
+ CHANGE_SCALE = "scale_convention_change"
31
+ CHANGE_TEXT = "text_revised"
32
+ CHANGE_ADDED = "added_in_later_release"
33
+ CHANGE_REMOVED = "removed_in_later_release"
34
+
35
+
36
+ def canonical(raw: str | None) -> tuple[str, float | str | None, int]:
37
+ """Reduce a published value to (kind, payload, decimals).
38
+
39
+ kind is "missing", "number" or "text"; decimals is the number of decimal places the number
40
+ was published with (0 for text/missing) so that comparisons respect published precision."""
41
+ if raw is None or (isinstance(raw, float) and math.isnan(raw)):
42
+ return "missing", None, 0
43
+ stripped = str(raw).strip()
44
+ if not stripped:
45
+ return "missing", None, 0
46
+ if GROUPED_NUMBER_RE.match(stripped):
47
+ stripped = stripped.replace(",", "")
48
+ if PLAIN_NUMBER_RE.match(stripped):
49
+ decimals = (
50
+ len(stripped.split(".")[1]) if "." in stripped and "e" not in stripped.lower() else 0
51
+ )
52
+ return "number", float(stripped), decimals
53
+ return "text", clean_text(stripped).casefold(), 0
54
+
55
+
56
+ def _numbers_equal(a: float, b: float, decimals: int = 15) -> bool:
57
+ """Equal within floating tolerance, or equal once both are rounded to the coarser published
58
+ precision (e.g. '26.95' in one release and '26.94513581' in the next is a rounding artefact)."""
59
+ if math.isclose(a, b, rel_tol=REL_TOL, abs_tol=1e-9):
60
+ return True
61
+ return round(a, decimals) == round(b, decimals)
62
+
63
+
64
+ def _is_scale_change(a: float, b: float) -> bool:
65
+ if a == 0 or b == 0:
66
+ return False
67
+ return _numbers_equal(a * SCALE_FACTOR, b) or _numbers_equal(b * SCALE_FACTOR, a)
68
+
69
+
70
+ def classify(values: list[str | None]) -> str | None:
71
+ """Classify a key's sequence of published values (oldest -> newest, only vintages that
72
+ cover the key's fiscal year). Returns a change type or None when nothing meaningful changed."""
73
+ forms = [canonical(v) for v in values]
74
+ presence = [kind != "missing" for kind, _, _ in forms]
75
+ if any(presence) and not all(presence):
76
+ return CHANGE_ADDED if presence.index(True) > 0 else CHANGE_REMOVED
77
+ present = [(k, p, d) for k, p, d in forms if k != "missing"]
78
+ if len(present) < 2:
79
+ return None
80
+ kinds = {k for k, _, _ in present}
81
+ if kinds == {"number"}:
82
+ nums = [p for _, p, _ in present]
83
+ decimals = min(d for _, _, d in present)
84
+ if all(_numbers_equal(n, nums[0], decimals) for n in nums):
85
+ return None
86
+ if all(_numbers_equal(n, nums[0], decimals) or _is_scale_change(n, nums[0]) for n in nums):
87
+ return CHANGE_SCALE
88
+ return CHANGE_VALUE
89
+ if kinds == {"text"}:
90
+ return CHANGE_TEXT if len({p for _, p, _ in present}) > 1 else None
91
+ return CHANGE_VALUE
92
+
93
+
94
+ def _vintage_frame(version: str, label: str) -> pd.DataFrame:
95
+ raw = read_raw("ISORA_LATEST_DATA_PUB", version)
96
+ return pd.DataFrame(
97
+ {
98
+ "jurisdiction_code": raw["JURISDICTION"].values,
99
+ "indicator_code": raw["INDICATOR"].values,
100
+ "fiscal_year": raw["TIME_PERIOD"].astype(int).values,
101
+ "value_raw": raw["OBSERVATION"].str.strip().values,
102
+ "vintage_version": version,
103
+ "vintage_label": label,
104
+ }
105
+ )
106
+
107
+
108
+ def _years_covered(spec: str) -> set[int]:
109
+ start, end = (int(x) for x in spec.split("-"))
110
+ return set(range(start, end + 1))
111
+
112
+
113
+ def build_revisions() -> tuple[pd.DataFrame, dict]:
114
+ vintages = [(v, lbl, _years_covered(yrs)) for v, lbl, yrs in config.VINTAGES]
115
+ versions = [v for v, _, _ in vintages]
116
+ stacked = pd.concat([_vintage_frame(v, lbl) for v, lbl, _ in vintages], ignore_index=True)
117
+ wide = stacked.pivot_table(
118
+ index=KEY, columns="vintage_version", values="value_raw", aggfunc="first"
119
+ )
120
+ wide = wide.reindex(columns=versions)
121
+
122
+ years = wide.index.get_level_values("fiscal_year")
123
+ change_types = []
124
+ for values, year in zip(wide[versions].to_numpy(), years):
125
+ covering = [v for v, (_, _, yrs) in zip(values, vintages) if year in yrs]
126
+ change_types.append(classify(list(covering)))
127
+ wide["change_type"] = change_types
128
+ changed = wide[wide["change_type"].notna()].reset_index()
129
+
130
+ long = changed.melt(
131
+ id_vars=KEY + ["change_type"], var_name="vintage_version", value_name="value_raw"
132
+ )
133
+ labels = {v: lbl for v, lbl, _ in vintages}
134
+ cover = {v: yrs for v, _, yrs in vintages}
135
+ long["vintage_label"] = long["vintage_version"].map(labels)
136
+ long["vintage_covers_year"] = [
137
+ y in cover[v] for v, y in zip(long["vintage_version"], long["fiscal_year"])
138
+ ]
139
+ long["present_in_vintage"] = long["value_raw"].notna()
140
+ long["fiscal_year"] = long["fiscal_year"].astype("int16")
141
+ long = long[
142
+ KEY
143
+ + [
144
+ "change_type",
145
+ "vintage_version",
146
+ "vintage_label",
147
+ "vintage_covers_year",
148
+ "present_in_vintage",
149
+ "value_raw",
150
+ ]
151
+ ]
152
+ long = long.sort_values(KEY + ["vintage_version"]).reset_index(drop=True)
153
+
154
+ summary = {
155
+ "vintages": [
156
+ {"version": v, "label": lbl, "rows": int((stacked["vintage_version"] == v).sum())}
157
+ for v, lbl, _ in vintages
158
+ ],
159
+ "keys_compared": len(wide),
160
+ "keys_with_changes": len(changed),
161
+ "change_types": {k: int(v) for k, v in changed["change_type"].value_counts().items()},
162
+ "keys_with_changes_by_fiscal_year": {
163
+ int(y): int(n) for y, n in changed.groupby("fiscal_year").size().items()
164
+ },
165
+ }
166
+ log.info("revisions: %s", summary)
167
+ return long, summary
pipeline/src/isora_hf/sdmx_client.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Thin client for the IMF SDMX API with on-disk caching of every response used by the build."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from datetime import UTC
7
+ from pathlib import Path
8
+
9
+ import requests
10
+
11
+ from isora_hf import config
12
+
13
+ log = logging.getLogger(__name__)
14
+
15
+ STRUCTURE_JSON = "application/vnd.sdmx.structure+json;version=2.0.0"
16
+ DATA_CSV = "application/vnd.sdmx.data+csv;version=2.0.0"
17
+ LEGACY_CSV = "text/csv"
18
+
19
+
20
+ def _get(url: str, accept: str, timeout: int = 300) -> bytes:
21
+ headers = {"Accept": accept, "User-Agent": config.USER_AGENT}
22
+ response = requests.get(url, headers=headers, timeout=timeout)
23
+ response.raise_for_status()
24
+ if response.status_code == 204 or not response.content:
25
+ raise RuntimeError(f"Empty response from {url}")
26
+ return response.content
27
+
28
+
29
+ def _cached(path: Path, url: str, accept: str, force: bool = False) -> Path:
30
+ if path.exists() and not force:
31
+ log.info("cache hit %s", path.name)
32
+ return path
33
+ path.parent.mkdir(parents=True, exist_ok=True)
34
+ log.info("GET %s", url)
35
+ path.write_bytes(_get(url, accept))
36
+ return path
37
+
38
+
39
+ def fetch_dataflows(force: bool = False) -> Path:
40
+ url = f"{config.SDMX3_BASE}/structure/dataflow/{config.AGENCY}/*/*"
41
+ return _cached(config.RAW_STRUCTURES_DIR / "dataflows__ISORA.json", url, STRUCTURE_JSON, force)
42
+
43
+
44
+ def fetch_dsd(version: str, force: bool = False) -> Path:
45
+ url = (
46
+ f"{config.SDMX3_BASE}/structure/datastructure/{config.AGENCY}/DSD_ISORA_PUBLISHED/"
47
+ f"{version}?references=descendants"
48
+ )
49
+ path = config.RAW_STRUCTURES_DIR / f"DSD_ISORA_PUBLISHED__{version}.json"
50
+ return _cached(path, url, STRUCTURE_JSON, force)
51
+
52
+
53
+ def fetch_hierarchies(force: bool = False) -> Path:
54
+ url = f"{config.SDMX3_BASE}/structure/hierarchy/{config.AGENCY}/*/*"
55
+ return _cached(config.RAW_STRUCTURES_DIR / "hierarchies__all.json", url, STRUCTURE_JSON, force)
56
+
57
+
58
+ def fetch_rafit_labels(force: bool = False) -> Path:
59
+ url = f"{config.SDMX3_BASE}/structure/codelist/{config.AGENCY}/CL_RAFIT_LABELS/*"
60
+ return _cached(
61
+ config.RAW_STRUCTURES_DIR / "CL_RAFIT_LABELS__all.json", url, STRUCTURE_JSON, force
62
+ )
63
+
64
+
65
+ def fetch_data(dataflow_id: str, version: str, force: bool = False) -> Path:
66
+ url = f"{config.SDMX3_BASE}/data/dataflow/{config.AGENCY}/{dataflow_id}/{version}/*"
67
+ path = config.RAW_DATA_DIR / f"{dataflow_id}__{version}.csv"
68
+ return _cached(path, url, DATA_CSV, force)
69
+
70
+
71
+ def fetch_dataset_metadata(dataflow_id: str, sample_key: str, force: bool = False) -> Path:
72
+ """The SDMX 2.1 CSV repeats dataset-level attributes (license, citation, dates) on every row,
73
+ so a single tiny series is enough to capture them."""
74
+ url = f"{config.SDMX21_BASE}/data/{dataflow_id}/{sample_key}"
75
+ path = config.RAW_STRUCTURES_DIR / f"dataset_metadata__{dataflow_id}.csv"
76
+ return _cached(path, url, LEGACY_CSV, force)
77
+
78
+
79
+ METADATA_SAMPLE_KEYS = {
80
+ "ISORA_2016_DATA_PUB": "111.10010.A",
81
+ "ISORA_2018_DATA_PUB": "111.337_001.A",
82
+ "ISORA_LATEST_DATA_PUB": "ABW.PARTICIPATION_RATE.A",
83
+ }
84
+
85
+
86
+ def download_everything(force: bool = False) -> None:
87
+ """Fetch every raw artifact the build needs. Safe to re-run; cached files are reused."""
88
+ fetch_dataflows(force)
89
+ fetch_hierarchies(force)
90
+ fetch_rafit_labels(force)
91
+ for flow in config.DATAFLOWS:
92
+ fetch_dsd(flow.dsd_version, force)
93
+ fetch_data(flow.id, flow.version, force)
94
+ fetch_dataset_metadata(flow.id, METADATA_SAMPLE_KEYS[flow.id], force)
95
+ for version, _label, _years in config.VINTAGES:
96
+ fetch_data("ISORA_LATEST_DATA_PUB", version, force)
97
+ stamp = config.RAW_DIR / "RETRIEVED_AT.txt"
98
+ if force or not stamp.exists():
99
+ from datetime import datetime
100
+
101
+ stamp.write_text(datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ") + "\n")
102
+
103
+
104
+ if __name__ == "__main__":
105
+ import sys
106
+
107
+ logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
108
+ download_everything(force="--force" in sys.argv)
pipeline/src/isora_hf/structures.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Parse SDMX structural metadata (codelists, hierarchies, dataset attributes) into tables."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import csv
6
+ import json
7
+ import re
8
+ from typing import Any
9
+
10
+ import pandas as pd
11
+
12
+ from isora_hf import config
13
+ from isora_hf.config import Dataflow
14
+
15
+ THOUSANDS_RE = re.compile(r"thousand|'000|\b000s\b", re.IGNORECASE)
16
+ DERIVED_PREFIXES = ("337_", "398_")
17
+
18
+
19
+ def _clean(text: str | None) -> str | None:
20
+ if text is None:
21
+ return None
22
+ cleaned = re.sub(r"\s+", " ", str(text)).strip()
23
+ return cleaned or None
24
+
25
+
26
+ def annotations(code: dict[str, Any]) -> dict[str, str]:
27
+ """Flatten SDMX annotations into {title: text}. Empty values are dropped."""
28
+ out: dict[str, str] = {}
29
+ for ann in code.get("annotations", []):
30
+ title = ann.get("title")
31
+ value = _clean(ann.get("text") or ann.get("value"))
32
+ if title and value:
33
+ out[title] = value
34
+ return out
35
+
36
+
37
+ def load_dsd(version: str) -> dict[str, Any]:
38
+ path = config.RAW_STRUCTURES_DIR / f"DSD_ISORA_PUBLISHED__{version}.json"
39
+ return json.loads(path.read_text(encoding="utf-8"))["data"]
40
+
41
+
42
+ def codelist(dsd: dict[str, Any], codelist_id: str) -> dict[str, Any]:
43
+ matches = [cl for cl in dsd["codelists"] if cl["id"] == codelist_id]
44
+ if not matches:
45
+ raise KeyError(f"codelist {codelist_id} not in DSD")
46
+ return matches[0]
47
+
48
+
49
+ def normalize_indicator_type(dissem_scale: str | None) -> str:
50
+ key = (dissem_scale or "").strip().lower()
51
+ return config.INDICATOR_TYPE_MAP.get(key, key or "unspecified")
52
+
53
+
54
+ def _is_derived(code_id: str, ann: dict[str, str]) -> bool:
55
+ return (
56
+ code_id.startswith(DERIVED_PREFIXES)
57
+ or bool(ann.get("OriginalFormula"))
58
+ or bool(ann.get("Numerator"))
59
+ )
60
+
61
+
62
+ def indicator_row(flow: Dataflow, cl_version: str, code: dict[str, Any]) -> dict[str, Any]:
63
+ ann = annotations(code)
64
+ label = _clean(code.get("name")) or code["id"]
65
+ subtitle = " | ".join(s for s in (ann.get("Subtitle1"), ann.get("Subtitle2")) if s) or None
66
+ return {
67
+ "questionnaire_generation": flow.generation,
68
+ "codelist_id": flow.indicator_codelist,
69
+ "codelist_version": cl_version,
70
+ "indicator_code": code["id"],
71
+ "label": label,
72
+ "display_label": ann.get("Display Indicator"),
73
+ "description": _clean(code.get("description")),
74
+ "form_code": ann.get("SubReport"),
75
+ "form_name": ann.get("ReportFormDescription"),
76
+ "question_ref": ann.get("Question"),
77
+ "section": ann.get("Category Tab"),
78
+ "report_table_index": ann.get("Table Index"),
79
+ "report_table_title": ann.get("Table Title"),
80
+ "subtitle": subtitle,
81
+ "scope": ann.get("Report"),
82
+ "indicator_type": normalize_indicator_type(ann.get("DissemScale")),
83
+ "is_local_currency": ann.get("DissemCurrency") == "NC",
84
+ "label_mentions_thousands": bool(THOUSANDS_RE.search(label)),
85
+ "is_derived": _is_derived(code["id"], ann),
86
+ "formula": ann.get("OriginalFormula"),
87
+ "numerator": ann.get("Numerator"),
88
+ "denominator": ann.get("Denominator"),
89
+ "legend": ann.get("Legend"),
90
+ "suppressed_in_source_tables": ann.get("Suppress") == "Yes",
91
+ "source_last_update": ann.get("Last Update"),
92
+ }
93
+
94
+
95
+ def indicator_table(flow: Dataflow) -> pd.DataFrame:
96
+ dsd = load_dsd(flow.dsd_version)
97
+ cl = codelist(dsd, flow.indicator_codelist)
98
+ rows = [indicator_row(flow, cl["version"], code) for code in cl["codes"]]
99
+ return pd.DataFrame(rows)
100
+
101
+
102
+ # ---------------------------------------------------------------- jurisdictions
103
+
104
+ MEMBERSHIP_FLAGS = {
105
+ "Member_ADB": "member_adb",
106
+ "Member_CIAT": "member_ciat",
107
+ "Member_IOTA": "member_iota",
108
+ "Member_OECD": "member_oecd",
109
+ "Member_EU": "member_eu",
110
+ "Member_G20": "member_g20",
111
+ "Member_G7": "member_g7",
112
+ "Member_WCO": "member_wco",
113
+ "Member_FTA": "member_oecd_fta",
114
+ "Member_WAEMU": "member_waemu",
115
+ }
116
+
117
+
118
+ def _yes_no(value: str | None) -> bool | None:
119
+ if value is None:
120
+ return None
121
+ lowered = value.strip().lower()
122
+ if lowered in ("yes", "1", "true"):
123
+ return True
124
+ if lowered in ("no", "0", "false"):
125
+ return False
126
+ return None
127
+
128
+
129
+ def jurisdiction_master() -> pd.DataFrame:
130
+ """One row per alpha-3 jurisdiction code, from the latest CL_ISORA_ISO_COUNTRY codelist."""
131
+ dsd = load_dsd(config.DATAFLOWS[-1].dsd_version)
132
+ cl = codelist(dsd, "CL_ISORA_ISO_COUNTRY")
133
+ rows = []
134
+ for code in cl["codes"]:
135
+ ann = annotations(code)
136
+ row = {
137
+ "jurisdiction_code": code["id"],
138
+ "jurisdiction_name": _clean(code.get("name")),
139
+ "imf_numeric_code": ann.get("Numerical Code") or ann.get("Primary Code"),
140
+ "imf_region": ann.get("IMF_Region"),
141
+ "imf_subregion": ann.get("IMF_SubRegion"),
142
+ "imf_regional_ta_center": ann.get("IMF_RTAC"),
143
+ "world_bank_region": ann.get("WB_Region"),
144
+ "world_bank_income_group_fy2015": ann.get("WB_IncomeGroup_FY15"),
145
+ "weo_group": ann.get("WEO_AdvancedVsDeveloping"),
146
+ "fragile_state_flag": ann.get("Fragile States"),
147
+ "small_developing_state_flag": ann.get("Small Developing States"),
148
+ }
149
+ for src, dst in MEMBERSHIP_FLAGS.items():
150
+ row[dst] = _yes_no(ann.get(src))
151
+ rows.append(row)
152
+ return pd.DataFrame(rows)
153
+
154
+
155
+ def numeric_to_alpha3() -> dict[str, str]:
156
+ """Map IMF numeric jurisdiction codes (used by ISORA 2016/2018) to the alpha-3 codes used
157
+ by the consolidated dataflow. The latest CL_JURISDICTION carries an ISO annotation."""
158
+ dsd = load_dsd(config.DATAFLOWS[-1].dsd_version)
159
+ mapping: dict[str, str] = {}
160
+ for code in codelist(dsd, "CL_JURISDICTION")["codes"]:
161
+ iso = annotations(code).get("ISO")
162
+ if iso and iso != "NULL":
163
+ mapping[code["id"]] = iso
164
+ # Older DSDs may know codes the latest one dropped; fill gaps without overriding.
165
+ for flow in config.DATAFLOWS[:2]:
166
+ for code in codelist(load_dsd(flow.dsd_version), "CL_COUNTRY")["codes"]:
167
+ iso = annotations(code).get("ISO")
168
+ if iso and iso != "NULL":
169
+ mapping.setdefault(code["id"], iso)
170
+ return mapping
171
+
172
+
173
+ # ---------------------------------------------------------------- hierarchies
174
+
175
+ HIERARCHY_VERSIONS = {
176
+ "H_CL_INDICATORS_BY_TOPIC": "2.2.0",
177
+ "H_CL_PERIODIC_INDICATORS": "2.0.0",
178
+ "H_CL_DERIVED_INDICATORS": "2.0.0",
179
+ "H_CL_REVIEW_INDICATORS": "2.1.0",
180
+ }
181
+
182
+
183
+ def _rafit_labels() -> dict[str, str]:
184
+ path = config.RAW_STRUCTURES_DIR / "CL_RAFIT_LABELS__all.json"
185
+ data = json.loads(path.read_text(encoding="utf-8"))["data"]
186
+ labels: dict[str, str] = {}
187
+ for cl in data.get("codelists", []):
188
+ for code in cl["codes"]:
189
+ labels[code["id"]] = _clean(code.get("name")) or code["id"]
190
+ return labels
191
+
192
+
193
+ def _walk(node: dict[str, Any], ancestors: list[str], labels: dict[str, str], out: list) -> None:
194
+ for child in node.get("hierarchicalCodes", []):
195
+ target = (child.get("code") or "").split("=")[-1] # e.g. CL_ISORA_TAX(6.0+.0).337_001
196
+ codelist_name, _, code_id = target.rpartition(").")
197
+ if "CL_RAFIT_LABELS" in codelist_name:
198
+ _walk(child, ancestors + [labels.get(code_id, code_id)], labels, out)
199
+ else:
200
+ out.append((code_id, ancestors, len(out)))
201
+ _walk(child, ancestors, labels, out)
202
+
203
+
204
+ def hierarchy_memberships() -> pd.DataFrame:
205
+ """Long table: hierarchy -> group path -> indicator code, for the versions used by the
206
+ current consolidated dataflow."""
207
+ path = config.RAW_STRUCTURES_DIR / "hierarchies__all.json"
208
+ data = json.loads(path.read_text(encoding="utf-8"))["data"]
209
+ labels = _rafit_labels()
210
+ rows = []
211
+ for hier in data.get("hierarchies", []):
212
+ if HIERARCHY_VERSIONS.get(hier["id"]) != hier["version"]:
213
+ continue
214
+ members: list = []
215
+ _walk(hier, [], labels, members)
216
+ for code_id, ancestors, order in members:
217
+ rows.append(
218
+ {
219
+ "hierarchy_id": hier["id"],
220
+ "hierarchy_name": _clean(hier.get("name")),
221
+ "group": ancestors[0] if ancestors else None,
222
+ "subgroup": ancestors[1] if len(ancestors) > 1 else None,
223
+ "indicator_code": code_id,
224
+ "position": order,
225
+ }
226
+ )
227
+ return pd.DataFrame(rows)
228
+
229
+
230
+ # ---------------------------------------------------------------- dataset attributes
231
+
232
+
233
+ def dataset_metadata(dataflow_id: str) -> dict[str, str]:
234
+ """Dataset-level attributes (license URL, citations, publication dates) from the 2.1 CSV."""
235
+ path = config.RAW_STRUCTURES_DIR / f"dataset_metadata__{dataflow_id}.csv"
236
+ with path.open(encoding="utf-8", newline="") as fh:
237
+ reader = csv.DictReader(fh)
238
+ first = next(reader)
239
+ keep = (
240
+ "DATAFLOW",
241
+ "FULL_DESCRIPTION",
242
+ "PUBLISHER",
243
+ "DEPARTMENT",
244
+ "CONTACT_POINT",
245
+ "PUBLICATION_DATE",
246
+ "UPDATE_DATE",
247
+ "ACCESS_SHARING_LEVEL",
248
+ "SECURITY_CLASSIFICATION",
249
+ "SHORT_SOURCE_CITATION",
250
+ "FULL_SOURCE_CITATION",
251
+ "LICENSE",
252
+ "SUGGESTED_CITATION",
253
+ "KEYWORDS_DATASET",
254
+ )
255
+ return {k: first.get(k, "") for k in keep}
256
+
257
+
258
+ def dataflow_versions() -> list[dict[str, str]]:
259
+ path = config.RAW_STRUCTURES_DIR / "dataflows__ISORA.json"
260
+ data = json.loads(path.read_text(encoding="utf-8"))["data"]
261
+ out = []
262
+ for df in data["dataflows"]:
263
+ updated = next(
264
+ (a.get("value") for a in df.get("annotations", []) if a.get("id") == "lastUpdatedAt"),
265
+ None,
266
+ )
267
+ out.append(
268
+ {
269
+ "dataflow_id": df["id"],
270
+ "version": df["version"],
271
+ "description": df.get("description"),
272
+ "data_structure": df["structure"].split("=")[-1],
273
+ "last_updated_at_source": updated,
274
+ }
275
+ )
276
+ return out
277
+
278
+
279
+ # ---------------------------------------------------------------- monetary detection
280
+
281
+ COUNT_LIKE_RE = re.compile(r"\b(number of|no\. of|stock of [a-z ]*cases)\b", re.IGNORECASE)
282
+
283
+
284
+ def declared_monetary_codes(indicators: pd.DataFrame) -> set[str]:
285
+ """Indicator codes of a 2016/2018 codelist that hold money amounts.
286
+
287
+ The source types them as 'currency' (a subset of the national-currency flag). A handful of
288
+ count questions are mistyped as currency; labels that read as counts are excluded unless they
289
+ explicitly say 'value'."""
290
+ money = indicators[indicators["indicator_type"] == "currency"]
291
+ keep = [
292
+ code
293
+ for code, label in zip(money["indicator_code"], money["label"])
294
+ if "value" in label.lower() or not COUNT_LIKE_RE.search(label)
295
+ ]
296
+ return set(keep)
pipeline/tests/test_crosswalk.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+
3
+ from isora_hf.crosswalk import build_indicator_history, label_similarity, normalize_label
4
+
5
+
6
+ def test_normalize_label_ignores_case_punctuation_and_spacing():
7
+ assert normalize_label("Annual report - prepared") == normalize_label(
8
+ "annual report prepared."
9
+ )
10
+
11
+
12
+ def test_similarity_is_one_for_equivalent_labels_and_none_when_missing():
13
+ assert label_similarity("Annual report - prepared", "Annual report prepared") == 1.0
14
+ assert label_similarity(None, "x") is None
15
+
16
+
17
+ def _indicators():
18
+ return pd.DataFrame(
19
+ [
20
+ {
21
+ "questionnaire_generation": "ISORA 2016",
22
+ "indicator_code": "A",
23
+ "label": "Staff total",
24
+ "indicator_type": "count",
25
+ },
26
+ {
27
+ "questionnaire_generation": "ISORA 2018",
28
+ "indicator_code": "A",
29
+ "label": "Staff total",
30
+ "indicator_type": "count",
31
+ },
32
+ {
33
+ "questionnaire_generation": "ISORA 2020+",
34
+ "indicator_code": "A",
35
+ "label": "Total staff (FTE)",
36
+ "indicator_type": "count",
37
+ },
38
+ {
39
+ "questionnaire_generation": "ISORA 2016",
40
+ "indicator_code": "B",
41
+ "label": "Old only",
42
+ "indicator_type": "binary",
43
+ },
44
+ ]
45
+ )
46
+
47
+
48
+ def _observations():
49
+ return pd.DataFrame(
50
+ [
51
+ {"indicator_code": "A", "fiscal_year": 2014, "value_status": "value"},
52
+ {"indicator_code": "A", "fiscal_year": 2024, "value_status": "not_available"},
53
+ {"indicator_code": "B", "fiscal_year": 2015, "value_status": "value"},
54
+ ]
55
+ )
56
+
57
+
58
+ def test_history_flags_label_changes_and_single_generation_codes():
59
+ hist = build_indicator_history(_indicators(), _observations()).set_index("indicator_code")
60
+ a = hist.loc["A"]
61
+ assert a["in_2016"] and a["in_2018"] and a["in_2020plus"]
62
+ assert a["label_changed_2016_to_2018"] is False or a["label_changed_2016_to_2018"] == False
63
+ assert a["label_changed_2018_to_2020plus"] == True
64
+ assert a["comparability_flag"] == "label_changed"
65
+ assert a["fiscal_years_with_data"] == [2014, 2024]
66
+ assert a["n_observations"] == 2 and a["n_observations_with_value"] == 1
67
+ b = hist.loc["B"]
68
+ assert b["comparability_flag"] == "single_generation"
69
+ assert pd.isna(b["label_2018"]) and b["n_generations"] == 1
pipeline/tests/test_observations.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from isora_hf.observations import (
2
+ STATUS_EMPTY,
3
+ STATUS_NOT_APPLICABLE,
4
+ STATUS_NOT_AVAILABLE,
5
+ STATUS_UNRECOGNIZED,
6
+ STATUS_VALUE,
7
+ clean_text,
8
+ parse_value,
9
+ )
10
+
11
+
12
+ def test_numeric_values_are_parsed_to_float():
13
+ parsed = parse_value(" 15.35949622 ")
14
+ assert parsed.status == STATUS_VALUE
15
+ assert parsed.numeric == 15.35949622
16
+ assert parsed.text is None
17
+
18
+
19
+ def test_negative_and_exponent_numbers_are_numeric():
20
+ assert parse_value("-3").numeric == -3.0
21
+ assert parse_value("1e3").numeric == 1000.0
22
+
23
+
24
+ def test_nan_and_inf_strings_are_not_numeric():
25
+ for raw in ("nan", "inf", "NaN", "Infinity"):
26
+ parsed = parse_value(raw)
27
+ assert parsed.numeric is None
28
+ assert parsed.text == raw
29
+
30
+
31
+ def test_d_is_not_available_sentinel():
32
+ parsed = parse_value("D")
33
+ assert parsed.status == STATUS_NOT_AVAILABLE
34
+ assert parsed.numeric is None and parsed.text is None
35
+
36
+
37
+ def test_p_is_flagged_as_unrecognized_but_kept():
38
+ parsed = parse_value("P")
39
+ assert parsed.status == STATUS_UNRECOGNIZED
40
+ assert parsed.text == "P"
41
+
42
+
43
+ def test_not_applicable_variants():
44
+ for raw in ("Not Applicable", "N/A", "not applicable "):
45
+ assert parse_value(raw).status == STATUS_NOT_APPLICABLE
46
+
47
+
48
+ def test_empty_string_is_empty_status():
49
+ assert parse_value("").status == STATUS_EMPTY
50
+ assert parse_value(None).status == STATUS_EMPTY
51
+
52
+
53
+ def test_categorical_answers_keep_text_and_strip_html():
54
+ parsed = parse_value("option a)<br/>")
55
+ assert parsed.status == STATUS_VALUE
56
+ assert parsed.text == "option a)"
57
+ assert parsed.numeric is None
58
+
59
+
60
+ def test_clean_text_collapses_whitespace_and_entities():
61
+ assert clean_text(" High &amp; Medium\n priority ") == "High & Medium priority"
62
+
63
+
64
+ def test_repair_mojibake_handles_double_encoding_and_leaves_clean_text():
65
+ from isora_hf.observations import repair_mojibake
66
+
67
+ assert repair_mojibake("from ‘tax type’") == "from ‘tax type’"
68
+ assert repair_mojibake("Türkiye") == "Türkiye"
69
+ assert repair_mojibake("Türkiye ‘quoted’") == "Türkiye ‘quoted’"
70
+
71
+
72
+ def test_space_grouped_numbers_are_numeric():
73
+ parsed = parse_value("163 310 020")
74
+ assert parsed.status == STATUS_VALUE and parsed.numeric == 163310020.0
75
+
76
+
77
+ def test_observed_value_kind_inference():
78
+ import pandas as pd
79
+
80
+ from isora_hf.observations import observed_value_kind
81
+
82
+ def kind(vals):
83
+ parsed = [parse_value(v) for v in vals]
84
+ return observed_value_kind(
85
+ pd.Series([p.numeric for p in parsed], dtype="float64"),
86
+ pd.Series([p.text for p in parsed], dtype="string"),
87
+ pd.Series([p.status for p in parsed], dtype="string"),
88
+ )
89
+
90
+ assert kind(["1", "2.5", "D", ""]) == "numeric"
91
+ assert kind(["Yes", "No", "yes", "D"]) == "binary"
92
+ assert kind(["High", "Low", "Medium"]) == "categorical"
93
+ assert kind(["1", "Yes"]) == "mixed"
94
+ assert kind(["D", "", "Not Applicable"]) == "no_values"
95
+ assert kind([f"free text {i}" for i in range(40)]) == "free_text"
96
+
97
+
98
+ def test_monetary_harmonization_by_generation():
99
+ import pandas as pd
100
+
101
+ from isora_hf.config import DATAFLOWS
102
+ from isora_hf.observations import UNIT_LCU, UNIT_LCU_THOUSANDS, monetary_columns
103
+
104
+ codes = pd.Series(["80040_3", "83690_206"])
105
+ numeric = pd.Series([407383000.0, 120.0])
106
+ unit, harmonized = monetary_columns(
107
+ DATAFLOWS[1], codes, pd.Series([0, 0]), numeric, {"80040_3"}
108
+ )
109
+ assert unit.tolist()[0] == UNIT_LCU_THOUSANDS and pd.isna(unit.tolist()[1])
110
+ assert harmonized.tolist()[0] == 407383000.0 * 1000 and pd.isna(harmonized.tolist()[1])
111
+
112
+ unit, harmonized = monetary_columns(
113
+ DATAFLOWS[2], codes, pd.Series([3, 0]), pd.Series([619373009000.0, 120.0]), set()
114
+ )
115
+ assert unit.tolist()[0] == UNIT_LCU and harmonized.tolist()[0] == 619373009000.0
116
+ assert pd.isna(harmonized.tolist()[1])
pipeline/tests/test_revisions.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from isora_hf.revisions import (
2
+ CHANGE_ADDED,
3
+ CHANGE_REMOVED,
4
+ CHANGE_SCALE,
5
+ CHANGE_TEXT,
6
+ CHANGE_VALUE,
7
+ canonical,
8
+ classify,
9
+ )
10
+
11
+
12
+ def test_canonical_strips_thousands_separators_and_parses_numbers():
13
+ assert canonical("1,148,486") == ("number", 1148486.0, 0)
14
+ assert canonical(" 12.5 ") == ("number", 12.5, 1)
15
+ assert canonical("") == ("missing", None, 0)
16
+ assert canonical(None) == ("missing", None, 0)
17
+ assert canonical("Yes ") == ("text", "yes", 0)
18
+
19
+
20
+ def test_formatting_and_precision_only_differences_are_not_changes():
21
+ assert classify(["31,378", "31378", "31378"]) is None
22
+ assert classify(["99.39464694945302", "99.39464695"]) is None
23
+ assert classify(["26.95", "26.94513581", "26.94513581"]) is None # rounded in older release
24
+ assert classify(["27", "26.6"]) is None # agrees at the coarser (integer) precision
25
+ assert classify(["26.95", "27.10"]) == CHANGE_VALUE
26
+ assert classify(["No", "No", "No"]) is None
27
+ assert classify(["Yes", "yes"]) is None
28
+
29
+
30
+ def test_scale_convention_change_is_detected():
31
+ assert classify(["4469256.066", "4469256066", "4469256066"]) == CHANGE_SCALE
32
+
33
+
34
+ def test_real_numeric_revision():
35
+ assert classify(["100", "100", "120"]) == CHANGE_VALUE
36
+ assert classify(["100", "D"]) == CHANGE_VALUE # number replaced by a sentinel
37
+
38
+
39
+ def test_added_and_removed_keys():
40
+ assert classify([None, "No", "No"]) == CHANGE_ADDED
41
+ assert classify(["No", "No", None]) == CHANGE_REMOVED
42
+ assert classify([None, None]) is None
43
+
44
+
45
+ def test_text_revision_ignores_mojibake_and_case():
46
+ same = ["from ‘tax type’", "from ‘tax type’"]
47
+ assert classify(same) is None
48
+ assert classify(["Produced and published", "Produced, not published"]) == CHANGE_TEXT
pipeline/tests/test_structures.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from isora_hf.config import DATAFLOWS
2
+ from isora_hf.structures import annotations, indicator_row, normalize_indicator_type
3
+
4
+
5
+ def test_normalize_indicator_type_handles_case_and_trailing_space():
6
+ assert normalize_indicator_type("Currency ") == "currency"
7
+ assert normalize_indicator_type("Counting") == "count"
8
+ assert normalize_indicator_type("") == "unspecified"
9
+ assert normalize_indicator_type(None) == "unspecified"
10
+ assert normalize_indicator_type("NA") == "unspecified"
11
+
12
+
13
+ def test_annotations_flatten_and_drop_empties():
14
+ code = {
15
+ "annotations": [
16
+ {"title": "A", "text": " x "},
17
+ {"title": "B", "text": ""},
18
+ {"title": "C", "value": "v"},
19
+ ]
20
+ }
21
+ assert annotations(code) == {"A": "x", "C": "v"}
22
+
23
+
24
+ def test_indicator_row_detects_derived_currency_and_thousands():
25
+ code = {
26
+ "id": "337_059",
27
+ "name": "Active taxpayers (in thousands in local currency)",
28
+ "annotations": [
29
+ {"title": "DissemScale", "text": "Currency"},
30
+ {"title": "DissemCurrency", "text": "NC"},
31
+ {"title": "OriginalFormula", "text": "+95860_38/+398_004"},
32
+ {"title": "Suppress", "text": "Yes"},
33
+ ],
34
+ }
35
+ row = indicator_row(DATAFLOWS[2], "6.0.6", code)
36
+ assert row["is_derived"] is True
37
+ assert row["is_local_currency"] is True
38
+ assert row["label_mentions_thousands"] is True
39
+ assert row["indicator_type"] == "currency"
40
+ assert row["suppressed_in_source_tables"] is True
41
+ assert row["questionnaire_generation"] == "ISORA 2020+"
42
+
43
+
44
+ def test_declared_monetary_codes_excludes_mistyped_counts():
45
+ import pandas as pd
46
+
47
+ from isora_hf.structures import declared_monetary_codes
48
+
49
+ frame = pd.DataFrame(
50
+ [
51
+ {
52
+ "indicator_code": "A",
53
+ "label": "Total revenue collections - Net",
54
+ "indicator_type": "currency",
55
+ },
56
+ {
57
+ "indicator_code": "B",
58
+ "label": "Number of complaints for the fiscal year",
59
+ "indicator_type": "currency",
60
+ },
61
+ {
62
+ "indicator_code": "C",
63
+ "label": "Opening stock of tax debt cases",
64
+ "indicator_type": "currency",
65
+ },
66
+ {
67
+ "indicator_code": "D",
68
+ "label": "Cases under litigation - Value of cases resolved",
69
+ "indicator_type": "currency",
70
+ },
71
+ {"indicator_code": "E", "label": "Staff total", "indicator_type": "count"},
72
+ ]
73
+ )
74
+ assert declared_monetary_codes(frame) == {"A", "D"}