Search code examples
pythonpandaskeyerror

Key error python algorithmic trading using google collab with iex cloud api


I am following this code from a youtube video it uses iex cloud API. I have followed the video till now but I am stuck at this point

enter code here
# Function sourced from 
# https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized- 
  chunks
def chunks(lst, n):
    """Yield successive n-sized chunks from last."""
    for i in range(0, len(lst), n):
        yield lst[i:i + n]
symbol_groups = list(chunks(stocks['Ticker'], 100))
symbol_strings = []
for i in range(0, len(symbol_groups)):
     symbol_strings.append(','.join(symbol_groups[i]))
for symbol_string in symbol_strings:
   batch_api_call_url = f'https://sandbox.iexapis.com/stable/stock/market/batch/? 
   types=quote&symbols={symbol_string}&token={IEX_CLOUD_API_TOKEN}'
   data = requests.get(batch_api_call_url).json()
   for symbol in symbol_string.split(','):
       final_dataframe = final_dataframe.append(
                                    pd.Series([symbol, 
                                               data[symbol]['quote']['latestPrice'], 
                                               data[symbol]['quote']['marketCap'], 
                                               'N/A'], 
                                              index = my_columns), 
                                    ignore_index = True)
    

 final_dataframe

I am getting a key error saying:

enter code 
hereKeyError                                  Traceback (most recent call last)
<ipython-input-16-23716615b418> in <module>()
 12         final_dataframe = final_dataframe.append(
 13                                         pd.Series([symbol, 
 ---> 14                                                    data[symbol]['quote'] 
                                                       ['latestPrice'],
 15                                                    data[symbol]['quote'] 
                                                       ['marketCap'],
 16                                                    'N/A'], 

 KeyError: 'HFC'

Solution

  •  for symbol in symbol_string.split(","):
        if symbol == 'HFC' or symbol == 'VIAC' or symbol == 'WLTW' or symbol == 'DISCA':
           continue
        else:
            final_dataframe=final_dataframe.append(
                pd.Series([
                    symbol,
                    data[symbol]["quote"]["latestPrice"],
                    data[symbol]["quote"]["marketCap"],
                    'N/A'
                ],
                index = columns),
                ignore_index=True
            )