尝试从Morningstar下载股票价格数据时出错

时间:2018-05-05 12:43:13

标签: python pandas error-handling finance stockquotes

    import math
    import pandas_datareader.data as web
    import matplotlib.pyplot as plot
    from datetime import datetime
    from matplotlib import style


    style.use('ggplot')

    import csv

    with open('sp500const.csv', newline='') as File:  
    reader = csv.reader(File)
    dataa=[]
    for i in reader:
      dataa.extend(i)

    Dates=[]
    Prices=[]
    Tick=[]
    for stock in dataa[2:100]:
       for year in range(2010,2019):
          if year==2012:  
            start = datetime(year,5,1)
            end=datetime(year,5,1)
            f = web.DataReader(stock, 'morningstar', start, end)
            temp=f['Close']
            Prices.append(float(temp))
            Dates.append(end.strftime('%m/%d/%Y'))
           Tick.append(stock)
         elif year==2013:
            start=datetime(year,5,3)
            end=datetime(year,5,3)
            f = web.DataReader(stock, 'morningstar', start, end)
            temp=f['Close']
            Prices.append(float(temp))
            Dates.append(end.strftime('%m/%d/%Y'))
            Tick.append(stock)
         elif year==2014:
            start=datetime(year,5,5)
            end=datetime(year,5,5)
            f = web.DataReader(stock, 'morningstar', start, end)
            temp=f['Close']
            Prices.append(float(temp))
            Dates.append(end.strftime('%m/%d/%Y'))
            Tick.append(stock)
         else:
            start=datetime(year,5,4)
            end=datetime(year,5,4)
            f = web.DataReader(stock, 'morningstar', start, end)
            temp=f['Close']
            Prices.append(float(temp))
            Dates.append(end.strftime('%m/%d/%Y'))
            Tick.append(stock)


    #datetime(Year,Month,Days)

    x=[Tick,Dates,Prices]
    z=[list(i) for i in zip(*x)]
    print(z)

我想下载S& 500成分的数据,其中的代码在2011年至2018年的sp500const.csv文件[维基百科上报道的代号]中。当我更改要下载的代码数量时(例如在代码中,我想下载代码数据的股票价格[2:100])。当我选择例如数据[2:4]时,代码完美无缺。我收到以下错误:

追踪(最近一次呼叫最后一次):

File "<ipython-input-5-5592627b16bf>", line 44, in <module>
    f = web.DataReader(stock, 'morningstar', start, end)

  File "C:\Users\coxs\Miniconda3\lib\site-packages\pandas_datareader\data.py", line 391, in DataReader
    session=session, interval="d").read()

  File "C:\Users\coxs\Miniconda3\lib\site-packages\pandas_datareader\mstar\daily.py", line 219, in read
    df = self._dl_mult_symbols(symbols=symbols)

  File "C:\Users\coxs\Miniconda3\lib\site-
packages\pandas_datareader\mstar\daily.py", line 126, in _dl_mult_symbols
    jsondata=jsondata)

  File "C:\Users\coxs\Miniconda3\lib\site-packages\pandas_datareader\mstar\daily.py", line 164, in _restruct_json

 volumes = jsondata["VolumeList"]["Datapoints"]

TypeError: 'NoneType' object is not subscriptable

1 个答案:

答案 0 :(得分:-1)

使用&#34;尝试&#34; &#34;除了&#34;声明。这应该避免返回错误并停止循环。问题应该来自API输出,因此您将丢失数据。