guialmachado
guialmachado

Reputation: 536

Historic Stock Prices in Pandas DataFrame

This code is able to get the history of stock prices and the dates are set as the index of the DataFrame.

How can I pass the dates (index) to a column and add the ticker out of iteration to another column?

import yfinance as yf
import pandas as pd

tickers = ["GOOG","AMZN"]

df2 = pd.DataFrame()

for ticker in tickers:
    try:
        tkr = yf.Ticker(ticker)
        hist = tkr.history(period="1y")
        df2 = df2.append(hist)
        print(df2)

Result:

               Open     High      Low  ...   Volume  Dividends  Stock Splits
Date                                   ...                                  
2019-06-06  1044.99  1047.49  1033.70  ...  1703200          0             0
2019-06-07  1050.63  1070.92  1048.40  ...  1802400          0             0
2019-06-10  1072.98  1092.66  1072.32  ...  1464200          0             0

Objective:

Ticker     Date     Open     High      Low  ...   Volume  Dividends  Stock Splits

GOOG 2019-06-06  1044.99  1047.49  1033.70  ...  1703200          0             0
GOOG 2019-06-07  1050.63  1070.92  1048.40  ...  1802400          0             0
GOOG 2019-06-10  1072.98  1092.66  1072.32  ...  1464200          0             0

Upvotes: 0

Views: 547

Answers (1)

NYC Coder
NYC Coder

Reputation: 7594

You can just do this:

for ticker in tickers:
    tkr = yf.Ticker(ticker)
    hist = tkr.history(period="1y")
    df2 = df2.append(hist)
    df2['Ticker'] = ticker

    print(df2.reset_index())  


        Date     Open     High      Low    Close   Volume  Dividends  Stock Splits Ticker
0 2019-06-06  1044.99  1047.49  1033.70  1044.34  1703200          0             0   GOOG
1 2019-06-07  1050.63  1070.92  1048.40  1066.04  1802400          0             0   GOOG
2 2019-06-10  1072.98  1092.66  1072.32  1080.38  1464200          0             0   GOOG
3 2019-06-11  1093.98  1101.99  1077.60  1078.72  1436700          0             0   GOOG
4 2019-06-12  1078.00  1080.93  1067.54  1077.03  1061000          0             0   GOOG
        Date     Open     High      Low    Close   Volume  Dividends  Stock Splits Ticker
0 2019-06-06  1044.99  1047.49  1033.70  1044.34  1703200          0             0   AMZN
1 2019-06-07  1050.63  1070.92  1048.40  1066.04  1802400          0             0   AMZN
2 2019-06-10  1072.98  1092.66  1072.32  1080.38  1464200          0             0   AMZN
3 2019-06-11  1093.98  1101.99  1077.60  1078.72  1436700          0             0   AMZN
4 2019-06-12  1078.00  1080.93  1067.54  1077.03  1061000          0             0   AMZN

Upvotes: 1

Related Questions