2024-11-08 11:18:40 +08:00
|
|
|
|
# 读取配置
|
2024-11-01 16:38:21 +08:00
|
|
|
|
from lib.dataread import *
|
2024-12-18 17:49:23 +08:00
|
|
|
|
from lib.tools import SendMail,exception_logger
|
2024-11-22 13:26:10 +08:00
|
|
|
|
from models.nerulforcastmodels import ex_Model,model_losss,model_losss_juxiting,brent_export_pdf,tansuanli_export_pdf,pp_export_pdf,model_losss_juxiting
|
2024-11-01 16:38:21 +08:00
|
|
|
|
|
|
|
|
|
import glob
|
|
|
|
|
import torch
|
|
|
|
|
torch.set_float32_matmul_precision("high")
|
|
|
|
|
|
|
|
|
|
|
2024-11-19 13:27:57 +08:00
|
|
|
|
|
2024-12-19 14:05:16 +08:00
|
|
|
|
def predict_main():
|
2024-11-19 13:27:57 +08:00
|
|
|
|
"""
|
|
|
|
|
主预测函数,用于从 ETA 获取数据、处理数据、训练模型并进行预测。
|
|
|
|
|
|
|
|
|
|
参数:
|
|
|
|
|
signature (BinanceAPI): Binance API 实例。
|
|
|
|
|
etadata (EtaReader): ETA 数据读取器实例。
|
|
|
|
|
is_eta (bool): 是否从 ETA 获取数据。
|
|
|
|
|
data_set (str): 数据集名称。
|
|
|
|
|
dataset (str): 数据集路径。
|
|
|
|
|
add_kdj (bool): 是否添加 KDJ 指标。
|
|
|
|
|
is_timefurture (bool): 是否添加时间衍生特征。
|
|
|
|
|
end_time (str): 结束时间。
|
|
|
|
|
is_edbnamelist (bool): 是否使用 EDB 名称列表。
|
|
|
|
|
edbnamelist (list): EDB 名称列表。
|
|
|
|
|
y (str): 预测目标列名。
|
|
|
|
|
sqlitedb (SQLiteDB): SQLite 数据库实例。
|
|
|
|
|
is_corr (bool): 是否进行相关性分析。
|
|
|
|
|
horizon (int): 预测时域。
|
|
|
|
|
input_size (int): 输入数据大小。
|
|
|
|
|
train_steps (int): 训练步数。
|
|
|
|
|
val_check_steps (int): 验证检查步数。
|
|
|
|
|
early_stop_patience_steps (int): 早停耐心步数。
|
|
|
|
|
is_debug (bool): 是否调试模式。
|
|
|
|
|
dataset (str): 数据集名称。
|
|
|
|
|
is_train (bool): 是否训练模型。
|
|
|
|
|
is_fivemodels (bool): 是否使用五个模型。
|
|
|
|
|
val_size (float): 验证集大小。
|
|
|
|
|
test_size (float): 测试集大小。
|
|
|
|
|
settings (dict): 模型设置。
|
|
|
|
|
now (str): 当前时间。
|
|
|
|
|
etadata (EtaReader): ETA 数据读取器实例。
|
|
|
|
|
modelsindex (list): 模型索引列表。
|
|
|
|
|
data (str): 数据类型。
|
|
|
|
|
is_eta (bool): 是否从 ETA 获取数据。
|
|
|
|
|
|
|
|
|
|
返回:
|
|
|
|
|
None
|
|
|
|
|
"""
|
2024-12-24 15:10:18 +08:00
|
|
|
|
global end_time
|
2024-11-01 16:38:21 +08:00
|
|
|
|
signature = BinanceAPI(APPID, SECRET)
|
|
|
|
|
etadata = EtaReader(signature=signature,
|
2024-11-19 13:27:57 +08:00
|
|
|
|
classifylisturl=classifylisturl,
|
|
|
|
|
classifyidlisturl=classifyidlisturl,
|
|
|
|
|
edbcodedataurl=edbcodedataurl,
|
|
|
|
|
edbcodelist=edbcodelist,
|
|
|
|
|
edbdatapushurl=edbdatapushurl,
|
|
|
|
|
edbdeleteurl=edbdeleteurl,
|
|
|
|
|
edbbusinessurl=edbbusinessurl
|
|
|
|
|
)
|
|
|
|
|
# 获取数据
|
|
|
|
|
if is_eta:
|
|
|
|
|
logger.info('从eta获取数据...')
|
|
|
|
|
signature = BinanceAPI(APPID, SECRET)
|
|
|
|
|
etadata = EtaReader(signature=signature,
|
|
|
|
|
classifylisturl=classifylisturl,
|
2024-11-01 16:38:21 +08:00
|
|
|
|
classifyidlisturl=classifyidlisturl,
|
|
|
|
|
edbcodedataurl=edbcodedataurl,
|
|
|
|
|
edbcodelist=edbcodelist,
|
|
|
|
|
edbdatapushurl=edbdatapushurl,
|
|
|
|
|
edbdeleteurl=edbdeleteurl,
|
2024-11-19 13:27:57 +08:00
|
|
|
|
edbbusinessurl=edbbusinessurl,
|
2024-11-01 16:38:21 +08:00
|
|
|
|
)
|
2024-11-19 13:27:57 +08:00
|
|
|
|
df_zhibiaoshuju, df_zhibiaoliebiao = etadata.get_eta_api_yuanyou_data(data_set=data_set, dataset=dataset) # 原始数据,未处理
|
2024-11-01 16:38:21 +08:00
|
|
|
|
|
2024-12-26 14:33:31 +08:00
|
|
|
|
if is_market:
|
|
|
|
|
logger.info('从市场信息平台获取数据...')
|
2024-12-26 15:58:14 +08:00
|
|
|
|
try:
|
|
|
|
|
df_zhibiaoshuju = get_market_data(end_time,df_zhibiaoshuju)
|
|
|
|
|
except :
|
|
|
|
|
logger.info('从市场信息平台获取数据失败')
|
|
|
|
|
|
|
|
|
|
# 保存到xlsx文件的sheet表
|
|
|
|
|
with pd.ExcelWriter(os.path.join(dataset,data_set)) as file:
|
|
|
|
|
df_zhibiaoshuju.to_excel(file, sheet_name='指标数据', index=False)
|
|
|
|
|
df_zhibiaoliebiao.to_excel(file, sheet_name='指标列表', index=False)
|
|
|
|
|
|
2024-12-26 14:33:31 +08:00
|
|
|
|
|
2024-11-01 16:38:21 +08:00
|
|
|
|
# 数据处理
|
2024-11-19 13:27:57 +08:00
|
|
|
|
df = datachuli(df_zhibiaoshuju, df_zhibiaoliebiao, y=y, dataset=dataset, add_kdj=add_kdj, is_timefurture=is_timefurture,
|
|
|
|
|
end_time=end_time)
|
2024-11-01 16:38:21 +08:00
|
|
|
|
|
|
|
|
|
else:
|
2024-11-14 10:21:25 +08:00
|
|
|
|
# 读取数据
|
2024-11-19 13:27:57 +08:00
|
|
|
|
logger.info('读取本地数据:' + os.path.join(dataset, data_set))
|
2024-12-03 14:56:06 +08:00
|
|
|
|
df,df_zhibiaoliebiao = getdata(filename=os.path.join(dataset, data_set), y=y, dataset=dataset, add_kdj=add_kdj,
|
2024-11-19 13:27:57 +08:00
|
|
|
|
is_timefurture=is_timefurture, end_time=end_time) # 原始数据,未处理
|
|
|
|
|
|
2024-11-01 16:38:21 +08:00
|
|
|
|
# 更改预测列名称
|
2024-11-19 13:27:57 +08:00
|
|
|
|
df.rename(columns={y: 'y'}, inplace=True)
|
|
|
|
|
|
2024-11-01 16:38:21 +08:00
|
|
|
|
if is_edbnamelist:
|
2024-11-19 13:27:57 +08:00
|
|
|
|
df = df[edbnamelist]
|
|
|
|
|
df.to_csv(os.path.join(dataset, '指标数据.csv'), index=False)
|
2024-11-01 16:38:21 +08:00
|
|
|
|
# 保存最新日期的y值到数据库
|
|
|
|
|
# 取第一行数据存储到数据库中
|
2024-11-19 13:27:57 +08:00
|
|
|
|
first_row = df[['ds', 'y']].tail(1)
|
2024-12-27 14:15:20 +08:00
|
|
|
|
print(first_row['ds'].values[0])
|
|
|
|
|
print(first_row['y'].values[0])
|
|
|
|
|
# 判断y的类型是否为float
|
|
|
|
|
if not isinstance(first_row['y'].values[0], float):
|
2024-12-26 14:33:31 +08:00
|
|
|
|
logger.info(f'{end_time}预测目标数据为空,跳过')
|
|
|
|
|
return None
|
2024-12-27 14:15:20 +08:00
|
|
|
|
|
2024-11-01 16:38:21 +08:00
|
|
|
|
# 将最新真实值保存到数据库
|
|
|
|
|
if not sqlitedb.check_table_exists('trueandpredict'):
|
2024-11-19 13:27:57 +08:00
|
|
|
|
first_row.to_sql('trueandpredict', sqlitedb.connection, index=False)
|
2024-11-01 16:38:21 +08:00
|
|
|
|
else:
|
|
|
|
|
for row in first_row.itertuples(index=False):
|
|
|
|
|
row_dict = row._asdict()
|
2024-11-05 15:38:14 +08:00
|
|
|
|
row_dict['ds'] = row_dict['ds'].strftime('%Y-%m-%d %H:%M:%S')
|
2024-11-19 13:27:57 +08:00
|
|
|
|
check_query = sqlitedb.select_data('trueandpredict', where_condition=f"ds = '{row.ds}'")
|
2024-11-01 16:38:21 +08:00
|
|
|
|
if len(check_query) > 0:
|
|
|
|
|
set_clause = ", ".join([f"{key} = '{value}'" for key, value in row_dict.items()])
|
2024-11-19 13:27:57 +08:00
|
|
|
|
sqlitedb.update_data('trueandpredict', set_clause, where_condition=f"ds = '{row.ds}'")
|
2024-11-01 16:38:21 +08:00
|
|
|
|
continue
|
2024-11-19 13:27:57 +08:00
|
|
|
|
sqlitedb.insert_data('trueandpredict', tuple(row_dict.values()), columns=row_dict.keys())
|
2024-11-01 16:38:21 +08:00
|
|
|
|
|
2024-12-25 16:13:22 +08:00
|
|
|
|
# 更新accuracy表的y值
|
|
|
|
|
if not sqlitedb.check_table_exists('accuracy'):
|
|
|
|
|
pass
|
|
|
|
|
else:
|
|
|
|
|
update_y = sqlitedb.select_data('accuracy',where_condition="y is null")
|
|
|
|
|
if len(update_y) > 0:
|
|
|
|
|
logger.info('更新accuracy表的y值')
|
|
|
|
|
# 找到update_y 中ds且df中的y的行
|
|
|
|
|
update_y = update_y[update_y['ds']<=end_time]
|
2024-12-27 14:15:20 +08:00
|
|
|
|
logger.info(f'要更新y的信息:{update_y}')
|
|
|
|
|
try:
|
|
|
|
|
for row in update_y.itertuples(index=False):
|
|
|
|
|
row_dict = row._asdict()
|
|
|
|
|
yy = df[df['ds']==row_dict['ds']]['y'].values[0]
|
|
|
|
|
LOW = df[df['ds']==row_dict['ds']]['Brentzdj'].values[0]
|
|
|
|
|
HIGH = df[df['ds']==row_dict['ds']]['Brentzgj'].values[0]
|
|
|
|
|
sqlitedb.update_data('accuracy', f"y = {yy},LOW_PRICE = {LOW},HIGH_PRICE = {HIGH}", where_condition=f"ds = '{row_dict['ds']}'")
|
|
|
|
|
except Exception as e:
|
|
|
|
|
logger.info(f'更新accuracy表的y值失败:{e}')
|
2024-12-25 16:13:22 +08:00
|
|
|
|
|
2024-11-01 16:38:21 +08:00
|
|
|
|
import datetime
|
|
|
|
|
# 判断当前日期是不是周一
|
2024-11-08 11:18:40 +08:00
|
|
|
|
is_weekday = datetime.datetime.now().weekday() == 0
|
2024-12-11 14:52:45 +08:00
|
|
|
|
if is_weekday:
|
|
|
|
|
logger.info('今天是周一,更新预测模型')
|
|
|
|
|
# 计算最近60天预测残差最低的模型名称
|
|
|
|
|
model_results = sqlitedb.select_data('trueandpredict', order_by="ds DESC", limit="60")
|
|
|
|
|
# 删除空值率为40%以上的列
|
|
|
|
|
if len(model_results) > 10:
|
|
|
|
|
model_results = model_results.dropna(thresh=len(model_results)*0.6,axis=1)
|
|
|
|
|
# 删除空行
|
|
|
|
|
model_results = model_results.dropna()
|
|
|
|
|
modelnames = model_results.columns.to_list()[2:]
|
|
|
|
|
for col in model_results[modelnames].select_dtypes(include=['object']).columns:
|
|
|
|
|
model_results[col] = model_results[col].astype(np.float32)
|
|
|
|
|
# 计算每个预测值与真实值之间的偏差率
|
|
|
|
|
for model in modelnames:
|
|
|
|
|
model_results[f'{model}_abs_error_rate'] = abs(model_results['y'] - model_results[model]) / model_results['y']
|
|
|
|
|
# 获取每行对应的最小偏差率值
|
|
|
|
|
min_abs_error_rate_values = model_results.apply(lambda row: row[[f'{model}_abs_error_rate' for model in modelnames]].min(), axis=1)
|
|
|
|
|
# 获取每行对应的最小偏差率值对应的列名
|
|
|
|
|
min_abs_error_rate_column_name = model_results.apply(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(lambda x: x.split('_')[0])
|
|
|
|
|
# 取出现次数最多的模型名称
|
|
|
|
|
most_common_model = min_abs_error_rate_column_name.value_counts().idxmax()
|
|
|
|
|
logger.info(f"最近60天预测残差最低的模型名称:{most_common_model}")
|
|
|
|
|
# 保存结果到数据库
|
|
|
|
|
if not sqlitedb.check_table_exists('most_model'):
|
|
|
|
|
sqlitedb.create_table('most_model', columns="ds datetime, most_common_model TEXT")
|
|
|
|
|
sqlitedb.insert_data('most_model', (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), most_common_model,), columns=('ds', 'most_common_model',))
|
2024-11-01 16:38:21 +08:00
|
|
|
|
|
2024-12-03 14:57:47 +08:00
|
|
|
|
try:
|
2024-12-11 15:54:57 +08:00
|
|
|
|
if is_weekday:
|
|
|
|
|
# if True:
|
2024-12-05 16:35:37 +08:00
|
|
|
|
logger.info('今天是周一,发送特征预警')
|
2024-12-03 14:57:47 +08:00
|
|
|
|
# 上传预警信息到数据库
|
|
|
|
|
warning_data_df = df_zhibiaoliebiao.copy()
|
|
|
|
|
warning_data_df = warning_data_df[warning_data_df['停更周期']> 3 ][['指标名称', '指标id', '频度','更新周期','指标来源','最后更新时间','停更周期']]
|
|
|
|
|
# 重命名列名
|
|
|
|
|
warning_data_df = warning_data_df.rename(columns={'指标名称': 'INDICATOR_NAME', '指标id': 'INDICATOR_ID', '频度': 'FREQUENCY', '更新周期': 'UPDATE_FREQUENCY', '指标来源': 'DATA_SOURCE', '最后更新时间': 'LAST_UPDATE_DATE', '停更周期': 'UPDATE_SUSPENSION_CYCLE'})
|
|
|
|
|
from sqlalchemy import create_engine
|
2024-12-11 14:52:45 +08:00
|
|
|
|
import urllib
|
|
|
|
|
global password
|
|
|
|
|
if '@' in password:
|
|
|
|
|
password = urllib.parse.quote_plus(password)
|
|
|
|
|
|
2024-12-03 14:57:47 +08:00
|
|
|
|
engine = create_engine(f'mysql+pymysql://{dbusername}:{password}@{host}:{port}/{dbname}')
|
2024-12-05 15:02:09 +08:00
|
|
|
|
warning_data_df['WARNING_DATE'] = datetime.date.today().strftime("%Y-%m-%d %H:%M:%S")
|
|
|
|
|
warning_data_df['TENANT_CODE'] = 'T0004'
|
2024-12-03 14:57:47 +08:00
|
|
|
|
# 插入数据之前查询表数据然后新增id列
|
|
|
|
|
existing_data = pd.read_sql(f"SELECT * FROM {table_name}", engine)
|
|
|
|
|
if not existing_data.empty:
|
2024-12-05 16:35:37 +08:00
|
|
|
|
max_id = existing_data['ID'].astype(int).max()
|
|
|
|
|
warning_data_df['ID'] = range(max_id + 1, max_id + 1 + len(warning_data_df))
|
2024-12-03 14:57:47 +08:00
|
|
|
|
else:
|
2024-12-05 16:35:37 +08:00
|
|
|
|
warning_data_df['ID'] = range(1, 1 + len(warning_data_df))
|
2024-12-03 14:57:47 +08:00
|
|
|
|
warning_data_df.to_sql(table_name, con=engine, if_exists='append', index=False)
|
2024-12-05 16:35:37 +08:00
|
|
|
|
if is_update_warning_data:
|
|
|
|
|
upload_warning_info(len(warning_data_df))
|
2024-12-03 14:57:47 +08:00
|
|
|
|
except:
|
|
|
|
|
logger.info('上传预警信息到数据库失败')
|
2024-12-03 14:56:06 +08:00
|
|
|
|
|
2024-11-01 16:38:21 +08:00
|
|
|
|
if is_corr:
|
|
|
|
|
df = corr_feature(df=df)
|
|
|
|
|
|
|
|
|
|
df1 = df.copy() # 备份一下,后面特征筛选完之后加入ds y 列用
|
|
|
|
|
logger.info(f"开始训练模型...")
|
2024-11-19 13:27:57 +08:00
|
|
|
|
row, col = df.shape
|
|
|
|
|
|
2024-11-01 16:38:21 +08:00
|
|
|
|
now = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
|
2024-12-13 18:25:23 +08:00
|
|
|
|
ex_Model(df,
|
|
|
|
|
horizon=horizon,
|
|
|
|
|
input_size=input_size,
|
|
|
|
|
train_steps=train_steps,
|
|
|
|
|
val_check_steps=val_check_steps,
|
|
|
|
|
early_stop_patience_steps=early_stop_patience_steps,
|
|
|
|
|
is_debug=is_debug,
|
|
|
|
|
dataset=dataset,
|
|
|
|
|
is_train=is_train,
|
|
|
|
|
is_fivemodels=is_fivemodels,
|
|
|
|
|
val_size=val_size,
|
|
|
|
|
test_size=test_size,
|
|
|
|
|
settings=settings,
|
|
|
|
|
now=now,
|
|
|
|
|
etadata=etadata,
|
|
|
|
|
modelsindex=modelsindex,
|
|
|
|
|
data=data,
|
|
|
|
|
is_eta=is_eta,
|
2024-12-24 15:10:18 +08:00
|
|
|
|
end_time=end_time,
|
2024-12-13 18:25:23 +08:00
|
|
|
|
)
|
2024-11-01 16:38:21 +08:00
|
|
|
|
|
2024-11-07 10:45:51 +08:00
|
|
|
|
|
|
|
|
|
logger.info('模型训练完成')
|
2024-12-10 17:01:26 +08:00
|
|
|
|
|
2024-11-07 10:45:51 +08:00
|
|
|
|
logger.info('训练数据绘图ing')
|
2024-12-15 19:43:14 +08:00
|
|
|
|
model_results3 = model_losss(sqlitedb,end_time=end_time)
|
2024-11-07 10:45:51 +08:00
|
|
|
|
logger.info('训练数据绘图end')
|
2024-11-01 16:38:21 +08:00
|
|
|
|
|
2024-11-19 13:27:57 +08:00
|
|
|
|
# 模型报告
|
2024-12-27 14:15:20 +08:00
|
|
|
|
logger.info('制作报告ing')
|
|
|
|
|
title = f'{settings}--{end_time}-预测报告' # 报告标题
|
2024-11-18 10:34:40 +08:00
|
|
|
|
|
2024-12-27 14:15:20 +08:00
|
|
|
|
brent_export_pdf(dataset=dataset,num_models = 5 if is_fivemodels else 22,time=end_time,
|
|
|
|
|
reportname=reportname,sqlitedb=sqlitedb),
|
2024-11-12 18:26:20 +08:00
|
|
|
|
|
2024-12-27 14:15:20 +08:00
|
|
|
|
logger.info('制作报告end')
|
|
|
|
|
logger.info('模型训练完成')
|
2024-11-19 13:27:57 +08:00
|
|
|
|
|
2024-11-01 16:38:21 +08:00
|
|
|
|
# # LSTM 单变量模型
|
|
|
|
|
# ex_Lstm(df,input_seq_len=input_size,output_seq_len=horizon,is_debug=is_debug,dataset=dataset)
|
|
|
|
|
|
|
|
|
|
# # lstm 多变量模型
|
|
|
|
|
# ex_Lstm_M(df,n_days=input_size,out_days=horizon,is_debug=is_debug,datasetpath=dataset)
|
|
|
|
|
|
|
|
|
|
# # GRU 模型
|
|
|
|
|
# # ex_GRU(df)
|
|
|
|
|
|
|
|
|
|
# 发送邮件
|
2024-12-24 15:10:18 +08:00
|
|
|
|
# m = SendMail(
|
|
|
|
|
# username=username,
|
|
|
|
|
# passwd=passwd,
|
|
|
|
|
# recv=recv,
|
|
|
|
|
# title=title,
|
|
|
|
|
# content=content,
|
|
|
|
|
# file=max(glob.glob(os.path.join(dataset,'*.pdf')), key=os.path.getctime),
|
|
|
|
|
# ssl=ssl,
|
|
|
|
|
# )
|
2024-12-18 17:49:23 +08:00
|
|
|
|
# m.send_mail()
|
2024-11-01 16:38:21 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
2024-12-24 15:10:18 +08:00
|
|
|
|
global end_time
|
2024-12-19 14:05:16 +08:00
|
|
|
|
is_on = True
|
2024-12-15 19:43:14 +08:00
|
|
|
|
# 遍历2024-11-25 到 2024-12-3 之间的工作日日期
|
2024-12-27 14:15:20 +08:00
|
|
|
|
for i_time in pd.date_range('2024-12-24', '2024-12-25', freq='B'):
|
2024-12-15 19:43:14 +08:00
|
|
|
|
end_time = i_time.strftime('%Y-%m-%d')
|
2024-12-19 14:05:16 +08:00
|
|
|
|
predict_main()
|