Search code examples
statastata-macros

Writing loop to retrieve multiple variables from an external Python database


I am using a Python package that allows me to integrate data retrieved in Python to be transferred to Stata. As I am doing this across 190 countries, it takes a long time to retrieve multiple variables when I call a command.

I was hoping to write a loop that would pull a single variable each time and then append it. However, I get either an invalid syntax or an invalid 'append' error.

Please find below my first attempt.

use "~\data.dta"
local indicator_list BFDA_BP6_USD BFDL_BP6_USD BFP_BP6_USD
foreach indicator in `indicator_list' {
local command ecosuse data, database(ECDATA_BOP) country(ALL) indicator(`indicator') freq(Q) clear
if `first_iteration' == 1 {
local first_iteration 0
}
else {
`command', append
}
}

Solution

  • You have too many commas in the else call. There is already a comma in the command and another comma isn't illegal in itself but turns out to be quite wrong for what I guess you want.

    Alternatively, this would be simpler for the major part of your code.

    ecosuse data, database(ECDATA_BOP) country(ALL) indicator(BFDA_BP6_USD) freq(Q) clear
    
    foreach indicator in BFDL_BP6_USD BFP_BP6_USD { 
        ecosuse data, database(ECDATA_BOP) country(ALL)  indicator(`indicator') freq(Q) clear append 
    }
    

    I've never used ecosuse or read its documentation, so there may be other errors. In any case there is not here a self-contained reproducible example.