# -*- coding: utf-8 -*-
"""The carbon cost of rerouting: Counterfactual evidence on the Red Sea shipping crisis from monthly operator-level emissions of 140 economies

GOMD arastirma makalesi 04 - makaledeki tum sayilari, tablolari ve sekilleri ureten kod (Google Colab surumu).
Colab: kodu tek bir hucreye yapistirip calistirin ya da .ipynb dosyasini Dosya > Not defteri yukle ile acin.
Kaynak: GOMD acik veri platformu (https://gomd.pirireis.edu.tr) - Piri Reis Universitesi ve
T.C. Cevre, Sehircilik ve Iklim Degisikligi Bakanligi Cevre Yonetimi Genel Mudurlugu.
"""

# # The carbon cost of rerouting: Counterfactual evidence on the Red Sea shipping crisis from monthly operator-level emissions of 140 economies
#
# Bu not defteri makaledeki **tüm sayıları, tabloları ve şekilleri** üreten kodun Colab sürümüdür (makalenin replikasyon paketindeki betiklerle aynı kod, hücrelere bölünmüş hâlde).
#
# **Çalıştırma:** Çalışma zamanı → Tümünü çalıştır (*Runtime → Run all*). Tahmini süre: 10–20 dakika.
#
# **Veri:** Varsayılan olarak veriler GOMD açık veri API'sinden canlı çekilir (`VERI_KAYNAGI = "api"`). Makaledeki sayıları birebir yeniden üretmek için replikasyon paketi ZIP'ini yükleyebilirsiniz (`VERI_KAYNAGI = "zip"`): API'deki seriler kaynak kurumlar tarafından güncellenirse sonuçlar küçük farklar gösterebilir. Veri çekim tarihi makalede 8 Kasım 2026'dır.
#
# Şekiller hem hücre altında görünür hem `fig/` klasörüne, sayısal sonuçlar `out/` klasörüne yazılır. Son hücre hepsini ZIP olarak indirir.

# ## 0. Kurulum

# Installs the packages used in the paper and the GOMD Python client. If Colab asks to restart the session, restart and run all cells again.
# [Colab Magic] !pip install -q statsforecast==2.1.1 statsmodels pycountry pycountry-convert
# [Colab Magic] !pip install -q --upgrade gomd

VERI_KAYNAGI = "api"   # "api": live from GOMD; "zip": upload the replication package ZIP (exact reproduction)
import os
os.makedirs("/content/rp04", exist_ok=True); os.chdir("/content/rp04")
for d in ("data", "out", "fig"): os.makedirs(d, exist_ok=True)
if VERI_KAYNAGI == "zip":
    import zipfile, glob, shutil
    from google.colab import files
    up = files.upload()                      # choose *_replication_package.zip
    with zipfile.ZipFile(next(iter(up))) as z:
        for n in z.namelist():
            if n.startswith("data/"): z.extract(n, ".")
    print(sorted(os.listdir("data")))
print("Calisma klasoru:", os.getcwd())

# ## 1. Veri

