0

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) 
fileref.close()


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))
  dataset.to_excel("x.xlsx")

Can anyone offer any help?

Ross

Ross Leavitt
  • 119
  • 4
  • 13
  • Is there a python library that you're using that will provide an export to excel functionality? I'm not familiar with yfinance, so I'm not sure if that's functionality it proivdes. – Jonhasacat Jan 14 '20 at 02:05
  • @Jonhasacat the "from pandas import dataframe" supports the export to excel functionality. – Ross Leavitt Jan 14 '20 at 03:06
  • in your code the variable dataset is not a dataframe, it's a string – Jonhasacat Jan 14 '20 at 03:08

1 Answers1

0

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:

df.to_excel(path)

Fab Dot
  • 504
  • 1
  • 5
  • 16