307 lines
14 KiB
Python
307 lines
14 KiB
Python
"""
|
|
月消费潜力、评级计算
|
|
"""
|
|
from goojia_utils import ElasticSearchClient, dateutils, nextcloudutils
|
|
import pandas as pd
|
|
import numpy as np
|
|
import logging
|
|
import os
|
|
from elasticsearch import helpers
|
|
import matplotlib.pyplot as plt
|
|
import sys
|
|
|
|
from sklearn.mixture import GaussianMixture
|
|
from sklearn.preprocessing import QuantileTransformer
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
es206_client = ElasticSearchClient(host='192.168.0.206')
|
|
index_name = "community_summary"
|
|
path = "/opt/airflow/dags/repo/dags/business/business/community/data"
|
|
save_path_prefix = "/home/airflow/data/community"
|
|
|
|
save_png_path = save_path_prefix + "/consumption_rating"
|
|
if not os.path.exists(save_png_path):
|
|
os.makedirs(save_png_path)
|
|
|
|
nextcloud_aim_file_path = '共享/财力评级/财力评级图'
|
|
|
|
reasonable_df = pd.read_excel(path + '/财力评级分布情况20221215.xlsx')
|
|
reasonable_dict = reasonable_df.set_index('city')['是否合理'].to_dict()
|
|
|
|
|
|
def calc_consumption_potential(city):
|
|
"""
|
|
计算消费潜力
|
|
"""
|
|
sql = "select id, city, region, name, total_price, estate_charge, estate_charge_fix, relative_price_ranking, avg_cost from community_summary where city='" + city + "'"
|
|
community_summary_df = es206_client.scan_by_sql_to_data_frame(sql)
|
|
columns = community_summary_df.columns
|
|
if 'total_price' not in columns or 'estate_charge' not in columns or 'relative_price_ranking' not in columns or 'avg_cost' not in columns:
|
|
return []
|
|
# 解决某些城市无修正物业费问题
|
|
if 'estate_charge_fix' not in community_summary_df.columns:
|
|
community_summary_df['estate_charge_fix'] = None
|
|
# 修正的物业费入模
|
|
community_summary_df['estate_charge_fix'].fillna(community_summary_df['estate_charge'], inplace=True)
|
|
|
|
community_summary_df = community_summary_df.dropna(how='any').copy()
|
|
if len(community_summary_df) == 0:
|
|
log.warning(f"{city}无法评级,缺少因子")
|
|
return []
|
|
|
|
# 户均总价计算时候改成万
|
|
community_summary_df['total_price'] = round(community_summary_df['total_price'] / 10000, 0)
|
|
|
|
community_summary_df['total_price_mean'] = community_summary_df.groupby(by=['city'])['total_price'].transform(
|
|
np.mean)
|
|
community_summary_df['total_price_std'] = community_summary_df.groupby(by=['city'])['total_price'].transform(np.std)
|
|
|
|
# 噪音词处理
|
|
community_summary_df['avg_cost_fixed'] = QuantileTransformer(output_distribution="normal").fit_transform(
|
|
community_summary_df[['avg_cost']])
|
|
|
|
community_summary_df['estate_charge_fixed'] = QuantileTransformer(output_distribution="normal").fit_transform(
|
|
community_summary_df[['estate_charge_fix']])
|
|
|
|
community_summary_df['estate_charge_mean'] = community_summary_df.groupby(by=['city'])['estate_charge_fixed'].transform(
|
|
np.mean)
|
|
community_summary_df['estate_charge_std'] = community_summary_df.groupby(by=['city'])['estate_charge_fixed'].transform(
|
|
np.std)
|
|
|
|
community_summary_df['relative_price_ranking_mean'] = community_summary_df.groupby(by=['city'])[
|
|
'relative_price_ranking'].transform(np.mean)
|
|
community_summary_df['relative_price_ranking_std'] = community_summary_df.groupby(by=['city'])[
|
|
'relative_price_ranking'].transform(np.std)
|
|
|
|
community_summary_df['avg_cost_mean'] = community_summary_df.groupby(by=['city'])['avg_cost_fixed'].transform(np.mean)
|
|
community_summary_df['avg_cost_std'] = community_summary_df.groupby(by=['city'])['avg_cost_fixed'].transform(np.std)
|
|
|
|
# 和田等小城市均值可能为0
|
|
if community_summary_df['total_price_std'].unique()[0] != 0:
|
|
community_summary_df['total_price_score'] = 286.0134196 * (community_summary_df['total_price'] - community_summary_df['total_price_mean']) / community_summary_df['total_price_std']
|
|
else:
|
|
community_summary_df['total_price_score'] = 0
|
|
|
|
if community_summary_df['estate_charge_std'].unique()[0] != 0:
|
|
community_summary_df['estate_charge_score'] = 139.1374524 * (community_summary_df['estate_charge_fixed'] - community_summary_df['estate_charge_mean']) / community_summary_df['estate_charge_std']
|
|
else:
|
|
community_summary_df['estate_charge_score'] = 0
|
|
|
|
if community_summary_df['relative_price_ranking_std'].unique()[0] != 0:
|
|
community_summary_df['relative_price_ranking_score'] = 21.8427926 * (community_summary_df['relative_price_ranking'] - community_summary_df['relative_price_ranking_mean']) / community_summary_df['relative_price_ranking_std']
|
|
else:
|
|
community_summary_df['relative_price_ranking_score'] = 0
|
|
|
|
if community_summary_df['avg_cost_std'].unique()[0] != 0:
|
|
community_summary_df['avg_cost_score'] = 67.0195871700 * (community_summary_df['avg_cost_fixed'] - community_summary_df['avg_cost_mean']) / community_summary_df['avg_cost_std']
|
|
else:
|
|
community_summary_df['avg_cost_score'] = 0
|
|
|
|
community_summary_df['consumption_potential'] = community_summary_df['total_price_score'] + community_summary_df[
|
|
'estate_charge_score'] + community_summary_df['relative_price_ranking_score'] + community_summary_df['avg_cost_score'] + community_summary_df['avg_cost_score'] + 4099.978248
|
|
return community_summary_df
|
|
|
|
|
|
def gmm_train(total_rate, consumption_df, source, target):
|
|
# 高斯混合模型
|
|
gmm = GaussianMixture(n_components=total_rate, covariance_type='tied', max_iter=200, n_init=10).fit(consumption_df[[source]])
|
|
consumption_df.loc[:, 'cluster'] = gmm.predict(consumption_df[[source]])
|
|
consumption_df.loc[:, 'price_mean_cluster'] = consumption_df.groupby('cluster')[source].transform('mean')
|
|
consumption_df.loc[:, target] = consumption_df['price_mean_cluster'].rank(method='dense', ascending=False).astype(int)
|
|
consumption_df = consumption_df.drop(columns=['cluster', 'price_mean_cluster'], axis=1)
|
|
return consumption_df
|
|
|
|
|
|
def calc_consumption_rating(community_summary_df):
|
|
"""
|
|
计算消费等级
|
|
"""
|
|
df = community_summary_df[['_id', 'city', 'consumption_potential']]
|
|
df = df.dropna(subset=['consumption_potential'])
|
|
source = "normal_consumption_potential"
|
|
target = "consumption_rating"
|
|
actions = list()
|
|
count = 0
|
|
|
|
# 总评级
|
|
total_rate = 6
|
|
if len(df) < total_rate:
|
|
# 对于样本低于5的直接排名
|
|
df[target] = df['consumption_potential'].rank(method='dense', ascending=False).astype(int)
|
|
else:
|
|
# 极值设置
|
|
df = filter_min_max(df)
|
|
df = gmm_train(total_rate, df, source, target)
|
|
# 批量更新
|
|
for index, item in df.iterrows():
|
|
row = dict()
|
|
_id = str(item["_id"])
|
|
row['consumption_rating'] = item['consumption_rating']
|
|
row['consumption_potential'] = item['consumption_potential']
|
|
row['m_date'] = dateutils.iso_format()
|
|
|
|
action = {'_op_type': 'update', # 操作 index update create delete
|
|
'_index': index_name, # index
|
|
'_id': _id, # 请勿忘记ID
|
|
'doc': row,
|
|
"_retry_on_conflict": 5
|
|
}
|
|
actions.append(action)
|
|
if len(actions) == 5000:
|
|
helpers.bulk(client=es206_client.elastic_client, actions=actions)
|
|
count += len(actions)
|
|
actions.clear()
|
|
log.info("评级中: 当前已评级{}".format(count))
|
|
if len(actions) > 0:
|
|
helpers.bulk(client=es206_client.elastic_client, actions=actions)
|
|
count += len(actions)
|
|
actions.clear()
|
|
log.info("评级完成,共更新: {}".format(count))
|
|
return pd.merge(community_summary_df, df, how='left', on=['_id', 'city', 'consumption_potential'])
|
|
|
|
|
|
def sync_by_city(city_now):
|
|
log.info(f"{city_now}开始评级....")
|
|
community_summary_df = calc_consumption_potential(city_now)
|
|
if len(community_summary_df) == 0:
|
|
log.warning(f"{city_now}无法评级,缺少因子")
|
|
return
|
|
community_summary_df = calc_consumption_rating(community_summary_df)
|
|
if len(community_summary_df) == 0:
|
|
log.warning(f"{city_now}无法评级,数量低于5")
|
|
return
|
|
save_png(community_summary_df)
|
|
nextcloudutils.up_to_nextcloud(save_png_path + "/" + city_now + ".png", nextcloud_aim_file_path + "/" + city_now + ".png")
|
|
|
|
|
|
def clear_rating(temp_df):
|
|
"""
|
|
清空评级信息
|
|
"""
|
|
actions = list()
|
|
count = 0
|
|
for index, item in temp_df.iterrows():
|
|
_id = str(item["_id"])
|
|
|
|
action = {'_op_type': 'update', # 操作 index update create delete
|
|
'_index': index_name, # index
|
|
'_id': _id, # 请勿忘记ID
|
|
'doc': {'consumption_rating': None, 'consumption_potential': None},
|
|
"_retry_on_conflict": 5
|
|
}
|
|
actions.append(action)
|
|
if len(actions) == 5000:
|
|
helpers.bulk(client=es206_client.elastic_client, actions=actions)
|
|
count += len(actions)
|
|
actions.clear()
|
|
log.info("清理中: 当前已清理{}".format(count))
|
|
if len(actions) > 0:
|
|
helpers.bulk(client=es206_client.elastic_client, actions=actions)
|
|
count += len(actions)
|
|
actions.clear()
|
|
log.info("清理完毕: 共清理{}".format(count))
|
|
|
|
|
|
def sync(city=None):
|
|
clear_sql = "select city, region, name from community_summary where consumption_potential is not null and (total_price is null or estate_charge is null or avg_cost is null) "
|
|
if pd.isna(city):
|
|
# 清空缺少因子的老潜力
|
|
temp_df = es206_client.scan_by_sql_to_data_frame(clear_sql)
|
|
clear_rating(temp_df)
|
|
for city_now in reasonable_df['city'].unique():
|
|
#if pd.isna(reasonable_dict[city_now]):
|
|
sync_by_city(city_now)
|
|
else:
|
|
clear_sql += f" and city='{city}' "
|
|
temp_df = es206_client.scan_by_sql_to_data_frame(clear_sql)
|
|
clear_rating(temp_df)
|
|
sync_by_city(city)
|
|
|
|
|
|
def filter_min_max(community_summary_df):
|
|
community_summary_df['normal_consumption_potential'] = QuantileTransformer(output_distribution="normal").fit_transform(community_summary_df[['consumption_potential']])
|
|
# total_price5 = np.percentile(a=community_summary_df['total_price'], q=2, axis=0)
|
|
# total_price95 = np.percentile(a=community_summary_df['total_price'], q=98, axis=0)
|
|
# community_summary_df.loc[community_summary_df['total_price'] > total_price95, 'total_price'] = total_price95
|
|
# community_summary_df.loc[community_summary_df['total_price'] < total_price5, 'total_price'] = total_price5
|
|
#
|
|
# estate_charge5 = np.percentile(a=community_summary_df['estate_charge'], q=2, axis=0)
|
|
# estate_charge95 = np.percentile(a=community_summary_df['estate_charge'], q=98, axis=0)
|
|
# community_summary_df.loc[community_summary_df['estate_charge'] > estate_charge95, 'estate_charge'] = estate_charge95
|
|
# community_summary_df.loc[community_summary_df['estate_charge'] < estate_charge5, 'estate_charge'] = estate_charge5
|
|
#
|
|
# avg_cost5 = np.percentile(a=community_summary_df['avg_cost'], q=2, axis=0)
|
|
# avg_cost95 = np.percentile(a=community_summary_df['avg_cost'], q=98, axis=0)
|
|
# community_summary_df.loc[community_summary_df['avg_cost'] > avg_cost95, 'avg_cost'] = avg_cost95
|
|
# community_summary_df.loc[community_summary_df['avg_cost'] < avg_cost5, 'avg_cost'] = avg_cost5
|
|
|
|
#if city in factor_dict:
|
|
# 户均总价按极值设置可靠性不高,当户均总价补充后,图中大于最大值的量非常多
|
|
# community_summary_df.loc[
|
|
# community_summary_df['total_price'] < factor_dict[city]['min_total_price'], 'total_price'] = \
|
|
# factor_dict[city]['min_total_price']
|
|
# community_summary_df.loc[
|
|
# community_summary_df['total_price'] > factor_dict[city]['max_total_price'], 'total_price'] = \
|
|
# factor_dict[city]['max_total_price']
|
|
|
|
# community_summary_df.loc[
|
|
# community_summary_df['estate_charge'] < factor_dict[city]['min_estate_charge'], 'estate_charge'] = \
|
|
# factor_dict[city]['min_estate_charge']
|
|
# community_summary_df.loc[
|
|
# community_summary_df['estate_charge'] > factor_dict[city]['max_estate_charge'], 'estate_charge'] = \
|
|
# factor_dict[city]['max_estate_charge']
|
|
# community_summary_df.loc[community_summary_df['avg_cost'] < factor_dict[city]['min_avg_cost'], 'avg_cost'] = \
|
|
# factor_dict[city]['min_avg_cost']
|
|
# community_summary_df.loc[community_summary_df['avg_cost'] > factor_dict[city]['max_avg_cost'], 'avg_cost'] = \
|
|
# factor_dict[city]['max_avg_cost']
|
|
return community_summary_df
|
|
|
|
|
|
def save_png(community_city):
|
|
"""
|
|
生成财力评级图表
|
|
"""
|
|
curr_city = community_city['city'].unique()[0]
|
|
# 解决中文显示问题
|
|
plt.rcParams['font.sans-serif'] = ['SimHei']
|
|
plt.rcParams['axes.unicode_minus'] = False
|
|
plt.title(curr_city)
|
|
plt.subplot(3, 1, 1)
|
|
community_city['consumption_rating'].hist(bins=100)
|
|
plt.xlabel('consumption_rating')
|
|
plt.tight_layout()
|
|
|
|
plt.subplot(3, 2, 3)
|
|
community_city['total_price'].hist(bins=100)
|
|
plt.xlabel('total_price')
|
|
plt.tight_layout()
|
|
|
|
plt.subplot(3, 2, 4)
|
|
community_city['estate_charge'].hist(bins=100)
|
|
plt.xlabel('estate_charge')
|
|
plt.tight_layout()
|
|
|
|
plt.subplot(3, 2, 5)
|
|
community_city['avg_cost'].hist(bins=100)
|
|
plt.xlabel('avg_cost')
|
|
plt.tight_layout()
|
|
|
|
plt.subplot(3, 2, 6)
|
|
community_city['relative_price_ranking'].hist(bins=100)
|
|
plt.xlabel('relative_price_ranking')
|
|
plt.tight_layout()
|
|
|
|
plt.savefig(save_png_path + "/" + curr_city + ".png")
|
|
# 清图
|
|
plt.clf()
|
|
# 清坐标轴
|
|
plt.cla()
|
|
# 关窗口
|
|
plt.close()
|
|
|
|
|
|
city = sys.argv[1] if len(sys.argv) > 1 else None
|
|
sync(city)
|
|
#dingutils.send_text("【分布图生成完毕】财力评级已完成, 请点击 https://nextcloud.fangjia.com/s/Jqs5BzXi8xLYeH9 查看分布图", "c7ac6c86bfbe49a95e30a68616c4d784ae7781c715430dc9c5f6b46d3e6ebd78")
|