# Data from the public GOMD open data API (entity lists as used in the paper). Requests run in a few parallel threads with retries.
import json, time
from concurrent.futures import ThreadPoolExecutor
import pandas as pd
from gomd import GOMDClient
client = GOMDClient("https://gomd.pirireis.edu.tr")
JOBS = [["OECD_MARITIME_CO2_RESIDENCE_M", "oecd_maritime_co2_monthly"], ["unctad_fleet_owned_dwt", "owned_dwt"], ["unctad_fleet_dwt_total", "flag_dwt"], ["unctad_fleet_dwt_container", "flag_dwt_container"], ["unctad_fleet_age_avg", "fleet_age"]]
ENTITIES = json.loads("{\"OECD_MARITIME_CO2_RESIDENCE_M\": [[\"TUR\", \"Sovereign Coastal State TUR\", \"country\"], [\"ASM\", \"American Samoa\", \"country\"], [\"AIA\", \"Anguilla\", \"country\"], [\"ATG\", \"Antigua and Barbuda\", \"country\"], [\"ABW\", \"Aruba\", \"country\"], [\"AZE\", \"Azerbaijan\", \"country\"], [\"BHS\", \"Bahamas, The\", \"country\"], [\"GGY\", \"Bailiwick of Guernsey\", \"country\"], [\"BRB\", \"Barbados\", \"country\"], [\"BLZ\", \"Belize\", \"country\"], [\"BMU\", \"Bermuda\", \"country\"], [\"VGB\", \"British Virgin Islands\", \"country\"], [\"BRN\", \"Brunei Darussalam\", \"country\"], [\"CYM\", \"Cayman Islands\", \"country\"], [\"COK\", \"Cook Islands\", \"country\"], [\"CUW\", \"Curacao\", \"country\"], [\"GNQ\", \"Equatorial Guinea\", \"country\"], [\"FLK\", \"Falkland Islands (Malvinas)\", \"country\"], [\"FRO\", \"Faroe Islands\", \"country\"], [\"PYF\", \"French Polynesia\", \"country\"], [\"GIB\", \"Gibraltar\", \"country\"], [\"GRL\", \"Greenland\", \"country\"], [\"GLP\", \"Guadeloupe\", \"country\"], [\"GTM\", \"Guatemala\", \"country\"], [\"GUY\", \"Guyana\", \"country\"], [\"HND\", \"Honduras\", \"country\"], [\"HKG\", \"Hong Kong SAR, China\", \"country\"], [\"IMN\", \"Isle of Man\", \"country\"], [\"JEY\", \"Jersey\", \"country\"], [\"KAZ\", \"Kazakhstan\", \"country\"], [\"KIR\", \"Kiribati\", \"country\"], [\"PRK\", \"Korea, Dem. People's Rep.\", \"country\"], [\"LUX\", \"Luxembourg\", \"country\"], [\"MAC\", \"Macao SAR, China\", \"country\"], [\"MHL\", \"Marshall Islands\", \"country\"], [\"FSM\", \"Micronesia, Fed. Sts.\", \"country\"], [\"MCO\", \"Monaco\", \"country\"], [\"MMR\", \"Myanmar\", \"country\"], [\"NRU\", \"Naoero\", \"country\"], [\"NCL\", \"New Caledonia\", \"country\"], [\"OECD\", \"Organisation for Economic Co-operation and Development (OECD)\", \"aggregate\"], [\"W_O\", \"Other countries\", \"aggregate\"], [\"PLW\", \"Palau\", \"country\"], [\"PRY\", \"Paraguay\", \"country\"], [\"PRI\", \"Puerto Rico (US)\", \"country\"], [\"WSM\", \"Samoa\", \"country\"], [\"SRB\", \"Serbia\", \"country\"], [\"SLB\", \"Solomon Islands\", \"country\"], [\"AGO\", \"Sovereign Coastal State AGO\", \"country\"], [\"ALB\", \"Sovereign Coastal State ALB\", \"country\"], [\"ARE\", \"Sovereign Coastal State ARE\", \"country\"], [\"ARG\", \"Sovereign Coastal State ARG\", \"country\"], [\"AUS\", \"Sovereign Coastal State AUS\", \"country\"], [\"BEL\", \"Sovereign Coastal State BEL\", \"country\"], [\"BGD\", \"Sovereign Coastal State BGD\", \"country\"], [\"BGR\", \"Sovereign Coastal State BGR\", \"country\"], [\"BHR\", \"Sovereign Coastal State BHR\", \"country\"], [\"BRA\", \"Sovereign Coastal State BRA\", \"country\"], [\"CAN\", \"Sovereign Coastal State CAN\", \"country\"], [\"CHL\", \"Sovereign Coastal State CHL\", \"country\"], [\"CHN\", \"Sovereign Coastal State CHN\", \"country\"], [\"CIV\", \"Sovereign Coastal State CIV\", \"country\"], [\"CMR\", \"Sovereign Coastal State CMR\", \"country\"], [\"COG\", \"Sovereign Coastal State COG\", \"country\"], [\"COL\", \"Sovereign Coastal State COL\", \"country\"], [\"COM\", \"Sovereign Coastal State COM\", \"country\"], [\"CPV\", \"Sovereign Coastal State CPV\", \"country\"], [\"CUB\", \"Sovereign Coastal State CUB\", \"country\"], [\"CYP\", \"Greek Cypriot Administration of Southern Cyprus (GCA)\", \"country\"], [\"DEU\", \"Sovereign Coastal State DEU\", \"country\"], [\"DNK\", \"Sovereign Coastal State DNK\", \"country\"], [\"DOM\", \"Sovereign Coastal State DOM\", \"country\"], [\"DZA\", \"Sovereign Coastal State DZA\", \"country\"], [\"ECU\", \"Sovereign Coastal State ECU\", \"country\"], [\"EGY\", \"Sovereign Coastal State EGY\", \"country\"], [\"ESP\", \"Sovereign Coastal State ESP\", \"country\"], [\"EST\", \"Sovereign Coastal State EST\", \"country\"], [\"FIN\", \"Sovereign Coastal State FIN\", \"country\"], [\"FJI\", \"Sovereign Coastal State FJI\", \"country\"], [\"FRA\", \"Sovereign Coastal State FRA\", \"country\"], [\"GAB\", \"Sovereign Coastal State GAB\", \"country\"], [\"GBR\", \"Sovereign Coastal State GBR\", \"country\"], [\"GEO\", \"Sovereign Coastal State GEO\", \"country\"], [\"GHA\", \"Sovereign Coastal State GHA\", \"country\"], [\"GIN\", \"Sovereign Coastal State GIN\", \"country\"], [\"GRC\", \"Sovereign Coastal State GRC\", \"country\"], [\"HRV\", \"Sovereign Coastal State HRV\", \"country\"], [\"IDN\", \"Sovereign Coastal State IDN\", \"country\"], [\"IND\", \"Sovereign Coastal State IND\", \"country\"], [\"IRL\", \"Sovereign Coastal State IRL\", \"country\"], [\"IRN\", \"Sovereign Coastal State IRN\", \"country\"], [\"IRQ\", \"Sovereign Coastal State IRQ\", \"country\"], [\"ISL\", \"Sovereign Coastal State ISL\", \"country\"], [\"ITA\", \"Sovereign Coastal State ITA\", \"country\"], [\"JAM\", \"Sovereign Coastal State JAM\", \"country\"], [\"JOR\", \"Sovereign Coastal State JOR\", \"country\"], [\"JPN\", \"Sovereign Coastal State JPN\", \"country\"], [\"KEN\", \"Sovereign Coastal State KEN\", \"country\"], [\"KHM\", \"Sovereign Coastal State KHM\", \"country\"], [\"KOR\", \"Sovereign Coastal State KOR\", \"country\"], [\"KWT\", \"Sovereign Coastal State KWT\", \"country\"], [\"LBN\", \"Sovereign Coastal State LBN\", \"country\"], [\"LBR\", \"Sovereign Coastal State LBR\", \"country\"], [\"LKA\", \"Sovereign Coastal State LKA\", \"country\"], [\"LTU\", \"Sovereign Coastal State LTU\", \"country\"], [\"LVA\", \"Sovereign Coastal State LVA\", \"country\"], [\"MAR\", \"Sovereign Coastal State MAR\", \"country\"], [\"MDG\", \"Sovereign Coastal State MDG\", \"country\"], [\"MDV\", \"Sovereign Coastal State MDV\", \"country\"], [\"MEX\", \"Sovereign Coastal State MEX\", \"country\"], [\"MLT\", \"Sovereign Coastal State MLT\", \"country\"], [\"MNE\", \"Sovereign Coastal State MNE\", \"country\"], [\"MOZ\", \"Sovereign Coastal State MOZ\", \"country\"], [\"MRT\", \"Sovereign Coastal State MRT\", \"country\"], [\"MUS\", \"Sovereign Coastal State MUS\", \"country\"], [\"MYS\", \"Sovereign Coastal State MYS\", \"country\"], [\"NAM\", \"Sovereign Coastal State NAM\", \"country\"], [\"NGA\", \"Sovereign Coastal State NGA\", \"country\"], [\"NLD\", \"Sovereign Coastal State NLD\", \"country\"], [\"NOR\", \"Sovereign Coastal State NOR\", \"country\"], [\"NZL\", \"Sovereign Coastal State NZL\", \"country\"], [\"OMN\", \"Sovereign Coastal State OMN\", \"country\"], [\"PAK\", \"Sovereign Coastal State PAK\", \"country\"], [\"PAN\", \"Sovereign Coastal State PAN\", \"country\"], [\"PER\", \"Sovereign Coastal State PER\", \"country\"], [\"PHL\", \"Sovereign Coastal State PHL\", \"country\"], [\"PNG\", \"Sovereign Coastal State PNG\", \"country\"], [\"POL\", \"Sovereign Coastal State POL\", \"country\"], [\"PRT\", \"Sovereign Coastal State PRT\", \"country\"], [\"QAT\", \"Sovereign Coastal State QAT\", \"country\"], [\"ROU\", \"Sovereign Coastal State ROU\", \"country\"], [\"RUS\", \"Sovereign Coastal State RUS\", \"country\"], [\"SAU\", \"Sovereign Coastal State SAU\", \"country\"], [\"SEN\", \"Sovereign Coastal State SEN\", \"country\"], [\"SGP\", \"Sovereign Coastal State SGP\", \"country\"], [\"SLE\", \"Sovereign Coastal State SLE\", \"country\"], [\"SVN\", \"Sovereign Coastal State SVN\", \"country\"], [\"SWE\", \"Sovereign Coastal State SWE\", \"country\"], [\"SYC\", \"Sovereign Coastal State SYC\", \"country\"], [\"SYR\", \"Sovereign Coastal State SYR\", \"country\"], [\"THA\", \"Sovereign Coastal State THA\", \"country\"], [\"TTO\", \"Sovereign Coastal State TTO\", \"country\"], [\"TUN\", \"Sovereign Coastal State TUN\", \"country\"], [\"TWN\", \"Sovereign Coastal State TWN\", \"country\"], [\"TZA\", \"Sovereign Coastal State TZA\", \"country\"], [\"UKR\", \"Sovereign Coastal State UKR\", \"country\"], [\"URY\", \"Sovereign Coastal State URY\", \"country\"], [\"USA\", \"Sovereign Coastal State USA\", \"country\"], [\"VEN\", \"Sovereign Coastal State VEN\", \"country\"], [\"VNM\", \"Sovereign Coastal State VNM\", \"country\"], [\"WLD\", \"Sovereign Coastal State WLD\", \"country\"], [\"YEM\", \"Sovereign Coastal State YEM\", \"country\"], [\"ZAF\", \"Sovereign Coastal State ZAF\", \"country\"], [\"KNA\", \"St. Kitts and Nevis\", \"country\"], [\"VCT\", \"St. Vincent and the Grenadines\", \"country\"], [\"SUR\", \"Suriname\", \"country\"], [\"CHE\", \"Switzerland\", \"country\"], [\"TLS\", \"Timor-Leste\", \"country\"], [\"TON\", \"Tonga\", \"country\"], [\"TKM\", \"Turkmenistan\", \"country\"], [\"TCA\", \"Turks and Caicos Islands\", \"country\"], [\"VUT\", \"Vanuatu\", \"country\"], [\"VIR\", \"Virgin Islands (U.S.)\", \"country\"]], \"unctad_fleet_owned_dwt\": [[\"TUR\", \"Turkiye\", \"country\"], [\"ALB\", \"Albania\", \"country\"], [\"DZA\", \"Algeria\", \"country\"], [\"DEU\", \"Germany\", \"country\"], [\"AGO\", \"Angola\", \"country\"], [\"AIA\", \"Anguilla\", \"country\"], [\"ATG\", \"Antigua and Barbuda\", \"country\"], [\"ARG\", \"Argentina\", \"country\"], [\"ABW\", \"Aruba\", \"country\"], [\"AUS\", \"Australia\", \"country\"], [\"AUT\", \"Austria\", \"country\"], [\"AZE\", \"Azerbaijan\", \"country\"], [\"BHS\", \"Bahamas, The\", \"country\"], [\"BHR\", \"Bahrain\", \"country\"], [\"BGD\", \"Bangladesh\", \"country\"], [\"BRB\", \"Barbados\", \"country\"], [\"BEL\", \"Belgium\", \"country\"], [\"BLZ\", \"Belize\", \"country\"], [\"BEN\", \"Benin\", \"country\"], [\"BMU\", \"Bermuda\", \"country\"], [\"BOL\", \"Bolivia\", \"country\"], [\"BES\", \"Bonaire, Sint Eustatius and Saba\", \"country\"], [\"BRA\", \"Brazil\", \"country\"], [\"VGB\", \"British Virgin Islands\", \"country\"], [\"BRN\", \"Brunei Darussalam\", \"country\"], [\"BGR\", \"Bulgaria\", \"country\"], [\"CPV\", \"Cabo Verde\", \"country\"], [\"KHM\", \"Cambodia\", \"country\"], [\"CMR\", \"Cameroon\", \"country\"], [\"CAN\", \"Canada\", \"country\"], [\"CYM\", \"Cayman Islands\", \"country\"], [\"CHL\", \"Chile\", \"country\"], [\"TWN\", \"Chinese Taipei\", \"country\"], [\"CHN\", \"China\", \"country\"], [\"COL\", \"Colombia\", \"country\"], [\"COG\", \"Congo, Rep.\", \"country\"], [\"COK\", \"Cook Islands\", \"country\"], [\"CRI\", \"Costa Rica\", \"country\"], [\"CIV\", \"Cote d'Ivoire\", \"country\"], [\"HRV\", \"Croatia\", \"country\"], [\"CUB\", \"Cuba\", \"country\"], [\"CUW\", \"Curacao\", \"country\"], [\"CYP\", \"Greek Cypriot Administration of Southern Cyprus (GCA)\", \"country\"], [\"COD\", \"Democratic Republic of Congo\", \"country\"], [\"DNK\", \"Denmark\", \"country\"], [\"DJI\", \"Djibouti\", \"country\"], [\"DMA\", \"Dominica\", \"country\"], [\"DOM\", \"Dominican Republic\", \"country\"], [\"WLD\", \"World (Global)\", \"aggregate\"], [\"ECU\", \"Ecuador\", \"country\"], [\"EGY\", \"Egypt\", \"country\"], [\"GNQ\", \"Equatorial Guinea\", \"country\"], [\"ERI\", \"Eritrea\", \"country\"], [\"EST\", \"Estonia\", \"country\"], [\"ETH\", \"Ethiopia\", \"country\"], [\"FRO\", \"Faroe Islands\", \"country\"], [\"FJI\", \"Fiji\", \"country\"], [\"FIN\", \"Finland\", \"country\"], [\"FRA\", \"France\", \"country\"], [\"PYF\", \"French Polynesia\", \"country\"], [\"GAB\", \"Gabon\", \"country\"], [\"GMB\", \"Gambia, The\", \"country\"], [\"GEO\", \"Georgia\", \"country\"], [\"GHA\", \"Ghana\", \"country\"], [\"GIB\", \"Gibraltar\", \"country\"], [\"GRL\", \"Greenland\", \"country\"], [\"GRD\", \"Grenada\", \"country\"], [\"GLP\", \"Guadeloupe\", \"country\"], [\"GUM\", \"Guam\", \"country\"], [\"GTM\", \"Guatemala\", \"country\"], [\"GGY\", \"Guernsey\", \"country\"], [\"GIN\", \"Guinea\", \"country\"], [\"GUY\", \"Guyana\", \"country\"], [\"HTI\", \"Haiti\", \"country\"], [\"HND\", \"Honduras\", \"country\"], [\"HKG\", \"Hong Kong SAR, China\", \"country\"], [\"ISL\", \"Iceland\", \"country\"], [\"IND\", \"India\", \"country\"], [\"IDN\", \"Indonesia\", \"country\"], [\"IRN\", \"Iran, Islamic Rep.\", \"country\"], [\"IRQ\", \"Iraq\", \"country\"], [\"IRL\", \"Ireland\", \"country\"], [\"ESP\", \"Spain\", \"country\"], [\"ISR\", \"Israel\", \"country\"], [\"ITA\", \"Italy\", \"country\"], [\"JAM\", \"Jamaica\", \"country\"], [\"JPN\", \"Japan\", \"country\"], [\"JEY\", \"Jersey\", \"country\"], [\"JOR\", \"Jordan\", \"country\"], [\"KAZ\", \"Kazakhstan\", \"country\"], [\"KEN\", \"Kenya\", \"country\"], [\"KIR\", \"Kiribati\", \"country\"], [\"KOR\", \"Korea Rep\", \"country\"], [\"PRK\", \"Korea, Dem. People's Rep.\", \"country\"], [\"KWT\", \"Kuwait\", \"country\"], [\"LAO\", \"Laos\", \"country\"], [\"LVA\", \"Latvia\", \"country\"], [\"LBN\", \"Lebanon\", \"country\"], [\"LBR\", \"Liberia\", \"country\"], [\"LBY\", \"Libya\", \"country\"], [\"LIE\", \"Liechtenstein\", \"country\"], [\"LTU\", \"Lithuania\", \"country\"], [\"LUX\", \"Luxembourg\", \"country\"], [\"MAC\", \"Macao SAR, China\", \"country\"], [\"MDG\", \"Madagascar\", \"country\"], [\"MYS\", \"Malaysia\", \"country\"], [\"MDV\", \"Maldives\", \"country\"], [\"MLT\", \"Malta\", \"country\"], [\"MHL\", \"Marshall Islands\", \"country\"], [\"MRT\", \"Mauritania\", \"country\"], [\"MUS\", \"Mauritius\", \"country\"], [\"MEX\", \"Mexico\", \"country\"], [\"FSM\", \"Micronesia, Fed. Sts.\", \"country\"], [\"MDA\", \"Moldova\", \"country\"], [\"MCO\", \"Monaco\", \"country\"], [\"MNG\", \"Mongolia\", \"country\"], [\"MNE\", \"Montenegro\", \"country\"], [\"MAR\", \"Morocco\", \"country\"], [\"MOZ\", \"Mozambique\", \"country\"], [\"MMR\", \"Myanmar\", \"country\"], [\"NAM\", \"Namibia\", \"country\"], [\"NRU\", \"Nauru\", \"country\"], [\"NLD\", \"Netherlands\", \"country\"], [\"NCL\", \"New Caledonia\", \"country\"], [\"NZL\", \"New Zealand\", \"country\"], [\"NIC\", \"Nicaragua\", \"country\"], [\"NGA\", \"Nigeria\", \"country\"], [\"MNP\", \"Northern Mariana Islands\", \"country\"], [\"NOR\", \"Norway\", \"country\"], [\"OMN\", \"Oman\", \"country\"], [\"PAK\", \"Pakistan\", \"country\"], [\"PAN\", \"Panama\", \"country\"], [\"PNG\", \"Papua New Guinea\", \"country\"], [\"PRY\", \"Paraguay\", \"country\"], [\"PER\", \"Peru\", \"country\"], [\"PHL\", \"Philippines\", \"country\"], [\"POL\", \"Poland\", \"country\"], [\"PRT\", \"Portugal\", \"country\"], [\"QAT\", \"Qatar\", \"country\"], [\"ROU\", \"Romania\", \"country\"], [\"RUS\", \"Russian Federation\", \"country\"], [\"WSM\", \"Samoa\", \"country\"], [\"STP\", \"Sao Tome and Principe\", \"country\"], [\"SAU\", \"Saudi Arabia\", \"country\"], [\"SEN\", \"Senegal\", \"country\"], [\"SRB\", \"Serbia\", \"country\"], [\"SYC\", \"Seychelles\", \"country\"], [\"SLE\", \"Sierra Leone\", \"country\"], [\"SGP\", \"Singapore\", \"country\"], [\"SVK\", \"Slovakia\", \"country\"], [\"SVN\", \"Slovenia\", \"country\"], [\"SLB\", \"Solomon Islands\", \"country\"], [\"SOM\", \"Somalia\", \"country\"], [\"ZAF\", \"South Africa\", \"country\"], [\"LKA\", \"Sri Lanka\", \"country\"], [\"KNA\", \"St. Kitts and Nevis\", \"country\"], [\"LCA\", \"St. Lucia\", \"country\"], [\"VCT\", \"St. Vincent and the Grenadines\", \"country\"], [\"SDN\", \"Sudan\", \"country\"], [\"SUR\", \"Suriname\", \"country\"], [\"SWE\", \"Sweden\", \"country\"], [\"CHE\", \"Switzerland\", \"country\"], [\"SYR\", \"Syrian Arab Republic\", \"country\"], [\"TZA\", \"Tanzania\", \"country\"], [\"THA\", \"Thailand\", \"country\"], [\"TLS\", \"Timor-Leste\", \"country\"], [\"TGO\", \"Togo\", \"country\"], [\"TON\", \"Tonga\", \"country\"], [\"TTO\", \"Trinidad and Tobago\", \"country\"], [\"TUN\", \"Tunisia\", \"country\"], [\"TKM\", \"Turkmenistan\", \"country\"], [\"TUV\", \"Tuvalu\", \"country\"], [\"GBR\", \"UK\", \"country\"], [\"UKR\", \"Ukraine\", \"country\"], [\"ARE\", \"United Arab Emirates\", \"country\"], [\"VIR\", \"United States Virgin Islands\", \"country\"], [\"URY\", \"Uruguay\", \"country\"], [\"USA\", \"USA\", \"country\"], [\"VUT\", \"Vanuatu\", \"country\"], [\"VEN\", \"Venezuela, RB\", \"country\"], [\"VNM\", \"Vietnam\", \"country\"], [\"YEM\", \"Yemen\", \"country\"], [\"GRC\", \"Greece\", \"country\"]], \"unctad_fleet_dwt_total\": [[\"TUR\", \"Turkiye\", \"country\"], [\"AFG\", \"Afghanistan\", \"country\"], [\"ALB\", \"Albania\", \"country\"], [\"DZA\", \"Algeria\", \"country\"], [\"DEU\", \"Germany\", \"country\"], [\"ASM\", \"American Samoa\", \"country\"], [\"AGO\", \"Angola\", \"country\"], [\"AIA\", \"Anguilla\", \"country\"], [\"ATG\", \"Antigua and Barbuda\", \"country\"], [\"ARG\", \"Argentina\", \"country\"], [\"ABW\", \"Aruba\", \"country\"], [\"AUS\", \"Australia\", \"country\"], [\"AUT\", \"Austria\", \"country\"], [\"AZE\", \"Azerbaijan\", \"country\"], [\"BHS\", \"Bahamas, The\", \"country\"], [\"BHR\", \"Bahrain\", \"country\"], [\"BGD\", \"Bangladesh\", \"country\"], [\"BRB\", \"Barbados\", \"country\"], [\"BLR\", \"Belarus\", \"country\"], [\"BEL\", \"Belgium\", \"country\"], [\"BLZ\", \"Belize\", \"country\"], [\"BEN\", \"Benin\", \"country\"], [\"BMU\", \"Bermuda\", \"country\"], [\"BOL\", \"Bolivia\", \"country\"], [\"BIH\", \"Bosnia and Herzegovina\", \"country\"], [\"BWA\", \"Botswana\", \"country\"], [\"BRA\", \"Brazil\", \"country\"], [\"VGB\", \"British Virgin Islands\", \"country\"], [\"BRN\", \"Brunei Darussalam\", \"country\"], [\"BGR\", \"Bulgaria\", \"country\"], [\"CPV\", \"Cabo Verde\", \"country\"], [\"KHM\", \"Cambodia\", \"country\"], [\"CMR\", \"Cameroon\", \"country\"], [\"CAN\", \"Canada\", \"country\"], [\"CYM\", \"Cayman Islands\", \"country\"], [\"CHL\", \"Chile\", \"country\"], [\"TWN\", \"Chinese Taipei\", \"country\"], [\"CHN\", \"China\", \"country\"], [\"COL\", \"Colombia\", \"country\"], [\"COM\", \"Comoros\", \"country\"], [\"COG\", \"Congo, Rep.\", \"country\"], [\"COK\", \"Cook Islands\", \"country\"], [\"CRI\", \"Costa Rica\", \"country\"], [\"CIV\", \"Cote d'Ivoire\", \"country\"], [\"HRV\", \"Croatia\", \"country\"], [\"CUB\", \"Cuba\", \"country\"], [\"CUW\", \"Curacao\", \"country\"], [\"CYP\", \"Greek Cypriot Administration of Southern Cyprus (GCA)\", \"country\"], [\"CZE\", \"Czechia\", \"country\"], [\"COD\", \"Democratic Republic of Congo\", \"country\"], [\"DNK\", \"Denmark\", \"country\"], [\"DJI\", \"Djibouti\", \"country\"], [\"DMA\", \"Dominica\", \"country\"], [\"DOM\", \"Dominican Republic\", \"country\"], [\"WLD\", \"World (Global)\", \"aggregate\"], [\"ECU\", \"Ecuador\", \"country\"], [\"EGY\", \"Egypt\", \"country\"], [\"SLV\", \"El Salvador\", \"country\"], [\"GNQ\", \"Equatorial Guinea\", \"country\"], [\"ERI\", \"Eritrea\", \"country\"], [\"EST\", \"Estonia\", \"country\"], [\"SWZ\", \"Eswatini\", \"country\"], [\"ETH\", \"Ethiopia\", \"country\"], [\"FLK\", \"Falkland Islands (Malvinas)\", \"country\"], [\"FRO\", \"Faroe Islands\", \"country\"], [\"FJI\", \"Fiji\", \"country\"], [\"FIN\", \"Finland\", \"country\"], [\"FRA\", \"France\", \"country\"], [\"PYF\", \"French Polynesia\", \"country\"], [\"ATF\", \"French Southern Territories\", \"country\"], [\"GAB\", \"Gabon\", \"country\"], [\"GMB\", \"Gambia, The\", \"country\"], [\"GEO\", \"Georgia\", \"country\"], [\"GHA\", \"Ghana\", \"country\"], [\"GIB\", \"Gibraltar\", \"country\"], [\"GRL\", \"Greenland\", \"country\"], [\"GRD\", \"Grenada\", \"country\"], [\"GUM\", \"Guam\", \"country\"], [\"GTM\", \"Guatemala\", \"country\"], [\"GIN\", \"Guinea\", \"country\"], [\"GNB\", \"Guinea-Bissau\", \"country\"], [\"GUY\", \"Guyana\", \"country\"], [\"HTI\", \"Haiti\", \"country\"], [\"HND\", \"Honduras\", \"country\"], [\"HKG\", \"Hong Kong SAR, China\", \"country\"], [\"HUN\", \"Hungary\", \"country\"], [\"ISL\", \"Iceland\", \"country\"], [\"IND\", \"India\", \"country\"], [\"IDN\", \"Indonesia\", \"country\"], [\"IRN\", \"Iran, Islamic Rep.\", \"country\"], [\"IRQ\", \"Iraq\", \"country\"], [\"IRL\", \"Ireland\", \"country\"], [\"IMN\", \"Isle of Man\", \"country\"], [\"ESP\", \"Spain\", \"country\"], [\"ISR\", \"Israel\", \"country\"], [\"ITA\", \"Italy\", \"country\"], [\"JAM\", \"Jamaica\", \"country\"], [\"JPN\", \"Japan\", \"country\"], [\"JOR\", \"Jordan\", \"country\"], [\"KAZ\", \"Kazakhstan\", \"country\"], [\"KEN\", \"Kenya\", \"country\"], [\"KIR\", \"Kiribati\", \"country\"], [\"KOR\", \"Korea Rep\", \"country\"], [\"PRK\", \"Korea, Dem. People's Rep.\", \"country\"], [\"KWT\", \"Kuwait\", \"country\"], [\"LAO\", \"Laos\", \"country\"], [\"LVA\", \"Latvia\", \"country\"], [\"LBN\", \"Lebanon\", \"country\"], [\"LSO\", \"Lesotho\", \"country\"], [\"LBR\", \"Liberia\", \"country\"], [\"LBY\", \"Libya\", \"country\"], [\"LTU\", \"Lithuania\", \"country\"], [\"LUX\", \"Luxembourg\", \"country\"], [\"MAC\", \"Macao SAR, China\", \"country\"], [\"MDG\", \"Madagascar\", \"country\"], [\"MWI\", \"Malawi\", \"country\"], [\"MYS\", \"Malaysia\", \"country\"], [\"MDV\", \"Maldives\", \"country\"], [\"MLI\", \"Mali\", \"country\"], [\"MLT\", \"Malta\", \"country\"], [\"MHL\", \"Marshall Islands\", \"country\"], [\"MRT\", \"Mauritania\", \"country\"], [\"MUS\", \"Mauritius\", \"country\"], [\"MEX\", \"Mexico\", \"country\"], [\"FSM\", \"Micronesia, Fed. Sts.\", \"country\"], [\"MDA\", \"Moldova\", \"country\"], [\"MCO\", \"Monaco\", \"country\"], [\"MNG\", \"Mongolia\", \"country\"], [\"MNE\", \"Montenegro\", \"country\"], [\"MSR\", \"Montserrat\", \"country\"], [\"MAR\", \"Morocco\", \"country\"], [\"MOZ\", \"Mozambique\", \"country\"], [\"MMR\", \"Myanmar\", \"country\"], [\"NAM\", \"Namibia\", \"country\"], [\"NRU\", \"Nauru\", \"country\"], [\"NLD\", \"Netherlands\", \"country\"], [\"NCL\", \"New Caledonia\", \"country\"], [\"NZL\", \"New Zealand\", \"country\"], [\"NIC\", \"Nicaragua\", \"country\"], [\"NER\", \"Niger\", \"country\"], [\"NGA\", \"Nigeria\", \"country\"], [\"NIU\", \"Niue\", \"country\"], [\"MKD\", \"North Macedonia\", \"country\"], [\"MNP\", \"Northern Mariana Islands\", \"country\"], [\"NOR\", \"Norway\", \"country\"], [\"OMN\", \"Oman\", \"country\"], [\"PAK\", \"Pakistan\", \"country\"], [\"PLW\", \"Palau\", \"country\"], [\"PAN\", \"Panama\", \"country\"], [\"PNG\", \"Papua New Guinea\", \"country\"], [\"PRY\", \"Paraguay\", \"country\"], [\"PER\", \"Peru\", \"country\"], [\"PHL\", \"Philippines\", \"country\"], [\"POL\", \"Poland\", \"country\"], [\"PRT\", \"Portugal\", \"country\"], [\"PRI\", \"Puerto Rico\", \"country\"], [\"QAT\", \"Qatar\", \"country\"], [\"REU\", \"R\u00e9union\", \"country\"], [\"ROU\", \"Romania\", \"country\"], [\"RUS\", \"Russian Federation\", \"country\"], [\"SHN\", \"Saint Helena\", \"country\"], [\"SPM\", \"Saint Pierre and Miquelon\", \"country\"], [\"WSM\", \"Samoa\", \"country\"], [\"SMR\", \"San Marino\", \"country\"], [\"STP\", \"Sao Tome and Principe\", \"country\"], [\"SAU\", \"Saudi Arabia\", \"country\"], [\"SEN\", \"Senegal\", \"country\"], [\"SYC\", \"Seychelles\", \"country\"], [\"SLE\", \"Sierra Leone\", \"country\"], [\"SGP\", \"Singapore\", \"country\"], [\"SVK\", \"Slovakia\", \"country\"], [\"SVN\", \"Slovenia\", \"country\"], [\"SLB\", \"Solomon Islands\", \"country\"], [\"SOM\", \"Somalia\", \"country\"], [\"ZAF\", \"South Africa\", \"country\"], [\"SSD\", \"South Sudan\", \"country\"], [\"LKA\", \"Sri Lanka\", \"country\"], [\"KNA\", \"St. Kitts and Nevis\", \"country\"], [\"LCA\", \"St. Lucia\", \"country\"], [\"VCT\", \"St. Vincent and the Grenadines\", \"country\"], [\"SDN\", \"Sudan\", \"country\"], [\"SUR\", \"Suriname\", \"country\"], [\"SWE\", \"Sweden\", \"country\"], [\"CHE\", \"Switzerland\", \"country\"], [\"SYR\", \"Syrian Arab Republic\", \"country\"], [\"TZA\", \"Tanzania\", \"country\"], [\"THA\", \"Thailand\", \"country\"], [\"TLS\", \"Timor-Leste\", \"country\"], [\"TGO\", \"Togo\", \"country\"], [\"TON\", \"Tonga\", \"country\"], [\"TTO\", \"Trinidad and Tobago\", \"country\"], [\"TUN\", \"Tunisia\", \"country\"], [\"TKM\", \"Turkmenistan\", \"country\"], [\"TCA\", \"Turks and Caicos Islands\", \"country\"], [\"TUV\", \"Tuvalu\", \"country\"], [\"UGA\", \"Uganda\", \"country\"], [\"GBR\", \"UK\", \"country\"], [\"UKR\", \"Ukraine\", \"country\"], [\"ARE\", \"United Arab Emirates\", \"country\"], [\"VIR\", \"United States Virgin Islands\", \"country\"], [\"URY\", \"Uruguay\", \"country\"], [\"USA\", \"USA\", \"country\"], [\"VUT\", \"Vanuatu\", \"country\"], [\"VEN\", \"Venezuela, RB\", \"country\"], [\"VNM\", \"Vietnam\", \"country\"], [\"WLF\", \"Wallis and Futuna Islands\", \"country\"], [\"YEM\", \"Yemen\", \"country\"], [\"GRC\", \"Greece\", \"country\"], [\"ZMB\", \"Zambia\", \"country\"]], \"unctad_fleet_dwt_container\": [[\"TUR\", \"Turkiye\", \"country\"], [\"AFG\", \"Afghanistan\", \"country\"], [\"ALB\", \"Albania\", \"country\"], [\"DZA\", \"Algeria\", \"country\"], [\"DEU\", \"Germany\", \"country\"], [\"AGO\", \"Angola\", \"country\"], [\"AIA\", \"Anguilla\", \"country\"], [\"ATG\", \"Antigua and Barbuda\", \"country\"], [\"ARG\", \"Argentina\", \"country\"], [\"ABW\", \"Aruba\", \"country\"], [\"AUS\", \"Australia\", \"country\"], [\"AUT\", \"Austria\", \"country\"], [\"AZE\", \"Azerbaijan\", \"country\"], [\"BHS\", \"Bahamas, The\", \"country\"], [\"BHR\", \"Bahrain\", \"country\"], [\"BGD\", \"Bangladesh\", \"country\"], [\"BRB\", \"Barbados\", \"country\"], [\"BLR\", \"Belarus\", \"country\"], [\"BEL\", \"Belgium\", \"country\"], [\"BLZ\", \"Belize\", \"country\"], [\"BEN\", \"Benin\", \"country\"], [\"BMU\", \"Bermuda\", \"country\"], [\"BOL\", \"Bolivia\", \"country\"], [\"BIH\", \"Bosnia and Herzegovina\", \"country\"], [\"BWA\", \"Botswana\", \"country\"], [\"BRA\", \"Brazil\", \"country\"], [\"VGB\", \"British Virgin Islands\", \"country\"], [\"BRN\", \"Brunei Darussalam\", \"country\"], [\"BGR\", \"Bulgaria\", \"country\"], [\"CPV\", \"Cabo Verde\", \"country\"], [\"KHM\", \"Cambodia\", \"country\"], [\"CMR\", \"Cameroon\", \"country\"], [\"CAN\", \"Canada\", \"country\"], [\"CYM\", \"Cayman Islands\", \"country\"], [\"CHL\", \"Chile\", \"country\"], [\"TWN\", \"Chinese Taipei\", \"country\"], [\"CHN\", \"China\", \"country\"], [\"COL\", \"Colombia\", \"country\"], [\"COM\", \"Comoros\", \"country\"], [\"COG\", \"Congo, Rep.\", \"country\"], [\"COK\", \"Cook Islands\", \"country\"], [\"CRI\", \"Costa Rica\", \"country\"], [\"CIV\", \"Cote d'Ivoire\", \"country\"], [\"HRV\", \"Croatia\", \"country\"], [\"CUB\", \"Cuba\", \"country\"], [\"CUW\", \"Curacao\", \"country\"], [\"CYP\", \"Greek Cypriot Administration of Southern Cyprus (GCA)\", \"country\"], [\"CZE\", \"Czechia\", \"country\"], [\"COD\", \"Democratic Republic of Congo\", \"country\"], [\"DNK\", \"Denmark\", \"country\"], [\"DJI\", \"Djibouti\", \"country\"], [\"DMA\", \"Dominica\", \"country\"], [\"DOM\", \"Dominican Republic\", \"country\"], [\"WLD\", \"World (Global)\", \"aggregate\"], [\"ECU\", \"Ecuador\", \"country\"], [\"EGY\", \"Egypt\", \"country\"], [\"SLV\", \"El Salvador\", \"country\"], [\"GNQ\", \"Equatorial Guinea\", \"country\"], [\"ERI\", \"Eritrea\", \"country\"], [\"EST\", \"Estonia\", \"country\"], [\"SWZ\", \"Eswatini\", \"country\"], [\"ETH\", \"Ethiopia\", \"country\"], [\"FLK\", \"Falkland Islands (Malvinas)\", \"country\"], [\"FRO\", \"Faroe Islands\", \"country\"], [\"FJI\", \"Fiji\", \"country\"], [\"FIN\", \"Finland\", \"country\"], [\"FRA\", \"France\", \"country\"], [\"PYF\", \"French Polynesia\", \"country\"], [\"ATF\", \"French Southern Territories\", \"country\"], [\"GAB\", \"Gabon\", \"country\"], [\"GMB\", \"Gambia, The\", \"country\"], [\"GEO\", \"Georgia\", \"country\"], [\"GHA\", \"Ghana\", \"country\"], [\"GIB\", \"Gibraltar\", \"country\"], [\"GRL\", \"Greenland\", \"country\"], [\"GRD\", \"Grenada\", \"country\"], [\"GUM\", \"Guam\", \"country\"], [\"GTM\", \"Guatemala\", \"country\"], [\"GIN\", \"Guinea\", \"country\"], [\"GNB\", \"Guinea-Bissau\", \"country\"], [\"GUY\", \"Guyana\", \"country\"], [\"HTI\", \"Haiti\", \"country\"], [\"HND\", \"Honduras\", \"country\"], [\"HKG\", \"Hong Kong SAR, China\", \"country\"], [\"HUN\", \"Hungary\", \"country\"], [\"ISL\", \"Iceland\", \"country\"], [\"IND\", \"India\", \"country\"], [\"IDN\", \"Indonesia\", \"country\"], [\"IRN\", \"Iran, Islamic Rep.\", \"country\"], [\"IRQ\", \"Iraq\", \"country\"], [\"IRL\", \"Ireland\", \"country\"], [\"IMN\", \"Isle of Man\", \"country\"], [\"ESP\", \"Spain\", \"country\"], [\"ISR\", \"Israel\", \"country\"], [\"ITA\", \"Italy\", \"country\"], [\"JAM\", \"Jamaica\", \"country\"], [\"JPN\", \"Japan\", \"country\"], [\"JOR\", \"Jordan\", \"country\"], [\"KAZ\", \"Kazakhstan\", \"country\"], [\"KEN\", \"Kenya\", \"country\"], [\"KIR\", \"Kiribati\", \"country\"], [\"KOR\", \"Korea Rep\", \"country\"], [\"PRK\", \"Korea, Dem. People's Rep.\", \"country\"], [\"KWT\", \"Kuwait\", \"country\"], [\"LAO\", \"Laos\", \"country\"], [\"LVA\", \"Latvia\", \"country\"], [\"LBN\", \"Lebanon\", \"country\"], [\"LSO\", \"Lesotho\", \"country\"], [\"LBR\", \"Liberia\", \"country\"], [\"LBY\", \"Libya\", \"country\"], [\"LTU\", \"Lithuania\", \"country\"], [\"LUX\", \"Luxembourg\", \"country\"], [\"MAC\", \"Macao SAR, China\", \"country\"], [\"MDG\", \"Madagascar\", \"country\"], [\"MYS\", \"Malaysia\", \"country\"], [\"MDV\", \"Maldives\", \"country\"], [\"MLT\", \"Malta\", \"country\"], [\"MHL\", \"Marshall Islands\", \"country\"], [\"MRT\", \"Mauritania\", \"country\"], [\"MUS\", \"Mauritius\", \"country\"], [\"MEX\", \"Mexico\", \"country\"], [\"FSM\", \"Micronesia, Fed. Sts.\", \"country\"], [\"MDA\", \"Moldova\", \"country\"], [\"MCO\", \"Monaco\", \"country\"], [\"MNG\", \"Mongolia\", \"country\"], [\"MNE\", \"Montenegro\", \"country\"], [\"MAR\", \"Morocco\", \"country\"], [\"MOZ\", \"Mozambique\", \"country\"], [\"MMR\", \"Myanmar\", \"country\"], [\"NAM\", \"Namibia\", \"country\"], [\"NRU\", \"Nauru\", \"country\"], [\"NLD\", \"Netherlands\", \"country\"], [\"NCL\", \"New Caledonia\", \"country\"], [\"NZL\", \"New Zealand\", \"country\"], [\"NIC\", \"Nicaragua\", \"country\"], [\"NER\", \"Niger\", \"country\"], [\"NGA\", \"Nigeria\", \"country\"], [\"NIU\", \"Niue\", \"country\"], [\"MKD\", \"North Macedonia\", \"country\"], [\"MNP\", \"Northern Mariana Islands\", \"country\"], [\"NOR\", \"Norway\", \"country\"], [\"OMN\", \"Oman\", \"country\"], [\"PAK\", \"Pakistan\", \"country\"], [\"PLW\", \"Palau\", \"country\"], [\"PAN\", \"Panama\", \"country\"], [\"PNG\", \"Papua New Guinea\", \"country\"], [\"PRY\", \"Paraguay\", \"country\"], [\"PER\", \"Peru\", \"country\"], [\"PHL\", \"Philippines\", \"country\"], [\"POL\", \"Poland\", \"country\"], [\"PRT\", \"Portugal\", \"country\"], [\"PRI\", \"Puerto Rico\", \"country\"], [\"QAT\", \"Qatar\", \"country\"], [\"REU\", \"R\u00e9union\", \"country\"], [\"ROU\", \"Romania\", \"country\"], [\"RUS\", \"Russian Federation\", \"country\"], [\"WSM\", \"Samoa\", \"country\"], [\"SMR\", \"San Marino\", \"country\"], [\"STP\", \"Sao Tome and Principe\", \"country\"], [\"SAU\", \"Saudi Arabia\", \"country\"], [\"SEN\", \"Senegal\", \"country\"], [\"SYC\", \"Seychelles\", \"country\"], [\"SLE\", \"Sierra Leone\", \"country\"], [\"SGP\", \"Singapore\", \"country\"], [\"SVK\", \"Slovakia\", \"country\"], [\"SVN\", \"Slovenia\", \"country\"], [\"SLB\", \"Solomon Islands\", \"country\"], [\"SOM\", \"Somalia\", \"country\"], [\"ZAF\", \"South Africa\", \"country\"], [\"SSD\", \"South Sudan\", \"country\"], [\"LKA\", \"Sri Lanka\", \"country\"], [\"KNA\", \"St. Kitts and Nevis\", \"country\"], [\"VCT\", \"St. Vincent and the Grenadines\", \"country\"], [\"SDN\", \"Sudan\", \"country\"], [\"SUR\", \"Suriname\", \"country\"], [\"SWE\", \"Sweden\", \"country\"], [\"CHE\", \"Switzerland\", \"country\"], [\"SYR\", \"Syrian Arab Republic\", \"country\"], [\"TZA\", \"Tanzania\", \"country\"], [\"THA\", \"Thailand\", \"country\"], [\"TLS\", \"Timor-Leste\", \"country\"], [\"TGO\", \"Togo\", \"country\"], [\"TON\", \"Tonga\", \"country\"], [\"TTO\", \"Trinidad and Tobago\", \"country\"], [\"TUN\", \"Tunisia\", \"country\"], [\"TKM\", \"Turkmenistan\", \"country\"], [\"TCA\", \"Turks and Caicos Islands\", \"country\"], [\"TUV\", \"Tuvalu\", \"country\"], [\"UGA\", \"Uganda\", \"country\"], [\"GBR\", \"UK\", \"country\"], [\"UKR\", \"Ukraine\", \"country\"], [\"ARE\", \"United Arab Emirates\", \"country\"], [\"VIR\", \"United States Virgin Islands\", \"country\"], [\"URY\", \"Uruguay\", \"country\"], [\"USA\", \"USA\", \"country\"], [\"VUT\", \"Vanuatu\", \"country\"], [\"VEN\", \"Venezuela, RB\", \"country\"], [\"VNM\", \"Vietnam\", \"country\"], [\"WLF\", \"Wallis and Futuna Islands\", \"country\"], [\"YEM\", \"Yemen\", \"country\"], [\"GRC\", \"Greece\", \"country\"], [\"ZMB\", \"Zambia\", \"country\"]], \"unctad_fleet_age_avg\": [[\"TUR\", \"Turkiye\", \"country\"], [\"AFG\", \"Afghanistan\", \"country\"], [\"ALB\", \"Albania\", \"country\"], [\"DZA\", \"Algeria\", \"country\"], [\"DEU\", \"Germany\", \"country\"], [\"AGO\", \"Angola\", \"country\"], [\"AIA\", \"Anguilla\", \"country\"], [\"ATG\", \"Antigua and Barbuda\", \"country\"], [\"ARG\", \"Argentina\", \"country\"], [\"ABW\", \"Aruba\", \"country\"], [\"AUS\", \"Australia\", \"country\"], [\"AUT\", \"Austria\", \"country\"], [\"AZE\", \"Azerbaijan\", \"country\"], [\"BHS\", \"Bahamas, The\", \"country\"], [\"BHR\", \"Bahrain\", \"country\"], [\"BGD\", \"Bangladesh\", \"country\"], [\"BRB\", \"Barbados\", \"country\"], [\"BLR\", \"Belarus\", \"country\"], [\"BEL\", \"Belgium\", \"country\"], [\"BLZ\", \"Belize\", \"country\"], [\"BEN\", \"Benin\", \"country\"], [\"BMU\", \"Bermuda\", \"country\"], [\"BOL\", \"Bolivia\", \"country\"], [\"BIH\", \"Bosnia and Herzegovina\", \"country\"], [\"BWA\", \"Botswana\", \"country\"], [\"BRA\", \"Brazil\", \"country\"], [\"VGB\", \"British Virgin Islands\", \"country\"], [\"BRN\", \"Brunei Darussalam\", \"country\"], [\"BGR\", \"Bulgaria\", \"country\"], [\"CPV\", \"Cabo Verde\", \"country\"], [\"KHM\", \"Cambodia\", \"country\"], [\"CMR\", \"Cameroon\", \"country\"], [\"CAN\", \"Canada\", \"country\"], [\"CYM\", \"Cayman Islands\", \"country\"], [\"CHL\", \"Chile\", \"country\"], [\"TWN\", \"Chinese Taipei\", \"country\"], [\"CHN\", \"China\", \"country\"], [\"COL\", \"Colombia\", \"country\"], [\"COM\", \"Comoros\", \"country\"], [\"COG\", \"Congo, Rep.\", \"country\"], [\"COK\", \"Cook Islands\", \"country\"], [\"CRI\", \"Costa Rica\", \"country\"], [\"CIV\", \"Cote d'Ivoire\", \"country\"], [\"HRV\", \"Croatia\", \"country\"], [\"CUB\", \"Cuba\", \"country\"], [\"CUW\", \"Curacao\", \"country\"], [\"CYP\", \"Greek Cypriot Administration of Southern Cyprus (GCA)\", \"country\"], [\"CZE\", \"Czechia\", \"country\"], [\"COD\", \"Democratic Republic of Congo\", \"country\"], [\"DNK\", \"Denmark\", \"country\"], [\"DJI\", \"Djibouti\", \"country\"], [\"DMA\", \"Dominica\", \"country\"], [\"DOM\", \"Dominican Republic\", \"country\"], [\"WLD\", \"World (Global)\", \"aggregate\"], [\"ECU\", \"Ecuador\", \"country\"], [\"EGY\", \"Egypt\", \"country\"], [\"SLV\", \"El Salvador\", \"country\"], [\"GNQ\", \"Equatorial Guinea\", \"country\"], [\"ERI\", \"Eritrea\", \"country\"], [\"EST\", \"Estonia\", \"country\"], [\"SWZ\", \"Eswatini\", \"country\"], [\"ETH\", \"Ethiopia\", \"country\"], [\"FLK\", \"Falkland Islands (Malvinas)\", \"country\"], [\"FRO\", \"Faroe Islands\", \"country\"], [\"FJI\", \"Fiji\", \"country\"], [\"FIN\", \"Finland\", \"country\"], [\"FRA\", \"France\", \"country\"], [\"PYF\", \"French Polynesia\", \"country\"], [\"ATF\", \"French Southern Territories\", \"country\"], [\"GAB\", \"Gabon\", \"country\"], [\"GMB\", \"Gambia, The\", \"country\"], [\"GEO\", \"Georgia\", \"country\"], [\"GHA\", \"Ghana\", \"country\"], [\"GIB\", \"Gibraltar\", \"country\"], [\"GRL\", \"Greenland\", \"country\"], [\"GRD\", \"Grenada\", \"country\"], [\"GUM\", \"Guam\", \"country\"], [\"GTM\", \"Guatemala\", \"country\"], [\"GIN\", \"Guinea\", \"country\"], [\"GNB\", \"Guinea-Bissau\", \"country\"], [\"GUY\", \"Guyana\", \"country\"], [\"HTI\", \"Haiti\", \"country\"], [\"HND\", \"Honduras\", \"country\"], [\"HKG\", \"Hong Kong SAR, China\", \"country\"], [\"HUN\", \"Hungary\", \"country\"], [\"ISL\", \"Iceland\", \"country\"], [\"IND\", \"India\", \"country\"], [\"IDN\", \"Indonesia\", \"country\"], [\"IRN\", \"Iran, Islamic Rep.\", \"country\"], [\"IRQ\", \"Iraq\", \"country\"], [\"IRL\", \"Ireland\", \"country\"], [\"IMN\", \"Isle of Man\", \"country\"], [\"ESP\", \"Spain\", \"country\"], [\"ISR\", \"Israel\", \"country\"], [\"ITA\", \"Italy\", \"country\"], [\"JAM\", \"Jamaica\", \"country\"], [\"JPN\", \"Japan\", \"country\"], [\"JOR\", \"Jordan\", \"country\"], [\"KAZ\", \"Kazakhstan\", \"country\"], [\"KEN\", \"Kenya\", \"country\"], [\"KIR\", \"Kiribati\", \"country\"], [\"KOR\", \"Korea Rep\", \"country\"], [\"PRK\", \"Korea, Dem. People's Rep.\", \"country\"], [\"KWT\", \"Kuwait\", \"country\"], [\"LAO\", \"Laos\", \"country\"], [\"LVA\", \"Latvia\", \"country\"], [\"LBN\", \"Lebanon\", \"country\"], [\"LSO\", \"Lesotho\", \"country\"], [\"LBR\", \"Liberia\", \"country\"], [\"LBY\", \"Libya\", \"country\"], [\"LTU\", \"Lithuania\", \"country\"], [\"LUX\", \"Luxembourg\", \"country\"], [\"MAC\", \"Macao SAR, China\", \"country\"], [\"MDG\", \"Madagascar\", \"country\"], [\"MYS\", \"Malaysia\", \"country\"], [\"MDV\", \"Maldives\", \"country\"], [\"MLT\", \"Malta\", \"country\"], [\"MHL\", \"Marshall Islands\", \"country\"], [\"MRT\", \"Mauritania\", \"country\"], [\"MUS\", \"Mauritius\", \"country\"], [\"MEX\", \"Mexico\", \"country\"], [\"FSM\", \"Micronesia, Fed. Sts.\", \"country\"], [\"MDA\", \"Moldova\", \"country\"], [\"MCO\", \"Monaco\", \"country\"], [\"MNG\", \"Mongolia\", \"country\"], [\"MNE\", \"Montenegro\", \"country\"], [\"MAR\", \"Morocco\", \"country\"], [\"MOZ\", \"Mozambique\", \"country\"], [\"MMR\", \"Myanmar\", \"country\"], [\"NAM\", \"Namibia\", \"country\"], [\"NRU\", \"Nauru\", \"country\"], [\"NLD\", \"Netherlands\", \"country\"], [\"NCL\", \"New Caledonia\", \"country\"], [\"NZL\", \"New Zealand\", \"country\"], [\"NIC\", \"Nicaragua\", \"country\"], [\"NER\", \"Niger\", \"country\"], [\"NGA\", \"Nigeria\", \"country\"], [\"NIU\", \"Niue\", \"country\"], [\"MKD\", \"North Macedonia\", \"country\"], [\"MNP\", \"Northern Mariana Islands\", \"country\"], [\"NOR\", \"Norway\", \"country\"], [\"OMN\", \"Oman\", \"country\"], [\"PAK\", \"Pakistan\", \"country\"], [\"PLW\", \"Palau\", \"country\"], [\"PAN\", \"Panama\", \"country\"], [\"PNG\", \"Papua New Guinea\", \"country\"], [\"PRY\", \"Paraguay\", \"country\"], [\"PER\", \"Peru\", \"country\"], [\"PHL\", \"Philippines\", \"country\"], [\"POL\", \"Poland\", \"country\"], [\"PRT\", \"Portugal\", \"country\"], [\"PRI\", \"Puerto Rico\", \"country\"], [\"QAT\", \"Qatar\", \"country\"], [\"REU\", \"R\u00e9union\", \"country\"], [\"ROU\", \"Romania\", \"country\"], [\"RUS\", \"Russian Federation\", \"country\"], [\"WSM\", \"Samoa\", \"country\"], [\"SMR\", \"San Marino\", \"country\"], [\"STP\", \"Sao Tome and Principe\", \"country\"], [\"SAU\", \"Saudi Arabia\", \"country\"], [\"SEN\", \"Senegal\", \"country\"], [\"SYC\", \"Seychelles\", \"country\"], [\"SLE\", \"Sierra Leone\", \"country\"], [\"SGP\", \"Singapore\", \"country\"], [\"SVK\", \"Slovakia\", \"country\"], [\"SVN\", \"Slovenia\", \"country\"], [\"SLB\", \"Solomon Islands\", \"country\"], [\"SOM\", \"Somalia\", \"country\"], [\"ZAF\", \"South Africa\", \"country\"], [\"SSD\", \"South Sudan\", \"country\"], [\"LKA\", \"Sri Lanka\", \"country\"], [\"KNA\", \"St. Kitts and Nevis\", \"country\"], [\"VCT\", \"St. Vincent and the Grenadines\", \"country\"], [\"SDN\", \"Sudan\", \"country\"], [\"SUR\", \"Suriname\", \"country\"], [\"SWE\", \"Sweden\", \"country\"], [\"CHE\", \"Switzerland\", \"country\"], [\"SYR\", \"Syrian Arab Republic\", \"country\"], [\"TZA\", \"Tanzania\", \"country\"], [\"THA\", \"Thailand\", \"country\"], [\"TLS\", \"Timor-Leste\", \"country\"], [\"TGO\", \"Togo\", \"country\"], [\"TON\", \"Tonga\", \"country\"], [\"TTO\", \"Trinidad and Tobago\", \"country\"], [\"TUN\", \"Tunisia\", \"country\"], [\"TKM\", \"Turkmenistan\", \"country\"], [\"TCA\", \"Turks and Caicos Islands\", \"country\"], [\"TUV\", \"Tuvalu\", \"country\"], [\"UGA\", \"Uganda\", \"country\"], [\"GBR\", \"UK\", \"country\"], [\"UKR\", \"Ukraine\", \"country\"], [\"ARE\", \"United Arab Emirates\", \"country\"], [\"VIR\", \"United States Virgin Islands\", \"country\"], [\"URY\", \"Uruguay\", \"country\"], [\"USA\", \"USA\", \"country\"], [\"VUT\", \"Vanuatu\", \"country\"], [\"VEN\", \"Venezuela, RB\", \"country\"], [\"VNM\", \"Vietnam\", \"country\"], [\"WLF\", \"Wallis and Futuna Islands\", \"country\"], [\"YEM\", \"Yemen\", \"country\"], [\"GRC\", \"Greece\", \"country\"], [\"ZMB\", \"Zambia\", \"country\"]]}")
CAP = {"OECD_MARITIME_CO2_RESIDENCE_M": "2026-06"}   # last period used in the paper (later months, if published, are excluded)

