Reputation: 304
I am trying to query the yahoo finance api via the yfinance library, and have a list of 4000 tickers.
I can query the data that I need individually via:
yf.Ticker('msft').info['sector']
and
yf.Ticker('msft').info['symbol']
But I need to get the symbol and sector in one dataframe.
This is easy enough to do with merging, but there's no shared columns to merge on.
Furthermore, I have 4000 tickers I need to do this for, so I tried.
ticker_test = ['MSFT','AAPL','AMZN']
data_test = []
for ticker in ticker_test:
try:
data_test.append(yf.Ticker(ticker).info['sector'] # also tried to do: ...info['sector','symbol'] but that did not work.
except:
print("An Error has occured")
data_test_df = pd.concat(data_test, axis = 0)
which yielded
TypeError: cannot concatenate object of type '<class 'dict'>'; only Series and DataFrame objs are valid
But the problem is that it's not even grabbing the information from the yfinance API.
The ideal outcome is a dataframe which resembles:
symbol sector
0 MSFT technology
1 AAPL technology
2 AMZN consumer cyclical
Any ideas on how I can achieve this would be greatly appreciated.
Upvotes: 0
Views: 1397
Reputation: 3066
The problem is that you get the result from the API and directly select only one item (sector
in your case). However, the result of the API is a dict with a lot of items. My solution would be to save the result of the API in a variable and then select both of the items you want for each ticker. From the list of these you can then create a dataframe.
Following is the code:
ticker_test = ['MSFT','AAPL','AMZN']
data_test = []
for ticker in ticker_test:
result = yf.Ticker(ticker).info
row_items = [result['symbol'], result['sector']]
data_test.append(row_items)
data_test_df = pd.DataFrame(data_test, columns=['symbol', 'sector'])
Output:
symbol sector
0 MSFT Technology
1 AAPL Technology
2 AMZN Consumer Cyclical
Upvotes: 0