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.
- How many records exist per trade type, and how many partners and commodities do they cover?
- Is the monthly coverage complete for every year and trade type?
- Are there invalid values (negative or zero value/weight)?
- 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
df.head()
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)
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
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
# The invalid records themselves
df[(df["price_bhd"] <= 0)][["date", "trade_type", "commodity_name", "country_name", "price_bhd", "weight_kg"]]
# Largest single records by value
df.nlargest(5, "price_bhd")[["date", "trade_type", "commodity_name", "country_name", "price_bhd", "weight_kg"]]
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")
Findings¶
- 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.
- 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.
- 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.
- 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.
- 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.