def fetch(indicator, entity, retries=6):
    for k in range(retries):
        try:
            rows = client.get_series(indicator=indicator, entity=entity, limit=50000, as_df=False)
            return [(str(r["period"]), float(r["value"])) for r in rows if str(r.get("entity_code") or "") == entity and r.get("value") is not None]
        except Exception as e:
            if k == retries - 1: raise
            time.sleep(2 ** k)

def fetch_panel(indicator, out_csv):
    ents = ENTITIES[indicator]
    with ThreadPoolExecutor(max_workers=4) as ex:
        res = list(ex.map(lambda e: fetch(indicator, e[0]), ents))
    recs = [(c, n, t, p, v) for (c, n, t), rows in zip(ents, res) for p, v in rows]
    df = pd.DataFrame(recs, columns=["entity", "name", "etype", "period", "value"]).drop_duplicates(["entity", "period"])
    if indicator in CAP: df = df[df.period <= CAP[indicator]]
    df.to_csv(out_csv, index=False)
    return df

if VERI_KAYNAGI == "api":
    for ind, f in JOBS:
        t = time.time(); df = fetch_panel(ind, f"data/{f}.csv")
        print(f"{f:28s} {len(df):7d} rows  {df.entity.nunique():4d} entities  {df.period.min()}-{df.period.max()}  ({time.time() - t:.0f} s)")

