Search code examples
pythonpandaslistloopsyfinance

Have a for loop return a dataframe when it produces a string


I have a list of tickers I need to retrieve the name for. I am trying to write a loop that returns a dataframe containing the Short_Name and the tic name.

Code below:

a = []
b = ['FFIV', 'FIS', 'FISV', 'FITB', 'FLS', 'FMC']

for i in b: #add 5 rows of data
    stock = yf.Ticker(i)
    a['Short_Name'] = stock.info['shortName']
    a['tic'] = i

Unfortunately when I run this code I get the following error:

TypeError: list indices must be integers or slices, not str

Any help would be fantastic.


Solution

  • Use this:

    a = []
    b = ['FFIV', 'FIS', 'FISV', 'FITB', 'FLS', 'FMC']
    
    for i in b: #add 5 rows of data
        stock = yf.Ticker(i)
        a.append([stock.info['shortName'], i])
    
    df = pd.DataFrame(data=a, columns=['Short_Name', 'tic'])