聚烯烃PP期货预测
This commit is contained in:
parent
97ef8b63a3
commit
f3971a94ec
@ -397,6 +397,9 @@ get_waring_data_value_list_data = {
|
|||||||
# 八大维度数据项编码
|
# 八大维度数据项编码
|
||||||
bdwd_items = {
|
bdwd_items = {
|
||||||
'ciri': 'jxtppbdwdcr',
|
'ciri': 'jxtppbdwdcr',
|
||||||
|
'cierri': 'jxtppbdwdcer',
|
||||||
|
'cisanri': 'jxtppbdwdcsanr',
|
||||||
|
'cisiri': 'jxtppbdwdcsir',
|
||||||
'benzhou': 'jxtppbdwdbz',
|
'benzhou': 'jxtppbdwdbz',
|
||||||
'cizhou': 'jxtppbdwdcz',
|
'cizhou': 'jxtppbdwdcz',
|
||||||
'gezhou': 'jxtppbdwdgz',
|
'gezhou': 'jxtppbdwdgz',
|
||||||
|
@ -86,11 +86,14 @@ bdwdname = [
|
|||||||
'次周',
|
'次周',
|
||||||
'隔周',
|
'隔周',
|
||||||
]
|
]
|
||||||
|
|
||||||
# 数据库预测结果表八大维度列名
|
# 数据库预测结果表八大维度列名
|
||||||
price_columns = [
|
price_columns = [
|
||||||
'day_price', 'week_price', 'second_week_price', 'next_week_price',
|
'day_price', 'week_price', 'second_week_price', 'next_week_price',
|
||||||
'next_month_price', 'next_february_price', 'next_march_price', 'next_april_price'
|
'next_month_price', 'next_february_price', 'next_march_price', 'next_april_price'
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
modelsindex = [{
|
modelsindex = [{
|
||||||
"NHITS": "SELF0000231",
|
"NHITS": "SELF0000231",
|
||||||
"Informer": "SELF0000232",
|
"Informer": "SELF0000232",
|
||||||
|
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
from lib.dataread import *
|
from lib.dataread import *
|
||||||
from config_juxiting import *
|
from config_juxiting import *
|
||||||
from lib.tools import SendMail, exception_logger, convert_df_to_pydantic_pp, exception_logger, get_modelsname, plot_pp_predict_result
|
from lib.tools import SendMail, exception_logger, convert_df_to_pydantic_pp, exception_logger, find_best_models, get_modelsname, plot_pp_predict_result
|
||||||
from models.nerulforcastmodels import ex_Model_Juxiting, model_losss_juxiting, pp_export_pdf
|
from models.nerulforcastmodels import ex_Model_Juxiting, model_losss_juxiting, pp_export_pdf
|
||||||
import datetime
|
import datetime
|
||||||
import torch
|
import torch
|
||||||
@ -103,49 +103,53 @@ global_config.update({
|
|||||||
|
|
||||||
def push_market_value():
|
def push_market_value():
|
||||||
config.logger.info('发送预测结果到市场信息平台')
|
config.logger.info('发送预测结果到市场信息平台')
|
||||||
|
|
||||||
|
current_end_time = global_config['end_time']
|
||||||
|
previous_trading_day = (pd.Timestamp(current_end_time) -
|
||||||
|
pd.tseries.offsets.BusinessDay(1)).strftime('%Y-%m-%d')
|
||||||
|
|
||||||
# 读取预测数据和模型评估数据
|
# 读取预测数据和模型评估数据
|
||||||
predict_file_path = os.path.join(config.dataset, 'predict.csv')
|
best_bdwd_price = find_best_models(
|
||||||
model_eval_file_path = os.path.join(config.dataset, 'model_evaluation.csv')
|
date=previous_trading_day, global_config=global_config)
|
||||||
try:
|
|
||||||
predictdata_df = pd.read_csv(predict_file_path)
|
|
||||||
top_models_df = pd.read_csv(model_eval_file_path)
|
|
||||||
except FileNotFoundError as e:
|
|
||||||
config.logger.error(f"文件未找到: {e}")
|
|
||||||
return
|
|
||||||
|
|
||||||
predictdata = predictdata_df.copy()
|
# 获取本周最佳模型的五日预测价格
|
||||||
|
five_days_predict_price = pd.read_csv('juxitingdataset/predict.csv')
|
||||||
# 取模型前十
|
week_price_modelname = best_bdwd_price['week_price']['model_name']
|
||||||
top_models = top_models_df['模型(Model)'].head(10).tolist()
|
five_days_predict_price = five_days_predict_price[['ds',week_price_modelname]]
|
||||||
# 去掉FDBformer
|
five_days_predict_price['ds'] = pd.to_datetime(five_days_predict_price['ds'])
|
||||||
if 'FEDformer' in top_models:
|
five_days_predict_price.rename(columns={week_price_modelname:'predictresult'},inplace=True)
|
||||||
top_models.remove('FEDformer')
|
# 设置索引 次日 次二日 次三日 次四日 次五日
|
||||||
|
index_labels = ["次日", "次二日", "次三日", "次四日", "次五日"]
|
||||||
# 计算前十模型的均值
|
five_days_predict_price.index = index_labels
|
||||||
predictdata_df['top_models_mean'] = predictdata_df[top_models].mean(axis=1)
|
global_config['logger'].info(f"best_bdwd_price: {best_bdwd_price}")
|
||||||
|
|
||||||
# 打印日期和前十模型均值
|
|
||||||
print(predictdata_df[['ds', 'top_models_mean']])
|
|
||||||
|
|
||||||
# 准备要推送的数据
|
|
||||||
first_mean = predictdata_df['top_models_mean'].iloc[0]
|
|
||||||
last_mean = predictdata_df['top_models_mean'].iloc[-1]
|
|
||||||
# 保留两位小数
|
|
||||||
first_mean = round(first_mean, 2)
|
|
||||||
last_mean = round(last_mean, 2)
|
|
||||||
|
|
||||||
predictdata = [
|
predictdata = [
|
||||||
{
|
{
|
||||||
"dataItemNo": global_config['bdwd_items']['ciri'],
|
"dataItemNo": global_config['bdwd_items']['ciri'],
|
||||||
"dataDate": global_config['end_time'].replace('-', ''),
|
"dataDate": global_config['end_time'].replace('-', ''),
|
||||||
"dataStatus": "add",
|
"dataStatus": "add",
|
||||||
"dataValue": first_mean
|
"dataValue": five_days_predict_price.loc['次日','predictresult'].round(2)
|
||||||
|
},{
|
||||||
|
"dataItemNo": global_config['bdwd_items']['cierri'],
|
||||||
|
"dataDate": global_config['end_time'].replace('-', ''),
|
||||||
|
"dataStatus": "add",
|
||||||
|
"dataValue": five_days_predict_price.loc['次二日','predictresult'].round(2)
|
||||||
|
},{
|
||||||
|
"dataItemNo": global_config['bdwd_items']['cisanri'],
|
||||||
|
"dataDate": global_config['end_time'].replace('-', ''),
|
||||||
|
"dataStatus": "add",
|
||||||
|
"dataValue": five_days_predict_price.loc['次三日','predictresult'].round(2)
|
||||||
|
},{
|
||||||
|
"dataItemNo": global_config['bdwd_items']['cisiri'],
|
||||||
|
"dataDate": global_config['end_time'].replace('-', ''),
|
||||||
|
"dataStatus": "add",
|
||||||
|
"dataValue": five_days_predict_price.loc['次四日','predictresult'].round(2)
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"dataItemNo": global_config['bdwd_items']['benzhou'],
|
"dataItemNo": global_config['bdwd_items']['benzhou'],
|
||||||
"dataDate": global_config['end_time'].replace('-', ''),
|
"dataDate": global_config['end_time'].replace('-', ''),
|
||||||
"dataStatus": "add",
|
"dataStatus": "add",
|
||||||
"dataValue": last_mean
|
"dataValue": five_days_predict_price.loc['次五日','predictresult'].round(2)
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|
||||||
@ -553,7 +557,7 @@ if __name__ == '__main__':
|
|||||||
# except Exception as e:
|
# except Exception as e:
|
||||||
# logger.info(f'预测失败:{e}')
|
# logger.info(f'预测失败:{e}')
|
||||||
# continue
|
# continue
|
||||||
|
global_config['end_time'] = '2025-08-04'
|
||||||
predict_main()
|
predict_main()
|
||||||
|
|
||||||
# push_market_value()
|
# push_market_value()
|
||||||
|
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
from lib.dataread import *
|
from lib.dataread import *
|
||||||
from config_juxiting_yuedu import *
|
from config_juxiting_yuedu import *
|
||||||
from lib.tools import SendMail, convert_df_to_pydantic_pp, exception_logger, get_modelsname
|
from lib.tools import SendMail, convert_df_to_pydantic_pp, exception_logger, find_best_models, get_modelsname
|
||||||
from models.nerulforcastmodels import ex_Model, model_losss_juxiting, pp_bdwd_png, pp_export_pdf
|
from models.nerulforcastmodels import ex_Model, model_losss_juxiting, pp_bdwd_png, pp_export_pdf
|
||||||
import datetime
|
import datetime
|
||||||
import torch
|
import torch
|
||||||
@ -93,35 +93,28 @@ global_config.update({
|
|||||||
|
|
||||||
def push_market_value():
|
def push_market_value():
|
||||||
logger.info('发送预测结果到市场信息平台')
|
logger.info('发送预测结果到市场信息平台')
|
||||||
|
current_end_time = global_config['end_time']
|
||||||
|
previous_trading_day = (pd.Timestamp(current_end_time) -
|
||||||
|
pd.tseries.offsets.BusinessDay(1)).strftime('%Y-%m-%d')
|
||||||
|
|
||||||
# 读取预测数据和模型评估数据
|
# 读取预测数据和模型评估数据
|
||||||
predict_file_path = os.path.join(config.dataset, 'predict.csv')
|
best_bdwd_price = find_best_models(
|
||||||
model_eval_file_path = os.path.join(config.dataset, 'model_evaluation.csv')
|
date=previous_trading_day, global_config=global_config)
|
||||||
try:
|
|
||||||
predictdata_df = pd.read_csv(predict_file_path)
|
|
||||||
top_models_df = pd.read_csv(model_eval_file_path)
|
|
||||||
except FileNotFoundError as e:
|
|
||||||
logger.error(f"文件未找到: {e}")
|
|
||||||
return
|
|
||||||
|
|
||||||
predictdata = predictdata_df.copy()
|
# 获取本月最佳模型的预测价格
|
||||||
|
four_month_predict_price = pd.read_csv(os.path.join(global_config['dataset'], 'predict.csv'))
|
||||||
# 取模型前十
|
four_month_predict_price['ds'] = pd.to_datetime(four_month_predict_price['ds'])
|
||||||
top_models = top_models_df['模型(Model)'].head(10).tolist()
|
# 设置索引 次月 次二月 次三月 次四月
|
||||||
# 去掉FDBformer
|
index_labels = ["次月", "次二月", "次三月", "次四月"]
|
||||||
if 'FEDformer' in top_models:
|
four_month_predict_price.index = index_labels
|
||||||
top_models.remove('FEDformer')
|
global_config['logger'].info(f"best_bdwd_price: {best_bdwd_price}")
|
||||||
# 计算前十模型的均值
|
|
||||||
predictdata_df['top_models_mean'] = predictdata_df[top_models].mean(axis=1)
|
|
||||||
|
|
||||||
# 打印日期和前十模型均值
|
|
||||||
print(predictdata_df[['ds', 'top_models_mean']])
|
|
||||||
|
|
||||||
# 准备要推送的数据
|
# 准备要推送的数据
|
||||||
ciyue_mean = predictdata_df['top_models_mean'].iloc[0]
|
ciyue_mean = four_month_predict_price[best_bdwd_price['next_month_price']['model_name']].iloc[0]
|
||||||
cieryue_mean = predictdata_df['top_models_mean'].iloc[1]
|
cieryue_mean = four_month_predict_price[best_bdwd_price['next_february_price']['model_name']].iloc[1]
|
||||||
cisanyue_mean = predictdata_df['top_models_mean'].iloc[2]
|
cisanyue_mean = four_month_predict_price[best_bdwd_price['next_march_price']['model_name']].iloc[2]
|
||||||
cisieryue_mean = predictdata_df['top_models_mean'].iloc[3]
|
cisieryue_mean = four_month_predict_price[best_bdwd_price['next_april_price']['model_name']].iloc[3]
|
||||||
# 保留两位小数
|
# # 保留两位小数
|
||||||
ciyue_mean = round(ciyue_mean, 2)
|
ciyue_mean = round(ciyue_mean, 2)
|
||||||
cieryue_mean = round(cieryue_mean, 2)
|
cieryue_mean = round(cieryue_mean, 2)
|
||||||
cisanyue_mean = round(cisanyue_mean, 2)
|
cisanyue_mean = round(cisanyue_mean, 2)
|
||||||
@ -292,211 +285,211 @@ def predict_main():
|
|||||||
返回:
|
返回:
|
||||||
None
|
None
|
||||||
"""
|
"""
|
||||||
end_time = global_config['end_time']
|
# end_time = global_config['end_time']
|
||||||
signature = BinanceAPI(APPID, SECRET)
|
# signature = BinanceAPI(APPID, SECRET)
|
||||||
etadata = EtaReader(signature=signature,
|
# etadata = EtaReader(signature=signature,
|
||||||
classifylisturl=global_config['classifylisturl'],
|
# classifylisturl=global_config['classifylisturl'],
|
||||||
classifyidlisturl=global_config['classifyidlisturl'],
|
# classifyidlisturl=global_config['classifyidlisturl'],
|
||||||
edbcodedataurl=global_config['edbcodedataurl'],
|
# edbcodedataurl=global_config['edbcodedataurl'],
|
||||||
edbcodelist=global_config['edbcodelist'],
|
# edbcodelist=global_config['edbcodelist'],
|
||||||
edbdatapushurl=global_config['edbdatapushurl'],
|
# edbdatapushurl=global_config['edbdatapushurl'],
|
||||||
edbdeleteurl=global_config['edbdeleteurl'],
|
# edbdeleteurl=global_config['edbdeleteurl'],
|
||||||
edbbusinessurl=global_config['edbbusinessurl'],
|
# edbbusinessurl=global_config['edbbusinessurl'],
|
||||||
classifyId=global_config['ClassifyId'],
|
# classifyId=global_config['ClassifyId'],
|
||||||
)
|
# )
|
||||||
# 获取数据
|
# # 获取数据
|
||||||
if is_eta:
|
# if is_eta:
|
||||||
logger.info('从eta获取数据...')
|
# logger.info('从eta获取数据...')
|
||||||
|
|
||||||
df_zhibiaoshuju, df_zhibiaoliebiao = etadata.get_eta_api_pp_data(
|
# df_zhibiaoshuju, df_zhibiaoliebiao = etadata.get_eta_api_pp_data(
|
||||||
data_set=data_set, dataset=dataset) # 原始数据,未处理
|
# data_set=data_set, dataset=dataset) # 原始数据,未处理
|
||||||
|
|
||||||
if is_market:
|
# if is_market:
|
||||||
logger.info('从市场信息平台获取数据...')
|
# logger.info('从市场信息平台获取数据...')
|
||||||
try:
|
# try:
|
||||||
# 如果是测试环境,最高价最低价取excel文档
|
# # 如果是测试环境,最高价最低价取excel文档
|
||||||
if server_host == '192.168.100.53':
|
# if server_host == '192.168.100.53':
|
||||||
logger.info('从excel文档获取最高价最低价')
|
# logger.info('从excel文档获取最高价最低价')
|
||||||
df_zhibiaoshuju = get_high_low_data(df_zhibiaoshuju)
|
# df_zhibiaoshuju = get_high_low_data(df_zhibiaoshuju)
|
||||||
else:
|
# else:
|
||||||
logger.info('从市场信息平台获取数据')
|
# logger.info('从市场信息平台获取数据')
|
||||||
df_zhibiaoshuju = get_market_data(
|
# df_zhibiaoshuju = get_market_data(
|
||||||
end_time, df_zhibiaoshuju)
|
# end_time, df_zhibiaoshuju)
|
||||||
|
|
||||||
except:
|
# except:
|
||||||
logger.info('最高最低价拼接失败')
|
# logger.info('最高最低价拼接失败')
|
||||||
|
|
||||||
# 保存到xlsx文件的sheet表
|
# # 保存到xlsx文件的sheet表
|
||||||
with pd.ExcelWriter(os.path.join(dataset, data_set)) as file:
|
# with pd.ExcelWriter(os.path.join(dataset, data_set)) as file:
|
||||||
df_zhibiaoshuju.to_excel(file, sheet_name='指标数据', index=False)
|
# df_zhibiaoshuju.to_excel(file, sheet_name='指标数据', index=False)
|
||||||
df_zhibiaoliebiao.to_excel(file, sheet_name='指标列表', index=False)
|
# df_zhibiaoliebiao.to_excel(file, sheet_name='指标列表', index=False)
|
||||||
|
|
||||||
# 数据处理
|
# # 数据处理
|
||||||
df = datachuli_juxiting(df_zhibiaoshuju, df_zhibiaoliebiao, y=global_config['y'], dataset=dataset, add_kdj=add_kdj, is_timefurture=is_timefurture,
|
# df = datachuli_juxiting(df_zhibiaoshuju, df_zhibiaoliebiao, y=global_config['y'], dataset=dataset, add_kdj=add_kdj, is_timefurture=is_timefurture,
|
||||||
end_time=end_time)
|
# end_time=end_time)
|
||||||
|
|
||||||
else:
|
# else:
|
||||||
# 读取数据
|
# # 读取数据
|
||||||
logger.info('读取本地数据:' + os.path.join(dataset, data_set))
|
# logger.info('读取本地数据:' + os.path.join(dataset, data_set))
|
||||||
df, df_zhibiaoliebiao = getdata_zhoudu_juxiting(filename=os.path.join(dataset, data_set), y=y, dataset=dataset, add_kdj=add_kdj,
|
# df, df_zhibiaoliebiao = getdata_zhoudu_juxiting(filename=os.path.join(dataset, data_set), y=y, dataset=dataset, add_kdj=add_kdj,
|
||||||
is_timefurture=is_timefurture, end_time=end_time) # 原始数据,未处理
|
# is_timefurture=is_timefurture, end_time=end_time) # 原始数据,未处理
|
||||||
|
|
||||||
# 更改预测列名称
|
# # 更改预测列名称
|
||||||
df.rename(columns={y: 'y'}, inplace=True)
|
# df.rename(columns={y: 'y'}, inplace=True)
|
||||||
|
|
||||||
if is_edbnamelist:
|
# if is_edbnamelist:
|
||||||
df = df[edbnamelist]
|
# df = df[edbnamelist]
|
||||||
df.to_csv(os.path.join(dataset, '指标数据.csv'), index=False)
|
# df.to_csv(os.path.join(dataset, '指标数据.csv'), index=False)
|
||||||
# 保存最新日期的y值到数据库
|
# # 保存最新日期的y值到数据库
|
||||||
# 取第一行数据存储到数据库中
|
# # 取第一行数据存储到数据库中
|
||||||
first_row = df[['ds', 'y']].tail(1)
|
# first_row = df[['ds', 'y']].tail(1)
|
||||||
# 判断y的类型是否为float
|
# # 判断y的类型是否为float
|
||||||
if not isinstance(first_row['y'].values[0], float):
|
# if not isinstance(first_row['y'].values[0], float):
|
||||||
logger.info(f'{end_time}预测目标数据为空,跳过')
|
# logger.info(f'{end_time}预测目标数据为空,跳过')
|
||||||
return None
|
# return None
|
||||||
|
|
||||||
# 将最新真实值保存到数据库
|
# # 将最新真实值保存到数据库
|
||||||
if not sqlitedb.check_table_exists('trueandpredict'):
|
# if not sqlitedb.check_table_exists('trueandpredict'):
|
||||||
first_row.to_sql('trueandpredict', sqlitedb.connection, index=False)
|
# first_row.to_sql('trueandpredict', sqlitedb.connection, index=False)
|
||||||
else:
|
# else:
|
||||||
for row in first_row.itertuples(index=False):
|
# for row in first_row.itertuples(index=False):
|
||||||
row_dict = row._asdict()
|
# row_dict = row._asdict()
|
||||||
config.logger.info(f'要保存的真实值:{row_dict}')
|
# config.logger.info(f'要保存的真实值:{row_dict}')
|
||||||
# 判断ds是否为字符串类型,如果不是则转换为字符串类型
|
# # 判断ds是否为字符串类型,如果不是则转换为字符串类型
|
||||||
if isinstance(row_dict['ds'], (pd.Timestamp, datetime.datetime)):
|
# if isinstance(row_dict['ds'], (pd.Timestamp, datetime.datetime)):
|
||||||
row_dict['ds'] = row_dict['ds'].strftime('%Y-%m-%d')
|
# row_dict['ds'] = row_dict['ds'].strftime('%Y-%m-%d')
|
||||||
elif not isinstance(row_dict['ds'], str):
|
# elif not isinstance(row_dict['ds'], str):
|
||||||
try:
|
# try:
|
||||||
row_dict['ds'] = pd.to_datetime(
|
# row_dict['ds'] = pd.to_datetime(
|
||||||
row_dict['ds']).strftime('%Y-%m-%d')
|
# row_dict['ds']).strftime('%Y-%m-%d')
|
||||||
except:
|
# except:
|
||||||
logger.warning(f"无法解析的时间格式: {row_dict['ds']}")
|
# logger.warning(f"无法解析的时间格式: {row_dict['ds']}")
|
||||||
# row_dict['ds'] = row_dict['ds'].strftime('%Y-%m-%d')
|
# # row_dict['ds'] = row_dict['ds'].strftime('%Y-%m-%d')
|
||||||
# row_dict['ds'] = row_dict['ds'].strftime('%Y-%m-%d %H:%M:%S')
|
# # row_dict['ds'] = row_dict['ds'].strftime('%Y-%m-%d %H:%M:%S')
|
||||||
check_query = sqlitedb.select_data(
|
# check_query = sqlitedb.select_data(
|
||||||
'trueandpredict', where_condition=f"ds = '{row.ds}'")
|
# 'trueandpredict', where_condition=f"ds = '{row.ds}'")
|
||||||
if len(check_query) > 0:
|
# if len(check_query) > 0:
|
||||||
set_clause = ", ".join(
|
# set_clause = ", ".join(
|
||||||
[f"{key} = '{value}'" for key, value in row_dict.items()])
|
# [f"{key} = '{value}'" for key, value in row_dict.items()])
|
||||||
sqlitedb.update_data(
|
# sqlitedb.update_data(
|
||||||
'trueandpredict', set_clause, where_condition=f"ds = '{row.ds}'")
|
# 'trueandpredict', set_clause, where_condition=f"ds = '{row.ds}'")
|
||||||
continue
|
# continue
|
||||||
sqlitedb.insert_data('trueandpredict', tuple(
|
# sqlitedb.insert_data('trueandpredict', tuple(
|
||||||
row_dict.values()), columns=row_dict.keys())
|
# row_dict.values()), columns=row_dict.keys())
|
||||||
|
|
||||||
# 更新accuracy表的y值
|
# # 更新accuracy表的y值
|
||||||
if not sqlitedb.check_table_exists('accuracy'):
|
# if not sqlitedb.check_table_exists('accuracy'):
|
||||||
pass
|
# pass
|
||||||
else:
|
# else:
|
||||||
update_y = sqlitedb.select_data(
|
# update_y = sqlitedb.select_data(
|
||||||
'accuracy', where_condition="y is null")
|
# 'accuracy', where_condition="y is null")
|
||||||
if len(update_y) > 0:
|
# if len(update_y) > 0:
|
||||||
logger.info('更新accuracy表的y值')
|
# logger.info('更新accuracy表的y值')
|
||||||
# 找到update_y 中ds且df中的y的行
|
# # 找到update_y 中ds且df中的y的行
|
||||||
update_y = update_y[update_y['ds'] <= end_time]
|
# update_y = update_y[update_y['ds'] <= end_time]
|
||||||
logger.info(f'要更新y的信息:{update_y}')
|
# logger.info(f'要更新y的信息:{update_y}')
|
||||||
# try:
|
# # try:
|
||||||
for row in update_y.itertuples(index=False):
|
# for row in update_y.itertuples(index=False):
|
||||||
try:
|
# try:
|
||||||
row_dict = row._asdict()
|
# row_dict = row._asdict()
|
||||||
yy = df[df['ds'] == row_dict['ds']]['y'].values[0]
|
# yy = df[df['ds'] == row_dict['ds']]['y'].values[0]
|
||||||
LOW = df[df['ds'] == row_dict['ds']]['Brentzdj'].values[0]
|
# LOW = df[df['ds'] == row_dict['ds']]['Brentzdj'].values[0]
|
||||||
HIGH = df[df['ds'] == row_dict['ds']]['Brentzgj'].values[0]
|
# HIGH = df[df['ds'] == row_dict['ds']]['Brentzgj'].values[0]
|
||||||
sqlitedb.update_data(
|
# sqlitedb.update_data(
|
||||||
'accuracy', f"y = {yy},LOW_PRICE = {LOW},HIGH_PRICE = {HIGH}", where_condition=f"ds = '{row_dict['ds']}'")
|
# 'accuracy', f"y = {yy},LOW_PRICE = {LOW},HIGH_PRICE = {HIGH}", where_condition=f"ds = '{row_dict['ds']}'")
|
||||||
except:
|
# except:
|
||||||
logger.info(f'更新accuracy表的y值失败:{row_dict}')
|
# logger.info(f'更新accuracy表的y值失败:{row_dict}')
|
||||||
# except Exception as e:
|
# # except Exception as e:
|
||||||
# logger.info(f'更新accuracy表的y值失败:{e}')
|
# # logger.info(f'更新accuracy表的y值失败:{e}')
|
||||||
|
|
||||||
# 判断当前日期是不是周一
|
# # 判断当前日期是不是周一
|
||||||
is_weekday = datetime.datetime.now().weekday() == 0
|
# is_weekday = datetime.datetime.now().weekday() == 0
|
||||||
if is_weekday:
|
# if is_weekday:
|
||||||
logger.info('今天是周一,更新预测模型')
|
# logger.info('今天是周一,更新预测模型')
|
||||||
# 计算最近60天预测残差最低的模型名称
|
# # 计算最近60天预测残差最低的模型名称
|
||||||
model_results = sqlitedb.select_data(
|
# model_results = sqlitedb.select_data(
|
||||||
'trueandpredict', order_by="ds DESC", limit="60")
|
# 'trueandpredict', order_by="ds DESC", limit="60")
|
||||||
# 删除空值率为90%以上的列
|
# # 删除空值率为90%以上的列
|
||||||
if len(model_results) > 10:
|
# if len(model_results) > 10:
|
||||||
model_results = model_results.dropna(
|
# model_results = model_results.dropna(
|
||||||
thresh=len(model_results)*0.1, axis=1)
|
# thresh=len(model_results)*0.1, axis=1)
|
||||||
# 删除空行
|
# # 删除空行
|
||||||
model_results = model_results.dropna()
|
# model_results = model_results.dropna()
|
||||||
modelnames = model_results.columns.to_list()[2:-1]
|
# modelnames = model_results.columns.to_list()[2:-1]
|
||||||
for col in model_results[modelnames].select_dtypes(include=['object']).columns:
|
# for col in model_results[modelnames].select_dtypes(include=['object']).columns:
|
||||||
model_results[col] = model_results[col].astype(np.float32)
|
# model_results[col] = model_results[col].astype(np.float32)
|
||||||
# 计算每个预测值与真实值之间的偏差率
|
# # 计算每个预测值与真实值之间的偏差率
|
||||||
for model in modelnames:
|
# for model in modelnames:
|
||||||
model_results[f'{model}_abs_error_rate'] = abs(
|
# model_results[f'{model}_abs_error_rate'] = abs(
|
||||||
model_results['y'] - model_results[model]) / model_results['y']
|
# model_results['y'] - model_results[model]) / model_results['y']
|
||||||
# 获取每行对应的最小偏差率值
|
# # 获取每行对应的最小偏差率值
|
||||||
min_abs_error_rate_values = model_results.apply(
|
# min_abs_error_rate_values = model_results.apply(
|
||||||
lambda row: row[[f'{model}_abs_error_rate' for model in modelnames]].min(), axis=1)
|
# lambda row: row[[f'{model}_abs_error_rate' for model in modelnames]].min(), axis=1)
|
||||||
# 获取每行对应的最小偏差率值对应的列名
|
# # 获取每行对应的最小偏差率值对应的列名
|
||||||
min_abs_error_rate_column_name = model_results.apply(
|
# min_abs_error_rate_column_name = model_results.apply(
|
||||||
lambda row: row[[f'{model}_abs_error_rate' for model in modelnames]].idxmin(), axis=1)
|
# lambda row: row[[f'{model}_abs_error_rate' for model in modelnames]].idxmin(), axis=1)
|
||||||
# 将列名索引转换为列名
|
# # 将列名索引转换为列名
|
||||||
min_abs_error_rate_column_name = min_abs_error_rate_column_name.map(
|
# min_abs_error_rate_column_name = min_abs_error_rate_column_name.map(
|
||||||
lambda x: x.split('_')[0])
|
# lambda x: x.split('_')[0])
|
||||||
# 取出现次数最多的模型名称
|
# # 取出现次数最多的模型名称
|
||||||
most_common_model = min_abs_error_rate_column_name.value_counts().idxmax()
|
# most_common_model = min_abs_error_rate_column_name.value_counts().idxmax()
|
||||||
logger.info(f"最近60天预测残差最低的模型名称:{most_common_model}")
|
# logger.info(f"最近60天预测残差最低的模型名称:{most_common_model}")
|
||||||
# 保存结果到数据库
|
# # 保存结果到数据库
|
||||||
if not sqlitedb.check_table_exists('most_model'):
|
# if not sqlitedb.check_table_exists('most_model'):
|
||||||
sqlitedb.create_table(
|
# sqlitedb.create_table(
|
||||||
'most_model', columns="ds datetime, most_common_model TEXT")
|
# 'most_model', columns="ds datetime, most_common_model TEXT")
|
||||||
sqlitedb.insert_data('most_model', (datetime.datetime.now().strftime(
|
# sqlitedb.insert_data('most_model', (datetime.datetime.now().strftime(
|
||||||
'%Y-%m-%d %H:%M:%S'), most_common_model,), columns=('ds', 'most_common_model',))
|
# '%Y-%m-%d %H:%M:%S'), most_common_model,), columns=('ds', 'most_common_model',))
|
||||||
|
|
||||||
if is_corr:
|
# if is_corr:
|
||||||
df = corr_feature(df=df)
|
# df = corr_feature(df=df)
|
||||||
|
|
||||||
df1 = df.copy() # 备份一下,后面特征筛选完之后加入ds y 列用
|
# df1 = df.copy() # 备份一下,后面特征筛选完之后加入ds y 列用
|
||||||
logger.info(f"开始训练模型...")
|
# logger.info(f"开始训练模型...")
|
||||||
row, col = df.shape
|
# row, col = df.shape
|
||||||
|
|
||||||
now = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
|
# now = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
|
||||||
ex_Model(df,
|
# ex_Model(df,
|
||||||
horizon=global_config['horizon'],
|
# horizon=global_config['horizon'],
|
||||||
input_size=global_config['input_size'],
|
# input_size=global_config['input_size'],
|
||||||
train_steps=global_config['train_steps'],
|
# train_steps=global_config['train_steps'],
|
||||||
val_check_steps=global_config['val_check_steps'],
|
# val_check_steps=global_config['val_check_steps'],
|
||||||
early_stop_patience_steps=global_config['early_stop_patience_steps'],
|
# early_stop_patience_steps=global_config['early_stop_patience_steps'],
|
||||||
is_debug=global_config['is_debug'],
|
# is_debug=global_config['is_debug'],
|
||||||
dataset=global_config['dataset'],
|
# dataset=global_config['dataset'],
|
||||||
is_train=global_config['is_train'],
|
# is_train=global_config['is_train'],
|
||||||
is_fivemodels=global_config['is_fivemodels'],
|
# is_fivemodels=global_config['is_fivemodels'],
|
||||||
val_size=global_config['val_size'],
|
# val_size=global_config['val_size'],
|
||||||
test_size=global_config['test_size'],
|
# test_size=global_config['test_size'],
|
||||||
settings=global_config['settings'],
|
# settings=global_config['settings'],
|
||||||
now=now,
|
# now=now,
|
||||||
etadata=etadata,
|
# etadata=etadata,
|
||||||
modelsindex=global_config['modelsindex'],
|
# modelsindex=global_config['modelsindex'],
|
||||||
data=data,
|
# data=data,
|
||||||
is_eta=global_config['is_eta'],
|
# is_eta=global_config['is_eta'],
|
||||||
end_time=global_config['end_time'],
|
# end_time=global_config['end_time'],
|
||||||
)
|
# )
|
||||||
|
|
||||||
logger.info('模型训练完成')
|
# logger.info('模型训练完成')
|
||||||
|
|
||||||
logger.info('训练数据绘图ing')
|
# logger.info('训练数据绘图ing')
|
||||||
model_results3 = model_losss_juxiting(
|
# model_results3 = model_losss_juxiting(
|
||||||
sqlitedb, end_time=global_config['end_time'], is_fivemodels=global_config['is_fivemodels'])
|
# sqlitedb, end_time=global_config['end_time'], is_fivemodels=global_config['is_fivemodels'])
|
||||||
logger.info('训练数据绘图end')
|
# logger.info('训练数据绘图end')
|
||||||
|
|
||||||
push_market_value()
|
# push_market_value()
|
||||||
|
|
||||||
sql_inset_predict(global_config)
|
# sql_inset_predict(global_config)
|
||||||
|
|
||||||
# 模型报告
|
# # 模型报告
|
||||||
logger.info('制作报告ing')
|
# logger.info('制作报告ing')
|
||||||
title = f'{settings}--{end_time}-预测报告' # 报告标题
|
# title = f'{settings}--{end_time}-预测报告' # 报告标题
|
||||||
reportname = f'聚烯烃PP大模型月度预测--{end_time}.pdf' # 报告文件名
|
# reportname = f'聚烯烃PP大模型月度预测--{end_time}.pdf' # 报告文件名
|
||||||
reportname = reportname.replace(':', '-') # 替换冒号
|
# reportname = reportname.replace(':', '-') # 替换冒号
|
||||||
pp_export_pdf(dataset=dataset, num_models=5 if is_fivemodels else 22, time=end_time,
|
# pp_export_pdf(dataset=dataset, num_models=5 if is_fivemodels else 22, time=end_time,
|
||||||
reportname=reportname, sqlitedb=sqlitedb),
|
# reportname=reportname, sqlitedb=sqlitedb),
|
||||||
|
|
||||||
logger.info('制作报告end')
|
# logger.info('制作报告end')
|
||||||
|
|
||||||
# 图片报告
|
# 图片报告
|
||||||
logger.info('图片报告ing')
|
logger.info('图片报告ing')
|
||||||
@ -538,6 +531,7 @@ if __name__ == '__main__':
|
|||||||
# continue
|
# continue
|
||||||
|
|
||||||
predict_main()
|
predict_main()
|
||||||
|
# push_market_value()
|
||||||
|
|
||||||
# 图片报告
|
# 图片报告
|
||||||
# global_config['end_time'] = '2025-07-31'
|
# global_config['end_time'] = '2025-07-31'
|
||||||
|
@ -2,8 +2,8 @@
|
|||||||
|
|
||||||
from lib.dataread import *
|
from lib.dataread import *
|
||||||
from config_juxiting_zhoudu import *
|
from config_juxiting_zhoudu import *
|
||||||
from lib.tools import SendMail, exception_logger, convert_df_to_pydantic_pp, exception_logger, get_modelsname
|
from lib.tools import SendMail, exception_logger, convert_df_to_pydantic_pp, exception_logger, find_best_models, get_modelsname
|
||||||
from models.nerulforcastmodels import ex_Model_Juxiting, model_losss_juxiting, pp_bdwd_png, pp_export_pdf
|
from models.nerulforcastmodels import ex_Model_Juxiting, model_losss_juxiting, pp_export_pdf
|
||||||
import datetime
|
import datetime
|
||||||
import torch
|
import torch
|
||||||
torch.set_float32_matmul_precision("high")
|
torch.set_float32_matmul_precision("high")
|
||||||
@ -23,7 +23,6 @@ global_config.update({
|
|||||||
'is_update_report': is_update_report,
|
'is_update_report': is_update_report,
|
||||||
'settings': settings,
|
'settings': settings,
|
||||||
'bdwdname': bdwdname,
|
'bdwdname': bdwdname,
|
||||||
'columnsrename': columnsrename,
|
|
||||||
'price_columns': price_columns,
|
'price_columns': price_columns,
|
||||||
|
|
||||||
|
|
||||||
@ -102,32 +101,26 @@ global_config.update({
|
|||||||
|
|
||||||
def push_market_value():
|
def push_market_value():
|
||||||
config.logger.info('发送预测结果到市场信息平台')
|
config.logger.info('发送预测结果到市场信息平台')
|
||||||
|
|
||||||
|
current_end_time = global_config['end_time']
|
||||||
|
previous_trading_day = (pd.Timestamp(current_end_time) -
|
||||||
|
pd.tseries.offsets.BusinessDay(1)).strftime('%Y-%m-%d')
|
||||||
|
|
||||||
# 读取预测数据和模型评估数据
|
# 读取预测数据和模型评估数据
|
||||||
predict_file_path = os.path.join(config.dataset, 'predict.csv')
|
best_bdwd_price = find_best_models(
|
||||||
model_eval_file_path = os.path.join(config.dataset, 'model_evaluation.csv')
|
date=previous_trading_day, global_config=global_config)
|
||||||
try:
|
|
||||||
predictdata_df = pd.read_csv(predict_file_path)
|
|
||||||
top_models_df = pd.read_csv(model_eval_file_path)
|
|
||||||
except FileNotFoundError as e:
|
|
||||||
config.logger.error(f"文件未找到: {e}")
|
|
||||||
return
|
|
||||||
|
|
||||||
predictdata = predictdata_df.copy()
|
# 获取次周,隔周 最佳模型的预测价格
|
||||||
|
weeks_predict_price = pd.read_csv(os.path.join(global_config['dataset'], 'predict.csv'))
|
||||||
# 取模型前十
|
weeks_predict_price['ds'] = pd.to_datetime(weeks_predict_price['ds'])
|
||||||
top_models = top_models_df['模型(Model)'].head(10).tolist()
|
# 设置索引 次周 隔周
|
||||||
# 去掉FDBformer
|
index_labels = ["次周", "隔周"]
|
||||||
if 'FEDformer' in top_models:
|
weeks_predict_price.index = index_labels
|
||||||
top_models.remove('FEDformer')
|
global_config['logger'].info(f"best_bdwd_price: {best_bdwd_price}")
|
||||||
# 计算前十模型的均值
|
|
||||||
predictdata_df['top_models_mean'] = predictdata_df[top_models].mean(axis=1)
|
|
||||||
|
|
||||||
# 打印日期和前十模型均值
|
|
||||||
print(predictdata_df[['ds', 'top_models_mean']])
|
|
||||||
|
|
||||||
# 准备要推送的数据
|
# 准备要推送的数据
|
||||||
first_mean = predictdata_df['top_models_mean'].iloc[0]
|
first_mean = weeks_predict_price[best_bdwd_price['second_week_price']['model_name']].iloc[0]
|
||||||
last_mean = predictdata_df['top_models_mean'].iloc[-1]
|
last_mean = weeks_predict_price[best_bdwd_price['next_week_price']['model_name']].iloc[-1]
|
||||||
# 保留两位小数
|
# 保留两位小数
|
||||||
first_mean = round(first_mean, 2)
|
first_mean = round(first_mean, 2)
|
||||||
last_mean = round(last_mean, 2)
|
last_mean = round(last_mean, 2)
|
||||||
@ -472,9 +465,6 @@ def predict_main():
|
|||||||
# sqlitedb, end_time=global_config['end_time'], is_fivemodels=global_config['is_fivemodels'])
|
# sqlitedb, end_time=global_config['end_time'], is_fivemodels=global_config['is_fivemodels'])
|
||||||
# logger.info('训练数据绘图end')
|
# logger.info('训练数据绘图end')
|
||||||
|
|
||||||
push_market_value()
|
|
||||||
sql_inset_predict(global_config)
|
|
||||||
|
|
||||||
# # # 模型报告
|
# # # 模型报告
|
||||||
# logger.info('制作报告ing')
|
# logger.info('制作报告ing')
|
||||||
# title = f'{settings}--{end_time}-预测报告' # 报告标题
|
# title = f'{settings}--{end_time}-预测报告' # 报告标题
|
||||||
@ -485,10 +475,8 @@ def predict_main():
|
|||||||
|
|
||||||
# logger.info('制作报告end')
|
# logger.info('制作报告end')
|
||||||
|
|
||||||
# 图片报告
|
push_market_value()
|
||||||
logger.info('图片报告ing')
|
sql_inset_predict(global_config)
|
||||||
pp_bdwd_png(global_config=global_config)
|
|
||||||
logger.info('图片报告end')
|
|
||||||
|
|
||||||
# # LSTM 单变量模型
|
# # LSTM 单变量模型
|
||||||
# ex_Lstm(df,input_seq_len=input_size,output_seq_len=horizon,is_debug=is_debug,dataset=dataset)
|
# ex_Lstm(df,input_seq_len=input_size,output_seq_len=horizon,is_debug=is_debug,dataset=dataset)
|
||||||
@ -515,7 +503,7 @@ def predict_main():
|
|||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
# global end_time
|
# global end_time
|
||||||
# 遍历2024-11-25 到 2024-12-3 之间的工作日日期
|
# 遍历2024-11-25 到 2024-12-3 之间的工作日日期
|
||||||
# for i_time in pd.date_range('2025-7-18', '2025-7-23', freq='B'):
|
# for i_time in pd.date_range('2025-7-28', '2025-7-28', freq='B'):
|
||||||
# try:
|
# try:
|
||||||
# global_config['end_time'] = i_time.strftime('%Y-%m-%d')
|
# global_config['end_time'] = i_time.strftime('%Y-%m-%d')
|
||||||
# global_config['db_mysql'].connect()
|
# global_config['db_mysql'].connect()
|
||||||
|
Loading…
Reference in New Issue
Block a user