# ## 2. 140 ekonominin tam aylık paneli

# Build the hierarchy World > Region > Economy from the OECD residence-principle maritime CO2 panel.
import pandas as pd, numpy as np, pycountry, pycountry_convert as pcc
df = pd.read_csv("data/oecd_maritime_co2_monthly.csv", dtype={"period": str})
piv = df.pivot(index="period", columns="entity", values="value").sort_index()
econ = [c for c in piv.columns if c not in ("WLD", "W_O", "OECD")]
full = [c for c in econ if piv[c].notna().all()]
MAN = {"TWN": "AS", "HKG": "AS", "MAC": "AS", "XKX": "EU", "GGY": "EU", "JEY": "EU", "IMN": "EU", "FLK": "SA", "ANT": "NA", "TLS": "AS", "SXM": "NA", "CUW": "NA", "BES": "NA", "VAT": "EU"}
REG = {"AF": "Africa", "AS": "Asia", "EU": "Europe", "NA": "Americas", "SA": "Americas", "OC": "Oceania"}
def region(iso3):
    if iso3 in MAN: return REG[MAN[iso3]]
    try:
        a2 = pycountry.countries.get(alpha_3=iso3).alpha_2
        return REG[pcc.country_alpha2_to_continent_code(a2)]
    except Exception:
        return None
