我正在使用 plotly 繪制燭臺圖。我正在從 yahoo Finance 獲取資料,并且每分鐘都在重繪 。下面的代碼生成繪圖并將其保存為 HTML 格式,直到這一點我能夠成功。
生成繪圖的代碼(檔案名為 get_VIP_graph_html.py):
import pandas as pd
import plotly.offline as po
import plotly.graph_objs as go
import yfinance as yf
def get_graph():
try:
sid = "VIPIND.NS"
df = yf.download(tickers=sid,interval="1m", period="1d")
df.reset_index(inplace = True)
df['Datetime'] = df['Datetime'].dt.tz_convert('Asia/Kolkata').dt.tz_localize(None)
df['Datetime'] = pd.to_datetime(df['Datetime'])
df=df.set_index('Datetime')
df=df.tail(70)
trace = go.Candlestick(x=df.index,open=df['Open'],high=df['High'],low=df['Low'],close=df['Close'],
name = 'sid')
data = [trace]
layout = {'title': sid}
fig = dict(data=data, layout=layout)
po.plot(fig, filename='templates/stock.html',auto_open=False)
return True
except:
return False
下面是我的燒瓶應用程式代碼(檔案名為 view.py):
from flask import render_template, Flask, request
from get_VIP_graph_html import get_graph
app = Flask(__name__)
@app.route('/', methods=["POST", "GET"])
def homepage():
try:
result = get_graph() #start
if result == True:
return render_template("main.html")
else:
return render_template('main.html', sign='Chart Not Generated')
except Exception as e:
return render_template("main.html", sign=e)
if __name__ == '__main__':
app.run(debug=True,port=8052)
現在是我的 main.html 模板代碼。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}">
<title>stock-graph</title>
<!--Bootstrap core CSS -->
<link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
<!--Bootstrap core js-->
<script src="{{ url_for('static', filename='js/bootstrap.min.js') }}"></script>
</head>
<body>
<div class="container-fluid">
<!--Data form-->
<h1 align="center">Candlestick Chart With Technical Analysis</h1>
{% include 'stock.html' %}
</div>
</body>
<script>
setInterval(function() {
fetch('/')
},60000
);
</script>
</html>
使用 plotly plot 生成的 stock.html 被嵌入到 main.html 中
{% include 'stock.html' %}
我正在使用 setInterval 函式再次運行 view.py,它通過每 1 分鐘執行一次來提取最新資料。下面的螢屏截圖顯示相同:

但是劇情還是沒有重繪 。不知何故,最新的 stock.html 檔案在重繪 期間沒有加載到 main.html 中。
我應該如何解決這個問題,我哪里出錯了。
感謝您的時間和努力。
蘇迪爾
uj5u.com熱心網友回復:
使用不同的方法
- 不保存 HTML,發送圖形定義
- 使用 AJAX 進行更新,然后按定義的時間間隔呼叫燒瓶
- 已將間隔設定為低以進行測驗。
console.log()出于除錯目的而留在原地 - 重要的是日期是python和javascript之間自動轉換的格式
應用程式.py
from get_VIP_graph import get_graph
from flask import Flask, render_template, Response, jsonify
app = Flask(__name__)
@app.route('/')
@app.route('/home')
def home():
return render_template('main.html')
@app.route('/fig')
def fig():
return jsonify(get_graph())
if __name__ == '__main__':
app.run(debug=True, port=3000)
get_VIP_graph.py
import yfinance as yf
import pandas as pd
import plotly.graph_objects as go
def get_graph():
sid = "VIPIND.NS"
df = yf.download(tickers=sid, interval="1m", period="1d")
df.reset_index(inplace=True)
df["Datetime"] = df["Datetime"].dt.tz_convert("Asia/Kolkata").dt.tz_localize(None)
df["Datetime"] = pd.to_datetime(df["Datetime"])
df = df.set_index("Datetime")
df = df.tail(70)
# make sure everything is json serializable, plus use ISO 8601 for dates
trace = go.Candlestick(
x=df.index.strftime('%Y-%m-%dT%H:%M:%SZ').tolist(),
open=df["Open"].tolist(),
high=df["High"].tolist(),
low=df["Low"].tolist(),
close=df["Close"].tolist(),
name="sid",
)
data = [trace]
layout = {"title": sid}
fig = dict(data=data, layout=layout)
return go.Figure(fig).to_dict()
if __name__ == '__main__':
print(get_graph())
main.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<!-- <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}"> -->
<title>stock-graph</title>
<!--Bootstrap core CSS -->
<link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
<!--Bootstrap core js-->
<script src="{{ url_for('static', filename='js/bootstrap.min.js') }}"></script>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdn.plot.ly/plotly-2.9.0.min.js"></script>
</head>
<body>
<div class="container-fluid">
<!--Data form-->
<h1 align="center">Candlestick Chart With Technical Analysis</h1>
<div id="graph" />
</div>
</body>
<script>
function apicall(url) {
$.ajax({
type:"GET", url:url,
success: (data) => {
console.log(data, $("#graph"));
Plotly.newPlot( $("#graph")[0], data );
}
});
}
window.onload = function () {
apicall("/fig");
}
setInterval(function() {apicall("/fig");},1000);
</script>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/451629.html
標籤:javascript html python-3.x 烧瓶 情节地
下一篇:從Flask中的變數渲染按鈕
