TypeError: string indices must be integers - Pandas yahoo finance DataReader

111 views Asked by At

I am trying to create a model to predict cryptocurrency prices. Here is part of the code.

crypto = "SAND-USD"
df = yf.download(crypto, start="2021-01-01", end="2022-08-01")

def get_data(start_date, end_date):
    return pandas_datareader.DataReader(crypto, 'yahoo', start=start_date, end=end_date)


start_date = datetime.datetime(2022, 1, 2)
end_date = datetime.datetime(2022, 1, 21)
get_data(start_date, end_date)

This gives the following error:

TypeError                                 Traceback (most recent call last)
<ipython-input-28-7e8d38c27ffe> in <cell line: 3>()
      1 start_date = datetime.datetime(2022, 1, 2)
      2 end_date = datetime.datetime(2022, 1, 21)
----> 3 get_data(start_date, end_date)

/usr/local/lib/python3.10/dist-packages/pandas_datareader/yahoo/daily.py in _read_one_data(self, url, params)
      151         try:
      152             j = json.loads(re.search(ptrn, resp.text, re.DOTALL).group(1))
  --> 153             data = j["context"]["dispatcher"]["stores"]["HistoricalPriceStore"]
      154         except KeyError:
      155             msg = "No data fetched for symbol {} using {}"

 TypeError: string indices must be integers

start_date and end_date have type of datetime.datetime. I don't understand what string indices it is talking about. Hope anybody can help.

1

There are 1 answers

0
Stefano Fusai On

Please check the pandas_datareader override section here

If your code uses pandas_datareader and you want to download data faster, you can "hijack" pandas_datareader.data.get_data_yahoo() method to use yfinance while making sure the returned data is in the same format as pandas_datareader's get_data_yahoo().

from pandas_datareader import data as pdr

import yfinance as yf
yf.pdr_override() # <== that's all it takes :-)

# download dataframe
data = pdr.get_data_yahoo("SPY", start="2017-01-01", end="2017-04-30")