reg = {c: region(c) for c in full}
miss = [c for c, r in reg.items() if r is None]
print("unmapped:", miss)
rows = []
for c in full:
    for p, v in piv[c].items():
        rows.append(("World", reg[c], c, p, v))
rest = piv["WLD"] - piv[full].sum(axis=1)
for p, v in rest.items():
    rows.append(("World", "Rest", "REST", p, v))
bot = pd.DataFrame(rows, columns=["World", "Region", "Economy", "period", "y"])
bot["ds"] = pd.to_datetime(bot.period + "-01")
bot.to_csv("data/bottom.csv", index=False)
print("economies with full 90 months:", len(full), "| rest share of world:", round((rest / piv.WLD).mean(), 4), "min rest", rest.min())
print(bot.groupby("Region").Economy.nunique())
names = df[["entity", "name"]].drop_duplicates().set_index("entity").name
names.to_csv("data/names.csv")

# ## 3. Kriz öncesi karşı-olgusal tahminler, plasebo başlangıçlar ve heterojenlik

# Paper 4: emissions effect of the Red Sea shipping crisis by economy of the ship operator. Counterfactual (pre-crisis) forecasts with placebo-in-time inference and cross-economy heterogeneity regressions.
import os, json, warnings
import numpy as np, pandas as pd
warnings.filterwarnings("ignore")
os.environ["NIXTLA_ID_AS_COL"] = "1"
from statsforecast import StatsForecast
from statsforecast.models import AutoETS, AutoARIMA, AutoTheta
import statsmodels.api as sm
from scipy import stats
import matplotlib
import matplotlib.pyplot as plt
plt.rcParams.update({"font.family": "DejaVu Serif", "font.size": 9, "axes.titlesize": 10, "legend.fontsize": 8,
                     "savefig.dpi": 300, "axes.spines.top": False, "axes.spines.right": False})
