Search code examples
pythonpython-3.9pandas-datareader

Python - pandas_datareader Error: "data = j["context"]["dispatcher"]["stores"]["HistoricalPriceStore"]TypeError: string indices must be integers"


I really can't seem to figure out this error that I keep getting from the simple code below. I am using Python 3.9.13 and pandas 2.1.2 . I appreciate in advance the help in figuring this out.

import datetime
import pandas_datareader.data as web
import requests
from bs4 import BeautifulSoup

start = datetime.datetime(2015, 1, 1)
end = datetime.datetime(2018, 2, 8)

df = web.DataReader('BTC-USD', 'yahoo', start='2022-01-01', end='2022-06-14')
df.tail(5)

The error message I get from the above piece of code is:

"data = j["context"]["dispatcher"]["stores"]["HistoricalPriceStore"]TypeError: string indices must be integers"

As a workaround, I have tried the following method, which worked. However, this is not an efficient method as I had to manually save the data file in my project repository.

df = pd.read_excel('../data/input/subSet.xlsx')
df.set_index("Date", inplace=True)
        

Solution

  • Yahoo changed their finance API and i don't think the pandas-datareader crew does anything about it. See discussion here: https://github.com/pydata/pandas-datareader/issues/952

    Its suggested to work with different packages. yfinance seems to work fine and is also using the Yahoo finance API (https://pypi.org/project/yfinance/).Here is a solution that could work:

    import yfinance as yf
    import datetime
    
    # Define the ticker symbol and date range
    ticker = "BTC-USD"
    start = datetime.datetime.now() - datetime.timedelta(days=365)
    end = datetime.datetime.now()
    
    # Download the historical stock prices
    data = yf.download(ticker, start=start, end=end)
    
    # Print the data
    print(data)