分类指标相关性及气泡图
This commit is contained in:
parent
fe96c5f1be
commit
a68ed336de
@ -167,12 +167,12 @@ upload_data = {
|
||||
|
||||
### 开关
|
||||
is_train = True # 是否训练
|
||||
is_debug = False # 是否调试
|
||||
is_eta = True # 是否使用eta接口
|
||||
is_debug = True # 是否调试
|
||||
is_eta = False # 是否使用eta接口
|
||||
is_timefurture = True # 是否使用时间特征
|
||||
is_fivemodels = False # 是否使用之前保存的最佳的5个模型
|
||||
is_edbcode = False # 特征使用edbcoding列表中的
|
||||
is_edbnamelist = False # 自定义特征,对应上面的edbnamelist
|
||||
is_fivemodels = True # 是否使用之前保存的最佳的5个模型
|
||||
is_edbcode = True # 特征使用edbcoding列表中的
|
||||
is_edbnamelist = True # 自定义特征,对应上面的edbnamelist
|
||||
is_update_eta = False # 预测结果上传到eta
|
||||
is_update_report = False # 是否上传报告
|
||||
|
||||
|
2611
debugdemo.ipynb
Normal file
2611
debugdemo.ipynb
Normal file
File diff suppressed because it is too large
Load Diff
@ -20,8 +20,8 @@ plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
|
||||
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
|
||||
|
||||
from datetime import timedelta
|
||||
# from config_jingbo import *
|
||||
from config_juxiting import *
|
||||
from config_jingbo import *
|
||||
# from config_juxiting import *
|
||||
from sklearn import metrics
|
||||
from reportlab.pdfbase import pdfmetrics # 注册字体
|
||||
from reportlab.pdfbase.ttfonts import TTFont # 字体类
|
||||
|
8
main.py
8
main.py
@ -1,7 +1,7 @@
|
||||
# 读取配置
|
||||
# from config_jingbo import *
|
||||
from config_jingbo import *
|
||||
# from config_tansuanli import *
|
||||
from config_juxiting import *
|
||||
# from config_juxiting import *
|
||||
from lib.dataread import *
|
||||
from lib.tools import *
|
||||
from models.nerulforcastmodels import ex_Model,model_losss,brent_export_pdf,tansuanli_export_pdf,pp_export_pdf
|
||||
@ -39,8 +39,8 @@ def predict_main():
|
||||
edbbusinessurl=edbbusinessurl,
|
||||
)
|
||||
|
||||
# df_zhibiaoshuju,df_zhibiaoliebiao = etadata.get_eta_api_yuanyou_data(data_set=data_set,dataset=dataset) # 原始数据,未处理
|
||||
df_zhibiaoshuju,df_zhibiaoliebiao = etadata.get_eta_api_pp_data(data_set=data_set,dataset=dataset) # 原始数据,未处理
|
||||
df_zhibiaoshuju,df_zhibiaoliebiao = etadata.get_eta_api_yuanyou_data(data_set=data_set,dataset=dataset) # 原始数据,未处理
|
||||
# df_zhibiaoshuju,df_zhibiaoliebiao = etadata.get_eta_api_pp_data(data_set=data_set,dataset=dataset) # 原始数据,未处理
|
||||
|
||||
|
||||
# 数据处理
|
||||
|
@ -249,11 +249,9 @@ def model_losss(sqlitedb):
|
||||
df_combined3['quantile_10'] = df_combined3['volatility'].rolling(60).quantile(0.1)
|
||||
df_combined3['quantile_90'] = df_combined3['volatility'].rolling(60).quantile(0.9)
|
||||
df_combined3 = df_combined3.round(4)
|
||||
# 计算分位数对应的价格,并移动到第二天
|
||||
# 计算分位数对应的价格
|
||||
df_combined3['quantile_10_price'] = df_combined3['y'] * (1 + df_combined3['quantile_10'])
|
||||
# df_combined3['quantile_10_price'] = df_combined3['quantile_10_price'].shift(1)
|
||||
df_combined3['quantile_90_price'] = df_combined3['y'] * (1 + df_combined3['quantile_90'])
|
||||
# df_combined3['quantile_90_price'] = df_combined3['quantile_90_price'].shift(1)
|
||||
|
||||
# 遍历行
|
||||
def find_min_max_within_quantile(row):
|
||||
@ -485,10 +483,67 @@ def model_losss(sqlitedb):
|
||||
plt.close()
|
||||
return model_results3
|
||||
|
||||
|
||||
import matplotlib.dates as mdates
|
||||
|
||||
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'):
|
||||
global y
|
||||
# 创建内容对应的空列表
|
||||
content = list()
|
||||
# 获取特征的近一月值
|
||||
import pandas as pd
|
||||
feature_data_df = pd.read_csv(f'dataset/指标数据添加时间特征.csv', parse_dates=['ds']).tail(20)
|
||||
def draw_feature_trend(feature_data_df, features):
|
||||
# 画特征近一周的趋势图
|
||||
feature_df = feature_data_df[['ds','y']+features]
|
||||
# 遍历X每一列,和yy画散点图 ,
|
||||
|
||||
for i, col in enumerate(features):
|
||||
# try:
|
||||
print(f'正在绘制第{i+1}个特征{col}与价格散点图...')
|
||||
if col not in ['ds', 'y']:
|
||||
fig, ax1 = plt.subplots(figsize=(10, 6))
|
||||
# 在第一个坐标轴上绘制数据
|
||||
sns.lineplot(data=feature_df, x='ds', y='y', ax=ax1, color='b')
|
||||
ax1.set_xlabel('日期')
|
||||
ax1.set_ylabel('y', color='b')
|
||||
ax1.tick_params('y', colors='b')
|
||||
# 在 ax1 上添加文本显示值,添加一定的偏移避免值与曲线重叠
|
||||
for j in range(1, len(feature_df), 2):
|
||||
value = feature_df['y'].iloc[j]
|
||||
date = feature_df['ds'].iloc[j]
|
||||
offset = 1.001
|
||||
ax1.text(date, value * offset, str(round(value, 2)), ha='center', va='bottom', color='b', fontsize=10)
|
||||
# 创建第二个坐标轴
|
||||
ax2 = ax1.twinx()
|
||||
# 在第二个坐标轴上绘制数据
|
||||
sns.lineplot(data=feature_df, x='ds', y=col, ax=ax2, color='r')
|
||||
ax2.set_ylabel(col, color='r')
|
||||
ax2.tick_params('y', colors='r')
|
||||
# 在 ax2 上添加文本显示值,添加一定的偏移避免值与曲线重叠
|
||||
for j in range(0, len(feature_df), 2):
|
||||
value = feature_df[col].iloc[j]
|
||||
date = feature_df['ds'].iloc[j]
|
||||
offset = 1.0003
|
||||
ax2.text(date, value * offset, str(round(value, 2)), ha='center', va='bottom', color='r', fontsize=10)
|
||||
# 添加标题
|
||||
plt.title(col)
|
||||
# 设置横坐标为日期格式并自动调整
|
||||
locator = mdates.AutoDateLocator()
|
||||
formatter = mdates.AutoDateFormatter(locator)
|
||||
ax1.xaxis.set_major_locator(locator)
|
||||
ax1.xaxis.set_major_formatter(formatter)
|
||||
# 文件名特殊字符处理
|
||||
col = col.replace('*', '-')
|
||||
col = col.replace(':', '-')
|
||||
col = col.replace(r'/', '-')
|
||||
plt.savefig(os.path.join(dataset, f'{col}与价格散点图.png'))
|
||||
content.append(Graphs.draw_img(os.path.join(dataset, f'{col}与价格散点图.png')))
|
||||
plt.close()
|
||||
# except Exception as e:
|
||||
# print(f'绘制第{i+1}个特征{col}与价格散点图时出错:{e}')
|
||||
|
||||
|
||||
|
||||
### 添加标题
|
||||
content.append(Graphs.draw_title(f'{y}{time}预测报告'))
|
||||
@ -578,295 +633,296 @@ def brent_export_pdf(num_indicators=475,num_models=21, num_dayindicator=202,inpu
|
||||
# 绘制特征相关气泡图
|
||||
content.append(Graphs.draw_text('气泡图中,横轴为指标名称,纵轴为指标名称,面积越大表示相关性越大,面积越小表示相关性越小。'))
|
||||
grouped = df_zhibiaofenlei.groupby('指标分类')
|
||||
for name, group in grouped:
|
||||
cols = group['指标名称'].tolist()
|
||||
for n in range(0, len(cols), 10):
|
||||
logger.info(f'开始绘制{name}类指标{n}的气泡图')
|
||||
cols_subset = cols[n:n+10]
|
||||
feature_names = ['y'] + cols_subset
|
||||
correlation_matrix = df_zhibiaoshuju[feature_names].corr()
|
||||
plt.figure(figsize=(10, 10))
|
||||
for i in range(len(feature_names)):
|
||||
for j in range(len(feature_names)):
|
||||
plt.scatter(i, j, s=abs(correlation_matrix.iloc[i, j]) * 1000, c=correlation_matrix.iloc[i, j], cmap='coolwarm', marker='o')
|
||||
for i in range(len(feature_names)):
|
||||
for j in range(len(feature_names)):
|
||||
plt.text(i, j, f'{correlation_matrix.iloc[i, j]:.2f}', ha='center', va='center', color='black')
|
||||
plt.xticks(range(len(feature_names)), feature_names, rotation=90)
|
||||
plt.yticks(range(len(feature_names)), feature_names)
|
||||
plt.title(f'{name}类指标{n}')
|
||||
plt.xlabel('指标名称')
|
||||
plt.ylabel('指标名称')
|
||||
plt.savefig(os.path.join(dataset, f'{name}{n}气泡图.png'), bbox_inches='tight')
|
||||
plt.close()
|
||||
content.append(Graphs.draw_img(os.path.join(dataset,f'{name}{n}气泡图.png')))
|
||||
logger.info(f'绘制指标相关性气泡图结束')
|
||||
grouped_corr = pd.DataFrame(columns=['指标分类', '指标数量', '相关性总和'])
|
||||
|
||||
# 计算特征相关性
|
||||
data.rename(columns={y: 'y'}, inplace=True)
|
||||
data['ds'] = pd.to_datetime(data['ds'])
|
||||
data.drop(columns=['ds'], inplace=True)
|
||||
# 创建一个空的 DataFrame 来保存相关系数
|
||||
correlation_df = pd.DataFrame(columns=['Feature', 'Correlation'])
|
||||
# 计算各特征与目标列的皮尔逊相关系数,并保存到新的 DataFrame 中
|
||||
for col in data.columns:
|
||||
if col!= 'y':
|
||||
pearson_correlation = np.corrcoef(data[col], data['y'])[0, 1]
|
||||
spearman_correlation, _ = spearmanr(data[col], data['y'])
|
||||
new_row = {'Feature': col, 'Pearson_Correlation': round(pearson_correlation,3), 'Spearman_Correlation': round(spearman_correlation,2)}
|
||||
correlation_df = correlation_df._append(new_row, ignore_index=True)
|
||||
|
||||
correlation_df.drop('Correlation', axis=1, inplace=True)
|
||||
correlation_df.dropna(inplace=True)
|
||||
correlation_df.to_csv(os.path.join(dataset,'指标相关性分析.csv'), index=False)
|
||||
|
||||
data = correlation_df['Pearson_Correlation'].values.tolist()
|
||||
# 生成 -1 到 1 的 20 个区间
|
||||
bins = np.linspace(-1, 1, 21)
|
||||
# 计算每个区间的统计数(这里是区间内数据的数量)
|
||||
hist_values = [np.sum((data >= bins[i]) & (data < bins[i + 1])) for i in range(len(bins) - 1)]
|
||||
|
||||
#设置画布大小
|
||||
plt.figure(figsize=(10, 6))
|
||||
# 绘制直方图
|
||||
plt.bar(bins[:-1], hist_values, width=(bins[1] - bins[0]))
|
||||
|
||||
# 添加标题和坐标轴标签
|
||||
plt.title('皮尔逊相关系数分布图')
|
||||
plt.xlabel('区间')
|
||||
plt.ylabel('统计数')
|
||||
plt.savefig(os.path.join(dataset, '皮尔逊相关性系数.png'))
|
||||
plt.close()
|
||||
|
||||
|
||||
#设置画布大小
|
||||
plt.figure(figsize=(10, 6))
|
||||
data = correlation_df['Spearman_Correlation'].values.tolist()
|
||||
# 计算每个区间的统计数(这里是区间内数据的数量)
|
||||
hist_values = [np.sum((data >= bins[i]) & (data < bins[i + 1])) for i in range(len(bins) - 1)]
|
||||
|
||||
# 绘制直方图
|
||||
plt.bar(bins[:-1], hist_values, width=(bins[1] - bins[0]))
|
||||
|
||||
# 添加标题和坐标轴标签
|
||||
plt.title('斯皮尔曼相关系数分布图')
|
||||
plt.xlabel('区间')
|
||||
plt.ylabel('统计数')
|
||||
plt.savefig(os.path.join(dataset, '斯皮尔曼相关性系数.png'))
|
||||
plt.close()
|
||||
content.append(Graphs.draw_text(f'指标相关性分析--皮尔逊相关系数:'))
|
||||
# 皮尔逊正相关 不相关 负相关 的表格
|
||||
content.append(Graphs.draw_img(os.path.join(dataset,'皮尔逊相关性系数.png')))
|
||||
content.append(Graphs.draw_little_title('按指标分类分别与预测目标进行皮尔逊相关系数分析:'))
|
||||
content.append(Graphs.draw_text('''皮尔逊相关系数说明:'''))
|
||||
content.append(Graphs.draw_text('''衡量两个特征之间的线性相关性。'''))
|
||||
content.append(Graphs.draw_text('''
|
||||
相关系数为1:表示两个变量之间存在完全正向的线性关系,即当一个变量增加时,另一个变量也相应增加,且变化是完全一致的。'''))
|
||||
content.append(Graphs.draw_text('''当前特征中正相关前十的有:'''))
|
||||
top10_columns = correlation_df.sort_values(by='Pearson_Correlation',ascending=False).head(10)['Feature'].to_list()
|
||||
top10 = ','.join(top10_columns)
|
||||
content.append(Graphs.draw_text(f'''{top10}'''))
|
||||
# 获取特征的近一月值
|
||||
feature_data_df = pd.read_csv(f'dataset/指标数据添加时间特征.csv', parse_dates=['ds']).tail(20)
|
||||
feature_df = feature_data_df[['ds','y']+top10_columns]
|
||||
# 遍历X每一列,和yy画散点图 ,
|
||||
for i, col in enumerate(feature_df.columns):
|
||||
print(f'正在绘制第{i+1}个特征{col}与价格散点图...')
|
||||
if col not in ['ds', 'y']:
|
||||
fig, ax1 = plt.subplots(figsize=(10, 6))
|
||||
# 在第一个坐标轴上绘制数据
|
||||
ax1.plot(feature_df['ds'], feature_df['y'], 'b-')
|
||||
ax1.set_xlabel('日期')
|
||||
ax1.set_ylabel('y', color='b')
|
||||
ax1.tick_params('y', colors='b')
|
||||
# 在 ax1 上添加文本显示值,添加一定的偏移避免值与曲线重叠
|
||||
for j in range(1,len(feature_df),2):
|
||||
value = feature_df['y'].iloc[j]
|
||||
date = feature_df['ds'].iloc[j]
|
||||
offset = 1.001
|
||||
ax1.text(date, value * offset, str(round(value, 2)), ha='center', va='bottom', color='b', fontsize=10)
|
||||
# 创建第二个坐标轴
|
||||
ax2 = ax1.twinx()
|
||||
# 在第二个坐标轴上绘制数据
|
||||
line2 = ax2.plot(feature_df['ds'], feature_df[col], 'r-')
|
||||
ax2.set_ylabel(col, color='r')
|
||||
ax2.tick_params('y', colors='r')
|
||||
# 在 ax2 上添加文本显示值,添加一定的偏移避免值与曲线重叠
|
||||
for j in range(0,len(feature_df),2):
|
||||
value = feature_df[col].iloc[j]
|
||||
date = feature_df['ds'].iloc[j]
|
||||
offset = 1.001
|
||||
ax2.text(date, value * offset, str(round(value, 2)), ha='center', va='bottom', color='r', fontsize=10)
|
||||
# 添加标题
|
||||
plt.title(col)
|
||||
# 设置横坐标为日期格式并自动调整
|
||||
locator = mdates.AutoDateLocator()
|
||||
formatter = mdates.AutoDateFormatter(locator)
|
||||
ax1.xaxis.set_major_locator(locator)
|
||||
ax1.xaxis.set_major_formatter(formatter)
|
||||
# 文件名特殊字符处理
|
||||
col = col.replace('*', '-')
|
||||
col = col.replace(':', '-')
|
||||
plt.savefig(os.path.join(dataset, f'{col}与价格散点图.png'))
|
||||
content.append(Graphs.draw_img(os.path.join(dataset, f'{col}与价格散点图.png')))
|
||||
plt.close()
|
||||
|
||||
content.append(Graphs.draw_text('''相关系数为-1:表示两个变量之间存在完全负向的线性关系,即当一个变量增加时,另一个变量会相应减少,且变化是完全相反的'''))
|
||||
content.append(Graphs.draw_text('''当前特征中负相关前十的有:'''))
|
||||
tail10_columns = correlation_df.sort_values(by='Pearson_Correlation',ascending=True).head(10)['Feature'].to_list()
|
||||
top10 = ','.join(tail10_columns)
|
||||
content.append(Graphs.draw_text(f'''{top10}'''))
|
||||
# 获取特征的近一周值
|
||||
feature_df = feature_data_df[['ds','y']+tail10_columns]
|
||||
# 遍历X每一列,和yy画散点图 ,
|
||||
for i, col in enumerate(feature_df.columns):
|
||||
print(f'正在绘制第{i+1}个特征{col}与价格散点图...')
|
||||
if col not in ['ds', 'y']:
|
||||
fig, ax1 = plt.subplots(figsize=(10, 6))
|
||||
# 在第一个坐标轴上绘制数据
|
||||
ax1.plot(feature_df['ds'], feature_df['y'], 'b-')
|
||||
ax1.set_xlabel('日期')
|
||||
ax1.set_ylabel('y', color='b')
|
||||
ax1.tick_params('y', colors='b')
|
||||
# 在 ax1 上添加文本显示值,添加一定的偏移避免值与曲线重叠
|
||||
for j in range(len(feature_df)):
|
||||
if j%2 == 1:
|
||||
value = feature_df['y'].iloc[j]
|
||||
date = feature_df['ds'].iloc[j]
|
||||
offset = 1.001
|
||||
ax1.text(date, value * offset, str(round(value, 2)), ha='center', va='bottom', color='b', fontsize=10)
|
||||
# 创建第二个坐标轴
|
||||
ax2 = ax1.twinx()
|
||||
# 在第二个坐标轴上绘制数据
|
||||
line2 = ax2.plot(feature_df['ds'], feature_df[col], 'r-')
|
||||
ax2.set_ylabel(col, color='r')
|
||||
ax2.tick_params('y', colors='r')
|
||||
# 在 ax2 上添加文本显示值,添加一定的偏移避免值与曲线重叠
|
||||
for j in range(1,len(feature_df),2):
|
||||
value = feature_df[col].iloc[j]
|
||||
date = feature_df['ds'].iloc[j]
|
||||
offset = 1.001
|
||||
ax2.text(date, value * offset, str(round(value, 2)), ha='center', va='bottom', color='r', fontsize=10)
|
||||
# 添加标题
|
||||
plt.title(col)
|
||||
# 设置横坐标为日期格式并自动调整
|
||||
locator = mdates.AutoDateLocator()
|
||||
formatter = mdates.AutoDateFormatter(locator)
|
||||
ax1.xaxis.set_major_locator(locator)
|
||||
ax1.xaxis.set_major_formatter(formatter)
|
||||
# 文件名特殊字符处理
|
||||
col = col.replace('*', '-')
|
||||
col = col.replace(':', '-')
|
||||
col = col.replace('/', '-')
|
||||
plt.savefig(os.path.join(dataset, f'{col}与价格散点图.png'))
|
||||
content.append(Graphs.draw_img(os.path.join(dataset, f'{col}与价格散点图.png')))
|
||||
plt.close()
|
||||
content.append(Graphs.draw_text('''相关系数接近0:表示两个变量之间不存在线性关系,即它们的变化不会随着对方的变化而变化。'''))
|
||||
content.append(Graphs.draw_text(f'指标相关性分析--斯皮尔曼相关系数:'))
|
||||
# 皮尔逊正相关 不相关 负相关 的表格
|
||||
content.append(Graphs.draw_img(os.path.join(dataset,'斯皮尔曼相关性系数.png')))
|
||||
content.append(Graphs.draw_text('斯皮尔曼相关系数(Spearmans rank correlation coefficient)是一种用于衡量两个变量之间的单调关系(不一定是线性关系)的统计指标。'))
|
||||
content.append(Graphs.draw_text('它的计算基于变量的秩次(即变量值的排序位置)而非变量的原始值。'))
|
||||
content.append(Graphs.draw_text('斯皮尔曼相关系数的取值范围在 -1 到 1 之间。'))
|
||||
content.append(Graphs.draw_text('当系数为 1 时,表示两个变量之间存在完全正的单调关系;'))
|
||||
content.append(Graphs.draw_text('''当前特征中正单调关系前十的有:'''))
|
||||
top10_columns = correlation_df.sort_values(by='Spearman_Correlation',ascending=False).head(10)['Feature'].to_list()
|
||||
top10 = ','.join(top10_columns)
|
||||
content.append(Graphs.draw_text(f'''{top10}'''))
|
||||
for name, group in grouped:
|
||||
cols = group['指标名称'].tolist()
|
||||
logger.info(f'开始绘制{name}类指标的相关性直方图')
|
||||
cols_subset = cols
|
||||
feature_names = ['y'] + cols_subset
|
||||
correlation_matrix = df_zhibiaoshuju[feature_names].corr()['y']
|
||||
|
||||
feature_df = feature_data_df[['ds','y']+top10_columns]
|
||||
# 遍历X每一列,和yy画散点图 ,
|
||||
for i, col in enumerate(feature_df.columns):
|
||||
print(f'正在绘制第{i+1}个特征{col}与价格散点图...')
|
||||
if col not in ['ds', 'y']:
|
||||
fig, ax1 = plt.subplots(figsize=(10, 6))
|
||||
# 在第一个坐标轴上绘制数据
|
||||
ax1.plot(feature_df['ds'], feature_df['y'], 'b-')
|
||||
ax1.set_xlabel('日期')
|
||||
ax1.set_ylabel('y', color='b')
|
||||
ax1.tick_params('y', colors='b')
|
||||
# 在 ax1 上添加文本显示值,添加一定的偏移避免值与曲线重叠
|
||||
for j in range(1,len(feature_df),2):
|
||||
value = feature_df['y'].iloc[j]
|
||||
date = feature_df['ds'].iloc[j]
|
||||
offset = 1.001
|
||||
ax1.text(date, value * offset, str(round(value, 2)), ha='center', va='bottom', color='b', fontsize=10)
|
||||
# 创建第二个坐标轴
|
||||
ax2 = ax1.twinx()
|
||||
# 在第二个坐标轴上绘制数据
|
||||
line2 = ax2.plot(feature_df['ds'], feature_df[col], 'r-')
|
||||
ax2.set_ylabel(col, color='r')
|
||||
ax2.tick_params('y', colors='r')
|
||||
# 在 ax2 上添加文本显示值,添加一定的偏移避免值与曲线重叠
|
||||
for j in range(0,len(feature_df),2):
|
||||
value = feature_df[col].iloc[j]
|
||||
date = feature_df['ds'].iloc[j]
|
||||
offset = 1.001
|
||||
ax2.text(date, value * offset, str(round(value, 2)), ha='center', va='bottom', color='r', fontsize=10)
|
||||
# 添加标题
|
||||
plt.title(col)
|
||||
# 设置横坐标为日期格式并自动调整
|
||||
locator = mdates.AutoDateLocator()
|
||||
formatter = mdates.AutoDateFormatter(locator)
|
||||
ax1.xaxis.set_major_locator(locator)
|
||||
ax1.xaxis.set_major_formatter(formatter)
|
||||
# 文件名特殊字符处理
|
||||
col = col.replace('*', '-')
|
||||
col = col.replace(':', '-')
|
||||
plt.savefig(os.path.join(dataset, f'{col}与价格散点图.png'))
|
||||
content.append(Graphs.draw_img(os.path.join(dataset, f'{col}与价格散点图.png')))
|
||||
plt.close()
|
||||
# 绘制特征相关性直方分布图
|
||||
plt.figure(figsize=(10,8))
|
||||
sns.histplot(correlation_matrix.values.flatten(), bins=20, kde=True, color='skyblue')
|
||||
plt.title(f'{name}类指标(共{len(cols_subset)}个)相关性直方分布图')
|
||||
plt.xlabel('相关系数')
|
||||
plt.ylabel('频数')
|
||||
plt.savefig(os.path.join(dataset, f'{name}类指标相关性直方分布图.png'), bbox_inches='tight')
|
||||
plt.close()
|
||||
content.append(Graphs.draw_img(os.path.join(dataset,f'{name}类指标相关性直方分布图.png')))
|
||||
content.append(Graphs.draw_text(f'{name}类指标(共{len(cols_subset)}个)的相关性直方分布图如上所示。'))
|
||||
# 相关性大于0的特征
|
||||
positive_corr_features = correlation_matrix[correlation_matrix > 0].sort_values(ascending=False).index.tolist()[1:]
|
||||
|
||||
content.append(Graphs.draw_text('当系数为 -1 时,表示存在完全负的单调关系;'))
|
||||
content.append(Graphs.draw_text('''当前特征中负单调关系前十的有:'''))
|
||||
tail10_columns = correlation_df.sort_values(by='Spearman_Correlation',ascending=True).head(10)['Feature'].to_list()
|
||||
top10 = ','.join(tail10_columns)
|
||||
content.append(Graphs.draw_text(f'''{top10}'''))
|
||||
# 获取特征的近一周值
|
||||
feature_df = feature_data_df[['ds','y']+tail10_columns]
|
||||
# 遍历X每一列,和yy画散点图 ,
|
||||
for i, col in enumerate(feature_df.columns):
|
||||
print(f'正在绘制第{i+1}个特征{col}与价格散点图...')
|
||||
if col not in ['ds', 'y']:
|
||||
fig, ax1 = plt.subplots(figsize=(10, 6))
|
||||
# 在第一个坐标轴上绘制数据
|
||||
ax1.plot(feature_df['ds'], feature_df['y'], 'b-')
|
||||
ax1.set_xlabel('日期')
|
||||
ax1.set_ylabel('y', color='b')
|
||||
ax1.tick_params('y', colors='b')
|
||||
# 在 ax1 上添加文本显示值,添加一定的偏移避免值与曲线重叠
|
||||
for j in range(len(feature_df)):
|
||||
if j%2 == 1:
|
||||
value = feature_df['y'].iloc[j]
|
||||
date = feature_df['ds'].iloc[j]
|
||||
offset = 1.001
|
||||
ax1.text(date, value * offset, str(round(value, 2)), ha='center', va='bottom', color='b', fontsize=10)
|
||||
# 创建第二个坐标轴
|
||||
ax2 = ax1.twinx()
|
||||
# 在第二个坐标轴上绘制数据
|
||||
line2 = ax2.plot(feature_df['ds'], feature_df[col], 'r-')
|
||||
ax2.set_ylabel(col, color='r')
|
||||
ax2.tick_params('y', colors='r')
|
||||
# 在 ax2 上添加文本显示值,添加一定的偏移避免值与曲线重叠
|
||||
for j in range(1,len(feature_df),2):
|
||||
value = feature_df[col].iloc[j]
|
||||
date = feature_df['ds'].iloc[j]
|
||||
offset = 1.001
|
||||
ax2.text(date, value * offset, str(round(value, 2)), ha='center', va='bottom', color='r', fontsize=10)
|
||||
# 添加标题
|
||||
plt.title(col)
|
||||
# 设置横坐标为日期格式并自动调整
|
||||
locator = mdates.AutoDateLocator()
|
||||
formatter = mdates.AutoDateFormatter(locator)
|
||||
ax1.xaxis.set_major_locator(locator)
|
||||
ax1.xaxis.set_major_formatter(formatter)
|
||||
# 文件名特殊字符处理
|
||||
col = col.replace('*', '-')
|
||||
col = col.replace(':', '-')
|
||||
plt.savefig(os.path.join(dataset, f'{col}与价格散点图.png'))
|
||||
content.append(Graphs.draw_img(os.path.join(dataset, f'{col}与价格散点图.png')))
|
||||
plt.close()
|
||||
content.append(Graphs.draw_text('当系数为 0 时,表示两个变量之间不存在单调关系。'))
|
||||
content.append(Graphs.draw_text('与皮尔逊相关系数相比,斯皮尔曼相关系数对于数据中的异常值不敏感,更适用于处理非线性关系或存在极端值的数据。'))
|
||||
print(f'{name}下正相关的特征值有:',positive_corr_features)
|
||||
if len(positive_corr_features) > 5:
|
||||
positive_corr_features = positive_corr_features[0:5]
|
||||
content.append(Graphs.draw_text(f'{name}类指标中,与预测目标y正相关前五的特征有:{positive_corr_features}'))
|
||||
draw_feature_trend(feature_data_df, positive_corr_features)
|
||||
elif len(positive_corr_features) == 0:
|
||||
pass
|
||||
else:
|
||||
positive_corr_features = positive_corr_features
|
||||
content.append(Graphs.draw_text(f'其中,与预测目标y正相关的特征有:{positive_corr_features}'))
|
||||
draw_feature_trend(feature_data_df, positive_corr_features)
|
||||
|
||||
# 相关性小于0的特征
|
||||
negative_corr_features = correlation_matrix[correlation_matrix < 0].sort_values(ascending=True).index.tolist()
|
||||
|
||||
print(f'{name}下负相关的特征值有:',negative_corr_features)
|
||||
if len(negative_corr_features) > 5:
|
||||
negative_corr_features = negative_corr_features[:5]
|
||||
content.append(Graphs.draw_text(f'与预测目标y负相关前五的特征有:{negative_corr_features}'))
|
||||
draw_feature_trend(feature_data_df, negative_corr_features)
|
||||
elif len(negative_corr_features) == 0:
|
||||
pass
|
||||
else:
|
||||
content.append(Graphs.draw_text(f'{name}类指标中,与预测目标y负相关的特征有:{negative_corr_features}'))
|
||||
draw_feature_trend(feature_data_df, negative_corr_features)
|
||||
|
||||
|
||||
# 计算correlation_sum 第一行的相关性的绝对值的总和
|
||||
correlation_sum = correlation_matrix.abs().sum()
|
||||
logger.info(f'{name}类指标的相关性总和为:{correlation_sum}')
|
||||
# 分组的相关性总和拼接到grouped_corr
|
||||
goup_corr = pd.DataFrame({'指标分类': [name], '指标数量': [len(cols_subset)], '相关性总和': [correlation_sum]})
|
||||
grouped_corr = pd.concat([grouped_corr, goup_corr], axis=0, ignore_index=True)
|
||||
|
||||
# 绘制相关性总和的气泡图
|
||||
logger.info(f'开始绘制相关性总和的气泡图')
|
||||
plt.figure(figsize=(10, 10))
|
||||
sns.scatterplot(data=grouped_corr, x='相关性总和', y='指标数量', size='相关性总和', sizes=(grouped_corr['相关性总和'].min()*5, grouped_corr['相关性总和'].max()*5), hue='指标分类', palette='viridis')
|
||||
plt.title('指标分类相关性总和的气泡图')
|
||||
plt.ylabel('数量')
|
||||
plt.savefig(os.path.join(dataset, '指标分类相关性总和的气泡图.png'), bbox_inches='tight')
|
||||
plt.close()
|
||||
content.append(Graphs.draw_img(os.path.join(dataset,'指标分类相关性总和的气泡图.png')))
|
||||
logger.info(f'绘制相关性总和的气泡图结束')
|
||||
|
||||
|
||||
|
||||
# # 计算特征相关性
|
||||
# data.rename(columns={y: 'y'}, inplace=True)
|
||||
# data['ds'] = pd.to_datetime(data['ds'])
|
||||
# data.drop(columns=['ds'], inplace=True)
|
||||
# # 创建一个空的 DataFrame 来保存相关系数
|
||||
# correlation_df = pd.DataFrame(columns=['Feature', 'Correlation'])
|
||||
# # 计算各特征与目标列的皮尔逊相关系数,并保存到新的 Data 中
|
||||
# for col in data.columns:
|
||||
# if col!= 'y':
|
||||
# pearson_correlation = np.corrcoef(data[col], data['y'])[0, 1]
|
||||
# spearman_correlation, _ = spearmanr(data[col], data['y'])
|
||||
# new_row = {'Feature': col, 'Pearson_Correlation': round(pearson_correlation,3), 'Spearman_Correlation': round(spearman_correlation,2)}
|
||||
# correlation_df = correlation_df._append(new_row, ignore_index=True)
|
||||
|
||||
# correlation_df.drop('Correlation', axis=1, inplace=True)
|
||||
# correlation_df.dropna(inplace=True)
|
||||
# correlation_df.to_csv(os.path.join(dataset,'指标相关性分析.csv'), index=False)
|
||||
|
||||
# data = correlation_df['Pearson_Correlation'].values.tolist()
|
||||
# # 生成 -1 到 1 的 20 个区间
|
||||
# bins = np.linspace(-1, 1, 21)
|
||||
# # 计算每个区间的统计数(这里是区间内数据的数量)
|
||||
# hist_values = [np.sum((data >= bins[i]) & (data < bins[i + 1])) for i in range(len(bins) - 1)]
|
||||
|
||||
# #设置画布大小
|
||||
# plt.figure(figsize=(10, 6))
|
||||
# # 绘制直方图
|
||||
# plt.bar(bins[:-1], hist_values, width=(bins[1] - bins[0]))
|
||||
|
||||
# # 添加标题和坐标轴标签
|
||||
# plt.title('皮尔逊相关系数分布图')
|
||||
# plt.xlabel('区间')
|
||||
# plt.ylabel('统计数')
|
||||
# plt.savefig(os.path.join(dataset, '皮尔逊相关性系数.png'))
|
||||
# plt.close()
|
||||
|
||||
|
||||
# #设置画布大小
|
||||
# plt.figure(figsize=(10, 6))
|
||||
# data = correlation_df['Spearman_Correlation'].values.tolist()
|
||||
# # 计算每个区间的统计数(这里是区间内数据的数量)
|
||||
# hist_values = [np.sum((data >= bins[i]) & (data < bins[i + 1])) for i in range(len(bins) - 1)]
|
||||
|
||||
# # 绘制直方图
|
||||
# plt.bar(bins[:-1], hist_values, width=(bins[1] - bins[0]))
|
||||
|
||||
# # 添加标题和坐标轴标签
|
||||
# plt.title('斯皮尔曼相关系数分布图')
|
||||
# plt.xlabel('区间')
|
||||
# plt.ylabel('统计数')
|
||||
# plt.savefig(os.path.join(dataset, '斯皮尔曼相关性系数.png'))
|
||||
# plt.close()
|
||||
# content.append(Graphs.draw_text(f'指标相关性分析--皮尔逊相关系数:'))
|
||||
# # 皮尔逊正相关 不相关 负相关 的表格
|
||||
# content.append(Graphs.draw_img(os.path.join(dataset,'皮尔逊相关性系数.png')))
|
||||
# content.append(Graphs.draw_text('''皮尔逊相关系数说明:'''))
|
||||
# content.append(Graphs.draw_text('''衡量两个特征之间的线性相关性。'''))
|
||||
# content.append(Graphs.draw_text('''
|
||||
# 相关系数为1:表示两个变量之间存在完全正向的线性关系,即当一个变量增加时,另一个变量也相应增加,且变化是完全一致的。'''))
|
||||
# content.append(Graphs.draw_text('''当前特征中正相关前十的有:'''))
|
||||
# top10_columns = correlation_df.sort_values(by='Pearson_Correlation',ascending=False).head(10)['Feature'].to_list()
|
||||
# top10 = ','.join(top10_columns)
|
||||
# content.append(Graphs.draw_text(f'''{top10}'''))
|
||||
|
||||
# feature_df = feature_data_df[['ds','y']+top10_columns]
|
||||
# # 遍历X每一列,和yy画散点图 ,
|
||||
# for i, col in enumerate(feature_df.columns):
|
||||
# print(f'正在绘制第{i+1}个特征{col}与价格散点图...')
|
||||
# if col not in ['ds', 'y']:
|
||||
# fig, ax1 = plt.subplots(figsize=(10, 6))
|
||||
# # 在第一个坐标轴上绘制数据
|
||||
# ax1.plot(feature_df['ds'], feature_df['y'], 'b-')
|
||||
# ax1.set_xlabel('日期')
|
||||
# ax1.set_ylabel('y', color='b')
|
||||
# ax1.tick_params('y', colors='b')
|
||||
# # 在 ax1 上添加文本显示值,添加一定的偏移避免值与曲线重叠
|
||||
# for j in range(1,len(feature_df),2):
|
||||
# value = feature_df['y'].iloc[j]
|
||||
# date = feature_df['ds'].iloc[j]
|
||||
# offset = 1.001
|
||||
# ax1.text(date, value * offset, str(round(value, 2)), ha='center', va='bottom', color='b', fontsize=10)
|
||||
# # 创建第二个坐标轴
|
||||
# ax2 = ax1.twinx()
|
||||
# # 在第二个坐标轴上绘制数据
|
||||
# line2 = ax2.plot(feature_df['ds'], feature_df[col], 'r-')
|
||||
# ax2.set_ylabel(col, color='r')
|
||||
# ax2.tick_params('y', colors='r')
|
||||
# # 在 ax2 上添加文本显示值,添加一定的偏移避免值与曲线重叠
|
||||
# for j in range(0,len(feature_df),2):
|
||||
# value = feature_df[col].iloc[j]
|
||||
# date = feature_df['ds'].iloc[j]
|
||||
# offset = 1.001
|
||||
# ax2.text(date, value * offset, str(round(value, 2)), ha='center', va='bottom', color='r', fontsize=10)
|
||||
# # 添加标题
|
||||
# plt.title(col)
|
||||
# # 设置横坐标为日期格式并自动调整
|
||||
# locator = mdates.AutoDateLocator()
|
||||
# formatter = mdates.AutoDateFormatter(locator)
|
||||
# ax1.xaxis.set_major_locator(locator)
|
||||
# ax1.xaxis.set_major_formatter(formatter)
|
||||
# # 文件名特殊字符处理
|
||||
# col = col.replace('*', '-')
|
||||
# col = col.replace(':', '-')
|
||||
# plt.savefig(os.path.join(dataset, f'{col}与价格散点图.png'))
|
||||
# content.append(Graphs.draw_img(os.path.join(dataset, f'{col}与价格散点图.png')))
|
||||
# plt.close()
|
||||
|
||||
|
||||
# content.append(Graphs.draw_text(f'指标相关性分析--斯皮尔曼相关系数:'))
|
||||
# # 皮尔逊正相关 不相关 负相关 的表格
|
||||
# content.append(Graphs.draw_img(os.path.join(dataset,'斯皮尔曼相关性系数.png')))
|
||||
# content.append(Graphs.draw_text('斯皮尔曼相关系数(Spearmans rank correlation coefficient)是一种用于衡量两个变量之间的单调关系(不一定是线性关系)的统计指标。'))
|
||||
# content.append(Graphs.draw_text('它的计算基于变量的秩次(即变量值的排序位置)而非变量的原始值。'))
|
||||
# content.append(Graphs.draw_text('斯皮尔曼相关系数的取值范围在 -1 到 1 之间。'))
|
||||
# content.append(Graphs.draw_text('当系数为 1 时,表示两个变量之间存在完全正的单调关系;'))
|
||||
# content.append(Graphs.draw_text('''当前特征中正单调关系前十的有:'''))
|
||||
# top10_columns = correlation_df.sort_values(by='Spearman_Correlation',ascending=False).head(10)['Feature'].to_list()
|
||||
# top10 = ','.join(top10_columns)
|
||||
# content.append(Graphs.draw_text(f'''{top10}'''))
|
||||
|
||||
# feature_df = feature_data_df[['ds','y']+top10_columns]
|
||||
# # 遍历X每一列,和yy画散点图 ,
|
||||
# for i, col in enumerate(feature_df.columns):
|
||||
# print(f'正在绘制第{i+1}个特征{col}与价格散点图...')
|
||||
# if col not in ['ds', 'y']:
|
||||
# fig, ax1 = plt.subplots(figsize=(10, 6))
|
||||
# # 在第一个坐标轴上绘制数据
|
||||
# ax1.plot(feature_df['ds'], feature_df['y'], 'b-')
|
||||
# ax1.set_xlabel('日期')
|
||||
# ax1.set_ylabel('y', color='b')
|
||||
# ax1.tick_params('y', colors='b')
|
||||
# # 在 ax1 上添加文本显示值,添加一定的偏移避免值与曲线重叠
|
||||
# for j in range(1,len(feature_df),2):
|
||||
# value = feature_df['y'].iloc[j]
|
||||
# date = feature_df['ds'].iloc[j]
|
||||
# offset = 1.001
|
||||
# ax1.text(date, value * offset, str(round(value, 2)), ha='center', va='bottom', color='b', fontsize=10)
|
||||
# # 创建第二个坐标轴
|
||||
# ax2 = ax1.twinx()
|
||||
# # 在第二个坐标轴上绘制数据
|
||||
# line2 = ax2.plot(feature_df['ds'], feature_df[col], 'r-')
|
||||
# ax2.set_ylabel(col, color='r')
|
||||
# ax2.tick_params('y', colors='r')
|
||||
# # 在 ax2 上添加文本显示值,添加一定的偏移避免值与曲线重叠
|
||||
# for j in range(0,len(feature_df),2):
|
||||
# value = feature_df[col].iloc[j]
|
||||
# date = feature_df['ds'].iloc[j]
|
||||
# offset = 1.001
|
||||
# ax2.text(date, value * offset, str(round(value, 2)), ha='center', va='bottom', color='r', fontsize=10)
|
||||
# # 添加标题
|
||||
# plt.title(col)
|
||||
# # 设置横坐标为日期格式并自动调整
|
||||
# locator = mdates.AutoDateLocator()
|
||||
# formatter = mdates.AutoDateFormatter(locator)
|
||||
# ax1.xaxis.set_major_locator(locator)
|
||||
# ax1.xaxis.set_major_formatter(formatter)
|
||||
# # 文件名特殊字符处理
|
||||
# col = col.replace('*', '-')
|
||||
# col = col.replace(':', '-')
|
||||
# plt.savefig(os.path.join(dataset, f'{col}与价格散点图.png'))
|
||||
# content.append(Graphs.draw_img(os.path.join(dataset, f'{col}与价格散点图.png')))
|
||||
# plt.close()
|
||||
|
||||
# content.append(Graphs.draw_text('当系数为 -1 时,表示存在完全负的单调关系;'))
|
||||
# content.append(Graphs.draw_text('''当前特征中负单调关系前十的有:'''))
|
||||
# tail10_columns = correlation_df.sort_values(by='Spearman_Correlation',ascending=True).head(10)['Feature'].to_list()
|
||||
# top10 = ','.join(tail10_columns)
|
||||
# content.append(Graphs.draw_text(f'''{top10}'''))
|
||||
# # 获取特征的近一周值
|
||||
# feature_df = feature_data_df[['ds','y']+tail10_columns]
|
||||
# # 遍历X每一列,和yy画散点图 ,
|
||||
# for i, col in enumerate(feature_df.columns):
|
||||
# print(f'正在绘制第{i+1}个特征{col}与价格散点图...')
|
||||
# if col not in ['ds', 'y']:
|
||||
# fig, ax1 = plt.subplots(figsize=(10, 6))
|
||||
# # 在第一个坐标轴上绘制数据
|
||||
# ax1.plot(feature_df['ds'], feature_df['y'], 'b-')
|
||||
# ax1.set_xlabel('日期')
|
||||
# ax1.set_ylabel('y', color='b')
|
||||
# ax1.tick_params('y', colors='b')
|
||||
# # 在 ax1 上添加文本显示值,添加一定的偏移避免值与曲线重叠
|
||||
# for j in range(len(feature_df)):
|
||||
# if j%2 == 1:
|
||||
# value = feature_df['y'].iloc[j]
|
||||
# date = feature_df['ds'].iloc[j]
|
||||
# offset = 1.001
|
||||
# ax1.text(date, value * offset, str(round(value, 2)), ha='center', va='bottom', color='b', fontsize=10)
|
||||
# # 创建第二个坐标轴
|
||||
# ax2 = ax1.twinx()
|
||||
# # 在第二个坐标轴上绘制数据
|
||||
# line2 = ax2.plot(feature_df['ds'], feature_df[col], 'r-')
|
||||
# ax2.set_ylabel(col, color='r')
|
||||
# ax2.tick_params('y', colors='r')
|
||||
# # 在 ax2 上添加文本显示值,添加一定的偏移避免值与曲线重叠
|
||||
# for j in range(1,len(feature_df),2):
|
||||
# value = feature_df[col].iloc[j]
|
||||
# date = feature_df['ds'].iloc[j]
|
||||
# offset = 1.001
|
||||
# ax2.text(date, value * offset, str(round(value, 2)), ha='center', va='bottom', color='r', fontsize=10)
|
||||
# # 添加标题
|
||||
# plt.title(col)
|
||||
# # 设置横坐标为日期格式并自动调整
|
||||
# locator = mdates.AutoDateLocator()
|
||||
# formatter = mdates.AutoDateFormatter(locator)
|
||||
# ax1.xaxis.set_major_locator(locator)
|
||||
# ax1.xaxis.set_major_formatter(formatter)
|
||||
# # 文件名特殊字符处理
|
||||
# col = col.replace('*', '-')
|
||||
# col = col.replace(':', '-')
|
||||
# plt.savefig(os.path.join(dataset, f'{col}与价格散点图.png'))
|
||||
# content.append(Graphs.draw_img(os.path.join(dataset, f'{col}与价格散点图.png')))
|
||||
# plt.close()
|
||||
# content.append(Graphs.draw_text('当系数为 0 时,表示两个变量之间不存在单调关系。'))
|
||||
# content.append(Graphs.draw_text('与皮尔逊相关系数相比,斯皮尔曼相关系数对于数据中的异常值不敏感,更适用于处理非线性关系或存在极端值的数据。'))
|
||||
content.append(Graphs.draw_little_title('模型选择:'))
|
||||
content.append(Graphs.draw_text(f'预测使用了{num_models}个模型进行训练拟合,通过评估指标MAE从小到大排列,前5个模型的简介如下:'))
|
||||
|
||||
@ -934,6 +990,8 @@ def brent_export_pdf(num_indicators=475,num_models=21, num_dayindicator=202,inpu
|
||||
except TimeoutError as e:
|
||||
print(f"请求超时: {e}")
|
||||
|
||||
|
||||
|
||||
def pp_export_pdf(num_indicators=475,num_models=21, num_dayindicator=202,inputsize=5,dataset='dataset',time = '2024-07-30',reportname='report.pdf'):
|
||||
global y
|
||||
# 创建内容对应的空列表
|
||||
|
Loading…
Reference in New Issue
Block a user