R = {}
EVENT = pd.Timestamp("2023-12-01")        # first month after the origin (diversions from mid-December 2023)
T0 = pd.Timestamp("2023-11-01")
bot = pd.read_csv("data/bottom.csv", parse_dates=["ds"])
bot = bot[bot.Region != "Rest"].copy()
reg = bot.drop_duplicates("Economy").set_index("Economy").Region
eco = bot.rename(columns={"Economy": "unique_id"})[["unique_id", "ds", "y"]]
agg = pd.concat([bot.groupby("ds").y.sum().reset_index().assign(unique_id="WORLD"),
                 bot.groupby(["Region", "ds"]).y.sum().reset_index().rename(columns={"Region": "unique_id"})])
ALL = pd.concat([eco, agg[["unique_id", "ds", "y"]]]).sort_values(["unique_id", "ds"]).reset_index(drop=True)
ALL["y"] = np.log(ALL.y)
pre = ALL[ALL.ds <= T0]
MODELS = [AutoETS(season_length=12), AutoARIMA(season_length=12), AutoTheta(season_length=12)]

# ---- placebo-in-time: 13 origins (Nov 2021 ... Nov 2022), 12-month horizon, all ending before the crisis ----
sf = StatsForecast(models=MODELS, freq="MS", n_jobs=-1)
cv = sf.cross_validation(df=pre, h=12, n_windows=13, step_size=1)
cv["Comb"] = cv[["AutoETS", "AutoARIMA", "AutoTheta"]].mean(axis=1)
cv.to_csv("out/placebo_cv.csv", index=False)

