简体   繁体   中英

Put yfinance stock data into pandas dataframe Python

I have a Pandas DataFrame that looks like this:

DataFrame:

Ticker Date
AAPL 2022-11-22
MSFT 2022-11-22
META 2022-11-22

And I want to add a column that includes the stock price of each stock at that date like this:

Ticker Date Price
AAPL 2022-11-22 147,47
MSFT 2022-11-22 243,71
META 2022-11-22 108,50

In the ideal situation, I would append each price for the Ticker[i] inside the for loop, so I can easily make an Except: "not available" command for the stocks that are not found.

What I have done so far is creating the following for loop, which let me to get all stock prices. However, I cannot find a way to merge/append/concatenate it to the dataframe. I currently have 2 separate dataframes, without a common column which makes it hard to merge.

for i in DataFrame.index:
    ticker = DataFrame.index['Ticker'][i]
    start_date = DataFrame.index['Date'][i]
    data1 = pd.DataFrame(yf.download(ticker, start_date, start_date))

no loop is needed, not familiar with yf but nevertheless you can use apply:

df['price'] = df.apply(lambda x : yf.download(x.['ticker'], x.['start_date'], x.['start_date']))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM