3

I'm trying to create a code to show me some stock stats. For that I need to iterate through a list of stocks in python and for each one show some details.

So far I have this code:

import yfinance as yf
import pandas as pd

tickerlist = ['AAPL', 'MSFT', 'AMZN']

stock_data = []
for stock in tickerlist:
    info = yf.Ticker(stock).info
    stock_data.append(info.get("symbol"))
    stock_data.append(info.get("bookValue")))

df = pd.DataFrame(stock_data)
df

But it shows only one column with all data instead of one line per stock, with data headers. image_of_output_data

I tweaked the code a little bit and I got one row per item but it repeats the last item only, instead of add each entry to row with its values.

import yfinance as yf
import pandas as pd

tickerlist = ['AAPL', 'MSFT', 'AMZN']

for stock in tickerlist:
    info = yf.Ticker(stock).info
    df = pd.DataFrame({
    'symbol': info.get("symbol"),
    'bookValue': info.get("bookValue")}, index=('0', '1', '2'))

df

image_of_output_data2

1 Answer 1

3

Instead of adding each piece of info you need as a separate element to stock_data, you should have a list of iterables, where each element of the list contains all of the relevant data for that stock. Note that you can also explicitly provide the column names to get a "nicer" output:

mport yfinance as yf
import pandas as pd

tickerlist = ['AAPL', 'MSFT', 'AMZN']

stock_data = []
for stock in tickerlist:
    info = yf.Ticker(stock).info
    stock_data.append((info.get("symbol"), info.get("bookValue")))

df = pd.DataFrame(stock_data, columns=("symbol", "bookValue"))
print(df)

Output:

  symbol  bookValue
0   AAPL      3.767
1   MSFT     38.693
2   AMZN     24.655
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much, that was huge! One last question, if I need to divide every bookValue by 10, I would just need to change to this code: info.get("bookValue")*100 ?
@diguinhosl I'm not sure where the *100 came from (it doesn't appear in the original question), but yes - you can perform calculations on the values retrieved from info before you add them to stock_data.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.