nickmccullum / algorithmic-trading-python

The repository for freeCodeCamp's YouTube course, Algorithmic Trading in Python
2.43k stars 2.42k forks source link

KeyError: 'WLTW' #21

Closed dekacypher closed 2 years ago

dekacypher commented 2 years ago

Here is my code:

def chunks(lst, n): 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]))

print(symbol_strings[i])

final_dataframe = pd.DataFrame(columns = my_columns)

for symbol_string in symbol_strings: batch_api_call_url = f'https://sandbox.iexapis.com/stable/stock/market/batch?symbols={symbol_string}&types=quote&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

Here is the error code:

(Cannot paste the pic here for some reason)

But i get a KeyError: 'WLTW'

I have no idea how to fix this, and i can't find any result on google. Please help.

codeguy88 commented 2 years ago

same problem

codeguy88 commented 2 years ago

@dekacypher Are you using a different IDE like PyCharm?

dekacypher commented 2 years ago

No, i use IDLE for Python

dekacypher commented 2 years ago

And i think i have found the cause for this error. Because in the section ''Looping Through The Tickers in Our List of Stocks", I realised i only get a list of around 484 stocks instead of 505 stocks. Then i used: print(data.status_code) this line of code should print '200' if it runs successful for each loop, after i ran the code for a while it went well, but then this is the end of the output:

Screenshot 2022-01-16 at 18 23 46

So i have concluded that the problem occurs with the stock 'WLTW', it is not an error code but it refers to the key value in the dictionary which the code threw an error. But still it continues to loop over the dictionary successfully (prints 200) except for the stock WLTW, it prints (404). As you can see on the picture of the output of my code above.

dekacypher commented 2 years ago

if you got a solution, please tell me. I have struggled with this for almost a week (!!)

codeguy88 commented 2 years ago

no solution yet

chidoman321 commented 2 years ago

i didn't follow exactly his code

symbol_groups = list(chunks(stocks['Ticker'],100)) symbol_strings = [] params=f"&token={api_token}" for group in range(0,len(symbol_groups)): symbol_strings.append(','.join(symbol_groups[group]))

print(symbol_strings[group])

final_dataframe = pd.DataFrame(columns = my_colum)

for symbol_string in symbol_strings[:5]: batch_endpoint = f'/stock/market/batch?symbols={symbol_string}&types=quote' request_url = base_api_url + batch_endpoint + params data = req.get(request_url).json() for symbol in symbol_string.split(','):

    if data.get(symbol) != None:
        final_dataframe = final_dataframe.append(pd.Series([
            symbol,
            data[symbol]['quote']['latestPrice'],
            data[symbol]['quote']['marketCap'],
            'NA'
        ],index = my_colum),ignore_index=True)

final_dataframe

chidoman321 commented 2 years ago

so i guess some of those stock were removed from sp 500, so if you wanna get all the stocks you will need an updated version of the stocks.csv

davidmandia commented 2 years ago

if you got a solution, please tell me. I have struggled with this for almost a week (!!) Add this at the beginning of your for loop, I think that stock has been removed or they changed the name. therefore, when you call the request it does not find anything.

   if symbol == 'WLTW':
        continue
dekacypher commented 2 years ago

Hey, i'm trying to solve this by use my potential solution and also yours. But as I'm using the Jupyter Notebook ipykernel it's exceptionally slow and it's been running the code for approximately 20(!!) hours with no output and it's still running. Do you know how to fix this?

I tried using tips from this website: https://towardsdatascience.com/how-to-effortlessly-optimize-jupyter-notebooks-e864162a06ee

davidmandia commented 2 years ago

Hi. I am not an expert, I would say it there either might be a bug that keeps the for loop running or i genuinely have no idea. I hope you get it sort it

dekacypher commented 2 years ago

if you got a solution, please tell me. I have struggled with this for almost a week (!!) Add this at the beginning of your for loop, I think that stock has been removed or they changed the name. therefore, when you call the request it does not find anything.

   if symbol == 'WLTW':
        continue

Thank you so much, it did work. Here's my code: ` symbol_groups = list(chunks(stocks['Ticker'],100)) symbol_strings = [] for i in range(0, len(symbol_groups)): symbol_strings.append(','.join(symbol_groups[i]))

print(symbol_strings[i])

final_dataframe = pd.DataFrame(columns = my_columns)

for symbol_string in symbol_strings[:1]:

print(symbol_string)

batch_api_call_url = f'https://sandbox.iexapis.com/stable/stock/market/batch?symbols={symbol_string}&types=quote&token={IEX_CLOUD_API_TOKEN}'
#print(batch_api_call_url)
data = requests.get(batch_api_call_url).json()
#print(data.status_code)

#if data.status_code == 200:
    #data = data.json()

for symbol in symbol_string.split(','):
    if symbol == "WLTW":
        continue
    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

    `
dekacypher commented 2 years ago

Hi. I am not an expert, I would say it there either might be a bug that keeps the for loop running or i genuinely have no idea. I hope you get it sort it

Thank you for your advice, i think it was inevitably running on a loop. Because it couldn't find the stock "WLTW", as you said it probably changed or something.

dekacypher commented 2 years ago

The code still works as intended. I noticed that the loop only ran once, but if you remove the [:1] it still works perfectly:

for symbol_string in symbol_strings[:1]:

Screen Shot 2022-01-24 at 17 21 51
dekacypher commented 2 years ago

Hi. I am not an expert, I would say it there either might be a bug that keeps the for loop running or i genuinely have no idea. I hope you get it sort it

Thank you for your advice, i think it was inevitably running on a loop. Because it couldn't find the stock "WLTW", as you said it probably changed or something.

You was right it the stock changed from WLTW to WTW

Screen Shot 2022-01-24 at 17 24 45

https://finance.yahoo.com/news/willis-towers-watson-announces-nasdaq-130000226.html?guccounter=1&guce_referrer=aHR0cHM6Ly93d3cuZ29vZ2xlLmNvbS8&guce_referrer_sig=AQAAAHc0R-wDKwrM1P1p4mIAyHhpRHxAwH2vStFykjOaAd14QZKG7l281MhigObei-WHx0uOjU3CklAsRK8MhiG04-s-Y1IfzT5zAJJWr8nNT4_G7jqSPyHTfgcVBiPT2SFWrVXXXyODe2HDkOFwlOR5BV_tsqUnWwcjUSQBCztnL2us