简体   繁体   中英

Pandas DataReader Throws a Date Error When Getting Stock Quotes From Yahoo Finance

When I was running the DateReader program to get the quotes from Yahoo finance, it gave me an error message "KeyError: 'Date'"

import pandas as pd
import pandas_datareader.data as web
from datetime import datetime

start = datetime(2015, 1, 1)
end = datetime.today()
ticker_dict = {}
for idx, ticker in enumerate(['AAPL', 'TSLA', 'IBM', 'LNKD']):
    df_ticker = web.DataReader(ticker, 'yahoo', start, end) 
    ticker_dict[ticker] = df_ticker['Close']
stocks = DataFrame(ticker_dict) 

However, if I just ran the DataReader line, it worked.

df = web.DataReader(['AAPL', 'TSLA', 'IBM', 'LNKD'], 'yahoo', start, end)

Anyone know what's wrong with the first codes?

The problem is there because it throws an exception for 'LNKD' in the first code. Put a try/except block.

import pandas as pd
import pandas_datareader.data as web
from datetime import datetime

start = datetime(2015, 1, 1)
end = datetime.today()
ticker_dict = {}
for idx, ticker in enumerate(['AAPL', 'TSLA', 'IBM', 'LNKD']):
    try:
        df_ticker = web.DataReader(ticker, 'yahoo', start, end) 
        ticker_dict[ticker] = df_ticker['Close']
    except:pass
stocks = pd.DataFrame(ticker_dict) 

Output:

                  AAPL         TSLA         IBM
Date
2014-12-31  110.379997   222.410004  160.440002
2015-01-02  109.330002   219.309998  162.059998
2015-01-05  106.250000   210.089996  159.509995
2015-01-06  106.260002   211.279999  156.070007
2015-01-07  107.750000   210.949997  155.050003
...                ...          ...         ...
2020-08-03  435.750000  1485.000000  124.309998
2020-08-04  438.660004  1487.000000  125.839996
2020-08-05  440.250000  1485.020020  125.449997
2020-08-06  455.609985  1489.579956  126.120003
2020-08-07  444.450012  1452.709961  124.959999

[1411 rows x 3 columns]

In the second code too, there is no data for 'LNKD'. All are NaNs

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