Search code examples
python-3.xwhile-looppython-requestssleep

How to evualate a function in a while loop


I am trying to stream data in real time while comparing two values. However, it seems as if the function is only being evaluated once. However, time.sleep is also being ran, because it pauses in between loops. However the time is always the same.

x = f'https://api.polygon.io/v1/last/stocks/SPY?{key}'
def get_data():
    time.sleep(5)
    data = requests.get(x)
    json_data = data.json()
    
    #last price, datetime object
    print ((json_data['last'])['price'], epoch_to_date_time( (json_data['last'])['timestamp'] ).__str__())
    return (json_data['last'])['price']


def while_no_match(x):
    counter = 0
    while get_data()!=x and counter < 5 :
        get_data()
        counter +=1

if __name__ == '__main__':
    while_no_match(100)
316.63 2020-07-08 19:01:42.457000
316.63 2020-07-08 19:01:42.457000
316.63 2020-07-08 19:01:42.457000
316.63 2020-07-08 19:01:42.457000
316.63 2020-07-08 19:01:42.457000
316.63 2020-07-08 19:01:42.457000
316.63 2020-07-08 19:01:42.457000
316.63 2020-07-08 19:01:42.457000
316.63 2020-07-08 19:01:42.457000
316.63 2020-07-08 19:01:42.457000
316.63 2020-07-08 19:01:42.457000

Solution

  • after running get_data manually a few time i received the following outputs:

    316.69 2020-07-08 19:36:39.535000
    316.71 2020-07-08 19:37:07.138000
    316.71 2020-07-08 19:37:07.138000
    

    It must be the API.