提交 79e868dc 编写于 作者: L linkedin_21843693

初始提交

上级 0520122c
run = "pip install -r requirements.txt;streamlit run --server.enableXsrfProtection=false main.py"
run = ""
language = "python"
[packager]
......
import efinance as ef
from flask import Flask, request, jsonify
app = Flask(__name__)
# 大家可以不一样的,用于生成随机ID的随机种子,类似random的seed
app.secret_key = "randomstring12345"
messages = []
def get_stock_data(
quantity_ratio_min,
quantity_ratio_max,
change_min,change_max):
df = ef.stock.get_realtime_quotes()
df['量比'] = df['量比'].replace("-", 0)
df['量比'] = df['量比'].astype('float16')
selected = df[
(df['量比'] >= quantity_ratio_min) &
(df['量比'] <= quantity_ratio_max) &
(df['换手率'] >= change_min) &
(df['换手率'] <= change_max)
]
# 排序
selected = selected.sort_values(by='量比', ascending=False)
selected = selected[["股票代码", "股票名称", "换手率", "量比", "涨跌幅", "流通市值", "更新时间"]]
return selected
@app.route("/api/stock", methods=["GET", "POST"]) # 允许的方法有POST和GET,其他不写methods默认就是GET
def get_stock():
# 从URL参数中获取两个数值
quantity_ratio_min = request.form.get('quantity_ratio_min', type=float, default=0)
quantity_ratio_max = request.form.get('quantity_ratio_max', type=float, default=8)
up_min = request.form.get('up_min', type=float, default=10)
up_max = request.form.get('up_max', type=float, default=12)
# 根据参数处理DataFrame
filtered_df = get_stock_data(quantity_ratio_min, quantity_ratio_max, up_min, up_max)
# 将DataFrame转换为JSON格式
json_data = filtered_df.to_json(orient='records')
# 返回JSON数据
return jsonify(json_data)
#登录接口
@app.route("/api/login", methods=["GET", "POST"])
def login():
username = request.form.get('username')
password = request.form.get('password')
if username == 'admin' and password == '123456':
return jsonify({'status': 'success', 'message': '登录成功'}, 200)
else:
return jsonify({'status': 'fail', 'message': '登录失败'}, 400)
if __name__ == '__main__':
app.run() # 启动服务器
\ No newline at end of file
import streamlit as st
from streamlit_option_menu import option_menu
# 设置Streamlit应用程序的标题
st.set_page_config(page_title="app name", layout="wide")
menu1="菜单1"
menu2="菜单2"
with st.sidebar:
menu = option_menu("菜单", [menu1, menu2],
icons=['house', "list-task"],
menu_icon="cast", default_index=0)
def main():
if menu == menu1:
st.subheader(f"{menu1}")
if menu == menu2:
st.subheader(f"{menu2}")
if __name__ == '__main__':
main()
import streamlit as st
from streamlit_option_menu import option_menu
import requests
import pandas as pd
# 建议把账号密码放到环境变量或数据库中,这里只是演示,不安全
USERS = {
"admin": "123456", # 账号密码
"test": "123456",
"test2": "123457",
}
API_URL = "http://127.0.0.1:5000"
# 设置Streamlit应用程序的标题
st.set_page_config(page_title="app name", layout="wide")
menu1="菜单1"
menu2="菜单2"
def login_page(has_login):
if has_login:
# 登录后可以进入应用
df = None
with st.form("my_form1"):
st.write("投资策略")
# 创建2个滑块,用于选择量比和换手率范围
quantity_ratio = st.slider(
'选择量比范围:',
0.0, 10.0, (1.0, 8.0))
with st.sidebar:
menu = option_menu("菜单", [menu1, menu2],
icons=['house', "list-task"],
menu_icon="cast", default_index=0)
change_ratio = st.slider(
'选择换手率范围:',
0.0, 20.0, (10.0, 12.0))
# 创建一个提交按钮,用于提交表单
submit_res = st.form_submit_button(label='查询')
if submit_res:
st.info(f"提交参数:{quantity_ratio} {change_ratio}")
response = requests.post(
f'{API_URL}/api/stock',
data={
"quantity_ratio_min": quantity_ratio[0],
"quantity_ratio_max": quantity_ratio[1],
"change_min": change_ratio[0],
"change_max": change_ratio[1]
})
response_json = response.json()
df = pd.read_json(response_json)
# 优化股票代码显示
df["股票代码"] = df["股票代码"].astype("object")
# 补充零
df["股票代码"] = df["股票代码"].apply(lambda x: str(x).zfill(6))
# 会自动处理Dataframe数据,变成表格
st.dataframe(df)
# 如果有数据,则显示下载按钮
if df is not None:
st.download_button(
label="下载数据",
data=df.to_csv().encode("utf-8"),
file_name='股票数据.csv',
mime='text/csv',
)
def main():
else:
# 没有登录进入登录页面
with st.form("my_form"):
# 创建一个表单,用于用户登录
username = st.text_input(label='用户:')
# 获取用户输入的用户名
password = st.text_input(label='密码:', type="password")
submit_res = st.form_submit_button(label='登录')
# 提交表单并获取结果
if submit_res:
user_password = USERS.get(username)
# 获取用户输入的用户名对应的密码
if user_password is None:
# 如果用户名不存在或密码错误
st.warning("账号或密码有误,请重试")
return
# 如果用户名存在且密码正确
if user_password == password:
# 显示登录成功的提示信息
st.info("登录成功")
# 将登录状态保存到session_state中
st.session_state.key = 'applicant-token'
st.session_state['has_login'] = True
# 重新运行程序
st.rerun()
else:
# 如果用户名存在但密码错误
st.warning("账号或密码有误,请重试")
def log_out(has_login):
if has_login:
with st.form("my_form"):
st.write("确定想退出登录?")
submit_res = st.form_submit_button(label='点击退出系统')
if submit_res:
st.session_state['has_login'] = False
st.write("成功退出")
st.rerun()
else:
st.write("您还没有登录系统。")
if menu == menu1:
st.subheader(f"{menu1}")
if menu == menu2:
st.subheader(f"{menu2}")
def main():
# 设置左侧栏选项
add_selectbox = st.sidebar.selectbox(
"请选择功能呢",
("登录", "退出")
)
has_login = False
if 'has_login' in st.session_state:
has_login = st.session_state['has_login']
# 根据选项进入不同函数
if add_selectbox == '登录':
login_page(has_login=has_login)
elif add_selectbox == '退出':
log_out(has_login=has_login)
if __name__ == '__main__':
main()
if __name__ == "__main__":
# 命令行启动服务,app.py则为程序名称
# streamlit run stock_app.py --server.port 80
main()
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册