Closed dekacypher closed 2 years ago
I have found a solution:
The JSONDecodeError is caused by an HTTP error response that occurs in the midst of the loop, which causes a 404 error and trying to parse this response as JSON is the cause of the JSONDecodeError. Heres where the error occurs:
data = requests.get(api_url).json()
To visualize I printed the status code of each response in the loop:
So after researching and trying, i found that by first using if/else to check if the status code of the response is successful (Code: 200) and then continuing to parse the response as JSON is the key to avoid this case.
And now when i print the final_dataframe i get all the 505 sp stocks, because as seen above in the original problem i had, it only printed 484 stocks, this is because the JSONDecodeError gets raised on the 485th stock and therefore STOPS executing the for loop.
My solution:
final_dataframe = pd.DataFrame(columns = my_columns) for stock in stocks['Ticker']: api_url = f'https://sandbox.iexapis.com/stable/stock/{stock}/quote/?token={IEX_CLOUD_API_TOKEN}' data = requests.get(api_url) if data.status_code == 200: data = data.json() final_dataframe = final_dataframe.append( pd.Series( [ stock, data['latestPrice'], data['marketCap'], 'N/A' ], index = my_columns), ignore_index = True ) else: print(f'An error occured, status code: {data.status_code}')
Sstill giving the same error
My code from the section "Looping Through The Tickers in Our List of Stocks":
The error:
I don't understand what is wrong with my code, i wrote exactly like code from the Algorithmic Trading in Python Course.
And when i print the final_dataframe, the output only shows 484 stocks, and not 505 as in the .csv document? Why is that?