nickmccullum / algorithmic-trading-python

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

I keep getting JSONDecodeError #23

Closed dekacypher closed 2 years ago

dekacypher commented 2 years ago

My code from the section "Looping Through The Tickers in Our List of Stocks":

Screen Shot 2022-01-19 at 21 15 14

The error:

Screen Shot 2022-01-19 at 21 15 49

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?

Screen Shot 2022-01-19 at 21 20 05
dekacypher commented 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:

Screen Shot 2022-01-20 at 14 45 45

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.

Screen Shot 2022-01-20 at 14 27 12

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}')

Shanu2092 commented 1 year ago

Sstill giving the same error