2

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')
HedgeHog
  • 22,146
  • 4
  • 14
  • 36
Marcus N
  • 29
  • 3

2 Answers2

0

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')```
svfat
  • 3,273
  • 1
  • 15
  • 34
  • Hello I tried it, but it did not help. Index_name is still a string. Result :It trys to download the csv for g,d,a,x,i – Marcus N Sep 06 '22 at 15:05
  • @MarcusN are you sure you wrote this line `indizies = [gdaxi, mdaxi]` exactly as is - without quote marks around gdaxi, mdaxi? – svfat Sep 07 '22 at 09:49
  • Hello, if I do it without quote marks, I get n error GDAXI not defined – Marcus N Sep 15 '22 at 06:25
  • @MarcusN are you getting GDAXI not defined, where GDAXI is written in capital letters? Could you copy-paste the full error output? – svfat Sep 16 '22 at 11:45
-1

We can use "locals" method to get the variables as strings. It will look like a dictionary and you can get the results using keys.

indizies = ['GDAXI', 'MDAXI']  
gdaxi = ["ADS.DE", "AIR.DE", "ALV.DE"]
mdaxi = ["AIXA.DE", "AT1.DE"]

Variables = locals()
for index_name in indizies:
    for ticker in Variables[index_name.lower()]:
        print(ticker)

Try this bro. It is case sensitive. So pls check the variable names before using them. Hope it helps! Happy Coding:)

Tiger God
  • 6
  • 2