0

I am currently working on a simple simulated stock price movement model using Python, and I have used Flask to turn the code into an API that can output the latest price upon page refresh. But now, I'd like to make this API automatically output the latest price value every second, without needing to manually hit refresh or make a GET request.

The code I currently have is this, and I have called the file app.py:

from flask import Flask, jsonify
import numpy as np
import random as random
import os
# from matplotlib import pyplot as plt
# from scipy.stats import norm

app = Flask(__name__)
S = [10000]

@app.route('/', methods = ['GET'])
def random_walk():
    A = random.choices((0,1), weights=(99, 1), k=1)
    unif = np.random.uniform(0, 1, 1)
    price_move = np.round(-1.5 + 100*A[0] + unif, 6)
    curr_price = S[-1] + price_move
    S.append(curr_price)
    # return jsonify({'data3': np.round(-1.5 + 100*A[0] + unif, 6).tolist()})
    return jsonify({'current_price': curr_price.tolist()}) 
    # return  '{} {}'.format(price_move, curr_price)

port= os.environ.get("PORT")
port = port if port != None else 8080

if __name__ == '__main__':
    app.run(debug=True, port=port, host='0.0.0.0')

So far, I have called out in my terminal python3 app.py and have gotten the following output

 * Serving Flask app 'app'
 * Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on all addresses (0.0.0.0)
 * Running on http://127.0.0.1:8080
 * Running on http://10.10.31.97:8080
Press CTRL+C to quit
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 550-185-703

And going to my localhost server correctly gives out the latest price, but as mentioned, it only outputs me a new price for the next timestamp upon hitting refresh.

Any help would be greatly appreciated, and if the question is lacking / needs more clarification, please do let me know since this is my first time posting a question on Stack Overflow and my knowledge to Flask is very minimal at best.

davidism
  • 121,510
  • 29
  • 395
  • 339
Hxess
  • 9
  • 3
  • Hello, I believe [this answer](https://stackoverflow.com/a/45669876/11955835) is applicable to your application as well. – Anonyme2000 Oct 31 '22 at 10:33

0 Answers0