Search code examples
pythonpandasdataframeyfinance

adding a column to my dataframe with yFinance


beginner question coming up and cant seem to connect the dots.

I have a portfolio data frame called my_pf which includes the tickers that I use for collecting the opening price. I success in collecting the opening data via the next two steps.

#create a list from the column 'ticker'
my_tickers = my_pf['ticker'].tolist()

#collect the opening data per ticker
for ticker in my_tickers:
    open_price = yf.Ticker(ticker).info.get('open')
    
    print(ticker, open_price)

The next step is adding the extracted data to my initial data frame. But how would i go about this?

Thank you for your help in advance.


Solution

  • There are many ways to add data to a column, such as df.append() and pd.concat(), but we created our code with df.append(). We start with an empty data frame to create the stock column and the opening price column. Once we have the opening price, we add the brand name and opening price to the data frame we just created.

    import pandas as pd
    import yfinance as yf
    
    # my_tickers = my_pf['ticker'].tolist()
    my_tickers = ['msft', 'aapl', 'goog']
    tickers = yf.Tickers(my_tickers)
    
    df = pd.DataFrame(index=[], columns=['ticker','Open'])
    for ticker in my_tickers:
        open_price = yf.Ticker(ticker).info.get('open')
        df = df.append(pd.Series([ticker,open_price], index=df.columns), ignore_index=True)
        
    print(df)
    
    ticker  Open
    0   msft    204.07
    1   aapl    112.37
    2   goog    1522.36