Iterating through a list of countries to pull data from Datastream

69 views Asked by At

I am pulling data from Datastream for a project. I have a list of 40 countries for which I want their bond issuance information.

The query is as follows:

All1 = rd.discovery.search(
    view = rd.discovery.Views.GOV_CORP_INSTRUMENTS,
    top = 2000,
    filter = "((DbType eq 'GOVT') and ((RCSCurrencyLeaf eq 'US Dollar') or (RCSCurrencyLeaf eq 'Euro')) and\
 (\
 (\
 (DTSubjectName eq 'Angola')\
 and MaturityDate gt 2000-01-01)))",
    select = "DTSubjectName,RCSCountryLeaf,IssueDate,MaturityDate,RCSCurrencyLeaf,CouponRate,FaceIssuedUSD"
)

Final1 = All1.sort_values(by=['DTSubjectName', 'IssueDate'])
Final1

I would like to get the data for all 40 countries in my list at once, but I am not sure how to do so without brute force typing in every country as I did for Angola. While such a solution works in the short-term, it is very inflexible if I would like to add or take away countries from the query.

I am imagining that the best way to do this without just manually inputting every country would be to use a for loop with an f-string.

I tried putting all country names in manually, i.e., but this is inflexible.

All1 = rd.discovery.search(
    view = rd.discovery.Views.GOV_CORP_INSTRUMENTS,
    top = 2000,
    filter = "((DbType eq 'GOVT') and ((RCSCurrencyLeaf eq 'US Dollar') or (RCSCurrencyLeaf eq 'Euro')) and\
 (\
 (\
 (DTSubjectName eq 'Angola') or\
 (DTSubjectName eq 'Benin') or\
 (DTSubjectName eq 'Botswana')\
and MaturityDate gt 2000-01-01)))",
    select = "DTSubjectName,RCSCountryLeaf,IssueDate,MaturityDate,RCSCurrencyLeaf,CouponRate,FaceIssuedUSD"
)

Final1 = All1.sort_values(by=['DTSubjectName', 'IssueDate'])
Final1
1

There are 1 answers

1
Rawson On BEST ANSWER

You could split your filter into a couple of strings. Then using a join for creating the required country filter lines and concatenate together:

filter_start =  """((DbType eq 'GOVT') and ((RCSCurrencyLeaf eq 'US Dollar') 
or (RCSCurrencyLeaf eq 'Euro')) and\
 (\
 (\
"""

countries = ["Angola", "Argentina", "Botswana", "Chile", "Colombia"]
country_filter_str = " or ".join(
    [f"(DTSubjectName eq '{country}')" for country in countries]
)

filter_end = """\
and MaturityDate gt 2000-01-01)))"""

filter_string = filter_start + coutnry_filter_str + filter_end

This loops through the countries and creates the text string, then joins all of these together with the " or " string. Then you just set filter=filter_string.