此代碼使用plotly列出台灣銀行黃金存摺的所有歷史價格
#!/usr/bin/python3 import datetime import plotly.graph_objects as go import numpy as np import plotly import mysql.connector as mysql file='plotly_gold.html' conn=mysql.connect(host="ip",user="account", password="password", database="db") d=datetime.datetime.now() cmd="select * from taiwan_bank_gold where gd_date >= '2018/01/01'order by gd_date" cursor=conn.cursor() cursor.execute(cmd) rows=cursor.fetchall() x=range(len(rows)) sale=[] buy=[] dates=[] for row in rows: dates.append(row[1]) buy.append(row[2]) sale.append(row[3]) f=np.poly1d(np.polyfit(x,sale,15)) reg=f(x) fig=go.Figure() fig.add_trace( go.Scatter( x=dates, y=sale, mode='lines', name='黃金賣出', line=dict(color='royalblue', width=2) ) ) fig.add_trace( go.Scatter( x=dates, y=buy, mode='lines', name='黃金買進', line=dict(color='green', width=2) ) ) fig.add_trace( go.Scatter( x=dates, y=reg, mode='lines', name='趨勢線', line=dict(color='orange', width=2) ) ) fig.update_layout( dragmode="pan", title_text="台灣黃金存摺歷史價格", xaxis=go.layout.XAxis( rangeselector=dict( buttons=list([ dict(count=1, label="1 month", step="month", stepmode="backward"), dict(count=6, label="6 month", step="month", stepmode="backward"), dict(count=1, label="1 year", step="year", stepmode="backward"), dict(count=1, label="1 day", step="day", stepmode="todate"), dict(step="all") ]) ), rangeslider=dict( visible=True ), #range=[datetime.datetime(d.year, 1,1),datetime.datetime(d.year, d.month, d.day)], type="date" ), yaxis=dict(fixedrange=False) ) plotly.offline.plot(fig,filename=file, auto_open=True) print('<iframe src="/python/plotly/{0}" width="800" height="650"></iframe>'.format(file))