# ---- real counterfactual from the Nov 2023 origin, to June 2026 (h = 31) ----
H = int(((ALL.ds.max().year - T0.year) * 12 + ALL.ds.max().month - T0.month))
fc = sf.forecast(df=pre, h=H, level=[80, 95])
fc["Comb"] = fc[["AutoETS", "AutoARIMA", "AutoTheta"]].mean(axis=1)
fc = fc.merge(ALL, on=["unique_id", "ds"], how="left"); fc.to_csv("out/counterfactual.csv", index=False)
R["H"] = H

def excess(df, model, months=12):
    """log of (sum of actual / sum of counterfactual) over the first `months` forecast months, per series (and per cutoff if present)."""
    d = df.copy(); keys = ["unique_id"] + (["cutoff"] if "cutoff" in d else [])
    d["h"] = d.groupby(keys).ds.rank().astype(int); d = d[d.h <= months]
    g = d.assign(a=np.exp(d.y), f=np.exp(d[model])).groupby(keys)[["a", "f"]].sum()
    return np.log(g.a / g.f)
out = {}
for model in ("AutoETS", "Comb"):
    real = excess(fc, model)                                  # by series
    plac = excess(cv, model).unstack("cutoff")                # series x 13 cutoffs
    D = pd.DataFrame({"real": real, "plac_mean": plac.mean(axis=1), "plac_sd": plac.std(axis=1)})
    D["did"] = D.real - D.plac_mean; D["z"] = D.did / D.plac_sd
    D.to_csv(f"out/excess_{model}.csv")
    E = D.loc[[u for u in D.index if u in reg.index]]
    w = stats.wilcoxon(E.real, E.plac_mean)
    out[model] = {"world_real": round(float(D.loc["WORLD", "real"]), 4), "world_plac_mean": round(float(D.loc["WORLD", "plac_mean"]), 4),
                  "world_plac_min": round(float(plac.loc["WORLD"].min()), 4), "world_plac_max": round(float(plac.loc["WORLD"].max()), 4),
                  "world_did": round(float(D.loc["WORLD", "did"]), 4), "world_z": round(float(D.loc["WORLD", "z"]), 2),
                  "regions": {r: {"real": round(float(D.loc[r, "real"]), 4), "did": round(float(D.loc[r, "did"]), 4), "z": round(float(D.loc[r, "z"]), 2)} for r in ["Africa", "Americas", "Asia", "Europe", "Oceania"]},
                  "eco_median_real": round(float(E.real.median()), 4), "eco_median_plac": round(float(E.plac_mean.median()), 4), "eco_median_did": round(float(E.did.median()), 4),
                  "eco_share_did_pos": round(float((E.did > 0).mean()), 3), "eco_share_z_gt_196": round(float((E.z > 1.96).mean()), 3), "eco_share_z_lt_m196": round(float((E.z < -1.96).mean()), 3),
                  "wilcoxon_real_vs_placebo_p": float(w.pvalue), "n": int(len(E))}
    # placebo-in-time accuracy: distribution of world 12-month log errors at the 13 placebo origins
R["excess"] = out

# ---- world excess in Mt (ETS and Comb), first and second year, and the path to June 2026 ----
W = fc[fc.unique_id == "WORLD"].sort_values("ds").copy()
W["act"] = np.exp(W.y) / 1e6
for mdl in ("AutoETS", "Comb"):
    W[f"cf_{mdl}"] = np.exp(W[mdl]) / 1e6
yrs = {"Dec23-Nov24": (pd.Timestamp("2023-12-01"), pd.Timestamp("2024-11-01")), "Dec24-Nov25": (pd.Timestamp("2024-12-01"), pd.Timestamp("2025-11-01")),
       "Dec25-Jun26": (pd.Timestamp("2025-12-01"), pd.Timestamp("2026-06-01"))}
R["world_Mt"] = {k: {"actual": round(float(W[(W.ds >= a) & (W.ds <= b)].act.sum()), 1), "cf_ets": round(float(W[(W.ds >= a) & (W.ds <= b)].cf_AutoETS.sum()), 1),
                     "cf_comb": round(float(W[(W.ds >= a) & (W.ds <= b)].cf_Comb.sum()), 1)} for k, (a, b) in yrs.items()}
for k in R["world_Mt"]:
    v = R["world_Mt"][k]; v["excess_ets"] = round(v["actual"] - v["cf_ets"], 1); v["excess_comb"] = round(v["actual"] - v["cf_comb"], 1)
    v["excess_ets_pct"] = round(100 * (v["actual"] / v["cf_ets"] - 1), 2); v["excess_comb_pct"] = round(100 * (v["actual"] / v["cf_comb"] - 1), 2)
W["above95"] = np.exp(W.y) > np.exp(W["AutoETS-hi-95"]); W["below95"] = np.exp(W.y) < np.exp(W["AutoETS-lo-95"])
R["world_months_above95"] = {k: int(W[(W.ds >= a) & (W.ds <= b)].above95.sum()) for k, (a, b) in yrs.items()}
R["world_months_n"] = {k: int(((W.ds >= a) & (W.ds <= b)).sum()) for k, (a, b) in yrs.items()}
# placebo world 12-month errors (ETS) in per cent
pw = excess(cv, "AutoETS").unstack("cutoff").loc["WORLD"]
R["world_placebo_pct"] = {str(k.date()): round(float(100 * (np.exp(v) - 1)), 2) for k, v in pw.items()}

# ---- heterogeneity: DiD excess (ETS) on economy characteristics ----
def ann(f):
    d = pd.read_csv(f"data/{f}.csv", dtype={"period": str}); d = d[d.etype == "country"]; d["yr"] = d.period.str[:4].astype(int)
    return d.pivot_table(index="yr", columns="entity", values="value", aggfunc="mean")
