diff --git a/debugdemo.ipynb b/debugdemo.ipynb index da48355..58183b2 100644 --- a/debugdemo.ipynb +++ b/debugdemo.ipynb @@ -147,519 +147,12 @@ "metadata": {}, "outputs": [], "source": [ - "\n", - "import matplotlib.dates as mdates\n", - "\n", - "def brent_export_pdf(num_indicators=475,num_models=21, num_dayindicator=202,inputsize=5,dataset='dataset',time = '2024-07-30',reportname='report.pdf',sqlitedb='jbsh_yuanyou.db'): \n", - " global y\n", - " # 创建内容对应的空列表\n", - " content = list()\n", - " # 获取特征的近一月值\n", - " import pandas as pd\n", - " feature_data_df = pd.read_csv(f'dataset/指标数据添加时间特征.csv', parse_dates=['ds']).tail(20)\n", - " def draw_feature_trend(feature_data_df, features):\n", - " # 画特征近一周的趋势图\n", - " feature_df = feature_data_df[['ds','y']+features]\n", - " # 遍历X每一列,和yy画散点图 ,\n", - " \n", - " for i, col in enumerate(features):\n", - " # try:\n", - " print(f'正在绘制第{i+1}个特征{col}与价格散点图...')\n", - " if col not in ['ds', 'y']:\n", - " fig, ax1 = plt.subplots(figsize=(10, 6))\n", - " # 在第一个坐标轴上绘制数据\n", - " sns.lineplot(data=feature_df, x='ds', y='y', ax=ax1, color='b')\n", - " ax1.set_xlabel('日期')\n", - " ax1.set_ylabel('y', color='b')\n", - " ax1.tick_params('y', colors='b')\n", - " # 在 ax1 上添加文本显示值,添加一定的偏移避免值与曲线重叠\n", - " for j in range(1, len(feature_df), 2):\n", - " value = feature_df['y'].iloc[j]\n", - " date = feature_df['ds'].iloc[j]\n", - " offset = 1.001\n", - " ax1.text(date, value * offset, str(round(value, 2)), ha='center', va='bottom', color='b', fontsize=10)\n", - " # 创建第二个坐标轴\n", - " ax2 = ax1.twinx()\n", - " # 在第二个坐标轴上绘制数据\n", - " sns.lineplot(data=feature_df, x='ds', y=col, ax=ax2, color='r')\n", - " ax2.set_ylabel(col, color='r')\n", - " ax2.tick_params('y', colors='r')\n", - " # 在 ax2 上添加文本显示值,添加一定的偏移避免值与曲线重叠\n", - " for j in range(0, len(feature_df), 2):\n", - " value = feature_df[col].iloc[j]\n", - " date = feature_df['ds'].iloc[j]\n", - " offset = 1.0003\n", - " ax2.text(date, value * offset, str(round(value, 2)), ha='center', va='bottom', color='r', fontsize=10)\n", - " # 添加标题\n", - " plt.title(col)\n", - " # 设置横坐标为日期格式并自动调整\n", - " locator = mdates.AutoDateLocator()\n", - " formatter = mdates.AutoDateFormatter(locator)\n", - " ax1.xaxis.set_major_locator(locator)\n", - " ax1.xaxis.set_major_formatter(formatter)\n", - " # 文件名特殊字符处理\n", - " col = col.replace('*', '-')\n", - " col = col.replace(':', '-')\n", - " col = col.replace(r'/', '-')\n", - " plt.savefig(os.path.join(dataset, f'{col}与价格散点图.png'))\n", - " content.append(Graphs.draw_img(os.path.join(dataset, f'{col}与价格散点图.png')))\n", - " plt.close()\n", - " # except Exception as e:\n", - " # print(f'绘制第{i+1}个特征{col}与价格散点图时出错:{e}')\n", - " \n", - " \n", - " \n", - " ### 添加标题\n", - " content.append(Graphs.draw_title(f'{y}{time}预测报告'))\n", - "\n", - " ### 预测结果\n", - " content.append(Graphs.draw_little_title('一、预测结果:'))\n", - " # 添加图片\n", - " # 找出后缀是历史价格-预测值.png的图片\n", - " # import glob\n", - " # imgs = glob.glob(os.path.join(dataset,'*历史价格-预测值.png'))\n", - " # for img in imgs:\n", - " # content.append(Graphs.draw_img(img))\n", - " content.append(Graphs.draw_img(os.path.join(dataset,'历史价格-预测值.png')))\n", - "\n", - " # 取df中y列为空的行\n", - " import pandas as pd\n", - " df = pd.read_csv(os.path.join(dataset,'predict.csv'),encoding='gbk') \n", - " df_true = pd.read_csv(os.path.join(dataset,'指标数据添加时间特征.csv'),encoding='utf-8') # 获取预测日期对应的真实值\n", - " df_true = df_true[['ds','y']]\n", - " eval_df = pd.read_csv(os.path.join(dataset,'model_evaluation.csv'),encoding='utf-8') \n", - " # 按评估指标排序,取前五\n", - " fivemodels_list = eval_df['模型(Model)'].values # 列表形式,后面当作列名索引使用\n", - " # 取 fivemodels_list 和 ds 列\n", - " df = df[['ds'] + fivemodels_list.tolist() ]\n", - " # 拼接预测日期对应的真实值\n", - " df = pd.merge(df, df_true, on='ds', how='left')\n", - " # 删除全部为nan的列\n", - " df = df.dropna(how='all', axis=1)\n", - " # 选择除 'ds' 列外的数值列,并进行类型转换和四舍五入\n", - " num_cols = [col for col in df.columns if col!= 'ds' and pd.api.types.is_numeric_dtype(df[col])]\n", - " for col in num_cols:\n", - " df[col] = df[col].astype(float).round(2)\n", - " # 添加最大值、最小值、平均值三列\n", - " df['平均值'] = df[num_cols].mean(axis=1).round(2)\n", - " df['最大值'] = df[num_cols].max(axis=1)\n", - " df['最小值'] = df[num_cols].min(axis=1)\n", - " # df转置\n", - " df = df.T\n", - " # df重置索引\n", - " df = df.reset_index()\n", - " # 添加预测值表格\n", - " data = df.values.tolist()\n", - " col_width = 500/len(df.columns)\n", - " content.append(Graphs.draw_table(col_width,*data))\n", - " content.append(Graphs.draw_little_title('二、上一预测周期偏差率分析:'))\n", - " df = pd.read_csv(os.path.join(dataset,'testandpredict_groupby.csv'),encoding='utf-8')\n", - " df4 = df.copy() # 计算偏差率使用\n", - " # 计算模型偏差率\n", - " #计算各列对于y列的差值百分比\n", - " df3 = pd.DataFrame() # 存储偏差率\n", - " \n", - " # 删除有null的行\n", - " df4 = df4.dropna()\n", - " df3['ds'] = df4['ds']\n", - " for col in fivemodels_list:\n", - " df3[col] = round(abs(df4[col] - df4['y']) / df4['y'] * 100,2) \n", - " # 找出决定系数前五的偏差率\n", - " df3 = df3[['ds']+fivemodels_list.tolist()][-inputsize:]\n", - " # 找出上一预测区间的时间\n", - " stime = df3['ds'].iloc[0]\n", - " etime = df3['ds'].iloc[-1]\n", - " # 添加偏差率表格\n", - " fivemodels = '、'.join(eval_df['模型(Model)'].values[:5]) # 字符串形式,后面写入字符串使用\n", - " content.append(Graphs.draw_text(f'预测使用了{num_models}个模型进行训练,使用评估结果MAE前五的模型分别是 {fivemodels} ,模型上一预测区间 {stime} -- {etime}的偏差率(%)分别是:'))\n", - " # # 添加偏差率表格\n", - " df3 = df3.T\n", - " df3 = df3.reset_index()\n", - " data = df3.values.tolist()\n", - " col_width = 500/len(df3.columns)\n", - " content.append(Graphs.draw_table(col_width,*data))\n", - "\n", - "\n", - " content.append(Graphs.draw_little_title('三、预测过程解析:'))\n", - " ### 特征、模型、参数配置\n", - " content.append(Graphs.draw_little_title('模型选择:'))\n", - " content.append(Graphs.draw_text(f'本次预测使用了一个专门收集时间序列的NeuralForecast库中的{num_models}个模型:'))\n", - " content.append(Graphs.draw_text(f'使用40天的数据预测未来{inputsize}天的数据。'))\n", - " content.append(Graphs.draw_little_title('指标情况:'))\n", - " with open(os.path.join(dataset,'特征频度统计.txt'),encoding='utf-8') as f:\n", - " for line in f.readlines():\n", - " content.append(Graphs.draw_text(line))\n", - "\n", - " data = pd.read_csv(os.path.join(dataset,'指标数据添加时间特征.csv'),encoding='utf-8') # 计算相关系数用\n", - " df_zhibiaofenlei = loadcsv(os.path.join(dataset,'特征处理后的指标名称及分类.csv')) # 气泡图用\n", - " df_zhibiaoshuju = data.copy() # 气泡图用\n", - "\n", - " # 绘制特征相关气泡图\n", - " content.append(Graphs.draw_text('气泡图中,横轴为指标名称,纵轴为指标名称,面积越大表示相关性越大,面积越小表示相关性越小。'))\n", - " grouped = df_zhibiaofenlei.groupby('指标分类')\n", - " grouped_corr = pd.DataFrame(columns=['指标分类', '指标数量', '相关性总和'])\n", - " \n", - " content.append(Graphs.draw_little_title('按指标分类分别与预测目标进行皮尔逊相关系数分析:'))\n", - " content.append(Graphs.draw_text('''皮尔逊相关系数说明:''')) \n", - " content.append(Graphs.draw_text('''衡量两个特征之间的线性相关性。''')) \n", - " content.append(Graphs.draw_text('''\n", - " 相关系数为1:表示两个变量之间存在完全正向的线性关系,即当一个变量增加时,另一个变量也相应增加,且变化是完全一致的。''')) \n", - " content.append(Graphs.draw_text('''相关系数为-1:表示两个变量之间存在完全负向的线性关系,即当一个变量增加时,另一个变量会相应减少,且变化是完全相反的''')) \n", - " content.append(Graphs.draw_text('''相关系数接近0:表示两个变量之间不存在线性关系,即它们的变化不会随着对方的变化而变化。''')) \n", - " for name, group in grouped:\n", - " cols = group['指标名称'].tolist()\n", - " logger.info(f'开始绘制{name}类指标的相关性直方图')\n", - " cols_subset = cols\n", - " feature_names = ['y'] + cols_subset\n", - " correlation_matrix = df_zhibiaoshuju[feature_names].corr()['y']\n", - "\n", - " # 绘制特征相关性直方分布图\n", - " plt.figure(figsize=(10,8))\n", - " sns.histplot(correlation_matrix.values.flatten(), bins=20, kde=True, color='skyblue')\n", - " plt.title(f'{name}类指标(共{len(cols_subset)}个)相关性直方分布图')\n", - " plt.xlabel('相关系数')\n", - " plt.ylabel('频数')\n", - " plt.savefig(os.path.join(dataset, f'{name}类指标相关性直方分布图.png'), bbox_inches='tight')\n", - " plt.close()\n", - " content.append(Graphs.draw_img(os.path.join(dataset,f'{name}类指标相关性直方分布图.png')))\n", - " content.append(Graphs.draw_text(f'{name}类指标(共{len(cols_subset)}个)的相关性直方分布图如上所示。'))\n", - " # 相关性大于0的特征\n", - " positive_corr_features = correlation_matrix[correlation_matrix > 0].sort_values(ascending=False).index.tolist()[1:]\n", - " \n", - " print(f'{name}下正相关的特征值有:',positive_corr_features)\n", - " if len(positive_corr_features) > 5:\n", - " positive_corr_features = positive_corr_features[0:5]\n", - " content.append(Graphs.draw_text(f'{name}类指标中,与预测目标y正相关前五的特征有:{positive_corr_features}'))\n", - " draw_feature_trend(feature_data_df, positive_corr_features)\n", - " elif len(positive_corr_features) == 0:\n", - " pass\n", - " else:\n", - " positive_corr_features = positive_corr_features\n", - " content.append(Graphs.draw_text(f'其中,与预测目标y正相关的特征有:{positive_corr_features}'))\n", - " draw_feature_trend(feature_data_df, positive_corr_features)\n", - " \n", - " # 相关性小于0的特征\n", - " negative_corr_features = correlation_matrix[correlation_matrix < 0].sort_values(ascending=True).index.tolist()\n", - " \n", - " print(f'{name}下负相关的特征值有:',negative_corr_features)\n", - " if len(negative_corr_features) > 5:\n", - " negative_corr_features = negative_corr_features[:5]\n", - " content.append(Graphs.draw_text(f'与预测目标y负相关前五的特征有:{negative_corr_features}'))\n", - " draw_feature_trend(feature_data_df, negative_corr_features)\n", - " elif len(negative_corr_features) == 0:\n", - " pass\n", - " else:\n", - " content.append(Graphs.draw_text(f'{name}类指标中,与预测目标y负相关的特征有:{negative_corr_features}'))\n", - " draw_feature_trend(feature_data_df, negative_corr_features)\n", - " \n", - " \n", - " # 计算correlation_sum 第一行的相关性的绝对值的总和\n", - " correlation_sum = correlation_matrix.abs().sum()\n", - " logger.info(f'{name}类指标的相关性总和为:{correlation_sum}')\n", - " # 分组的相关性总和拼接到grouped_corr\n", - " goup_corr = pd.DataFrame({'指标分类': [name], '指标数量': [len(cols_subset)], '相关性总和': [correlation_sum]})\n", - " grouped_corr = pd.concat([grouped_corr, goup_corr], axis=0, ignore_index=True)\n", - "\n", - " # 绘制相关性总和的气泡图\n", - " logger.info(f'开始绘制相关性总和的气泡图')\n", - " plt.figure(figsize=(10, 10))\n", - " sns.scatterplot(data=grouped_corr, x='相关性总和', y='指标数量', size='相关性总和', sizes=(grouped_corr['相关性总和'].min()*5, grouped_corr['相关性总和'].max()*5), hue='指标分类', palette='viridis')\n", - " plt.title('指标分类相关性总和的气泡图')\n", - " plt.ylabel('数量')\n", - " plt.savefig(os.path.join(dataset, '指标分类相关性总和的气泡图.png'), bbox_inches='tight')\n", - " plt.close()\n", - " content.append(Graphs.draw_img(os.path.join(dataset,'指标分类相关性总和的气泡图.png')))\n", - " logger.info(f'绘制相关性总和的气泡图结束')\n", - " \n", - "\n", - "\n", - " # # 计算特征相关性\n", - " # data.rename(columns={y: 'y'}, inplace=True) \n", - " # data['ds'] = pd.to_datetime(data['ds']) \n", - " # data.drop(columns=['ds'], inplace=True)\n", - " # # 创建一个空的 DataFrame 来保存相关系数\n", - " # correlation_df = pd.DataFrame(columns=['Feature', 'Correlation'])\n", - " # # 计算各特征与目标列的皮尔逊相关系数,并保存到新的 Data 中\n", - " # for col in data.columns:\n", - " # if col!= 'y':\n", - " # pearson_correlation = np.corrcoef(data[col], data['y'])[0, 1]\n", - " # spearman_correlation, _ = spearmanr(data[col], data['y'])\n", - " # new_row = {'Feature': col, 'Pearson_Correlation': round(pearson_correlation,3), 'Spearman_Correlation': round(spearman_correlation,2)}\n", - " # correlation_df = correlation_df._append(new_row, ignore_index=True)\n", - "\n", - " # correlation_df.drop('Correlation', axis=1, inplace=True)\n", - " # correlation_df.dropna(inplace=True)\n", - " # correlation_df.to_csv(os.path.join(dataset,'指标相关性分析.csv'), index=False)\n", - "\n", - " # data = correlation_df['Pearson_Correlation'].values.tolist()\n", - " # # 生成 -1 到 1 的 20 个区间\n", - " # bins = np.linspace(-1, 1, 21)\n", - " # # 计算每个区间的统计数(这里是区间内数据的数量)\n", - " # hist_values = [np.sum((data >= bins[i]) & (data < bins[i + 1])) for i in range(len(bins) - 1)]\n", - "\n", - " # #设置画布大小\n", - " # plt.figure(figsize=(10, 6))\n", - " # # 绘制直方图\n", - " # plt.bar(bins[:-1], hist_values, width=(bins[1] - bins[0]))\n", - "\n", - " # # 添加标题和坐标轴标签\n", - " # plt.title('皮尔逊相关系数分布图')\n", - " # plt.xlabel('区间')\n", - " # plt.ylabel('统计数')\n", - " # plt.savefig(os.path.join(dataset, '皮尔逊相关性系数.png'))\n", - " # plt.close()\n", - "\n", - "\n", - " # #设置画布大小\n", - " # plt.figure(figsize=(10, 6))\n", - " # data = correlation_df['Spearman_Correlation'].values.tolist()\n", - " # # 计算每个区间的统计数(这里是区间内数据的数量)\n", - " # hist_values = [np.sum((data >= bins[i]) & (data < bins[i + 1])) for i in range(len(bins) - 1)]\n", - "\n", - " # # 绘制直方图\n", - " # plt.bar(bins[:-1], hist_values, width=(bins[1] - bins[0]))\n", - "\n", - " # # 添加标题和坐标轴标签\n", - " # plt.title('斯皮尔曼相关系数分布图')\n", - " # plt.xlabel('区间')\n", - " # plt.ylabel('统计数')\n", - " # plt.savefig(os.path.join(dataset, '斯皮尔曼相关性系数.png'))\n", - " # plt.close()\n", - " # content.append(Graphs.draw_text(f'指标相关性分析--皮尔逊相关系数:'))\n", - " # # 皮尔逊正相关 不相关 负相关 的表格\n", - " # content.append(Graphs.draw_img(os.path.join(dataset,'皮尔逊相关性系数.png')))\n", - " # content.append(Graphs.draw_text('''皮尔逊相关系数说明:''')) \n", - " # content.append(Graphs.draw_text('''衡量两个特征之间的线性相关性。''')) \n", - " # content.append(Graphs.draw_text('''\n", - " # 相关系数为1:表示两个变量之间存在完全正向的线性关系,即当一个变量增加时,另一个变量也相应增加,且变化是完全一致的。''')) \n", - " # content.append(Graphs.draw_text('''当前特征中正相关前十的有:''')) \n", - " # top10_columns = correlation_df.sort_values(by='Pearson_Correlation',ascending=False).head(10)['Feature'].to_list()\n", - " # top10 = ','.join(top10_columns)\n", - " # content.append(Graphs.draw_text(f'''{top10}''')) \n", - "\n", - " # feature_df = feature_data_df[['ds','y']+top10_columns]\n", - " # # 遍历X每一列,和yy画散点图 ,\n", - " # for i, col in enumerate(feature_df.columns):\n", - " # print(f'正在绘制第{i+1}个特征{col}与价格散点图...')\n", - " # if col not in ['ds', 'y']:\n", - " # fig, ax1 = plt.subplots(figsize=(10, 6))\n", - " # # 在第一个坐标轴上绘制数据\n", - " # ax1.plot(feature_df['ds'], feature_df['y'], 'b-')\n", - " # ax1.set_xlabel('日期')\n", - " # ax1.set_ylabel('y', color='b')\n", - " # ax1.tick_params('y', colors='b')\n", - " # # 在 ax1 上添加文本显示值,添加一定的偏移避免值与曲线重叠\n", - " # for j in range(1,len(feature_df),2):\n", - " # value = feature_df['y'].iloc[j]\n", - " # date = feature_df['ds'].iloc[j]\n", - " # offset = 1.001\n", - " # ax1.text(date, value * offset, str(round(value, 2)), ha='center', va='bottom', color='b', fontsize=10)\n", - " # # 创建第二个坐标轴\n", - " # ax2 = ax1.twinx()\n", - " # # 在第二个坐标轴上绘制数据\n", - " # line2 = ax2.plot(feature_df['ds'], feature_df[col], 'r-')\n", - " # ax2.set_ylabel(col, color='r')\n", - " # ax2.tick_params('y', colors='r')\n", - " # # 在 ax2 上添加文本显示值,添加一定的偏移避免值与曲线重叠\n", - " # for j in range(0,len(feature_df),2):\n", - " # value = feature_df[col].iloc[j]\n", - " # date = feature_df['ds'].iloc[j]\n", - " # offset = 1.001\n", - " # ax2.text(date, value * offset, str(round(value, 2)), ha='center', va='bottom', color='r', fontsize=10)\n", - " # # 添加标题\n", - " # plt.title(col)\n", - " # # 设置横坐标为日期格式并自动调整\n", - " # locator = mdates.AutoDateLocator()\n", - " # formatter = mdates.AutoDateFormatter(locator)\n", - " # ax1.xaxis.set_major_locator(locator)\n", - " # ax1.xaxis.set_major_formatter(formatter)\n", - " # # 文件名特殊字符处理\n", - " # col = col.replace('*', '-')\n", - " # col = col.replace(':', '-')\n", - " # plt.savefig(os.path.join(dataset, f'{col}与价格散点图.png'))\n", - " # content.append(Graphs.draw_img(os.path.join(dataset, f'{col}与价格散点图.png')))\n", - " # plt.close()\n", - "\n", - "\n", - " # content.append(Graphs.draw_text(f'指标相关性分析--斯皮尔曼相关系数:'))\n", - " # # 皮尔逊正相关 不相关 负相关 的表格\n", - " # content.append(Graphs.draw_img(os.path.join(dataset,'斯皮尔曼相关性系数.png')))\n", - " # content.append(Graphs.draw_text('斯皮尔曼相关系数(Spearmans rank correlation coefficient)是一种用于衡量两个变量之间的单调关系(不一定是线性关系)的统计指标。'))\n", - " # content.append(Graphs.draw_text('它的计算基于变量的秩次(即变量值的排序位置)而非变量的原始值。'))\n", - " # content.append(Graphs.draw_text('斯皮尔曼相关系数的取值范围在 -1 到 1 之间。'))\n", - " # content.append(Graphs.draw_text('当系数为 1 时,表示两个变量之间存在完全正的单调关系;'))\n", - " # content.append(Graphs.draw_text('''当前特征中正单调关系前十的有:''')) \n", - " # top10_columns = correlation_df.sort_values(by='Spearman_Correlation',ascending=False).head(10)['Feature'].to_list()\n", - " # top10 = ','.join(top10_columns)\n", - " # content.append(Graphs.draw_text(f'''{top10}''')) \n", - "\n", - " # feature_df = feature_data_df[['ds','y']+top10_columns]\n", - " # # 遍历X每一列,和yy画散点图 ,\n", - " # for i, col in enumerate(feature_df.columns):\n", - " # print(f'正在绘制第{i+1}个特征{col}与价格散点图...')\n", - " # if col not in ['ds', 'y']:\n", - " # fig, ax1 = plt.subplots(figsize=(10, 6))\n", - " # # 在第一个坐标轴上绘制数据\n", - " # ax1.plot(feature_df['ds'], feature_df['y'], 'b-')\n", - " # ax1.set_xlabel('日期')\n", - " # ax1.set_ylabel('y', color='b')\n", - " # ax1.tick_params('y', colors='b')\n", - " # # 在 ax1 上添加文本显示值,添加一定的偏移避免值与曲线重叠\n", - " # for j in range(1,len(feature_df),2):\n", - " # value = feature_df['y'].iloc[j]\n", - " # date = feature_df['ds'].iloc[j]\n", - " # offset = 1.001\n", - " # ax1.text(date, value * offset, str(round(value, 2)), ha='center', va='bottom', color='b', fontsize=10)\n", - " # # 创建第二个坐标轴\n", - " # ax2 = ax1.twinx()\n", - " # # 在第二个坐标轴上绘制数据\n", - " # line2 = ax2.plot(feature_df['ds'], feature_df[col], 'r-')\n", - " # ax2.set_ylabel(col, color='r')\n", - " # ax2.tick_params('y', colors='r')\n", - " # # 在 ax2 上添加文本显示值,添加一定的偏移避免值与曲线重叠\n", - " # for j in range(0,len(feature_df),2):\n", - " # value = feature_df[col].iloc[j]\n", - " # date = feature_df['ds'].iloc[j]\n", - " # offset = 1.001\n", - " # ax2.text(date, value * offset, str(round(value, 2)), ha='center', va='bottom', color='r', fontsize=10)\n", - " # # 添加标题\n", - " # plt.title(col)\n", - " # # 设置横坐标为日期格式并自动调整\n", - " # locator = mdates.AutoDateLocator()\n", - " # formatter = mdates.AutoDateFormatter(locator)\n", - " # ax1.xaxis.set_major_locator(locator)\n", - " # ax1.xaxis.set_major_formatter(formatter)\n", - " # # 文件名特殊字符处理\n", - " # col = col.replace('*', '-')\n", - " # col = col.replace(':', '-')\n", - " # plt.savefig(os.path.join(dataset, f'{col}与价格散点图.png'))\n", - " # content.append(Graphs.draw_img(os.path.join(dataset, f'{col}与价格散点图.png')))\n", - " # plt.close()\n", - "\n", - " # content.append(Graphs.draw_text('当系数为 -1 时,表示存在完全负的单调关系;'))\n", - " # content.append(Graphs.draw_text('''当前特征中负单调关系前十的有:''')) \n", - " # tail10_columns = correlation_df.sort_values(by='Spearman_Correlation',ascending=True).head(10)['Feature'].to_list()\n", - " # top10 = ','.join(tail10_columns)\n", - " # content.append(Graphs.draw_text(f'''{top10}''')) \n", - " # # 获取特征的近一周值\n", - " # feature_df = feature_data_df[['ds','y']+tail10_columns]\n", - " # # 遍历X每一列,和yy画散点图 ,\n", - " # for i, col in enumerate(feature_df.columns):\n", - " # print(f'正在绘制第{i+1}个特征{col}与价格散点图...')\n", - " # if col not in ['ds', 'y']:\n", - " # fig, ax1 = plt.subplots(figsize=(10, 6))\n", - " # # 在第一个坐标轴上绘制数据\n", - " # ax1.plot(feature_df['ds'], feature_df['y'], 'b-')\n", - " # ax1.set_xlabel('日期')\n", - " # ax1.set_ylabel('y', color='b')\n", - " # ax1.tick_params('y', colors='b')\n", - " # # 在 ax1 上添加文本显示值,添加一定的偏移避免值与曲线重叠\n", - " # for j in range(len(feature_df)):\n", - " # if j%2 == 1:\n", - " # value = feature_df['y'].iloc[j]\n", - " # date = feature_df['ds'].iloc[j]\n", - " # offset = 1.001\n", - " # ax1.text(date, value * offset, str(round(value, 2)), ha='center', va='bottom', color='b', fontsize=10)\n", - " # # 创建第二个坐标轴\n", - " # ax2 = ax1.twinx()\n", - " # # 在第二个坐标轴上绘制数据\n", - " # line2 = ax2.plot(feature_df['ds'], feature_df[col], 'r-')\n", - " # ax2.set_ylabel(col, color='r')\n", - " # ax2.tick_params('y', colors='r')\n", - " # # 在 ax2 上添加文本显示值,添加一定的偏移避免值与曲线重叠\n", - " # for j in range(1,len(feature_df),2):\n", - " # value = feature_df[col].iloc[j]\n", - " # date = feature_df['ds'].iloc[j]\n", - " # offset = 1.001\n", - " # ax2.text(date, value * offset, str(round(value, 2)), ha='center', va='bottom', color='r', fontsize=10)\n", - " # # 添加标题\n", - " # plt.title(col)\n", - " # # 设置横坐标为日期格式并自动调整\n", - " # locator = mdates.AutoDateLocator()\n", - " # formatter = mdates.AutoDateFormatter(locator)\n", - " # ax1.xaxis.set_major_locator(locator)\n", - " # ax1.xaxis.set_major_formatter(formatter)\n", - " # # 文件名特殊字符处理\n", - " # col = col.replace('*', '-')\n", - " # col = col.replace(':', '-')\n", - " # plt.savefig(os.path.join(dataset, f'{col}与价格散点图.png'))\n", - " # content.append(Graphs.draw_img(os.path.join(dataset, f'{col}与价格散点图.png')))\n", - " # plt.close()\n", - " # content.append(Graphs.draw_text('当系数为 0 时,表示两个变量之间不存在单调关系。'))\n", - " # content.append(Graphs.draw_text('与皮尔逊相关系数相比,斯皮尔曼相关系数对于数据中的异常值不敏感,更适用于处理非线性关系或存在极端值的数据。'))\n", - " content.append(Graphs.draw_little_title('模型选择:'))\n", - " content.append(Graphs.draw_text(f'预测使用了{num_models}个模型进行训练拟合,通过评估指标MAE从小到大排列,前5个模型的简介如下:'))\n", - "\n", - " ### 读取模型简介\n", - " with open(os.path.join(dataset,'model_introduction.txt'), 'r', encoding='utf-8') as f:\n", - " for line in f:\n", - " line_split = line.strip().split('--')\n", - " if line_split[0] in fivemodels_list:\n", - " for introduction in line_split:\n", - " content.append(Graphs.draw_text(introduction))\n", - "\n", - " content.append(Graphs.draw_little_title('模型评估:'))\n", - " \n", - " df = pd.read_csv(os.path.join(dataset,'model_evaluation.csv'),encoding='utf-8') \n", - " # 判断 df 的数值列转为float\n", - " for col in eval_df.columns:\n", - " if col not in ['模型(Model)']:\n", - " eval_df[col] = eval_df[col].astype(float)\n", - " eval_df[col] = eval_df[col].round(3)\n", - " # 筛选 fivemodels_list.tolist() 的行\n", - " eval_df = eval_df[eval_df['模型(Model)'].isin(fivemodels_list)]\n", - " # df转置\n", - " eval_df = eval_df.T\n", - " # df重置索引\n", - " eval_df = eval_df.reset_index()\n", - " eval_df = eval_df.T\n", - " # # 添加表格\n", - " data = eval_df.values.tolist()\n", - " col_width = 500/len(eval_df.columns)\n", - " content.append(Graphs.draw_table(col_width,*data))\n", - " content.append(Graphs.draw_text('评估指标释义:'))\n", - " content.append(Graphs.draw_text('1. 均方根误差(RMSE):均方根误差是衡量预测值与实际值之间误差的一种方法,取值越小,误差越小,预测效果越好。'))\n", - " content.append(Graphs.draw_text('2. 平均绝对误差(MAE):平均绝对误差是衡量预测值与实际值之间误差的一种方法,取值越小,误差越小,预测效果越好。'))\n", - " content.append(Graphs.draw_text('3. 平均平方误差(MSE):平均平方误差是衡量预测值与实际值之间误差的一种方法,取值越小,误差越小,预测效果越好。'))\n", - " content.append(Graphs.draw_text('模型拟合:'))\n", - " # 添加图片\n", - " content.append(Graphs.draw_img(os.path.join(dataset,'预测值与真实值对比图.png')))\n", - "\n", - " # 附1,特征列表\n", - " content.append(Graphs.draw_little_title('附1、特征列表:'))\n", - " df_fuyi = pd.read_csv(os.path.join(dataset,'特征频度统计.csv'),encoding='utf-8') \n", - " for col in df_fuyi.columns:\n", - " fuyi = df_fuyi[col]\n", - " fuyi = fuyi.dropna()\n", - " content.append(Graphs.draw_text(f'{col}:'))\n", - " for i in range(len(fuyi)):\n", - " content.append(Graphs.draw_text(f'{i+1}、{fuyi[i]}'))\n", - " \n", - "\n", - "\n", - " ### 生成pdf文件\n", - " doc = SimpleDocTemplate(os.path.join(dataset,reportname), pagesize=letter)\n", - " # doc = SimpleDocTemplate(os.path.join(dataset,'reportname.pdf'), pagesize=letter)\n", - " doc.build(content)\n", - " # pdf 上传到数字化信息平台\n", - " # 读取pdf并转为base64\n", - " try:\n", - " if is_update_report:\n", - " with open(os.path.join(dataset,reportname), 'rb') as f:\n", - " base64_data = base64.b64encode(f.read()).decode('utf-8')\n", - " upload_data[\"data\"][\"fileBase64\"] = base64_data\n", - " upload_data[\"data\"][\"fileName\"] = reportname\n", - " token = get_head_auth_report()\n", - " upload_report_data(token, upload_data)\n", - " except TimeoutError as e:\n", - " print(f\"请求超时: {e}\")\n", - " \n", - " " + "\n" ] }, { "cell_type": "code", - "execution_count": 51, + "execution_count": null, "id": "a97ed0d6-72c5-4747-a0cf-1d61a67c6efb", "metadata": {}, "outputs": [ @@ -2568,15 +2061,7 @@ ] } ], - "source": [ - " \n", - "title = f'{settings}--{now}-预测报告' # 报告标题\n", - "brent_export_pdf(dataset=dataset,num_models = 5 if is_fivemodels else 22,time=end_time,\n", - " reportname=reportname,sqlitedb=sqlitedb),\n", - "# pp_export_pdf(dataset=dataset,num_models = 5 if is_fivemodels else 22,time=end_time,\n", - " # reportname=reportname),\n", - "logger.info('模型训练完成')" - ] + "source": [] }, { "cell_type": "code", diff --git a/models/nerulforcastmodels.py b/models/nerulforcastmodels.py index 471b1b1..22a177c 100644 --- a/models/nerulforcastmodels.py +++ b/models/nerulforcastmodels.py @@ -554,8 +554,8 @@ def brent_export_pdf(num_indicators=475,num_models=21, num_dayindicator=202,inpu content.append(Graphs.draw_img(os.path.join(dataset,'历史价格-预测值.png'))) content.append(Graphs.draw_text('图示说明:')) content.append(Graphs.draw_text('1. 确定波动率置信区间:统计近60个交易日的真实价格波动率,找出在 10% ,90% 的分位值作为波动率置信区间;')) - content.append(Graphs.draw_text('2. 确定通道上界:在所有模型的预测结果中 <= 前一天真实价格 乘以 90%置信')) - content.append(Graphs.draw_text('3. 确定通道下界:在所有模型的预测结果中 >= 前一天真实价格 乘以 10%置信')) + content.append(Graphs.draw_text('2. 确定通道上界:在所有模型的预测结果中 <= 前一天真实价格 乘以 90%的置信波动分位数')) + content.append(Graphs.draw_text('3. 确定通道下界:在所有模型的预测结果中 >= 前一天真实价格 乘以 10%的置信波动分位数')) content.append(Graphs.draw_text('4. 预测结果没有真实值作为参考依据,通道上界取近20个交易日内预测在上界值的模型对应的预测值,通道下界同理;')) content.append(Graphs.draw_text('5. 预测结果选用近20个交易日内,最多接近真实值的模型的预测值对应的预测结果;')) content.append(Graphs.draw_text('6. 预测结果在通道外的,代表最接近真实值的预测结果不在置信波动范围内。'))