How do you export a data set to excel using python? Keep getting the following error "str object has no attribute 'to_excel'"

I am trying to write a code that will utilize an api to get data from yahoo finance and then export that data to an excel spreadsheet. The code worked fine before I added the last line that's supposed to export to excel. I keep getting the following error message "str object has no attribute 'to_excel'".

import yfinance as yf
from pandas import DataFrame

#opens txt document that has stock ticker symbols
fileref = open("a.txt","r")
listOfLines = fileref.readlines()  
listOfLines = map(lambda line: line.strip(), listOfLines) 

ticker_symbols = listOfLines

#loop over each element and store it in the variable ticker
for ticker in ticker_symbols:
  ticker_query = yf.Ticker(ticker)
  price_to_book = ticker_query.get_info()["priceToBook"]
  industry = ticker_query.get_info()["industry"]
  dividend = ticker_query.get_info()["dividendYield"]
  trailingPe = ticker_query.get_info()["trailingPE"]
  dataset = (ticker + "  : " + str(price_to_book) + " " + str(industry) + " " + str(dividend) + " " + str(trailingPe))

Can anyone offer any help?


1 answer

  • answered 2020-01-14 08:11 Fab Dot

    You're not using the pandas module in the above.

    In order to export to excel you need to create a DataFrame to which you can call the export method. You also need to provide the rows in a dict format, as opposed to the current string i.e. dataset

    Create a list of dictionaries to add, looping through the Yahoo! finance date. Then use this list to create your DataFrame. See this SO answer which details exactly how to do this.

    You should then be able to use the to_excel() or to_csv functions to output the Dataframe: