Skip to content

Instantly share code, notes, and snippets.

@mikeyee
Created October 1, 2018 08:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mikeyee/200c39a9c02df3b0410fa3d3f1b7cb3a to your computer and use it in GitHub Desktop.
Save mikeyee/200c39a9c02df3b0410fa3d3f1b7cb3a to your computer and use it in GitHub Desktop.
以flask框架製作港股通北水追蹤器
#!/usr/bin/env python
from flask import Flask, render_template, flash, request, jsonify, Markup
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.font_manager as mfm
import matplotlib.ticker as ticker
import pandas as pd
import io, base64, os
font_path="/home/bigfish/mysite/NotoSerifCJKtc-Regular.otf"
prop = mfm.FontProperties(fname=font_path, size=30)
table=pd.read_csv('/home/bigfish/mysite/northwater.csv')
app = Flask(__name__)
def sortdate(table):
alldate=list(table)[2:]
alldate.sort()
cols=list(table)[0:2]+alldate
table=table[cols]
return table
result=sortdate(table)
def checkcodeduplicate(code):
tseries=result[result['股票編號']==code]
print(len(tseries))
if len(tseries)>1:
t1=tseries.iloc[0]
t2=tseries.iloc[1]
tseries.iloc[0]=t1.combine_first(t2)
tseries=tseries[:1]
return tseries
@app.route("/", methods=['POST', 'GET'])
def submit_new_profile():
code=700
name=""
submit_value=""
tseries_table=""
if request.method == 'POST':
code = int(request.form['selected_code'])
submit_value=request.form['submit']
try:
tseries = checkcodeduplicate(code)
name = tseries['公司名稱'].iat[0]
tseries = tseries.iloc[:,2:]
tseries = tseries.T
tseries.columns = [code]
tseries.index.name = 'Date'
change = tseries.diff()
pattern = '{:,.0f}'.format
plt.rcParams["figure.figsize"] = (10,10)
fig = plt.figure()
ax = fig.add_subplot(2,1,1)
ax.xaxis.set_major_locator(ticker.MultipleLocator(40))
ax.plot(tseries)
plt.title(name, fontproperties = prop)
ax2 = fig.add_subplot(2,1,2)
ax2.plot(change)
ax2.xaxis.set_major_locator(ticker.MultipleLocator(40))
plt.axhline(linewidth=1, color='r')
img = io.BytesIO()
plt.savefig(img, format='png')
img.seek(0)
plot_url = base64.b64encode(img.getvalue()).decode()
return render_template('index.html',
model_plot = Markup('<img src="data:image/png;base64,{}">'.format(plot_url)),
selected_code = str(code),
name=name,
tseries_table=Markup(tseries.to_html()))
except:
return render_template('index.html',
model_plot = "",
selected_code = str(code),name="你選擇的股票沒有數據",
tseries_table="")
elif request.method == 'GET':
return render_template('index.html',
model_plot = '',
selected_code = str(code),
name=name,
tseries_table="")
# when running app locally
if __name__=='__main__':
app.run(debug=False)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment