02 · Data Understanding and Quality Assessment

Objective. Describe the structure, coverage and value distribution of the cleaned dataset, and identify anomalies that affect later analyses.

Questions.

  1. How many records exist per trade type, and how many partners and commodities do they cover?
  2. Is the monthly coverage complete for every year and trade type?
  3. Are there invalid values (negative or zero value/weight)?
  4. How are record-level trade values distributed?
%load_ext autoreload
%autoreload 2

import numpy as np
import pandas as pd
import plotly.express as px

from scripts.analysis import load_trade
from scripts.plotly_theme import use_metro

use_metro()
pd.options.display.float_format = "{:,.2f}".format

df = load_trade()

1. Structure

Each record is one commodity × partner × month × trade-type observation. price_bhd is the declared value in Bahraini dinars and weight_kg the net weight.

print(f"{df.shape[0]:,} records × {df.shape[1]} columns")
print(f"Period: {df['date'].min():%b %Y} – {df['date'].max():%b %Y}")
df.dtypes
2,150,478 records × 12 columns
Period: Jan 2021 – Sep 2026
year                           int64
month                          int64
commodity_no                   int64
commodity_name                   str
country_code                     str
country_name                     str
price_bhd                    float64
weight_kg                    float64
trade_type                       str
date                  datetime64[us]
commodity_category          category
region                           str
dtype: object
df.head()
year month commodity_no commodity_name country_code country_name price_bhd weight_kg trade_type date commodity_category region
0 2021 1 1012910 HORSES FOR SPORT AE UNITED ARAB EMIRATES 6,191.21 4,000.00 import 2021-01-01 Animal & Animal Products GCC
1 2021 1 1012910 HORSES FOR SPORT GB UNITED KINGDOM 993.23 2,200.00 import 2021-01-01 Animal & Animal Products Non-GCC
2 2021 1 1012910 HORSES FOR SPORT IE IRELAND 967.98 900.00 import 2021-01-01 Animal & Animal Products Non-GCC
3 2021 1 1012910 HORSES FOR SPORT US UNITED STATES OF AMERICA 708.24 700.00 import 2021-01-01 Animal & Animal Products Non-GCC
4 2021 1 1022100 PURE-BRED BREEDING BOVINE NL NETHERLANDS 7,826.03 3,050.00 import 2021-01-01 Animal & Animal Products Non-GCC

2. Records, partners and commodities by trade type

records = df["trade_type"].value_counts().rename("records").to_frame()
records["share_%"] = records["records"] / records["records"].sum() * 100

diversity = df.groupby("trade_type").agg(
    partners=("country_code", "nunique"),
    commodities=("commodity_no", "nunique"),
)
records.join(diversity)
records share_% partners commodities
trade_type
import 1806826 84.02 248 7428
re-export 242253 11.27 177 5638
export 101399 4.72 177 3591
fig = px.pie(
    records.reset_index(),
    names="trade_type",
    values="records",
    hole=0.4,
    title="Distribution of Records by Trade Type",
)

fig.update_traces(textinfo="percent+label")

fig.show()

3. Temporal coverage

The heatmap shows the number of months with data for each year and trade type. A value below 12 indicates a partial year.

coverage = df.pivot_table(index="trade_type", columns="year", values="month", aggfunc="nunique")

fig = px.imshow(
    coverage,
    text_auto=True,
    zmin=0,
    zmax=12,
    aspect="auto",
    title="Monthly Data Coverage by Year",
    labels={
        "x": "Year",
        "y": "Trade Type",
        "color": "Months"
    }
)

fig.update_xaxes(type="category")

fig.show()

4. Descriptive statistics and invalid values

