简体   繁体   中英

How to convert a string to a variable / list name?

I have a list of stock indexes (indizies) and several lists of stock tickers (eg gdaxi, mdaxi).

I want to download the stocks from yahoo in two loops.

Background: In the real program the user can choose which index, indexes he wants to download.

The problem is, that the type of index_name is a string and for the second loop index_name has to be a list. But the second loop takes index_name as a string.

Result:It trys to download the csv for g,d,a,x,i

Question: How can I transform index_name from string to list?

from pandas_datareader import data as pdr   
indizies = ['GDAXI', 'MDAXI']  
gdaxi = ["ADS.DE", "AIR.DE", "ALV.DE"]
mdaxi = ["AIXA.DE", "AT1.DE"]
    
    for index_name in indizies:
    
            for ticker in index_name:
                df = pdr.get_data_yahoo(ticker)
                df.to_csv(f'{ticker}.csv')

In ticker in index_name you are iterating over the letters in given strings.

I guess you to change your code to something like:

from pandas_datareader import data as pdr   
  
gdaxi = ["ADS.DE", "AIR.DE", "ALV.DE"]
mdaxi = ["AIXA.DE", "AT1.DE"]
indizies = [gdaxi, mdaxi]   

for index_name in indizies:
    for ticker in index_name:
        df = pdr.get_data_yahoo(ticker)
        df.to_csv(f'{ticker}.csv')```

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM