AnalyticsEngine¶
The analytics engine exposes typed, frozen, Decimal-safe analytics
functions on top of CanonicalDataset. Six submodules cover country,
partner, commodity, time-series, balance, and comparison analytics.
API reference¶
The full reference is generated from the SDK's docstrings via mkdocstrings.
AnalyticsEngine
¶
High-level orchestrator for the analytics layer.
A single AnalyticsEngine instance holds:
- A filter chain — filters are applied in order; the resulting dataset is what each metric and aggregation sees.
- A list of metrics — each is computed once on the filtered dataset.
- A list of aggregations — each is computed once on the filtered dataset.
Construction is purely declarative; no work
happens until run(dataset) is called.
Usage::
engine = (
AnalyticsEngine(name="india_2022_summary")
.add_filter(Filter.reporter(699))
.add_filter(Filter.year(2022))
.add_metric(Metric.count())
.add_metric(Metric.sum_primary_value())
.add_aggregation(
Aggregation(
name="by_partner",
group_by=("partner_code",),
metric=Metric.sum_primary_value(),
)
)
)
result = engine.run(dataset)
Source code in un_comtrade/analytics/__init__.py
922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 | |
add_filter
¶
Append a Filter to the engine's filter
chain. Returns self for chaining.
Source code in un_comtrade/analytics/__init__.py
add_metric
¶
Append a Metric to be computed against
the filtered dataset. Returns self for
chaining.
Source code in un_comtrade/analytics/__init__.py
add_aggregation
¶
Append an Aggregation to be computed
against the filtered dataset. Returns self
for chaining.
Source code in un_comtrade/analytics/__init__.py
run
¶
Apply the filter chain, compute metrics, and run aggregations.
Returns a frozen AnalysisResult. Raises
AnalyticsError if dataset is not a
CanonicalDataset. Metric / aggregation
failures are surfaced as warnings on the
result's context (rather than re-raised) so
that one broken metric doesn't abort the
whole analysis.
Source code in un_comtrade/analytics/__init__.py
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 | |
country
¶
Country-level analytics (P6-002).
This module is the first concrete analytics
submodule built on top of the AnalyticsEngine
foundation (P6-001). It provides five
country-level analytics that operate exclusively
on CanonicalDataset:
total_imports(...)— sum of imports for a given reporter (optionally filtered by year / window).total_exports(...)— sum of exports for a given reporter (optionally filtered by year / window).country_ranking(...)— rank reporters by total trade / exports / imports, with optional flow filter and limit.country_summary(...)— one-stop summary per reporter: totals, balance, partner count, year range.country_trend(...)— exports / imports / balance per year (or per period) for a given reporter.
All functions accept a CanonicalDataset and
return either a Decimal (for total_*), a frozen
dataclass (for summary / trend / ranking), or a
tuple of frozen dataclasses (for ranking).
QE-007 refactor: this module's filter /
group / aggregate / sort logic is now built on
top of the internal Query engine (see
un_comtrade.analytics._query_engine). The
public API is unchanged; only the internal
implementation now delegates to Query(...),
Query.filter(...), Query.group_by(...),
sum(...), summarize(...), and Query.sort(...).
The dataclasses are frozen (ADR-0013) and use
Decimal for monetary values (ADR-0027).
The module is decoupled from the transport
layer (same constraint as AnalyticsEngine):
only stdlib + intra-package imports.
CountryAnalyticsError
¶
Bases: Exception
Raised when a country-level analytics operation cannot be performed (e.g. unknown ranking field, missing reporter).
CountryRankingRow
dataclass
¶
One row of a country ranking.
Captures totals for a single reporter plus the ISO3 / name metadata if present in the source records.
Source code in un_comtrade/analytics/country.py
CountrySummary
dataclass
¶
One-stop summary of a single reporter's
activity in a CanonicalDataset.
Captures totals, trade balance, partner count, record count, and the observed year range.
Source code in un_comtrade/analytics/country.py
CountryTrendPoint
dataclass
¶
One point on a country trend (one year or one period).
Source code in un_comtrade/analytics/country.py
CountryTrend
dataclass
¶
Time-series of country activity for one reporter.
points is sorted by (year, period) in
ascending order.
Source code in un_comtrade/analytics/country.py
total_imports
¶
total_imports(
dataset: CanonicalDataset,
*,
reporter_code: int | None = None,
year: int | None = None,
years: tuple[int, ...] | None = None,
) -> Decimal
Sum of imports (flow_code == "M") for the
optional filters.
Parameters¶
dataset
The CanonicalDataset to analyse.
reporter_code
If supplied, only records whose
reporter.reporter_code == reporter_code
contribute.
year
If supplied, only records with
ref_year == year contribute.
years
If supplied, only records whose ref_year
is in this tuple contribute. Mutually
exclusive with year.
Returns¶
Decimal
Total import value (USD). Returns
Decimal("0") when no records match.
Source code in un_comtrade/analytics/country.py
total_exports
¶
total_exports(
dataset: CanonicalDataset,
*,
reporter_code: int | None = None,
year: int | None = None,
years: tuple[int, ...] | None = None,
) -> Decimal
Sum of exports (flow_code == "X") for the
optional filters. Mirror of total_imports.
Source code in un_comtrade/analytics/country.py
country_ranking
¶
country_ranking(
dataset: CanonicalDataset,
*,
flow: str | None = None,
by: str = "total_trade_value",
descending: bool = True,
limit: int | None = None,
) -> tuple[CountryRankingRow, ...]
Rank reporters by total trade (or by a specific flow / metric).
Parameters¶
dataset
The CanonicalDataset to analyse.
flow
Optional flow filter. "X" keeps exports
only; "M" keeps imports only; None
(default) keeps both flows (totals are
exports + imports).
by
One of "total_trade_value" (default),
"exports", "imports", "trade_balance",
or "record_count".
descending
When True (default), largest values
first; when False, smallest values
first.
limit
If supplied, return only the top limit
rows (after sorting).
Returns¶
tuple[CountryRankingRow, ...]
Rows sorted by by in the requested
direction. Empty tuple if no records match.
Source code in un_comtrade/analytics/country.py
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 | |
country_summary
¶
country_summary(
dataset: CanonicalDataset, reporter_code: int
) -> CountrySummary | None
Build a CountrySummary for one reporter.
Returns None when the reporter has no records
in the dataset.
Source code in un_comtrade/analytics/country.py
country_trend
¶
country_trend(
dataset: CanonicalDataset,
reporter_code: int,
*,
granularity: str = "year",
) -> CountryTrend
Build a CountryTrend for one reporter.
Parameters¶
dataset
The CanonicalDataset to analyse.
reporter_code
The reporter to summarise.
granularity
"year" (default) groups by ref_year;
"period" groups by period (e.g.
"2022", "202201", etc.). "year"
produces one point per calendar year;
"period" can produce intra-year points.
Returns¶
CountryTrend
Trend with points sorted by
(year, period). Returns an empty
CountryTrend when the reporter has no
records.
Source code in un_comtrade/analytics/country.py
636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 | |
partner
¶
Partner-level analytics (P6-003).
This module is the second concrete analytics
submodule built on top of the AnalyticsEngine
foundation (P6-001). It provides four
partner-level analytics that operate
exclusively on CanonicalDataset:
top_partners(...)— rank partners by trade value for a given reporter.partner_growth(...)— year-over-year (or period-over-period) growth of a specific partner's trade with the reporter.partner_balance(...)— exports minus imports per partner for a given reporter.bilateral_summary(...)— comprehensive summary of trade between two reporters (or a reporter and a partner), including the mirror flow from the partner's perspective.
All functions accept a CanonicalDataset and
return either a frozen dataclass (for
bilateral_summary) or a tuple of frozen
dataclasses (for top_partners,
partner_balance). The growth function returns
a PartnerGrowth container that includes both
the per-period points and the absolute /
relative change summary.
The module reuses the Filter, Metric, and
Aggregation primitives from the parent
AnalyticsEngine — no new abstractions are
introduced. The dataclasses are frozen
(ADR-0013) and use Decimal for monetary values
(ADR-0027).
The module is decoupled from the transport
layer (same constraint as AnalyticsEngine):
only stdlib + intra-package imports.
PartnerAnalyticsError
¶
Bases: AnalyticsError
Raised when a partner-level analytics operation cannot be performed (e.g. unknown ranking field, missing reporter / partner).
PartnerRankingRow
dataclass
¶
One row of a partner ranking.
Captures totals for a single partner (relative to a fixed reporter) plus the ISO3 / name metadata if present in the source records.
Source code in un_comtrade/analytics/partner.py
PartnerGrowthPoint
dataclass
¶
One point on a partner growth series.
Source code in un_comtrade/analytics/partner.py
PartnerGrowth
dataclass
¶
Time-series of partner growth for one reporter / partner pair.
points is sorted by (year, period). The
absolute_change is last_total_trade -
first_total_trade. The relative_change is
(last - first) / first when first != 0,
else None. The cagr is the compound
annual growth rate when there are ≥ 2 points
spanning at least 1 year, else None.
Source code in un_comtrade/analytics/partner.py
PartnerBalanceRow
dataclass
¶
One row of a partner balance view.
Sibling of PartnerRankingRow — kept as a
separate type so callers can opt into the
balance view semantically.
Source code in un_comtrade/analytics/partner.py
BilateralSummary
dataclass
¶
Comprehensive summary of trade between a reporter and a partner.
Captures BOTH sides of the relationship:
reporter_to_partner_exports/reporter_to_partner_imports— flows reported byreporter_codewithpartner_codeas counterparty.partner_to_reporter_exports/partner_to_reporter_imports— mirror flows where the counterparty is the reporter and the partner is the partner (i.e.reporter == partner_codeandpartner == reporter_code). Useful for reconciling asymmetries between the two sides' reporting.
Returns None from bilateral_summary(...)
when the pair has no records on either side.
Source code in un_comtrade/analytics/partner.py
top_partners
¶
top_partners(
dataset: CanonicalDataset,
*,
reporter_code: int,
flow: str | None = None,
by: str = "total_trade",
descending: bool = True,
limit: int | None = None,
) -> tuple[PartnerRankingRow, ...]
Rank partners by trade value for a fixed reporter.
Parameters¶
dataset
The CanonicalDataset to analyse.
reporter_code
The reporter whose partners to rank.
flow
Optional flow filter. "X" keeps exports
only; "M" keeps imports only; None
(default) keeps both flows (totals are
exports + imports).
by
One of "total_trade" (default),
"exports", "imports", "trade_balance",
"abs_trade_balance", or "record_count".
descending
When True (default), largest values
first.
limit
If supplied, return only the top limit
rows (after sorting).
Returns¶
tuple[PartnerRankingRow, ...]
Sorted by by. Empty tuple when no
partners match.
Source code in un_comtrade/analytics/partner.py
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 | |
partner_growth
¶
partner_growth(
dataset: CanonicalDataset,
*,
reporter_code: int,
partner_code: int,
granularity: str = "year",
) -> PartnerGrowth
Compute partner growth for one reporter / partner pair.
Parameters¶
dataset
The CanonicalDataset to analyse.
reporter_code
The reporter whose side of the trade is
counted.
partner_code
The partner whose growth is computed.
granularity
"year" (default) groups by ref_year;
"period" groups by period string.
Returns¶
PartnerGrowth
Container with sorted per-period
points plus absolute / relative
change summary and CAGR. Returns an
empty PartnerGrowth when the pair has
no records.
Source code in un_comtrade/analytics/partner.py
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 | |
partner_balance
¶
partner_balance(
dataset: CanonicalDataset,
*,
reporter_code: int,
by: str = "trade_balance",
descending: bool = True,
limit: int | None = None,
) -> tuple[PartnerBalanceRow, ...]
Compute per-partner trade balance for one reporter.
Equivalent to top_partners(...,
by="trade_balance") but typed separately
(returns PartnerBalanceRow instead of
PartnerRankingRow) so callers can opt into
the balance view semantically.
Parameters¶
dataset
The CanonicalDataset to analyse.
reporter_code
The reporter whose partners to summarise.
by
One of "trade_balance" (default),
"abs_trade_balance", "total_trade",
"exports", "imports", or
"record_count".
descending
When True (default), largest values
first.
limit
If supplied, return only the top limit
rows (after sorting).
Returns¶
tuple[PartnerBalanceRow, ...]
Sorted by by. Empty tuple when no
partners match.
Source code in un_comtrade/analytics/partner.py
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 | |
bilateral_summary
¶
bilateral_summary(
dataset: CanonicalDataset,
*,
reporter_code: int,
partner_code: int,
) -> BilateralSummary | None
Compute the bilateral summary for one reporter / partner pair.
Returns None when no records exist on
either side.
Source code in un_comtrade/analytics/partner.py
704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 | |
commodity
¶
Commodity / HS Analytics (P6-004).
This module is the third concrete analytics
submodule built on top of AnalyticsEngine
(P6-001). It provides four commodity-level
analytics that operate exclusively on
CanonicalDataset:
top_hs_codes(...)— rank HS codes (commodity_code) by trade value for a given reporter (or globally). Supports flow filter, HS-level filter (2/4/6 digit), and limit.commodity_ranking(...)— rank commodities with optionalsharefield (each commodity's percentage of the grand total).commodity_trend(...)— time-series of trade for one HS code.sector_summaries(...)— aggregate by HS section (the 21 WCO Harmonized System sections identified by Roman numerals), using the standard chapter-to-section mapping.
All monetary fields are Decimal (ADR-0027).
All dataclasses are frozen=True (ADR-0013).
The module is decoupled from the transport layer: only stdlib + intra-package imports.
CommodityAnalyticsError
¶
HSCodeRankingRow
dataclass
¶
One row of a commodity ranking.
Captures exports / imports / total trade / balance for a single HS code (or commodity code) plus the commodity name (if present in the source records).
Source code in un_comtrade/analytics/commodity.py
CommodityRankingRow
dataclass
¶
One row of a commodity ranking with an
optional share field (each commodity's
percentage of the grand total trade).
share is in [0, 1]. When
include_share=False (default), share
is None.
Source code in un_comtrade/analytics/commodity.py
CommodityTrendPoint
dataclass
¶
One point on a commodity trend (one year or one period).
Source code in un_comtrade/analytics/commodity.py
SectorSummaryRow
dataclass
¶
One row of the sector summary.
Captures totals per WCO Harmonized System
section. The chapter_codes tuple lists the
2-digit chapter numbers that fall within
this section.
Source code in un_comtrade/analytics/commodity.py
sector_for_chapter
¶
Return (section_id, section_name) for a
2-digit HS chapter code. Returns
("??", "Unknown") for chapters outside the
standard WCO HS range (1-98).
Source code in un_comtrade/analytics/commodity.py
top_hs_codes
¶
top_hs_codes(
dataset: CanonicalDataset,
*,
reporter_code: int | None = None,
flow: str | None = None,
by: str = "total_trade",
descending: bool = True,
limit: int | None = None,
hs_level: int | None = None,
) -> tuple[HSCodeRankingRow, ...]
Rank HS codes by trade value.
Parameters¶
dataset
The CanonicalDataset to analyse.
reporter_code
If supplied, only records with this
reporter contribute.
flow
"X" keeps exports; "M" keeps imports;
None (default) keeps both flows.
by
"total_trade" (default), "exports",
"imports", "trade_balance",
"abs_trade_balance", or "record_count".
descending
When True (default), largest first.
limit
If supplied, return only the top limit
rows.
hs_level
If supplied (one of 2, 4, 6), keep
only records whose commodity code has
exactly that many leading digits. Useful
for ranking at the HS section, HS
heading, or HS subheading level.
Returns¶
tuple[HSCodeRankingRow, ...]
Sorted by by. Empty when no records
match.
Source code in un_comtrade/analytics/commodity.py
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 | |
commodity_ranking
¶
commodity_ranking(
dataset: CanonicalDataset,
*,
reporter_code: int | None = None,
flow: str | None = None,
by: str = "total_trade",
descending: bool = True,
limit: int | None = None,
hs_level: int | None = None,
include_share: bool = False,
) -> tuple[CommodityRankingRow, ...]
Rank commodities with optional share.
Same shape as top_hs_codes(...) but with
an optional share field
(commodity.total_trade / grand_total_trade)
that lets callers see each commodity's
percentage of the grand total. Useful for
concentration analysis (e.g. "top 5
commodities account for 60% of trade").
Parameters¶
include_share
When True, attach a share field
(in [0, 1]) to each row.
Source code in un_comtrade/analytics/commodity.py
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 | |
commodity_trend
¶
commodity_trend(
dataset: CanonicalDataset,
*,
commodity_code: str,
reporter_code: int | None = None,
granularity: str = "year",
) -> tuple[CommodityTrendPoint, ...]
Build a commodity trend for one HS code.
Parameters¶
dataset
The CanonicalDataset to analyse.
commodity_code
The HS / commodity code to track (exact
match against record.commodity.commodity_code).
reporter_code
If supplied, only records with this
reporter contribute.
granularity
"year" (default) groups by ref_year;
"period" groups by period string.
Returns¶
tuple[CommodityTrendPoint, ...]
Sorted by (year, period). Empty when
no records match.
Source code in un_comtrade/analytics/commodity.py
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 | |
sector_summaries
¶
sector_summaries(
dataset: CanonicalDataset,
*,
reporter_code: int | None = None,
flow: str | None = None,
) -> tuple[SectorSummaryRow, ...]
Build sector summaries (per WCO HS section).
Parameters¶
dataset
The CanonicalDataset to analyse.
reporter_code
If supplied, only records with this
reporter contribute.
flow
"X" keeps exports; "M" keeps imports;
None (default) keeps both flows.
Returns¶
tuple[SectorSummaryRow, ...] One row per WCO HS section (21 sections plus an "Unknown" pseudo-section for commodity codes outside the HS range). Sections with zero records are still included (with zero totals) so callers can render a complete matrix.
Source code in un_comtrade/analytics/commodity.py
699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 | |
timeseries
¶
Time-series analytics (P6-005).
This module is the fourth concrete analytics
submodule built on top of the AnalyticsEngine
foundation (P6-001). It provides five
time-series analytics that operate exclusively
on CanonicalDataset:
annual_trend(...)— yearly time-series ofsum_primary_value()(or any user-supplied metric) for a reporter / partner / commodity, with optional flow filter.monthly_trend(...)— same shape but bucketed per month (UN Comtrade periods"202201".."202212"are parsed foryear + month; pure-year periods like"2022"are excluded).rolling_average(points, *, window=3)— rolling mean over a window ofnpoints applied to any time-series ofTrendPoints.cagr(points, *, field="value")— compound annual growth rate between the first and last point of a series.growth_rates(points, *, field="value")— per-point period-over-period growth rates (relative change).
All monetary fields are Decimal (ADR-0027).
All dataclasses are frozen=True (ADR-0013).
The module is decoupled from the transport
layer (same constraint as AnalyticsEngine):
only stdlib + intra-package imports.
TimeSeriesAnalyticsError
¶
TrendPoint
dataclass
¶
One point on a time-series trend.
year is the calendar year. period is the
canonical period string from the source
record ("2022", "202201", etc.). value
is the metric value at this point. For
monthly trends month is set; for annual
trends it's None.
record_count is the number of source
records that contributed to this point.
Source code in un_comtrade/analytics/timeseries.py
GrowthRatePoint
dataclass
¶
Per-point growth rate observation.
growth is (current - previous) / previous
as a fraction. previous is None for the
first point (no prior value to compare
against).
Source code in un_comtrade/analytics/timeseries.py
annual_trend
¶
annual_trend(
dataset: CanonicalDataset,
*,
reporter_code: int | None = None,
flow: str | None = None,
partner_code: int | None = None,
commodity_code: str | None = None,
metric: Metric | None = None,
) -> tuple[TrendPoint, ...]
Build an annual time-series trend.
Parameters¶
dataset
The CanonicalDataset to analyse.
reporter_code, partner_code, flow,
commodity_code
Optional filters (any combination).
metric
The Metric to compute per year.
Defaults to Metric.sum_primary_value()
(total trade value).
Returns¶
tuple[TrendPoint, ...] Sorted ascending by year. Empty when no records match.
Source code in un_comtrade/analytics/timeseries.py
monthly_trend
¶
monthly_trend(
dataset: CanonicalDataset,
*,
reporter_code: int | None = None,
flow: str | None = None,
partner_code: int | None = None,
commodity_code: str | None = None,
metric: Metric | None = None,
) -> tuple[TrendPoint, ...]
Build a monthly time-series trend.
Same shape as annual_trend(...) but
bucketed per month. Records with annual-only
period strings (e.g. "2022") are excluded
because they cannot be mapped to a specific
month.
Source code in un_comtrade/analytics/timeseries.py
rolling_average
¶
rolling_average(
points: Sequence[TrendPoint],
*,
window: int = 3,
field: str = "value",
) -> tuple[TrendPoint, ...]
Compute the rolling average of a time- series over a window.
At each index i, the output point's
field value is the mean of the input
field values from max(0, i - window + 1)
through i (inclusive — i.e., a
trailing window). The first window - 1
output points are based on a partial
window (e.g. for window=3, index 0 uses
just point 0, index 1 uses points 0–1, etc.).
Parameters¶
points
Input time-series. Should be sorted by
(year, period).
window
Number of consecutive points to average.
Default 3.
field
Name of the dataclass attribute to
average. Default "value".
Returns¶
tuple[TrendPoint, ...]
Same length as the input. Each point's
field is replaced with the rolling
average; all other attributes are
preserved from the input point.
Source code in un_comtrade/analytics/timeseries.py
cagr
¶
cagr(
points: Sequence[TrendPoint],
*,
field: str = "value",
years: int | None = None,
) -> Decimal | None
Compute the Compound Annual Growth Rate between the first and last point of a series.
Parameters¶
points
Input time-series (sorted ascending).
field
Dataclass attribute to use. Default
"value".
years
Override for the time span (in years).
When None, derived from the
year difference between the first
and last points.
Returns¶
Decimal | None
The CAGR as a fraction (e.g.
Decimal("0.5") for 50 % annual growth).
Returns None when the calculation is
undefined (zero / negative first, no
span, or fewer than 2 points).
Source code in un_comtrade/analytics/timeseries.py
growth_rates
¶
growth_rates(
points: Sequence[TrendPoint], *, field: str = "value"
) -> tuple[GrowthRatePoint, ...]
Compute period-over-period growth rates.
For each point i ≥ 1, the growth is
(value[i] - value[i-1]) / value[i-1].
For i = 0, growth is None (no prior
value).
Parameters¶
points
Input time-series (sorted ascending).
field
Dataclass attribute to compare. Default
"value".
Returns¶
tuple[GrowthRatePoint, ...]
One row per input point. previous
is None for the first row.
Source code in un_comtrade/analytics/timeseries.py
balance
¶
Trade-balance analytics (P6-006).
This module is the fifth concrete analytics
submodule built on top of the AnalyticsEngine
foundation (P6-001). It provides four
trade-balance analytics that operate
exclusively on CanonicalDataset:
country_balance(...)— exports minus imports aggregated per reporter (country). Withreporter_code=None, returns balance for ALL reporters (effectively a per-country breakdown of the global balance).partner_trade_balance(...)— exports minus imports aggregated per partner for one reporter.commodity_balance(...)— exports minus imports aggregated per HS code for one reporter (or globally whenreporter_codeisNone).global_balance(...)— global trade balance across all reporters, all partners, all commodities (singleBalanceSummary).
All monetary fields are Decimal (ADR-0027).
All dataclasses are frozen=True (ADR-0013).
The module is decoupled from the transport
layer (same constraint as AnalyticsEngine):
only stdlib + intra-package imports.
PartnerBalanceRow
dataclass
¶
One row of a partner balance view.
Sibling of PartnerRankingRow — kept as a
separate type so callers can opt into the
balance view semantically.
Source code in un_comtrade/analytics/partner.py
BalanceAnalyticsError
¶
BalanceSummary
dataclass
¶
A single-snapshot trade balance summary.
trade_balance = total_exports - total_imports.
total_trade = total_exports + total_imports.
Source code in un_comtrade/analytics/balance.py
CountryBalanceRow
dataclass
¶
One row of the country balance breakdown.
Source code in un_comtrade/analytics/balance.py
CommodityBalanceRow
dataclass
¶
One row of the commodity balance breakdown.
Source code in un_comtrade/analytics/balance.py
country_balance
¶
country_balance(
dataset: CanonicalDataset,
*,
reporter_code: int | None = None,
descending: bool = True,
limit: int | None = None,
) -> tuple[CountryBalanceRow, ...]
Compute the trade balance per reporter (country).
Parameters¶
dataset
The CanonicalDataset to analyse.
reporter_code
If supplied, restrict to this single
reporter. The result is then a
zero-or-one-element tuple (zero when no
records match).
descending
When True (default), the largest
balances first.
limit
If supplied, return only the top limit
rows.
Returns¶
tuple[CountryBalanceRow, ...]
Sorted by trade_balance (descending by
default). Empty when no records match.
Source code in un_comtrade/analytics/balance.py
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 | |
partner_trade_balance
¶
partner_trade_balance(
dataset: CanonicalDataset,
*,
reporter_code: int,
descending: bool = True,
limit: int | None = None,
) -> tuple[PartnerBalanceRow, ...]
Compute the trade balance per partner for one reporter.
Parameters¶
dataset
The CanonicalDataset to analyse.
reporter_code
The reporter whose partners to rank.
descending
When True (default), the largest
balances first.
limit
If supplied, return only the top limit
rows.
Returns¶
tuple[PartnerBalanceRow, ...]
Sorted by trade_balance (descending by
default). Empty when no records match.
Notes¶
Named partner_trade_balance (not
partner_balance) to disambiguate from
partner.partner_balance in P6-003, which
has a different signature (by=...) and a
different shape (per-partner ranking keyed
by any sortable field, not strictly
trade_balance).
Source code in un_comtrade/analytics/balance.py
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 | |
commodity_balance
¶
commodity_balance(
dataset: CanonicalDataset,
*,
reporter_code: int | None = None,
descending: bool = True,
limit: int | None = None,
) -> tuple[CommodityBalanceRow, ...]
Compute the trade balance per commodity (HS code).
Parameters¶
dataset
The CanonicalDataset to analyse.
reporter_code
If supplied, restrict to this reporter's
trades. When None (default), aggregate
across all reporters (a global per-
commodity breakdown).
descending
When True (default), the largest
balances first.
limit
If supplied, return only the top limit
rows.
Returns¶
tuple[CommodityBalanceRow, ...]
Sorted by trade_balance (descending by
default). Empty when no records match.
Source code in un_comtrade/analytics/balance.py
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 | |
global_balance
¶
global_balance(dataset: CanonicalDataset) -> BalanceSummary
Compute the global trade balance across ALL reporters, ALL partners, ALL commodities and ALL flows.
Returns a single BalanceSummary with
total_exports, total_imports,
trade_balance (= exports - imports),
total_trade (= exports + imports), and
record_count.
The flow classification is exhaustive: any
record whose flow.flow_code is not "X"
(export) is counted as an import. This
matches UN Comtrade's two-flow model.
Returns a BalanceSummary with all zero
values when the dataset is empty (the
caller can detect an empty dataset via
record_count == 0).
Source code in un_comtrade/analytics/balance.py
compare
¶
Comparative analytics (P6-007).
This module is the sixth concrete analytics
submodule built on top of the AnalyticsEngine
foundation (P6-001). It provides four
"side-by-side" comparison analytics that
operate exclusively on CanonicalDataset:
country_vs_country(...)— compare trade profiles of two or more reporters.year_vs_year(...)— compare the same reporter's trade between two periods.commodity_vs_commodity(...)— compare two or more commodities (HS codes).partner_vs_partner(...)— compare two or more partners for one reporter.
All four produce a common shape so callers can swap comparisons without rewriting downstream code:
ComparisonRow(
dimension_key=...,
dimension_label=...,
values=(v1, v2, ...), # one per side
deltas=(d1, d2, ...), # delta vs. first side
pct_changes=(p1, p2, ...), # delta / first
record_counts=(c1, c2, ...),
)
All monetary fields are Decimal (ADR-0027).
All dataclasses are frozen=True (ADR-0013).
The module is decoupled from the transport
layer (same constraint as AnalyticsEngine):
only stdlib + intra-package imports.
ComparativeAnalyticsError
¶
ComparisonRow
dataclass
¶
One row of a comparative breakdown.
All numeric arrays (values, deltas,
pct_changes, record_counts) are aligned
by index with the comparison's labels:
values[0] corresponds to the first label
(comparison.labels[0]), values[1] to
the second, etc.
deltas[i] is values[i] - values[0].
pct_changes[i] is (values[i] - values[0]) /
values[0] * 100, or None when the
baseline (values[0]) is zero (cannot
divide) — callers should treat None as
"undefined" rather than "no change".
Source code in un_comtrade/analytics/compare.py
ComparisonSummary
dataclass
¶
Aggregate totals across all matched records (not filtered by the breakdown dimension).
Source code in un_comtrade/analytics/compare.py
CountryComparison
dataclass
¶
Result of country_vs_country(...).
Source code in un_comtrade/analytics/compare.py
YearComparison
dataclass
¶
Result of year_vs_year(...).
Source code in un_comtrade/analytics/compare.py
CommodityComparison
dataclass
¶
Result of commodity_vs_commodity(...).
Source code in un_comtrade/analytics/compare.py
PartnerComparison
dataclass
¶
Result of partner_vs_partner(...).
Source code in un_comtrade/analytics/compare.py
country_vs_country
¶
country_vs_country(
dataset: CanonicalDataset,
*,
reporter_codes: Sequence[int],
breakdown_by: str = "commodity",
flow: str | None = None,
period: str | None = None,
descending: bool = True,
limit: int | None = None,
) -> CountryComparison
Compare trade profiles of two or more reporters (countries).
Parameters¶
dataset
The CanonicalDataset to analyse.
reporter_codes
Reporter codes to compare (must contain
at least 2). The first entry is the
baseline.
breakdown_by
Group-by dimension: "commodity",
"partner", or "period".
flow
Restrict to exports ("X") or imports
("M"). When None, all flows are
summed (useful for total trade volume).
period
Restrict to a single period (e.g.
"2022"). When None, all periods are
included.
descending
Sort rows by the last-side delta
descending (True, default) or
ascending.
limit
If supplied, return only the top limit
rows.
Returns¶
CountryComparison
Frozen dataclass with reporter metadata,
aggregate ComparisonSummary, and a
tuple of ComparisonRows.
Source code in un_comtrade/analytics/compare.py
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 | |
year_vs_year
¶
year_vs_year(
dataset: CanonicalDataset,
*,
reporter_code: int,
period_a: str,
period_b: str,
breakdown_by: str = "commodity",
flow: str | None = None,
descending: bool = True,
limit: int | None = None,
) -> YearComparison
Compare the same reporter's trade between two periods.
Parameters¶
dataset
The CanonicalDataset to analyse.
reporter_code
The reporter whose trade to compare.
period_a
Baseline period (e.g. "2020" or
"202001").
period_b
Comparison period.
breakdown_by
Group-by dimension: "commodity",
"partner", or "period".
flow
Restrict to "X", "M", or all.
descending
Sort rows by delta (period_b -
period_a) descending or ascending.
limit
If supplied, return only the top limit
rows.
Returns¶
YearComparison
Frozen dataclass with period labels,
reporter metadata, ComparisonSummary,
and a tuple of ComparisonRows.
Source code in un_comtrade/analytics/compare.py
833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 | |
commodity_vs_commodity
¶
commodity_vs_commodity(
dataset: CanonicalDataset,
*,
commodity_codes: Sequence[str],
reporter_code: int | None = None,
breakdown_by: str = "partner",
period: str | None = None,
flow: str | None = None,
descending: bool = True,
limit: int | None = None,
) -> CommodityComparison
Compare trade profiles of two or more commodities (HS codes).
Parameters¶
dataset
The CanonicalDataset to analyse.
commodity_codes
HS codes to compare (must contain at
least 2). The first entry is the
baseline.
reporter_code
Restrict to a single reporter. When
None (default), aggregate across all
reporters.
breakdown_by
Group-by dimension: "commodity",
"partner", or "period". Note: when
grouping by "commodity", each row
represents a non-compared HS code that
appears in the dataset (useful as a
"context" view).
period
Restrict to a single period. When None,
all periods are included.
flow
Restrict to "X", "M", or all.
descending
Sort rows by the last-side delta
descending or ascending.
limit
If supplied, return only the top limit
rows.
Returns¶
CommodityComparison
Frozen dataclass with commodity codes,
names, optional reporter, aggregate
ComparisonSummary, and ComparisonRows.
Source code in un_comtrade/analytics/compare.py
931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 | |
partner_vs_partner
¶
partner_vs_partner(
dataset: CanonicalDataset,
*,
partner_codes: Sequence[int],
reporter_code: int,
breakdown_by: str = "commodity",
period: str | None = None,
flow: str | None = None,
descending: bool = True,
limit: int | None = None,
) -> PartnerComparison
Compare trade profiles of two or more partners for one reporter.
Parameters¶
dataset
The CanonicalDataset to analyse.
partner_codes
Partner codes to compare (must contain
at least 2). The first entry is the
baseline.
reporter_code
The reporter whose partners to compare.
breakdown_by
Group-by dimension: "commodity",
"partner", or "period".
period
Restrict to a single period. When None,
all periods are included.
flow
Restrict to "X", "M", or all.
descending
Sort rows by the last-side delta
descending or ascending.
limit
If supplied, return only the top limit
rows.
Returns¶
PartnerComparison
Frozen dataclass with partner codes,
ISO3, names, aggregate
ComparisonSummary, and
ComparisonRows.
Source code in un_comtrade/analytics/compare.py
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 | |
Examples¶
from un_comtrade import ComtradeClient
with ComtradeClient() as client:
exports = client.trade.get_exports(reporter_code=699, period="2022")
top = client.analytics.top_partners(exports, by="exports", limit=5)
Related Recipes¶
- RECIPE-021 — Compute a country trade balance.
- RECIPE-024 — Country comparison.
Related Guides¶
- Python SDK → Analytics — full Python API surface.