pythondataframestockyfinance

Create row for each data in list - python


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


Solution

  • 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