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

Viewed 67

I have a list of stock indexes (indizies) and several lists of stock tickers (e.g. 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')
1 Answers

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')```
Related