stock / app.py
MKE0108's picture
add
320cf3b
from flask import Flask, request, jsonify, render_template
import pandas as pd
import datetime
app = Flask(__name__)
def get_tags(_H,_L,_C,last_H,last_L,last_C):
if(_H>last_H and _C>last_H):
tags="日出"
elif(_L<last_L and _C<last_L):#ok
tags="日落"
elif(_H<last_H and _L>last_L):
tags="母子"
elif(_H>last_H and _L<last_L):
tags="子母"
elif(_L<last_L and _C>last_C):#ok
tags="日落收高"
elif(_H>last_H):
tags="出頭"
elif(_L<last_L):
tags="落尾"
else:
tags="無"
return tags
def get_info(stock_id, date):
'''
stock_id: 股票代碼
date: 日期格式為 YYYYMMDD
'''
mouth = int(date[4:6])
year = int(date[:4])
url = f'https://www.twse.com.tw/rwd/zh/afterTrading/STOCK_DAY?date={date}&stockNo={stock_id}&response=html'
last_month = mouth - 1 if mouth > 1 else 12
last_year = year if mouth > 1 else year - 1
last_url = f'https://www.twse.com.tw/rwd/zh/afterTrading/STOCK_DAY?date={last_year}{last_month:02d}12&stockNo={stock_id}&response=html'
try:
data = pd.read_html(url)[0]
data.columns = data.columns.get_level_values(1)
except Exception:
pass
try:
last_data = pd.read_html(last_url)[0]
last_data.columns = last_data.columns.get_level_values(1)
except Exception:
return None
data = pd.concat([last_data, data], axis=0)
data.reset_index(drop=True, inplace=True)
H,L,C= data['最高價'],data['最低價'],data['收盤價']
_H=H.iloc[-1]
_L=L.iloc[-1]
_C=C.iloc[-1]
last_H=H.iloc[-2]
last_L=L.iloc[-2]
last_C=C.iloc[-2]
tags=get_tags(_H,_L,_C,last_H,last_L,last_C)
data=data[-2:]
data['標籤']=tags
#第一個標籤要是X
data['標籤'].iloc[0]="---"
return data[-2:].to_dict(orient="records") # 回傳 JSON 格式的資料
@app.route('/get_stock_info', methods=['POST'])
def get_stock_info():
try:
data = request.json
stock_ids = data.get("stocks", [])
#date取得當前月份
date = datetime.datetime.now().strftime('%Y%m')
date+="01"
results = {}
for stock_id in stock_ids:
stock_data = get_info(stock_id, date)
results[stock_id] = stock_data if stock_data else "No data"
return jsonify(results)
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/')
def index():
return render_template('index.html')
# return 'Hello World!'
# if __name__ == '__main__':
# app.run(debug=True)