China export to country i, loop by year

python:
import json
import numpy        as  np
import pandas       as  pd
import requests

def Comtrade_Scraper   (ps: int,
                       type: str=   'C',
                       freq: str=   'A',
                       px  : str=  'S2',
                       p   : str= 'all',
                       r   : int=     156,
                       rg  : int=     2,
                       cc  : str= 'AG2'):
    """
    Wrapper for creating URLs to access the Comtrade API

    ARGUMENTS
    *********
    Required
	ps   = year
    """
    base      = 'https://comtrade.un.org/api/get?max=10000'
    url       = f'{base}&type={type}&freq={freq}&px={px}&ps={ps}&r={r}&p={p}&rg={rg}&cc={cc}'

    result    = requests.get(url).json()
    if 'dataset' in result: 
        df        = pd.DataFrame(result['dataset'])
        df        = df.replace({None: np.nan})
        df.columns= [i[:32] for i in df.columns]

        df.to_stata(f'CHN_X_i_{ps}.dta')
        return df

for i in range(2000,2022): Comtrade_Scraper(i)
end

di "`c(pwd)'" // Display path to current folder
local files : dir "`c(pwd)'" files "*.dta" 
foreach x of local files {
    di "`x'" // Display file name
	append using `x'
}
save CHN_X_i_2000_2021.dta, replace

Changes made:

  • Flipped: r : str= 'all', p : int= 156 to the opposite