dwt = ann("owned_dwt"); cont = ann("flag_dwt_container"); flag = ann("flag_dwt"); age = ann("fleet_age")
D = pd.read_csv("out/excess_AutoETS.csv", index_col=0); D = D.loc[[u for u in D.index if u in reg.index]]
base = bot[(bot.ds >= "2022-12-01") & (bot.ds <= T0)].groupby("Economy").y.sum() / 1e6
X = pd.DataFrame(index=D.index)
X["did_pct"] = 100 * D.did
X["region"] = reg[X.index]
X["log_co2_pre"] = np.log(base[X.index])
X["dlog_dwt"] = [100 * np.log(dwt.loc[2025, e] / dwt.loc[2024, e]) if (e in dwt.columns and dwt.loc[2024, e] > 0 and dwt.loc[2025, e] > 0) else np.nan for e in X.index]
X["container_share"] = [100 * cont.loc[2023, e] / flag.loc[2023, e] if (e in cont.columns and e in flag.columns and flag.loc[2023, e] > 0) else np.nan for e in X.index]
X["fleet_age"] = [age.loc[2023, e] if e in age.columns else np.nan for e in X.index]
X.to_csv("out/heterogeneity_data.csv")
Xd = X.dropna().copy()
Xd["dlog_dwt"] = Xd.dlog_dwt.clip(-50, 50)
dm = pd.get_dummies(Xd.region, drop_first=False).astype(float)[["Asia", "Europe", "Africa", "Oceania"]]   # Americas = reference
reg_vars = ["log_co2_pre", "dlog_dwt", "container_share", "fleet_age"]
Xm = sm.add_constant(pd.concat([dm, Xd[reg_vars]], axis=1))
ols = sm.OLS(Xd.did_pct, Xm).fit(cov_type="HC1")
wls = sm.WLS(Xd.did_pct, Xm, weights=np.exp(Xd.log_co2_pre)).fit(cov_type="HC1")
def tab(m): return {k: {"b": round(float(m.params[k]), 3), "se": round(float(m.bse[k]), 3), "p": float(m.pvalues[k])} for k in m.params.index} | {"_n": int(m.nobs), "_r2": round(float(m.rsquared), 3)}
R["het_ols"] = tab(ols); R["het_wls"] = tab(wls)
R["did_by_region"] = {r: {"median": round(float(g.did_pct.median()), 2), "mean": round(float(g.did_pct.mean()), 2), "n": int(len(g))} for r, g in X.groupby("region")}
R["het_n"] = int(len(Xd))
F = ["TUR", "GRC", "CHN", "JPN", "SGP", "DNK", "NOR", "DEU", "CHE", "USA", "KOR", "HKG", "GBR", "ITA", "FRA", "IND"]
R["focus"] = {e: {"did_pct": round(float(X.did_pct[e]), 2), "z": round(float(D.z[e]), 2), "region": reg[e]} for e in F if e in X.index}
R["top_did"] = X.did_pct.sort_values(ascending=False).round(1).head(10).to_dict()
R["bottom_did"] = X.did_pct.sort_values().round(1).head(10).to_dict()
# emissions-weighted contribution of regions to the world excess, Dec23-Nov24 (ETS, sum of economy excess)
e12 = fc[fc.unique_id.isin(reg.index) & (fc.ds >= EVENT) & (fc.ds <= pd.Timestamp("2024-11-01"))].copy()
e12["ex"] = (np.exp(e12.y) - np.exp(e12.AutoETS)) / 1e6; e12["region"] = reg[e12.unique_id].values
R["region_excess_Mt"] = e12.groupby("region").ex.sum().round(1).to_dict()
R["region_excess_Mt_total"] = round(float(e12.ex.sum()), 1)
json.dump(R, open("out/results_redsea.json", "w"), indent=1, default=str)

# ================= FIGURES =================
hist = ALL[(ALL.unique_id == "WORLD")].copy(); hist["v"] = np.exp(hist.y) / 1e6
fig, ax = plt.subplots(figsize=(7.2, 3.6))
ax.plot(hist.ds, hist.v, color="k", lw=1.1, label="Actual")
ax.plot(W.ds, W.cf_AutoETS, color="#1f77b4", lw=1.2, label="Counterfactual (ETS, data to Nov 2023)")
ax.fill_between(W.ds, np.exp(W["AutoETS-lo-95"]) / 1e6, np.exp(W["AutoETS-hi-95"]) / 1e6, color="#1f77b4", alpha=0.15, lw=0, label="95% interval")
ax.fill_between(W.ds, np.exp(W["AutoETS-lo-80"]) / 1e6, np.exp(W["AutoETS-hi-80"]) / 1e6, color="#1f77b4", alpha=0.2, lw=0)
ax.axvline(EVENT, color="#d62728", ls="--", lw=0.9); ax.text(EVENT, ax.get_ylim()[1] * 0.995, " Red Sea diversions", color="#d62728", fontsize=7, va="top")
ax.set_ylabel("Mt CO$_2$ per month"); ax.legend(frameon=False, loc="lower right", fontsize=7)
fig.tight_layout(); fig.savefig("fig/fig1_world.png"); plt.show()
Dd = pd.read_csv("out/excess_AutoETS.csv", index_col=0)
fig, ax = plt.subplots(figsize=(6.3, 3.4))
Ee = Dd.loc[[u for u in Dd.index if u in reg.index]]
bins = np.linspace(-60, 80, 36)
ax.hist(100 * Ee.plac_mean.clip(-0.6, 0.8), bins=bins, alpha=0.55, color="grey", label="Placebo origins (mean of 13)")
ax.hist(100 * Ee.real.clip(-0.6, 0.8), bins=bins, alpha=0.55, color="#d62728", label="Crisis origin (Nov 2023)")
ax.axvline(100 * Ee.plac_mean.median(), color="grey", ls="--"); ax.axvline(100 * Ee.real.median(), color="#d62728", ls="--")
ax.set_xlabel("12-month excess emissions, 100·log(actual/counterfactual)"); ax.set_ylabel("Economies"); ax.legend(frameon=False)
fig.tight_layout(); fig.savefig("fig/fig2_distribution.png"); plt.show()
fig, ax = plt.subplots(figsize=(6.3, 3.4))
order = ["Asia", "Europe", "Americas", "Africa", "Oceania"]
data = [X[X.region == r].did_pct.clip(-60, 80) for r in order]
ax.boxplot(data, tick_labels=[f"{r}\n(n = {len(d)})" for r, d in zip(order, data)], patch_artist=True, boxprops=dict(facecolor="#fdd0a2"))
ax.axhline(0, color="k", lw=0.7)
if "TUR" in X.index: ax.plot(order.index(reg["TUR"]) + 1, X.did_pct["TUR"], "D", color="#d62728", ms=5, label="Türkiye"); ax.legend(frameon=False)
ax.set_ylabel("Excess over placebo (%)"); fig.tight_layout(); fig.savefig("fig/fig3_regions.png"); plt.show()
fig, ax = plt.subplots(figsize=(6.3, 3.4))
kk = ["Asia", "Europe", "Africa", "Oceania", "log_co2_pre", "dlog_dwt", "container_share", "fleet_age"]
lab = ["Asia (vs Americas)", "Europe (vs Americas)", "Africa (vs Americas)", "Oceania (vs Americas)", "log pre-crisis CO$_2$", "Fleet growth 2024 (%)", "Container share of flag fleet (%)", "Mean fleet age (years)"]
b = [R["het_ols"][k]["b"] for k in kk]; se = [R["het_ols"][k]["se"] for k in kk]
ax.errorbar(b, range(len(kk)), xerr=[1.96 * s for s in se], fmt="o", color="k", capsize=3); ax.axvline(0, color="grey", lw=0.8)
ax.set_yticks(range(len(kk))); ax.set_yticklabels(lab); ax.set_xlabel("Effect on excess emissions (percentage points), 95% CI"); ax.invert_yaxis()
fig.tight_layout(); fig.savefig("fig/fig4_het.png"); plt.show()
print(json.dumps({k: R[k] for k in ["excess", "world_Mt", "world_months_above95", "world_placebo_pct", "did_by_region", "het_ols", "region_excess_Mt", "region_excess_Mt_total", "focus", "top_did", "bottom_did"]}, indent=1, default=str))

# ## 4. En büyük 20 ekonomi (Şekil 4)

# Figure 5 of paper 4: excess emissions for the 20 largest operator economies with placebo-based 95% bands.
import numpy as np, pandas as pd
import matplotlib.pyplot as plt
plt.rcParams.update({"font.family": "DejaVu Serif", "font.size": 9, "savefig.dpi": 300, "axes.spines.top": False, "axes.spines.right": False})
X = pd.read_csv("out/heterogeneity_data.csv", index_col=0); D = pd.read_csv("out/excess_AutoETS.csv", index_col=0)
names = pd.read_csv("data/owned_dwt.csv").drop_duplicates("entity").set_index("entity").name.to_dict() | {"TWN": "Taiwan", "HKG": "Hong Kong, China", "TUR": "Türkiye"}
top = X.assign(co2=np.exp(X.log_co2_pre)).sort_values("co2", ascending=False).head(20).index
d = D.loc[top].assign(did=lambda t: 100 * t.did, band=lambda t: 196 * t.plac_sd).sort_values("did")
fig, ax = plt.subplots(figsize=(6.3, 5.2))
col = ["#d62728" if abs(z) > 1.96 else "#9e9e9e" for z in d.z]
ax.barh(range(len(d)), d.did, color=col); ax.errorbar(d.did, range(len(d)), xerr=d.band, fmt="none", ecolor="k", lw=0.8, capsize=2)
ax.set_yticks(range(len(d))); ax.set_yticklabels([f"{names.get(i, i)} ({np.exp(X.log_co2_pre[i]):.0f} Mt)" for i in d.index], fontsize=7.5)
ax.axvline(0, color="k", lw=0.7); ax.set_xlabel("Excess emissions Dec 2023–Nov 2024 over placebo mean (%)")
fig.tight_layout(); fig.savefig("fig/fig5_top20.png"); plt.show()
print(d[["did", "band", "z"]].round(2).to_string())

# ## Sonuçlar ve çıktılar

# Packs figures and numerical results for download.
import shutil
from google.colab import files
shutil.make_archive("/content/rp04_outputs", "zip", ".", ".")
files.download("/content/rp04_outputs.zip")
