You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
249 lines
8.1 KiB
249 lines
8.1 KiB
import os
|
|
|
|
import django
|
|
from django.conf import settings
|
|
|
|
os.chdir('D:/python/djangoProject/test_Bootstrap')
|
|
# 设置 Django 环境变量
|
|
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'test_Bootstrap.settings')
|
|
# print('开始初始化')
|
|
# # 强制初始化 Django
|
|
django.setup()
|
|
# print("Django configured.")
|
|
|
|
print("Starting Streamlit...")
|
|
import streamlit as st
|
|
from streamlit_vertical_slider import vertical_slider
|
|
from st_pages import Page, Section, show_pages, add_page_title, add_indentation
|
|
add_page_title()
|
|
add_indentation()
|
|
|
|
import streamlit as st
|
|
import streamlit as st
|
|
|
|
# 定义点击回调函数
|
|
def reset_weights():
|
|
st.session_state.slider_values = [32, 12, 43, 12, 12]
|
|
st.session_state.reset_trigger += 1
|
|
|
|
# 初始化 session state 中的键
|
|
if 'slider_values' not in st.session_state:
|
|
st.session_state.slider_values = [32, 12, 43, 12, 12]
|
|
if 'reset_trigger' not in st.session_state:
|
|
st.session_state.reset_trigger = 0
|
|
if 'fund_code' not in st.session_state:
|
|
st.session_state['fund_code'] = ''
|
|
col1, col2 = st.columns([0.8, 0.2])
|
|
|
|
with col1:
|
|
# 使用 HTML 和内联CSS来增加字体大小
|
|
st.markdown("""
|
|
<div style='font-size: 34px; font-weight: bold;'>
|
|
基金推荐
|
|
</div>
|
|
""", unsafe_allow_html=True)
|
|
|
|
# with col2:
|
|
# st.button("使用默认权重", key="hidden_button", on_click=reset_weights)
|
|
col1, col2 = st.columns([0.8, 0.2])
|
|
with col1:
|
|
st.markdown('######')
|
|
# 创建滑块
|
|
columns = st.columns(5)
|
|
labels = [
|
|
"国家流感中心周报数据",
|
|
"北京疾控中心数据",
|
|
"百度流感指数数据",
|
|
"药品相关股票数据",
|
|
"流感相关基金数据"
|
|
]
|
|
descriptions = [
|
|
"详细数据来自国家流感中心的周报。",
|
|
"来自北京市疾控中心的相关数据。",
|
|
"基于百度搜索指数的流感数据。",
|
|
"涉及流感药品的股票数据。",
|
|
"投资于流感相关领域的基金数据。"
|
|
]
|
|
|
|
|
|
# 定义点击回调函数
|
|
def reset_model_weights():
|
|
st.session_state.model_slider_values = [2, 12, 43, 12, 12]
|
|
st.session_state.reset_trigger += 1
|
|
|
|
# 初始化 session state 中的键
|
|
if 'model_slider_values' not in st.session_state:
|
|
st.session_state.model_slider_values = [2, 12, 43, 12, 12]
|
|
if 'reset_trigger' not in st.session_state:
|
|
st.session_state.reset_trigger = 0
|
|
|
|
# #从滑块获取模型权重
|
|
model_values_list = [2, 12, 43, 12, 12]
|
|
# st.write('滑块数值:',model_values_list)
|
|
# print(model_values_list)
|
|
|
|
#基金预测函数
|
|
# 添加项目根目录到sys.path
|
|
import os
|
|
import sys
|
|
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), r'D:\python\djangoProject\\test_Bootstrap'))
|
|
sys.path.append(project_root)
|
|
from app_test.add_fund_data import add_fund_data
|
|
from app_test.VAR import VAR_run
|
|
from app_test.RF import RF_run
|
|
from app_test.ARIMA import ARIMA_run
|
|
import pandas as pd
|
|
import json
|
|
from pyecharts import options as opts
|
|
import streamlit.components.v1 as components
|
|
import numpy as np
|
|
from app_test.models import RecommendedFund
|
|
|
|
|
|
def fund_predect(fund_code,idx):
|
|
# fund_code = st.session_state.fund_code
|
|
print(f'开始预测')
|
|
data = add_fund_data(fund_code)
|
|
VAR_result = VAR_run(data, 'fund_data', '')
|
|
power_var = model_values_list[2] / (model_values_list[1] + model_values_list[2])
|
|
power_rf = model_values_list[1] / (model_values_list[1] + model_values_list[2])
|
|
VAR_result = VAR_result.to_frame(name='fund_data')
|
|
# print(VAR_result, type(VAR_result))
|
|
RF_result = RF_run(data, 'fund_data',
|
|
['liugan_index', 'infection_number_x', 'infection_number_y', 'jijin_data', 'shoupan'])
|
|
# print(ARIMA_run(data,'fund_data',['liugan_index','infection_number_x', 'infection_number_y', 'jijin_data', 'shoupan']))
|
|
# print(RF_result, type(RF_result))
|
|
VAR = [item[0] for item in VAR_result.values.tolist()]
|
|
RF = [item[0] for item in RF_result.values.tolist()]
|
|
pre = [VAR[i] * power_var + RF[i] * power_rf for i in range(len(VAR))]
|
|
# 找到列表中的最小值和最大值
|
|
min_val = min(pre)
|
|
max_val = max(pre)
|
|
|
|
# 计算每个值相对于最小值的差异比例
|
|
pre = [(x - min_val) / (max_val - min_val) for x in pre]
|
|
|
|
# 将差异比例放大
|
|
pre= [x * 100 for x in pre]
|
|
print("放大差异后的列表:", pre)
|
|
# print(pre,type(pre))
|
|
date_column = VAR_result.iloc[:, 0]
|
|
date = date_column.index.tolist()
|
|
date = [str(i)[:10] for i in date]
|
|
print('这是预测结果')
|
|
result = pd.DataFrame({
|
|
'date': date,
|
|
'prediction': pre
|
|
})
|
|
print(result, type(result))
|
|
# 可视化预测结果
|
|
# date_js = json.dumps(date)
|
|
# data_js = json.dumps(pre)
|
|
fund_recommand(date,pre,idx)
|
|
return date,pre
|
|
|
|
def result_visualization(date_js, data_js,pic_name,fund_code):
|
|
col = columns = st.columns(1)[0]
|
|
with col:
|
|
st.markdown(f"##### {pic_name}")
|
|
st.markdown("基金代码:" + fund_code) # 使用 Markdown 来提供一致的文本框高度
|
|
# st.markdown()
|
|
|
|
date_js = json.dumps(date_js)
|
|
data_js = json.dumps(data_js)
|
|
html_content = f"""
|
|
<style>
|
|
#echarts-container {{
|
|
position: fixed;
|
|
bottom: 0;
|
|
left: 50%;
|
|
transform: translateX(-50%);
|
|
width: 700px;
|
|
height: 300px;
|
|
background: #f5f5f5;
|
|
z-index: 100;
|
|
}}
|
|
</style>
|
|
<div id="echarts-container"></div>
|
|
<script src="https://cdn.bootcdn.net/ajax/libs/echarts/5.5.0/echarts.min.js"></script>
|
|
<script>
|
|
var main = echarts.init(document.getElementById("echarts-container"));
|
|
|
|
option = {{
|
|
backgroundColor: '#f5f5f5', // 设置背景颜色为浅灰色
|
|
legend: {{
|
|
data: [\'{pic_name}\']
|
|
}},
|
|
xAxis: {{
|
|
type: 'category',
|
|
data: {date_js}
|
|
}},
|
|
yAxis: {{
|
|
type: 'value'
|
|
}},
|
|
series: [{{
|
|
name: '{pic_name}',
|
|
data: {data_js},
|
|
type: 'line'
|
|
}}]
|
|
}};
|
|
main.setOption(option);
|
|
</script>
|
|
"""
|
|
|
|
# 使用 Streamlit 的 HTML 函数将 HTML 内容嵌入页面中
|
|
components.html(html_content, height=350)
|
|
def fund_recommand(date,pre,idx):
|
|
date_js = date
|
|
data_js = pre
|
|
print("===数据===")
|
|
print("date_js:",date_js)
|
|
print("data_js:",data_js)
|
|
is_up = False
|
|
print("基金推荐结果:",fund_name[idx])
|
|
print(data_js)
|
|
print(data_js[0],data_js[-1])
|
|
if(data_js[0]<data_js[-1]):
|
|
is_up = True
|
|
print("is_up:",is_up)
|
|
print("fund_name:",fund_name[idx])
|
|
if is_up:
|
|
#存入数据库
|
|
fund_of_up.append([data_js,date_js,idx])
|
|
#可视化
|
|
# result_visualization(date_js, data_js,fund_name[idx]+"预测走势",idx)
|
|
|
|
fund_codes = ["000684","017313","006218","011308","015619"]
|
|
fund_name = ["长盛养老健康混合A","农银医疗精选股票C","富国生物医药科技混合A","富国生物医药科技混合C","宏利红利先锋混合C"]
|
|
|
|
def run_recommend():
|
|
#基金筛选并存入列表然后放入数据库
|
|
global fund_of_up
|
|
fund_of_up = []
|
|
for idx,fc in enumerate(fund_codes):
|
|
fund_predect(fc,idx)
|
|
|
|
#存入数据库RecommendedFund表
|
|
RecommendedFund.objects.all().delete()#清空数据库原有数据
|
|
for data in fund_of_up:
|
|
# 使用get_or_create来避免重复数据
|
|
obj, created = RecommendedFund.objects.get_or_create(fund_code=fund_codes[data[2]], defaults={'fund_name': fund_name[data[2]],'data_js':data[0],'date_js':data[1]})
|
|
if created:
|
|
print(f"Added new record for date {fund_codes[data[2]]}")
|
|
else:
|
|
print(f"Record for date {fund_codes[data[2]]} already exists.")
|
|
print('成功存入数据库')
|
|
|
|
|
|
#读取数据库中的被推荐基金数据并可视化
|
|
def show_recommended_fund():
|
|
recommended_fund = RecommendedFund.objects.all()
|
|
for fund in recommended_fund:
|
|
pic_name = fund.fund_name
|
|
fund_code = fund.fund_code
|
|
date_js = fund.date_js
|
|
data_js = fund.data_js
|
|
result_visualization(date_js, data_js, pic_name, fund_code)
|
|
|
|
show_recommended_fund()
|
|
# run_recommend() |