pandaspandas-datareader

Pandas Error: AttributeError: 'NoneType' object has no attribute 'group'


I am trying to fetch historical stock data for Apple Inc. (ticker symbol 'AAPL') from Yahoo Finance.

import pandas_datareader as web
data = web.DataReader('AAPL', data_source='yahoo')
data.head()

But I get this error

AttributeError                            Traceback (most recent call last)
<ipython-input-6-ab4a9c7ea326> in <cell line: 2>()
      1 import pandas_datareader as web
----> 2 data = web.DataReader('AAPL', data_source='yahoo')
      3 print(data)

3 frames
/usr/local/lib/python3.10/dist-packages/pandas_datareader/yahoo/daily.py in _read_one_data(self, url, params)
    150         ptrn = r"root\.App\.main = (.*?);\n}\(this\)\);"
    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:

AttributeError: 'NoneType' object has no attribute 'group'

Solution

  • You can use yfinance to do this:

    import yfinance as yf
    
    data = yf.download('AAPL')
    
    print(data.head())
    

    which gives

    [*********************100%%**********************]  1 of 1 completed
                    Open      High       Low     Close  Adj Close     Volume
    Date                                                                    
    1980-12-12  0.128348  0.128906  0.128348  0.128348   0.099058  469033600
    1980-12-15  0.122210  0.122210  0.121652  0.121652   0.093890  175884800
    1980-12-16  0.113281  0.113281  0.112723  0.112723   0.086999  105728000
    1980-12-17  0.115513  0.116071  0.115513  0.115513   0.089152   86441600
    1980-12-18  0.118862  0.119420  0.118862  0.118862   0.091737   73449600
    

    If you absolutely want to use data_reader, then change the source (unless you have the api_key to yahoo:

    import pandas_datareader.data as web
    from datetime import datetime
    
    start_date = datetime(2020, 1, 1)
    end_date = datetime(2023, 1, 1)
    
    data = web.DataReader('AAPL', 'stooq', start=start_date, end=end_date)
    
    print(data.head())
    

    which gives you

                  Open      High     Low   Close      Volume
    Date                                                    
    2022-12-30  128.41  129.9500  127.43  129.93  77034209.0
    2022-12-29  127.99  130.4814  127.73  129.61  75703710.0
    2022-12-28  129.67  131.0275  125.87  126.04  85438391.0
    2022-12-27  131.38  131.4100  128.72  130.03  69007830.0
    2022-12-23  130.92  132.4150  129.64  131.86  63814893.0