df.groupby("trade_type")[["price_bhd", "weight_kg"]].describe().T
trade_type export import re-export
price_bhd count 101,399.00 1,806,826.00 242,253.00
mean 228,272.33 18,000.42 17,656.93
std 1,384,502.21 407,434.69 191,150.52
min 0.00 -313.20 0.00
25% 497.44 121.55 68.74
50% 6,104.28 665.00 397.90
75% 41,437.99 3,971.40 2,800.00
max 77,444,771.47 89,778,623.32 16,905,675.41
weight_kg count 101,399.00 1,806,826.00 242,253.00
mean 846,761.61 79,872.05 6,395.73
std 11,213,264.07 5,924,684.00 508,911.68
min 0.00 0.00 0.00
25% 172.80 10.79 10.00
50% 3,884.40 93.00 61.18
75% 41,166.00 1,000.00 505.82
max 934,245,950.00 1,668,216,945.00 202,486,555.00
checks = pd.DataFrame({
    "negative": [(df["price_bhd"] < 0).sum(), (df["weight_kg"] < 0).sum()],
    "zero": [(df["price_bhd"] == 0).sum(), (df["weight_kg"] == 0).sum()],
}, index=["price_bhd", "weight_kg"])
checks
negative zero
price_bhd 1 23
weight_kg 0 289
# The invalid records themselves
df[(df["price_bhd"] <= 0)][["date", "trade_type", "commodity_name", "country_name", "price_bhd", "weight_kg"]]
date trade_type commodity_name country_name price_bhd weight_kg
203758 2021-08-01 import MACHINES FOR TESTING METALS SWITZERLAND 0.00 5.30
451539 2022-07-01 import OTHER PARTS OF AERIALS AND AERIAL REFLECTORS O... AUSTRIA 0.00 7.00
521095 2022-12-01 import JEWELLERY OF PLATINIUM AND THE PLATINUM GROUP UNITED KINGDOM 0.00 0.50
989774 2024-02-01 import PHOSPHONIC ACID,  METHYL - MIXED WITH (AMINO A... LITHUANIA 0.00 0.25
1031727 2024-03-01 import RADIOS COMBINED WITH SOUND RECORDING OR REPROD... NETHERLANDS 0.00 0.00
1049238 2024-04-01 import OTHER FEMALE SPORTSWEAR, MAN-MADE FIBERS, NOT ... SPAIN 0.00 3.00
1053021 2024-04-01 import MANICURE OR PEDICURE SETS AND INSTRUMENTS SPAIN 0.00 30.00
1090092 2024-06-01 import AVOCADOS,  FRESH OR DRIED THAILAND 0.00 6.00
1194887 2024-10-01 import PERDIOXIDE METHYLETHYL KETONE BELGIUM 0.00 0.00
1195208 2024-10-01 import PARTS FOR SIGNALLING OR SAFETY EQUIPMENT NETHERLANDS 0.00 0.01
1200341 2024-10-01 import OTHER FOOTWEAR WITH UPPERS OF TEXTILE MATERIALS JAPAN 0.00 0.00
1201378 2024-10-01 import OTHER PARTS FOR HAND TOOLS WITH NON-ELCTRIC MO... SLOVAKIA 0.00 0.19
1205195 2024-10-01 import SETS OF RUGS, TABLE CLOTHS, ETC., FOR RETAIL INDONESIA 0.00 1.00
1207610 2024-10-01 import TABLE LINEN OF OTHER TEXTILE MATERIALS GERMANY 0.00 0.00
1212836 2024-10-01 import OTHER SHEETS, ETC., OF POLYMERS OF STYRENE UNITED STATES OF AMERICA 0.00 0.01
1213304 2024-10-01 import OTHER DUPLICATING PAPER UNITED STATES OF AMERICA 0.00 0.04
1215807 2024-10-01 import OTHER TABLEWARE NOT ELSEWHERE SPECIFIED TAIWAN 0.00 0.00
1406969 2025-05-01 import PARTS FOR MACHINERY FOR WORKING SOLID MINERALS PORTUGAL 0.00 188.00
1420954 2025-06-01 import RIGID TUBES OF OTHER PLASTICS TURKEY -313.20 1.48
1613161 2026-01-01 import PAPER AND PAPERBOARD, WEIGHING 40 G/M2 OR MORE... POLAND 0.00 0.10
1622956 2026-01-01 import OTHER PRINTING MACHINERY GERMANY 0.00 0.10
1925533 2021-06-01 re-export LEATHER FOOTWEAR NOT COVERING THE ANKLE, MALE SULTANATE OMAN 0.00 1,400.06
2005282 2023-06-01 re-export TEXTILE-UPPER FOOTWEAR WITH OUTER SOLES OF LEA... SAUDI ARABIA 0.00 1.00
2107622 2025-08-01 re-export TABLES WITH WHEELS, WOOD SAUDI ARABIA 0.00 200.00
# Largest single records by value
df.nlargest(5, "price_bhd")[["date", "trade_type", "commodity_name", "country_name", "price_bhd", "weight_kg"]]
date trade_type commodity_name country_name price_bhd weight_kg
184551 2021-08-01 import NON-AGGLOMERATED IRON ORES AND CONCENTRATES BRAZIL 89,778,623.32 1,145,762,267.00
1283897 2025-01-01 import OTHER ALUMINIUM OXIDE AUSTRALIA 86,084,338.87 303,614,000.00
1828281 2022-04-01 export UNWROUGHT ALUMINIUM ALLOYS UNITED STATES OF AMERICA 77,444,771.47 49,627,423.00
30837 2021-02-01 import NON-AGGLOMERATED IRON ORES AND CONCENTRATES BRAZIL 77,320,477.18 1,480,203,859.00
1310967 2025-02-01 import OTHER ALUMINIUM OXIDE AUSTRALIA 76,365,315.36 299,483,000.00

5. Distribution of record values

Record values span several orders of magnitude, so a linear histogram is dominated by a handful of very large shipments. Values are therefore grouped into logarithmic bands. Shares are computed within each trade type so that the three types can be compared despite their different record counts.

bands = [-np.inf, 0, 100, 1_000, 10_000, 100_000, 1_000_000, np.inf]
labels = ["≤ 0", "0–100", "100–1K", "1K–10K", "10K–100K", "100K–1M", "> 1M"]

value_bands = (
    df.assign(value_band=pd.cut(df["price_bhd"], bins=bands, labels=labels))
    .groupby(["trade_type", "value_band"], observed=False)
    .size()
    .rename("records")
    .reset_index()
)
value_bands["share_%"] = (
    value_bands["records"]
    / value_bands.groupby("trade_type")["records"].transform("sum")
    * 100
)
fig = px.bar(
    value_bands,
    x="value_band",
    y="share_%",
    color="trade_type",
    barmode="group",
)

fig.update_layout(
    title="Distribution of Record Values by Trade Type",
    xaxis_title="Record Value (BHD)",
    yaxis_title="Share of Records (%)",
    legend_title_text="Trade Type"
)

fig.show()
# Concentration of value: share of total value held by the largest 1% of records
top_1pct = df["price_bhd"].quantile(0.99)
share_top = df.loc[df["price_bhd"] >= top_1pct, "price_bhd"].sum() / df["price_bhd"].sum() * 100
print(f"Median record value: {df['price_bhd'].median():,.0f} BHD; mean: {df['price_bhd'].mean():,.0f} BHD")
print(f"The largest 1% of records (≥ {top_1pct:,.0f} BHD) account for {share_top:.1f}% of total value")
Median record value: 676 BHD; mean: 27,876 BHD
The largest 1% of records (≥ 330,906 BHD) account for 69.8% of total value

Findings

  1. Imports dominate the record count. They make up 84.0% of records (1.81 M), against 11.3% re-exports and 4.7% domestic exports. Imports also cover the widest range: 248 partner codes and 7,428 commodity codes, compared with 177 / 3,591 for domestic exports.
  2. Coverage is complete for 2021–2025. All three trade types have 12 months in every year. 2026 has 9 months (January–September), which constrains year-on-year comparisons for 2026.
  3. Invalid values are negligible. One record has a negative value (−313 BHD), 23 have zero value and 289 have zero weight. Together they are under 0.02% of records and have no material effect on aggregates, so they are retained.
  4. Record values are highly skewed. The median record is worth 676 BHD while the mean is 27,876 BHD. The largest 1% of records hold 69.8% of total value, and the five largest single records are all iron ore from Brazil, alumina from Australia or aluminium alloy exports to the USA. Aggregates are therefore driven by a small number of bulk industrial flows, and medians or category-level views are more representative than means.
  5. Domestic export records are larger. 43% of domestic export records exceed 10,000 BHD, compared with 15% of import records. This is consistent with a few large industrial exporters (notably aluminium) versus many small consumer-goods import consignments.