Add a column and data from yahoo finance to existing dataframe

Hello, I’m a newbie. I have a csv file with the SP500 tickers. I created a data frame with it. I would like to add (for example) the price and the dividend besides each ticker (dowloading those new data from yahoo finance).

so far, I have this:

import yfinance as yf
import pandas as pd
import numpy as np

tickers_df = pd.read_csv(‘symbolssp500.csv’)
tickers_df

Unnamed: 0	Symbol

0 0 MMM
1 1 ABT
2 2 ABBV
3 3 ABMD
4 4 ACN
… … …
500 500 YUM
501 501 ZBRA
502 502 ZBH
503 503 ZION
504 504 ZTS
505 rows × 2 columns

thanks for the help!

Hi,

here is an example of how you can potentially set it up:

import pandas as pd

# Define column titles
col_titles = ['TICKER', 'PRICE', 'DIVIDEND']

# Define data to be displayed
data = [[' AMD',   145.25, 1.25], 
        [' TSLA',  198.23, 2.85],
        [' GOOG',  758.12, 1.74],
        [' INTL',   59.63, 0.89],
        [' MSFT',   36.85, 3.45],
        [' IBM',    74.08, 1.61]]   

# Create panda dataframe
df = pd.DataFrame(data, columns = col_titles)

# Print the dataframe
print('\n', df)

# Bonus - write info to a file:
csv_path = '/Users/your_pc_name_here/Desktop/test_purposes.csv'

with open(csv_path, 'w', encoding = 'UTF-8') as csv_file:
        df.to_csv(csv_file)

What you’ll have to do is read the data from your file and format it according to the data array provided in this example such that there are three columns as per the col_titles list. Once you have it in this format, it should be trivial in displaying it. Because you have many tickers, you will have to implement a for loop iterable to create this array. If as you say you are a newbie, I would read up on iterables and for loop theory and applications. Workout some examples independent of this task so that you get a good grasp before tackling it.

Here is a heads up but you can perform your own search.

Thank you so much for answering back Paul! I will try your solution.

With yfinance, you can do:

import yfinance as yf
import pandas as pd
tickers = yf.Tickers('msft aapl goog')
df = tickers.history().stack(level=1)
print(df)

Thank you very much for your input Doomsdaychiken! I have a steep learning curve.