版本修改

This commit is contained in:
王文艳
2026-07-22 15:17:02 +08:00
parent 9467a62152
commit bfcdb591d3
21 changed files with 0 additions and 0 deletions
View File
+37
View File
@@ -0,0 +1,37 @@
import requests
import ssl
import datetime
import urllib3
from goojia_utils import nextcloudutils, dingutils
# 禁用 InsecureRequestWarning
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# 获取当前日期
current_date = datetime.datetime.now()
# 计算前一日的日期
previous_date = current_date - datetime.timedelta(days=1)
# 格式化日期
formatted_date = previous_date.strftime("%Y.%m.%d")
data = {
"parentCode": "001.002",
"dateRange": formatted_date + "," + formatted_date
}
headers = {
"Accept": "*/*",
"Content-Type": "application/json",
"Authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJhY2NvdW50IjoiYWlyZmxvdyIsImV4cCI6MTMxMzM5NDE2MzQwNDYxLCJvcmdDb2RlIjoiMDAxLjAwMSIsInJvbGVzIjpbIm5vcm1hbCJdLCJ1c2VySWQiOiIxODg5ODc0MDc4MTgxODMwNjU2IiwidXNlcm5hbWUiOiLlrprml7bku7vliqEifQ.SvD42b8XGlxYe_0dBr215ZgxR9aBdsipaySceZuuWR6g5cHelU5oc-dRtK63b0CMoN07BSvh2XYdlIzQ92ngOA"
}
ret = requests.post(url='https://api.fangjia.com/exportStatistics', json=data, headers=headers, verify=False)
#ret = requests.post(url='http://127.0.0.1:8080/exportStatistics', json=data, headers=headers, verify=False)
nextcloud_aim_file_path = '共享/AI估价/农行统计'
file_path = "AI估价农行" + formatted_date + ".xlsx"
with open(file_path, 'wb') as file:
# 将字节流写入文件
file.write(ret.content)
nextcloudutils.up_to_nextcloud(file_path, nextcloud_aim_file_path + "/" + "AI估价农行" + formatted_date + ".xlsx")
dingutils.send_text("【AI估价】农行" + formatted_date + "统计完成, 请点击 https://nextcloud.fangjia.com/s/WK9MzWwH5kjwMBB 查看", "f4f3b03c35c67d097f70affa27e7d47d7a1b6c0eed2438f4d8aa654834419a0b")
View File
@@ -0,0 +1,249 @@
# """
# 统计城市 区域 价格涨跌幅
# """
# import logging
# import pandas as pd
# from sqlalchemy import create_engine
# from goojia_utils import dateutils
# import datetime
# import os
# pathAll = "/home/airflow/data/cityPrice"
# if not os.path.exists(pathAll):
# os.makedirs(pathAll)
# # 创建数据库引擎
# engine235 = create_engine("postgresql+psycopg2://postgres:Goojia123456@192.168.0.235:5433/fangjia?client_encoding=utf8",
# echo=False)
# pd.set_option('mode.chained_assignment', None)
# year_month_day = dateutils.format_date(datetime.datetime.now())
# # 执行SQL查询获取城市价格数据
# city_sql = "SELECT DISTINCT urbn_nm FROM price_stat.avm_city_price"
# city_names_set = set(pd.read_sql(city_sql, engine235)['urbn_nm'])
# city_names = list(city_names_set)
# # 假设这是你的pgsql数据
# all_city_data = pd.DataFrame()
# # 执行SQL查询获取区域价格数据
# region_sql = "SELECT DISTINCT urbn_nm,gxda_admndiv_nm FROM price_stat.avm_district_price"
# region_data = pd.read_sql(region_sql, engine235)
# city_data_useinregion = pd.DataFrame()
# # 假设这是你的pgsql数据
# all_region_data = pd.DataFrame()
#
# def up_to_nextcloud(aim_file_name,aim_file_path):
# """
# 上传统计信息至nextcloud
# """
# from nextcloud import NextCloud
# NEXTCLOUD_URL = "https://nextcloud.fangjia.com"
# NEXTCLOUD_USERNAME = "shenjian@fangjia.com"
# NEXTCLOUD_PASSWORD = "goojia123456"
# nxc = NextCloud(endpoint=NEXTCLOUD_URL, user=NEXTCLOUD_USERNAME, password=NEXTCLOUD_PASSWORD, json_output=True)
# nxc.upload_file(aim_file_name, aim_file_path)
# def city_increase(city_names, all_city_data):
# global city_data_useinregion # 声明为全局变量
# # 遍历城市列表,对每个城市进行查询
# for city in city_names:
# query = f"SELECT urbn_nm as 城市, gujiabds_clc_yrmo_val as 月份, gujia_bds_clc_avprc as 估家计算均价, gujia_bds_urbn_avprc as 估家城市均价 FROM price_stat.avm_city_price WHERE urbn_nm = '{city}'"
# city_data = pd.read_sql(query, engine235)
#
# if city_data.empty:
# continue
#
# # 复制一份原始的日期列,用于计算涨跌幅时保持原始数据不变
# city_data['original_date'] = city_data['月份']
#
# # 将日期列转换为日期类型
# city_data['月份'] = pd.to_datetime(city_data['月份'], format='%Y%m')
#
# # 对价格数据按照月份排序
# city_data.sort_values(by='月份', inplace=True)
#
# # 计算涨跌幅
# city_data['涨跌幅'] = city_data['估家计算均价'].diff() / city_data['估家计算均价'].shift(1) * 100
#
# # 计算涨跌幅,并保留两位小数,展示为百分比形式
# price_change = city_data['估家计算均价'].pct_change() * 100
# city_data['涨跌幅'] = (price_change[price_change != 0].fillna(0).round(2).astype(str) + '%').replace('0.0%', '')
#
# # 将原始日期列替换为计算涨跌幅后的日期列
# city_data['月份'] = city_data['original_date']
#
# # 删除临时列
# city_data.drop(columns=['original_date'], inplace=True)
#
# # 将城市数据添加到总的数据中
# all_city_data = pd.concat([all_city_data, city_data], ignore_index=True)
# city_data_useinregion = all_city_data
# return all_city_data
#
#
# def city_missing():
# df = city_increase(city_names, all_city_data)
# df['月份1'] = df['月份']
# # 将日期字符串转换为日期时间对象
# df["月份"] = pd.to_datetime(df["月份"], format="%Y%m")
#
# # 获取当前时间
# current_time = pd.Timestamp.today().replace(hour=0, minute=0, second=0, microsecond=0)
#
# # 计算前一年到上月的时间范围
# one_year_ago = current_time - pd.DateOffset(years=1, days=current_time.day - 1)
# last_month = current_time - pd.DateOffset(months=1, days=current_time.day - 1)
#
# # 创建一个包含所有可能月份的日期范围
# all_months = pd.date_range(start=one_year_ago, end=last_month, freq="MS")
#
# # 获取每个城市缺失的月份
# missing_months = []
# for city, group in df.groupby("城市"):
# available_months = group["月份"]
# missing = all_months.difference(available_months)
# if len(missing) > 0:
# missing_str = ",".join([m.strftime("%Y%m") for m in missing])
# missing_months.append({"城市": city, "缺失月份": missing_str})
# if len(missing_months) > 0:
# # 创建DataFrame来存储结果
# missing_df = pd.DataFrame(missing_months)
# path = pathAll+'/城市价格数据缺失'+year_month_day+'.xlsx'
# missing_df.to_excel(path, index=False)
# logging.info(f"城市价格缺失数据已写入Excel文件:{path}")
#
# cloudPath = '共享/统计/城市区域涨跌幅/' + '城市价格数据缺失'+year_month_day+'.xlsx'
# up_to_nextcloud(path, cloudPath)
# logging.info(f"区域涨跌幅数据Excel文件已经上传到云盘")
#
# # print(missing_df)
# df['月份'] = df['月份1']
# # 删除月份1列
# df.drop(columns=['月份1'], inplace=True)
# output_path = pathAll+'/城市价格涨跌幅'+year_month_day+'.xlsx'
# df.to_excel(output_path, index=False)
# logging.info(f"城市涨跌幅数据已写入Excel文件:{output_path}")
#
# cloudPath = '共享/统计/城市区域涨跌幅/' + '城市价格涨跌幅'+year_month_day+'.xlsx'
# up_to_nextcloud(output_path, cloudPath)
# logging.info(f"区域涨跌幅数据Excel文件已经上传到云盘")
#
#
# def region_increase(region_data, all_region_data):
# # 遍历区域列表,对每个区域进行查询
# for index, row in region_data.iterrows():
# city = row['urbn_nm']
# region = row['gxda_admndiv_nm']
# query = f"SELECT urbn_nm as 城市, gxda_admndiv_nm as 区域, gujiabds_clc_yrmo_val as 月份, gujia_bds_clc_avprc as 估家计算均价, gujia_bds_urbn_avprc as 估家城市均价 FROM price_stat.avm_district_price WHERE urbn_nm = '{city}' AND gxda_admndiv_nm = '{region}'"
# region_data = pd.read_sql(query, engine235)
#
# if region_data.empty:
# continue
#
# # 复制一份原始的日期列,用于计算涨跌幅时保持原始数据不变
# region_data['original_date'] = region_data['月份']
#
# # 将日期列转换为日期类型
# region_data['月份'] = pd.to_datetime(region_data['月份'], format='%Y%m')
#
# # 对价格数据按照月份排序
# region_data.sort_values(by='月份', inplace=True)
#
# # 计算涨跌幅
# region_data['涨跌幅'] = region_data['估家计算均价'].diff() / region_data['估家计算均价'].shift(1) * 100
#
# # 计算涨跌幅,并保留两位小数,展示为百分比形式
# price_change = region_data['估家计算均价'].pct_change() * 100
# region_data['涨跌幅'] = (price_change[price_change != 0].fillna(0).round(2).astype(str) + '%').replace('0.0%',
# '')
#
# # 将原始日期列替换为计算涨跌幅后的日期列
# region_data['月份'] = region_data['original_date']
#
# # 删除临时列
# region_data.drop(columns=['original_date'], inplace=True)
#
# # 将区域数据添加到总的数据中
# all_region_data = pd.concat([all_region_data, region_data], ignore_index=True)
#
# return all_region_data
#
#
# # 城市价个和区域价格比较
# def add_price_comparison_by_month(region_data):
# # 遍历区域数据,比较城市和区域的价格,并添加比值超过3倍的情况到区域数据中
# for index, row in region_data.iterrows():
# city = row['城市']
# region = row['区域']
# region_month = row['月份']
# region_price = row['估家计算均价']
# city_data = city_data_useinregion
# # 获取城市对应月份的价格
# city_price_row = city_data[(city_data['城市'] == city) & (city_data['月份'] == region_month)]
# if city_price_row.empty:
# continue
# city_price = city_price_row['估家城市均价'].iloc[0]
#
# # 比较价格并计算比值
# price_ratio = max(city_price, region_price) / min(city_price, region_price)
#
# # 如果比值超过3倍,将结果添加到区域数据中
# if price_ratio > 3:
# region_data.loc[index, '城市区域价格比值超3倍'] = price_ratio
#
# return region_data
#
#
# def region_missing():
# df = region_increase(region_data, all_region_data)
# df['月份1'] = df['月份']
# # 将日期字符串转换为日期时间对象
# df["月份"] = pd.to_datetime(df["月份"], format="%Y%m")
#
# # 获取当前时间
# current_time = pd.Timestamp.today().replace(hour=0, minute=0, second=0, microsecond=0)
#
# # 计算前一年到上月的时间范围
# one_year_ago = current_time - pd.DateOffset(years=1, days=current_time.day - 1)
# last_month = current_time - pd.DateOffset(months=1, days=current_time.day - 1)
#
# # 创建一个包含所有可能月份的日期范围
# all_months = pd.date_range(start=one_year_ago, end=last_month, freq="MS")
#
# # 获取每个城市-区域组合缺失的月份
# missing_months = []
# for (city, region), group in df.groupby(["城市", "区域"]):
# available_months = group["月份"]
# missing = all_months.difference(available_months)
# if len(missing) > 0:
# missing_str = ",".join([m.strftime("%Y%m") for m in missing])
# missing_months.append({"城市": city, "区域": region, "缺失月份": missing_str})
#
# if missing_months:
# # 创建DataFrame来存储结果
# missing_df = pd.DataFrame(missing_months)
# path = pathAll+'/区域价格数据缺失'+year_month_day+'.xlsx'
# missing_df.to_excel(path, index=False)
# logging.info(f"区域价格缺失数据已写入Excel文件:{path}")
# cloudPath = '共享/统计/城市区域涨跌幅/' + '区域价格数据缺失' + year_month_day + '.xlsx'
# up_to_nextcloud(path, cloudPath)
# logging.info(f"区域价格缺失数据Excel文件已经上传到云盘")
#
# # 如果区域在 missing_df 中,则将 df 中的该区域数据删除
# for city, region in zip(missing_df['城市'], missing_df['区域']):
# df = df[(df['城市'] != city) | (df['区域'] != region)]
#
# df['月份'] = df['月份1']
# # 删除月份1列
# df.drop(columns=['月份1'], inplace=True)
#
# # 添加价格比值超过3倍的列
# # print(city_data_useinregion)
# df = add_price_comparison_by_month(df)
#
# output_path = pathAll+'/区域价格涨跌幅'+year_month_day+'.xlsx'
# df.to_excel(output_path, index=False)
# logging.info(f"区域涨跌幅数据已写入Excel文件:{output_path}")
#
# cloudPath = '共享/统计/城市区域涨跌幅/' + '区域价格涨跌幅'+year_month_day+'.xlsx'
# up_to_nextcloud(output_path, cloudPath)
# logging.info(f"区域涨跌幅数据Excel文件已经上传到云盘")
#
#
# city_missing()
# region_missing()
View File
@@ -0,0 +1,263 @@
"""
小区数量 租金 均价 及 覆盖率统计
"""
from goojia_utils import MAIN_MONGO_CLIENT, dateutils, ClickHouseClient, ElasticSearchClient, commutils
import pandas as pd
import os
import logging
log = logging.getLogger(__name__)
server_area_conn = MAIN_MONGO_CLIENT.get_collection('fangjia', 'server_area')
seaweed_conn = MAIN_MONGO_CLIENT.get_collection('fangjia', 'seaweed')
district_stat_conn = MAIN_MONGO_CLIENT.get_collection('fangjia_stat', 'district_stat')
sqmetre_rent_conn = MAIN_MONGO_CLIENT.get_collection('fangjia', 'sqmetre_rent')
clickHouseClient = ClickHouseClient(host="192.168.0.216", database='fangjia_stat')
deal_price_conn = MAIN_MONGO_CLIENT.get_collection('fangjia', 'deal_price')
es206_client = ElasticSearchClient(host='192.168.0.206')
city_df = pd.DataFrame(list(server_area_conn.find({}, {'city_grade': 1, 'display': 1})))
city_df = city_df.rename(columns={'city_grade': 'city_level', 'display': 'city'})
city_df = city_df[city_df['city_level'] != 0]
# 昆玉无小区
city_df = city_df[city_df['city'] != '昆玉'].reset_index(drop=True)
seaweed_df = pd.DataFrame(
list(seaweed_conn.find({'cat': 'district', 'status': 0},
{'city': 1, 'region': 1, 'name': 1, 'alias': 1, 'addr_alias': 1})
.batch_size(100000)))
path = "/opt/airflow/dags/repo/dags/business/business/community/data"
aim_path = "/home/airflow/data/stat"
if not os.path.exists(aim_path):
os.makedirs(aim_path)
ret_df = pd.read_excel(path + '/财力评级分布情况20221215.xlsx')
for index, item in city_df.iterrows():
city = item['city']
region_df = seaweed_df[(seaweed_df['city'] == city)].copy()
alias_count = 0
addr_count = 0
seaweed_count = 0
# 楼盘数量
city_df.loc[index, 'community_count'] = len(region_df)
if len(region_df) == 0:
log.error(f"该城市{city}小区数量为0")
for index1, item1 in region_df.iterrows():
flag = True
if type(item1['alias']) == list:
if len(item1['alias']) > 0:
alias_count += len(item1['alias'])
seaweed_count += 1
flag = False
if type(item1['addr_alias']) == list:
if len(item1['addr_alias']) > 0:
addr_count += len(item1['addr_alias'])
if len(item1['addr_alias']) > 0 and flag is True:
seaweed_count += 1
# 楼盘别名总数
city_df.loc[index, 'alias_count'] = alias_count
# 地址别名数量
city_df.loc[index, 'addr_alias_count'] = addr_count
# 有别名小区量【存在楼盘别名或地址别名】
city_df.loc[index, 'exist_alias_community_count'] = seaweed_count
# 【已过期】
# #### 1. 小区数量
# result_df = pd.DataFrame(list(seaweed_conn.aggregate([
# {'$match': {'cat': 'district', 'status': 0}},
# {'$group': {'_id': "$city", 'community_count': {'$sum': 1}}}])))
#
#
# result_df = result_df.rename(columns={'_id': 'city'})
# df = pd.merge(result_df, city_df, how='right', on='city')
# df.fillna(0, inplace=True)
# 有别名小区量 该方式统计不准,可能存在[]情况也算了
# alias_df = pd.DataFrame(list(seaweed_conn.aggregate([
# {'$match': {'cat': 'district', 'status': 0, 'mapping_alias': {'$ne': None}}},
# {'$group': {'_id': "$city", 'alias_count': {'$sum': 1}}}])))
# alias_df = alias_df.rename(columns={'_id': 'city'})
# df = pd.merge(df, alias_df, how='left', on=['city'])
df = city_df.copy()
# 主力户型
main_type_count = pd.DataFrame(list(seaweed_conn.aggregate([
{'$match': {'cat': 'district', 'status': 0, 'main_type': {'$ne': None}}},
{'$group': {'_id': "$city", 'main_type_count': {'$sum': 1}}}])))
main_type_count = main_type_count.rename(columns={'_id': 'city'})
df = pd.merge(df, main_type_count, how='left', on=['city'])
df['main_type_coverage'] = df['main_type_count'] * 100 / df['community_count']
# 主力面积
main_type_area_count = pd.DataFrame(list(seaweed_conn.aggregate([
{'$match': {'cat': 'district', 'status': 0, 'main_type_area': {'$ne': None}}},
{'$group': {'_id': "$city", 'main_type_area_count': {'$sum': 1}}}])))
main_type_area_count = main_type_area_count.rename(columns={'_id': 'city'})
df = pd.merge(df, main_type_area_count, how='left', on=['city'])
df['main_type_area_coverage'] = df['main_type_area_count'] * 100 / df['community_count']
# 物业类型
estate_type_count = pd.DataFrame(list(seaweed_conn.aggregate([
{'$match': {'cat': 'district', 'status': 0, 'estate_type2': {'$ne': None}}},
{'$group': {'_id': "$city", 'estate_type_count': {'$sum': 1}}}])))
estate_type_count = estate_type_count.rename(columns={'_id': 'city'})
df = pd.merge(df, estate_type_count, how='left', on=['city'])
df['estate_type_coverage'] = df['estate_type_count'] * 100 / df['community_count']
# 建成年代
finish_building_date_count = pd.DataFrame(list(seaweed_conn.aggregate([
{'$match': {'cat': 'district', 'status': 0, 'finish_building_date': {'$ne': None}}},
{'$group': {'_id': "$city", 'finish_building_date_count': {'$sum': 1}}}])))
finish_building_date_count = finish_building_date_count.rename(columns={'_id': 'city'})
df = pd.merge(df, finish_building_date_count, how='left', on=['city'])
df['finish_building_date_coverage'] = df['finish_building_date_count'] * 100 / df['community_count']
# 占地面积
all_area_count = pd.DataFrame(list(seaweed_conn.aggregate([
{'$match': {'cat': 'district', 'status': 0, 'all_area': {'$ne': None}}},
{'$group': {'_id': "$city", 'all_area_count': {'$sum': 1}}}])))
all_area_count = all_area_count.rename(columns={'_id': 'city'})
df = pd.merge(df, all_area_count, how='left', on=['city'])
df['all_area_coverage'] = df['all_area_count'] * 100 / df['community_count']
# 建筑面积
build_area_count = pd.DataFrame(list(seaweed_conn.aggregate([
{'$match': {'cat': 'district', 'status': 0, 'build_area': {'$ne': None}}},
{'$group': {'_id': "$city", 'build_area_count': {'$sum': 1}}}])))
build_area_count = build_area_count.rename(columns={'_id': 'city'})
df = pd.merge(df, build_area_count, how='left', on=['city'])
df['build_area_coverage'] = df['build_area_count'] * 100 / df['community_count']
# 绿化率
greening_rate_count = pd.DataFrame(list(seaweed_conn.aggregate([
{'$match': {'cat': 'district', 'status': 0, 'virescence_percent': {'$ne': None}}},
{'$group': {'_id': "$city", 'greening_rate_count': {'$sum': 1}}}])))
greening_rate_count = greening_rate_count.rename(columns={'_id': 'city'})
df = pd.merge(df, greening_rate_count, how='left', on=['city'])
df['greening_rate_coverage'] = df['greening_rate_count'] * 100 / df['community_count']
# 容积率
volume_rate_count = pd.DataFrame(list(seaweed_conn.aggregate([
{'$match': {'cat': 'district', 'status': 0, 'cubage_percent': {'$ne': None}}},
{'$group': {'_id': "$city", 'volume_rate_count': {'$sum': 1}}}])))
volume_rate_count = volume_rate_count.rename(columns={'_id': 'city'})
df = pd.merge(df, volume_rate_count, how='left', on=['city'])
df['volume_rate_coverage'] = df['volume_rate_count'] * 100 / df['community_count']
# 户均总价
df['total_price_count'] = None
# 物业费
df['estate_charge_count'] = None
# 人均消费
df['avg_cost_count'] = None
# 财力评级
df['consumption_rating_count'] = None
for index, item in df.iterrows():
curr_city = item['city']
sql = f"select count(*) from community_summary where city='{curr_city}' and total_price>0 "
num = es206_client.search_by_sql(sql)['hits']['total']['value']
df.loc[index, 'total_price_count'] = num
sql = f"select count(*) from community_summary where city='{curr_city}' and estate_charge>0 "
estate_charge_num = es206_client.search_by_sql(sql)['hits']['total']['value']
df.loc[index, 'estate_charge_count'] = estate_charge_num
sql = f"select count(*) from community_summary where city='{curr_city}' and avg_cost>0 "
avg_cost_count = es206_client.search_by_sql(sql)['hits']['total']['value']
df.loc[index, 'avg_cost_count'] = avg_cost_count
sql = f"select count(*) from community_summary where city='{curr_city}' and consumption_rating>0 "
consumption_rating_num = es206_client.search_by_sql(sql)['hits']['total']['value']
df.loc[index, 'consumption_rating_count'] = consumption_rating_num
df['total_price_coverage'] = df['total_price_count'] * 100 / df['community_count']
df['consumption_rating_coverage'] = df['consumption_rating_count'] * 100 / df['community_count']
df['estate_charge_coverage'] = df['estate_charge_count'] * 100 / df['community_count']
df['avg_cost_coverage'] = df['avg_cost_count'] * 100 / df['community_count']
##### 2. 近一年成交量
# 小区别名升级为单独df
actions = list()
for index, item in seaweed_df.iterrows():
if type(item['alias']) == list:
for name in item['alias']:
actions.append({'_id': item['_id'], 'city': item['city'], 'name': name, 'region': item['region']})
alias_df = pd.DataFrame(actions)
seaweed_alias_df = pd.concat([seaweed_df[['_id', 'city', 'region', 'name']], alias_df])
deal_price_df = pd.DataFrame(list(deal_price_conn.find(
{'trade_date': {'$gte': dateutils.add_months(dateutils.datetime.datetime.now(), days=-365)}},
{'city': 1, 'region': 1, 'district_name': 1, '_id': 0}).batch_size(10000)))
deal_price_df = deal_price_df.rename(columns={'district_name': 'name'})
deal_price_seaweed_df = pd.merge(deal_price_df, seaweed_alias_df, how='left', on=['city', 'region', 'name'])
# 剔除没有配到的小区
deal_price_seaweed_notnull_df = deal_price_seaweed_df.dropna(subset=['_id'])
deal_price_seaweed_notnull_df.loc[:, 'one_year_deal'] = deal_price_seaweed_notnull_df.groupby(['city'])[
'city'].transform('size')
deal_price_half_year_df = deal_price_seaweed_notnull_df[['city', 'one_year_deal']].drop_duplicates(keep='first')
df = pd.merge(df, deal_price_half_year_df, how='left', on=['city'])
# #### 2. 均价数量
avg_price_df = commutils.get_avg_price()
rent_price_df = commutils.get_rent_price()
avg_price_df['avg_price_count'] = avg_price_df.groupby(by=['city'])['_id'].transform('count')
rent_price_df['sqmetre_rent_count'] = rent_price_df.groupby(by=['city'])['_id'].transform('count')
avg_price_df = avg_price_df[['city', 'avg_price_count']].drop_duplicates(keep='first')
rent_price_df = rent_price_df[['city', 'sqmetre_rent_count']].drop_duplicates(keep='first')
df = pd.merge(df, avg_price_df, how='left', on=['city'])
df = pd.merge(df, rent_price_df, how='left', on=['city'])
df['avg_price_coverage'] = df['avg_price_count'] * 100 / df['community_count']
df['sqmetre_rent_coverage'] = df['sqmetre_rent_count'] * 100 / df['community_count']
df.fillna(0, inplace=True)
df['community_count'] = df['community_count'].astype(int)
df['avg_price_count'] = df['avg_price_count'].astype(int)
df['sqmetre_rent_count'] = df['sqmetre_rent_count'].astype(int)
df['one_year_deal'] = df['one_year_deal'].astype(int)
df['alias_count'] = df['alias_count'].astype(int)
df['addr_alias_count'] = df['addr_alias_count'].astype(int)
df['exist_alias_community_count'] = df['exist_alias_community_count'].astype(int)
df = df.round({'avg_price_coverage': 2, 'sqmetre_rent_coverage': 2, 'main_type_coverage': 2, 'main_type_area_coverage': 2, 'total_price_coverage': 2, 'estate_type_coverage': 2,
'finish_building_date_coverage': 2, 'all_area_coverage': 2, 'build_area_coverage': 2, 'estate_charge_coverage': 2, 'avg_cost_coverage': 2, 'consumption_rating_coverage': 2, 'greening_rate_coverage': 2, 'volume_rate_coverage': 2})
df = df[['city', 'community_count', 'city_level', 'avg_price_coverage', 'sqmetre_rent_coverage', 'alias_count', 'addr_alias_count',
'exist_alias_community_count', 'one_year_deal', 'main_type_coverage', 'main_type_area_coverage', 'total_price_coverage', 'estate_type_coverage',
'finish_building_date_coverage', 'all_area_coverage', 'build_area_coverage', 'estate_charge_coverage', 'avg_cost_coverage', 'consumption_rating_coverage', 'greening_rate_coverage', 'volume_rate_coverage']]
df['weekend'] = dateutils.datetime.datetime.now()
# 删除本日生成的重复数据,防止手工点击生成
clickHouseClient.execute(
"ALTER TABLE fangjia_stat.community_coverage_stat DELETE WHERE weekend = toDate('" + dateutils.format_date(dateutils.datetime.datetime.now(), '%Y-%m-%d') + "')")
clickHouseClient.to_sql(df, table='community_coverage_stat', if_exists='insert', order_by='weekend')
# 上传至nextcloud
ret_df = pd.merge(ret_df, df, how='left', on=['city'])
del ret_df['是否合理']
ret_df = ret_df.rename(columns={'city': '城市', 'city_level': '城市级别', 'community_count': "楼盘数量", "alias_count": "别名数量", "addr_alias_count": "地址别名数量", "exist_alias_community_count": "有别名覆盖小区数量",
'estate_type_coverage': '物业类型覆盖率', 'avg_price_coverage': '均价覆盖率', 'sqmetre_rent_coverage': '平米租金覆盖率', 'total_price_coverage': '户均总价覆盖率', 'estate_charge_coverage': '物业费覆盖率', 'avg_cost_coverage': '人均消费覆盖率', 'main_type_coverage': '主力户型覆盖率', 'main_type_area_coverage': '主力面积覆盖率', 'finish_building_date_coverage': '建成年代覆盖率', 'all_area_coverage': '占地面积覆盖率', 'build_area_coverage': '建筑面积覆盖率', 'consumption_rating_coverage': '财力评级覆盖率', 'greening_rate_coverage': '绿化率覆盖率', 'volume_rate_coverage': '容积率覆盖率'})
output_date = dateutils.format_date(dateutils.datetime.datetime.now())
aim_file_name = aim_path + "/" + output_date + '覆盖率统计.xlsx'
ret_df.to_excel(aim_file_name, index=False)
# https://nextcloud.fangjia.com/s/3aw663fy9BbiBeLji'bie
def up_to_nextcloud():
"""
上传统计信息至nextcloud
"""
from nextcloud import NextCloud
NEXTCLOUD_URL = "https://nextcloud.fangjia.com"
NEXTCLOUD_USERNAME = "shenjian@fangjia.com"
NEXTCLOUD_PASSWORD = "goojia123456"
aim_file_path = '共享/统计/常用覆盖率统计' + output_date + '.xlsx'
nxc = NextCloud(endpoint=NEXTCLOUD_URL, user=NEXTCLOUD_USERNAME, password=NEXTCLOUD_PASSWORD, json_output=True)
nxc.upload_file(aim_file_name, aim_file_path)
up_to_nextcloud()
+603
View File
@@ -0,0 +1,603 @@
import argparse
import logging
import os
import re
from datetime import datetime
import numpy as np
import pandas as pd
from goojia_utils import ElasticSearchClient
from goojia_utils import MAIN_MONGO_CLIENT, MongoDataFrameUpdater
from goojia_utils import areautils
from goojia_utils import dateutils
from sklearn.mixture import GaussianMixture
from sklearn.neighbors import BallTree
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import StandardScaler
from sqlalchemy import create_engine
os.environ["NLS_LANG"] = "AMERICAN_AMERICA.AL32UTF8"
engine236 = create_engine("postgresql+psycopg2://postgres:Goojia123456@192.168.0.235:5433/fangjia", echo=False)
logger = logging.getLogger(__name__)
seaweed_client = MAIN_MONGO_CLIENT.get_collection("fangjia", "seaweed")
stat_client = MAIN_MONGO_CLIENT.get_collection("fangjia_stat", "district_sell_stat")
city_sell_stat_client = MAIN_MONGO_CLIENT.get_collection("fangjia_stat", "city_sell_stat")
sqmetre_rent_client = MAIN_MONGO_CLIENT.get_collection("fangjia", "sqmetre_rent")
community_rate_client = MAIN_MONGO_CLIENT.get_collection("fangjia_stat", "community_rate")
elastic_client = ElasticSearchClient(host="192.168.0.89", username='elastic', password='elasticsearch')
administrative_mapping_client = MAIN_MONGO_CLIENT.get_collection("business", "administrative_mapping")
# 定义楼盘评级级别数量
COMM_RATING_LEVEL_COUNT = 5
COMM_RATING_LEVEL_NAMES = {1: "S", 2: "A", 3: "B", 4: "C", 5: "D"}
# 定义数据预处理函数
def extract_years(text, validate=True):
text = str(text)
# 匹配四位数且前后无其他数字
matches = re.findall(r'(?<!\d)\d{4}(?!\d)', text)
if validate:
current_year = datetime.now().year + 10
valid_years = [year for year in matches if 1800 <= int(year) <= current_year]
if len(valid_years) > 0:
return int(valid_years[0])
return None
def fill_missing_by_around(df, field):
"""
填充缺失的建筑年份:
1. 使用球树(BallTree)加速空间查询
2. 计算1公里范围内的有效建筑年份均值
3. 若无有效数据则保留NaN
"""
# 转换坐标系为弧度(Haversine距离要求)
coords = np.radians(df[['lat', 'lng']].values)
# 构建球树索引(使用Haversine距离公式)
tree = BallTree(coords, metric='haversine')
# 定义地球半径(公里)
EARTH_RADIUS_KM = 6371
# 遍历每一行
for idx, row in df.iterrows():
if pd.isna(row[field]):
# 查询半径(将1公里转换为弧度)
radius_radians = 1 / EARTH_RADIUS_KM
# 执行范围查询(排除自身)
neighbors = tree.query_radius(
[coords[idx]],
r=radius_radians,
return_distance=False
)[0]
neighbors = [n for n in neighbors if n != idx] # 排除当前点
# 获取有效建筑年份
valid_years = df.iloc[neighbors][field].dropna()
# 填充均值(若存在有效值)
if not valid_years.empty:
df.at[idx, field] = valid_years.mean()
return df
def str2number(text):
try:
return float(text)
except ValueError:
return None
except TypeError:
return None
def normalize_to_01(array):
"""
将一维数组归一化到 [0, 1] 区间
参数:
- array: 输入的一维数组(列表、NumPy数组、Pandas Series)
返回:
- 归一化后的NumPy数组(dtype=float64)
示例:
>>> normalize_to_01([10, 20, 30]) --> array([0. , 0.5, 1. ])
"""
# 转换为NumPy数组并确保是一维
arr = np.array(array).reshape(-1, 1)
# 处理全相同值的情况
if np.all(arr == arr[0]) or np.all(np.isnan(arr)):
return np.zeros_like(arr).flatten()
# 使用MinMaxScaler
x_z = StandardScaler().fit_transform(arr)
scaler = MinMaxScaler()
normalized = scaler.fit_transform(x_z)
return normalized.flatten() # 转回一维
def safe_qcut_rating(values, n_bins, ascending=False):
"""
安全的分位数评级函数,处理各种边界情况
Args:
values: 待分级的数值序列
n_bins: 期望的分箱数量
ascending: True表示数值越大评级越高,False相反
Returns:
评级序列(从1开始)
"""
if len(values) == 0:
return pd.Series(dtype=int)
unique_count = values.nunique()
# 如果唯一值数量小于等于分箱数,直接使用排名
if unique_count <= n_bins:
if ascending:
ratings = values.rank(method='dense', ascending=True)
else:
ratings = values.rank(method='dense', ascending=False)
return ratings.astype(int)
# 尝试使用qcut
try:
# 使用labels=False返回数字索引,然后+1使评级从1开始
if ascending:
# 升序:最小值得到最小评级
ratings = pd.qcut(values, q=n_bins, labels=False, duplicates='drop') + 1
else:
# 降序:最大值得到最小评级(等级1)
ratings = pd.qcut(values, q=n_bins, labels=False, duplicates='drop')
ratings = n_bins - ratings # 反转评级顺序
return ratings.astype(int)
except ValueError as e:
logging.error(f"qcut失败: {e},使用排名方法替代")
# 回退到排名方法
if ascending:
ratings = values.rank(method='dense', ascending=True)
else:
ratings = values.rank(method='dense', ascending=False)
return ratings.astype(int)
def exponential_decay_weights(distances):
"""
根据指数衰减方法计算权重。
参数:
distances (array-like): 数据点与目标点之间的距离数组。
decay_coefficient (float): 衰减系数,控制权重衰减速度。
返回:
numpy.ndarray: 归一化后的权重数组。
"""
distances = np.array(distances)
weights = 1 - np.log(distances + 1) / np.log(max(distances) + 1)
return weights
def gmm_train(total_rate, data, source, target):
data = data.copy()
source_values = data[source].dropna()
unique_values = source_values.nunique()
actual_components = min(total_rate, unique_values)
if unique_values <= 2:
data[target] = safe_qcut_rating(source_values, actual_components, ascending=False)
return data
# 高斯混合模型
gmm = GaussianMixture(
n_components=actual_components,
covariance_type='full',
max_iter=200,
n_init=10,
reg_covar=1e-6,
random_state=42
).fit(data[[source]])
data = data.copy()
data.loc[:, 'cluster'] = gmm.predict(data[[source]])
data.loc[:, 'price_mean_cluster'] = data.groupby('cluster')[source].transform('mean')
data.loc[:, target] = data['price_mean_cluster'].rank(method='dense', ascending=False).astype(int)
data = data.drop(columns=['cluster', 'price_mean_cluster'], axis=1)
return data.copy()
# ## 定义小区加载函数
def load_comms(city):
query = {"cat": "district", "status": 0, "city": city}
fields = {"city": 1, "region": 1, "name": 1, "address": 1, "lng": 1, "lat": 1, "estate_type2": 1, "create_year": 1,
"cubage_percent": 1, "virescence_percent": 1, "estate_charge": 1, "business_quarter": 1}
seaweed = pd.DataFrame(list(seaweed_client.find(query, fields)))
seaweed = seaweed.dropna(subset=['lng', 'lat'])
seaweed['_id'] = seaweed['_id'].apply(lambda x: str(x))
seaweed['lng'] = seaweed['lng'] / 10000000000
seaweed['lat'] = seaweed['lat'] / 10000000000
seaweed = seaweed.rename(columns={"create_year": "build_year", "estate_type2": "estate_type", "business_quarter": "block", "_id": "comm_id"})
year = datetime.now().year
seaweed['build_year'] = seaweed['build_year'].apply(lambda x: extract_years(x))
seaweed['org_build_year'] = seaweed['build_year']
seaweed['age'] = seaweed['build_year'].apply(lambda x: (year - x) if pd.notna(x) else None)
seaweed = seaweed.reset_index()
for field in ['age', "cubage_percent", "virescence_percent", "estate_charge"]:
seaweed[field] = seaweed[field].apply(lambda x: str2number(x))
seaweed[f"org_{field}"] = seaweed[field]
seaweed = fill_missing_by_around(seaweed, field)
seaweed[field] = seaweed[field].fillna(seaweed[field].mean())
if field == 'age':
seaweed['age'] = seaweed['age'].apply(lambda x: int(x))
else:
seaweed[field] = seaweed[field].apply(lambda x: round(x, 2))
return seaweed
# ## 加载小区价格数据
def load_comm_stat(city, calc_year_month):
one_year_ago = dateutils.add_months(dateutils.parse_date(str(calc_year_month),"%Y%m"), years=-1)
half_on_year = dateutils.add_months(dateutils.parse_date(str(calc_year_month),"%Y%m"), months=-6)
one_year_ago_year_month = int(dateutils.format_date(one_year_ago, "%Y%m"))
half_on_year_year_month = int(dateutils.format_date(half_on_year, "%Y%m"))
stat = pd.DataFrame(list(stat_client.find({"date": calc_year_month, "city": city}, {"city": 1, "region": 1, "district_name": 1, "avg_price": 1, "_id": 0})))
stat = stat.rename(columns={"district_name": "name"})
stat['org_avg_price'] = stat["avg_price"]
one_year_before_stat = pd.DataFrame(list(stat_client.find({"date": one_year_ago_year_month, "city": city}, {"city": 1, "region": 1, "district_name": 1, "avg_price": 1, "_id": 0})))
one_year_before_stat = one_year_before_stat.rename(columns={"district_name": "name", "avg_price": "one_year_before_avg_price"})
stat = stat.merge(one_year_before_stat, on=['city', 'region', 'name'], how="left")
stat['yoy'] = (stat['avg_price'] - stat['one_year_before_avg_price']) * 100 / stat['one_year_before_avg_price']
stat['org_yoy'] = stat["yoy"]
stat['yoy'] = stat['yoy'].fillna(stat['yoy'].mean())
stat['resistance_coef'] = normalize_to_01(stat['yoy']) * 95
stat['resistance_coef'] = stat['resistance_coef'] + 2
stat['yoy'] = stat['yoy'].apply(lambda x: round(x, 2))
del stat['one_year_before_avg_price']
half_on_year_stat = pd.DataFrame(list(stat_client.find({"date": half_on_year_year_month, "city": city}, {"city": 1, "region": 1, "district_name": 1, "avg_price": 1, "_id": 0})))
half_on_year_stat = half_on_year_stat.rename(columns={"district_name": "name", "avg_price": "half_on_year_avg_price"})
if half_on_year_stat.empty:
return pd.DataFrame()
stat = stat.merge(half_on_year_stat, on=['city', 'region', 'name'], how="left")
stat['half_on_year'] = (stat['avg_price'] - stat['half_on_year_avg_price']) * 100 / stat['half_on_year_avg_price']
stat['half_on_year'] = stat['yoy'].fillna(0)
stat['half_on_year'] = stat['yoy'].apply(lambda x: round(x, 2))
del stat['half_on_year_avg_price']
sqmetre_rent = pd.DataFrame(list(sqmetre_rent_client.find({"s_date": calc_year_month, "cat": "district", "city": city},{"city": 1, "region": 1, "district_name": 1, "avg_price": 1, "_id": 0})))
sqmetre_rent = sqmetre_rent.rename(columns={"district_name": "name", "avg_price": "sqmetre_rent"})
stat = stat.merge(sqmetre_rent, on=['city', 'region', 'name'], how='left')
stat['roi'] = round(stat['sqmetre_rent'] * 12 / stat['avg_price'] * 100, 2)
stat['rent_to_price_ratio'] =stat['sqmetre_rent'] /stat['avg_price']
stat["org_sqmetre_rent"] = stat['sqmetre_rent']
stat["org_rent_to_price_ratio"] = stat['rent_to_price_ratio']
stat['rent_to_price_ratio'] = stat['rent_to_price_ratio'].fillna(stat['rent_to_price_ratio'].mean())
return stat
# ## 加载小区配套数据
def load_comms_summary(city):
all_community_summary = []
for doc in elastic_client.scan_by_sql(f"select * from community_summary where city = '{city}'"):
source = doc['_source']
community_summary = {"comm_id": source["id"]}
for key in source.keys():
if (key.endswith("num") or key.endswith("_distance")) and key not in ["half_on_year_sell_num"]:
community_summary[key] = source[key]
community_summary[f"org_{key}"] = source[key]
all_community_summary.append(community_summary)
all_community_summary = pd.DataFrame(all_community_summary)
return all_community_summary
# ## 定义分类数据和连续性数据打分规则
def category_score(data, field, score_map):
data[f"{field}_score"] = data[field].apply(lambda x: score_map[x])
return data
def numbic_score(data, field):
data[f"{field}_score"] = normalize_to_01(data[field])
estate_type_source_map = {"普通住宅": 0.5, "商住": 0, "别墅": 1}
# ## 定义楼盘评级因子权重
factor_weights = {
'estate_type_score': 0.02,
'age_score': 0.02,
'cubage_percent_score': 0.02,
'virescence_percent_score': 0.02,
'estate_charge_score': 0.02,
'avg_price_score': 0.1,
'sqmetre_rent_score': 0.05,
'yoy_score': 0.15,
'nearest_business_district_distance_score': 0.03,
'nearest_subway_station_distance_score': 0.07,
'nearest_bus_station_distance_score': 0.05,
'rent_to_price_ratio_score': 0.1,
'volume_price_ratio_score': 0.1,
'supermarket_num_score': 0.02,
'park_num_score': 0.02,
'catering_num_score': 0.02,
'mall_num_score': 0.04,
'kindergarten_num_score': 0.01,
'key_primary_school_num_score': 0.06,
'ordinary_primary_school_num_score': 0.04,
'key_middle_school_num_score': 0.02,
'ordinary_middle_school_num_score': 0.02,
'top_three_hospital_num_score': 0.03,
'non_3a_hospital_num_score': 0.02
}
# ## 楼盘评级打分
def comms_rating(data):
number_fields = ["age", "cubage_percent", "virescence_percent", "estate_charge", "avg_price", "sqmetre_rent",
"yoy", "supermarket_num", "park_num", "catering_num", "mall_num", "kindergarten_num",
"key_primary_school_num", "ordinary_primary_school_num", "key_middle_school_num",
"ordinary_middle_school_num", "top_three_hospital_num", "non_3a_hospital_num",
"nearest_business_district_distance", "nearest_subway_station_distance",
"nearest_bus_station_distance", "rent_to_price_ratio", "volume_price_ratio"]
for number_field in number_fields:
threshold_95 = data[number_field].quantile(0.99)
threshold_5 = data[number_field].quantile(0.01)
# 2. 修正:将低于95分位的数据替换为 95分位值
data[number_field] = data[number_field].apply(lambda x: threshold_95 if x >= threshold_95 else x)
data[number_field] = data[number_field].apply(lambda x: threshold_5 if x <= threshold_5 else x)
data[f'{number_field}_score'] = normalize_to_01(data[number_field])
data['age'] = data['age'].apply(lambda x: int(x) if pd.notna(x) else x)
data['age'] = data['age'].astype(int)
for category_field in ['estate_type']:
category_score(data, category_field, estate_type_source_map)
data['total_score'] = 0
factors = ["estate_type", "age", "cubage_percent", "virescence_percent", "estate_charge", "avg_price",
"sqmetre_rent", "yoy", "nearest_business_district_distance", "nearest_subway_station_distance",
"nearest_bus_station_distance", "rent_to_price_ratio", "supermarket_num", "park_num", "catering_num",
"mall_num", "kindergarten_num", "key_primary_school_num", "ordinary_primary_school_num",
"key_middle_school_num", "ordinary_middle_school_num", "top_three_hospital_num", "non_3a_hospital_num"]
for factor in factors:
data['total_score'] = data[f"total_score"] + data[f"{factor}_score"] * factor_weights[f"{factor}_score"]
data['total_score'] = normalize_to_01(data['total_score'])
# 小区品质打分
community_quality_factors = ["estate_type", "age", "cubage_percent", "virescence_percent", "estate_charge"]
data['community_quality_score'] = 0
for factor in community_quality_factors:
data['community_quality_score'] = data[f"community_quality_score"] + data[f"{factor}_score"] * factor_weights[
f"{factor}_score"]
data['community_quality_score'] = normalize_to_01(data['community_quality_score'])
# 小区价格打分
community_price_factors = ["avg_price", "sqmetre_rent", "yoy"]
data['community_price_score'] = 0
for factor in community_price_factors:
data['community_price_score'] = data[f"community_price_score"] + data[f"{factor}_score"] * factor_weights[
f"{factor}_score"]
data['community_price_score'] = normalize_to_01(data['community_price_score'])
# 区位打分
location_advantage_factors = ["nearest_business_district_distance", "nearest_subway_station_distance",
"nearest_bus_station_distance"]
data['location_advantage_score'] = 0
for factor in location_advantage_factors:
data['location_advantage_score'] = data[f"location_advantage_score"] + data[f"{factor}_score"] * factor_weights[
f"{factor}_score"]
data['location_advantage_score'] = normalize_to_01(data['location_advantage_score'])
# 流动性打分
flowability_factors = ["rent_to_price_ratio", "volume_price_ratio"]
data['flowability_score'] = 0
for factor in flowability_factors:
data['flowability_score'] = data[f"flowability_score"] + data[f"{factor}_score"] * factor_weights[
f"{factor}_score"]
data['flowability_score'] = normalize_to_01(data['flowability_score'])
# 流动性生活配套打分
living_facilities_factors = ["supermarket_num", "park_num", "catering_num", "mall_num"]
data['living_facilities_score'] = 0
for factor in living_facilities_factors:
data['living_facilities_score'] = data[f"living_facilities_score"] + data[f"{factor}_score"] * factor_weights[
f"{factor}_score"]
data['living_facilities_score'] = normalize_to_01(data['living_facilities_score'])
# 教育资源打分
education_factors = ["kindergarten_num", "key_primary_school_num", "ordinary_primary_school_num",
"key_middle_school_num", "ordinary_middle_school_num"]
data['education_score'] = 0
for factor in education_factors:
data['education_score'] = data[f"education_score"] + data[f"{factor}_score"] * factor_weights[f"{factor}_score"]
data['education_score'] = normalize_to_01(data['education_score'])
# 医疗资源打分
hospital_factors = ["top_three_hospital_num", "non_3a_hospital_num"]
data['hospital_score'] = 0
for factor in hospital_factors:
data['hospital_score'] = data[f"hospital_score"] + data[f"{factor}_score"] * factor_weights[f"{factor}_score"]
data['hospital_score'] = normalize_to_01(data['hospital_score'])
data = data.dropna(subset=['total_score'])
for score_factor in ['total_score', 'community_quality_score', 'community_price_score', 'location_advantage_score',
'flowability_score', 'living_facilities_score', 'education_score', 'hospital_score']:
factor = score_factor.replace("_score", "")
if score_factor == 'total_score':
data = gmm_train(COMM_RATING_LEVEL_COUNT, data, score_factor, f'rating')
data[f'rating'] = data[f'rating'].map(COMM_RATING_LEVEL_NAMES)
else:
data = gmm_train(COMM_RATING_LEVEL_COUNT, data, score_factor, f'{factor}_rating')
data[f'{factor}_rating'] = data[f'{factor}_rating'].map(COMM_RATING_LEVEL_NAMES)
buffer = []
data_null = data[data['region'].isna()]
data_not_null = data[data['region'].notna()]
for item in data_not_null['region'].unique():
group = data_not_null[data_not_null['region'] == item]
group = gmm_train(COMM_RATING_LEVEL_COUNT, group, 'total_score', f'region_rating')
group[f'region_rating'] = group[f'region_rating'].map(COMM_RATING_LEVEL_NAMES)
buffer.append(group)
buffer.append(data_null)
data = pd.concat(buffer)
if "block" in data.columns:
buffer = []
data_null = data[data['block'].isna()].copy()
data_not_null = data[data['block'].notna()].copy()
buffer.append(data_null)
if len(data_not_null) > 0:
data_not_null['region_block'] = data_not_null['region'] + "_" + data_not_null['block']
for item in data_not_null['region_block'].unique():
group = data_not_null[(data_not_null['region'] == str(item).split("_")[0]) & (data_not_null['block'] == str(item).split("_")[1])]
group = gmm_train(COMM_RATING_LEVEL_COUNT, group, 'total_score', 'block_rating')
group['block_rating'] = group['block_rating'].map(COMM_RATING_LEVEL_NAMES)
buffer.append(group)
data = pd.concat(buffer)
else:
data['block_rating'] = None
data['block'] = None
for score_factor in ['total_score', 'community_quality_score', 'community_price_score', 'location_advantage_score',
'flowability_score', 'living_facilities_score', 'education_score', 'hospital_score']:
data[f'{score_factor}'] = data[f'{score_factor}'].apply(lambda x: round(x * 100, 6))
return data
city_code_map = {}
for doc in administrative_mapping_client.find({"type":"城市"}, {"city_short" :1, "mzb_city_code":1}):
city_code_map[doc['city_short']] = doc['mzb_city_code']
def load_house_stat(city, calc_year_month):
end_year_month = int(dateutils.format_date(dateutils.add_months(dateutils.parse_date(str(calc_year_month), "%Y%m"), months=1), "%Y%m"))
half_on_year = dateutils.add_months(dateutils.parse_date(str(calc_year_month), "%Y%m"), months=-6)
half_on_year_year_month = int(dateutils.format_date(half_on_year, "%Y%m"))
sql = f"""
select gujia_comm_id as comm_id, count(*) as half_on_year_sell_num from base.bigdata_forsale where urbn_id = '{city_code_map[city]}'
and data_crt_tm >= to_date('{half_on_year_year_month}', 'YYYYMM') and data_crt_tm < to_date('{end_year_month}', 'YYYYMM')
group by gujia_comm_id ;
"""
house_stat = pd.read_sql(sql, con=engine236)
house_stat['org_half_on_year_sell_num'] = house_stat['half_on_year_sell_num']
return pd.read_sql(sql, con=engine236)
# ## 按照城市加载楼盘评级数据宽表
def load_data_by_city(city, calc_year_month):
comms = load_comms(city=city)
stat = load_comm_stat(city, calc_year_month)
comms_summary = load_comms_summary(city=city)
house_stat = load_house_stat(city, calc_year_month)
comms_summary = comms_summary.merge(house_stat, on='comm_id', how='left')
data = comms.merge(stat, how="left", on=['city', 'region', 'name'])
data = data.merge(comms_summary, how="left", on=['comm_id'])
num_fields = ["supermarket_num", "park_num", "catering_num", "mall_num", "kindergarten_num",
"key_primary_school_num", "ordinary_primary_school_num", "key_middle_school_num",
"ordinary_middle_school_num", "top_three_hospital_num", "non_3a_hospital_num",
"avg_price"]
for num_field in num_fields:
data[num_field] = data[num_field].fillna(0)
distance_fields = ["nearest_business_district_distance", "nearest_subway_station_distance",
"nearest_bus_station_distance"]
for distance_field in distance_fields:
if distance_field not in data:
data[distance_field] = 0
else:
data[distance_field] = data[distance_field].fillna(data[distance_field].max())
data[distance_field] = exponential_decay_weights(data[distance_field])
data[distance_field] = data[distance_field].apply(lambda x: round(x, 6))
data['volume_price_ratio'] = data['avg_price'] / data['half_on_year'].replace(0, 1e-6)
data['volume_price_ratio'] = data['volume_price_ratio'].fillna(data['volume_price_ratio'].mean())
return data
import multiprocessing
def process_city(args):
city = args['city']
calc_year_month = args['calc_year_month']
try:
logger.info(f"开始计算楼盘评级:{city} 年月:{calc_year_month}")
data = load_data_by_city(city, calc_year_month)
data = comms_rating(data)
db_fields = ["comm_id", "city", "region", "name", 'block', 'block_rating', "address", "sqmetre_rent", "yoy",
"rent_to_price_ratio", "roi", "avg_price", "total_score", "community_quality_score",
"community_price_score", "location_advantage_score", "flowability_score", "living_facilities_score",
"education_score", "hospital_score", "rating", "community_quality_rating", "community_price_rating",
"location_advantage_rating", "flowability_rating", "living_facilities_rating", "education_rating",
"hospital_rating", "supermarket_num", "park_num", "catering_num", "mall_num", "kindergarten_num",
"key_primary_school_num", "ordinary_primary_school_num", "key_middle_school_num",
"ordinary_middle_school_num", "top_three_hospital_num", "non_3a_hospital_num", "build_year", "age",
"cubage_percent", "virescence_percent", "estate_charge", 'estate_type', 'resistance_coef', "region_rating"]
# 恢复经过转换,填充的数据
for field in data.columns:
if field.startswith("org_"):
data[f"{field.replace('org_', '')}"] = data[field]
del data[field]
df_simple = data[db_fields].copy()
if "block" not in df_simple.columns:
df_simple['block'] = None
if "resistance_coef" not in df_simple.columns:
df_simple['resistance_coef'] = None
for factor_score_field in ['total_score', 'community_quality_score', 'community_price_score',
'location_advantage_score', 'flowability_score', 'living_facilities_score',
'education_score', 'hospital_score']:
key = "" if factor_score_field == "total_score" else f"_{factor_score_field.replace('_score', '')}"
df_simple[f'city{key}_rank'] = df_simple[factor_score_field].rank(method='min', ascending=False).astype(int)
df_simple[f'city{key}_total_rank'] = df_simple[f'city{key}_rank'].max()
df_simple[f'region{key}_rank'] = df_simple.groupby(['city', 'region'])[factor_score_field].rank(method='min', ascending=False).astype(int)
df_simple[f'region{key}_total_rank'] = df_simple[f'region{key}_rank'].max()
df_simple[f'block{key}_rank'] = None
df_simple[f'block{key}_total_rank'] = None
if df_simple['block'].notna().any():
buffer = []
data_null = df_simple[df_simple['block'].isna()].copy()
data_not_null = df_simple[df_simple['block'].notna()].copy()
buffer.append(data_null)
if len(data_not_null) > 0:
data_not_null['region_block'] = data_not_null['region'] + "_" + data_not_null['block']
for item in data_not_null['region_block'].unique():
group = data_not_null[(data_not_null['region'] == str(item).split("_")[0])&(data_not_null['block'] == str(item).split("_")[1])].copy()
group[f'block{key}_rank'] = group[factor_score_field].rank(method='min', ascending=False).astype(int)
group[f'block{key}_total_rank'] = group[f'block{key}_rank'].max()
buffer.append(group)
df_simple = pd.concat(buffer)
if "region_block" in df_simple.columns:
del df_simple['region_block']
for score_factor in ['total_score', 'community_quality_score', 'community_price_score','location_advantage_score', 'flowability_score', 'living_facilities_score','education_score', 'hospital_score']:
df_simple[score_factor] = df_simple[score_factor].apply(lambda x: round(x, 2))
df_simple['rent_to_price_ratio'] = df_simple['rent_to_price_ratio'].apply(lambda x: round(x, 4))
df_simple['yoy'] = df_simple['yoy'].apply(lambda x: round(x, 2))
updater = MongoDataFrameUpdater(community_rate_client)
dtype = {"avg_price": int,"build_year": int, 'resistance_coef': int}
for field in db_fields:
if "_rank" in field or "_num" in field:
dtype[field] = int
for field in df_simple.columns:
if "_rank" in field or "_num" in field:
dtype[field] = int
df_simple['date'] = calc_year_month
updater.bulk_insert_or_update_by_id(df_simple, id_fields=['comm_id', 'date'], dtype=dtype)
logger.info(f"楼盘评级计算结束:{city}")
except Exception as e:
import traceback
traceback.print_exc()
logging.error(f"{city}楼盘评级计算失败;{e}")
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--city', type=str, default='all')
parser.add_argument('--month', type=str, default='')
args = parser.parse_args()
if args.city == 'all':
cities = areautils.get_all_cities()
else:
cities = [city.strip() for city in args.city.split(',') if city.strip()]
if args.month == '':
calc_year_months = [int(dateutils.format_date(dateutils.add_months(datetime.now(), months=-1), "%Y%m"))]
else:
calc_year_months = [int(calc_year_month.strip()) for calc_year_month in args.month.split(',') if calc_year_month.strip()]
# for city in cities:
# args_list = [{"city": city, "calc_year_month": calc_year_month} for calc_year_month in calc_year_months]
# for args in args_list:
# process_city(args)
with multiprocessing.Pool(processes=min(8, len(calc_year_months))) as pool:
# for calc_year_month in calc_year_months:
# args_list = [{"calc_year_month": calc_year_month, "city": city} for city in cities]
# pool.map(process_city, args_list)
# for calc_year_month in calc_year_months:
# args_list = [{"calc_year_month": calc_year_month, "city": city} for city in cities]
# pool.map(process_city, args_list)
for city in cities:
args_list = [{"city": city, "calc_year_month": calc_year_month} for calc_year_month in calc_year_months]
pool.map(process_city, args_list)
+52
View File
@@ -0,0 +1,52 @@
"""
小区周边1公里交通地铁入库业务逻辑
"""
import datetime
import logging
import pandas as pd
from goojia_utils import MAIN_MONGO_CLIENT
from goojia_utils import dateutils
from sklearn.mixture import GaussianMixture
from pymongo import InsertOne, DeleteMany, ReplaceOne, UpdateOne
logger = logging.getLogger(__name__)
district_stat_conn = MAIN_MONGO_CLIENT.get_collection('fangjia_stat', 'district_stat')
district_analy_data_conn = MAIN_MONGO_CLIENT.get_collection('fangjia_stat', 'district_analy_data')
server_area_conn = MAIN_MONGO_CLIENT.get_collection('fangjia', 'server_area')
weekend = list(district_stat_conn.find().sort([("weekend", -1)]).limit(1))[0]['weekend']
level_map = {"1": "S", "2": "A", "3": "B", "4": "C", "5": "D"}
logger.info(f"开始计算楼盘评级 weekend:{dateutils.format_date(weekend, '%Y-%m-%d')}")
for server_area in server_area_conn.find({'display': {'$ne': '全国'}}, {"display": 1}):
city = server_area["display"]
data = pd.DataFrame(
district_stat_conn.find({"city": city, "weekend": weekend},
{"_id": 0, "region": 1, "district_name": 1, "avg_price": 1}))
if "avg_price" not in data or len(data['avg_price'].unique()) < 5:
continue
data['city'] = city
logger.info(f"开始计算{city}楼盘评级 weekend:{dateutils.format_date(weekend, '%Y-%m-%d')}")
# 高斯混合模型
gmm = GaussianMixture(n_components=5, covariance_type='tied', max_iter=200, n_init=10).fit(
data[["avg_price"]])
data.loc[:, 'cluster'] = gmm.predict(data[["avg_price"]])
data.loc[:, 'price_mean_cluster'] = data.groupby('cluster')["avg_price"].transform('mean')
data.loc[:, "target"] = data['price_mean_cluster'].rank(method='dense', ascending=False).astype(int)
data = data.drop(columns=['cluster', 'price_mean_cluster'], axis=1)
data["community_rating"] = data['target'].apply(lambda x: level_map[str(x)])
opts = []
for item in data.to_dict('records'):
opts.append(UpdateOne({"city": city, "region": item["region"], "district_name": item["district_name"]},
{"$set": {"community_rating": item["community_rating"]}}, upsert=True
))
# 按照每 1000 条分割 updates 列表
batch_size = 1000
batches = [opts[i:i + batch_size] for i in range(0, len(opts), batch_size)]
# 逐个批次执行批量更新操作
cnt = 0
for batch in batches:
cnt = cnt + 1
logger.info(f"{city}楼盘评级更新数据库, 进度:{cnt}/{len(batches)}")
result = district_analy_data_conn.bulk_write(batch)
print(f"当前批次更新的文档数量: {result.modified_count}")
logger.info(f"楼盘评级计算结束{dateutils.format_date(datetime.datetime.utcnow(), '%Y-%m-%d')}")
+121
View File
@@ -0,0 +1,121 @@
import argparse
import logging
import os
import re
from datetime import datetime
import numpy as np
import pandas as pd
from dateutil.relativedelta import relativedelta
from goojia_utils import ElasticSearchClient
from goojia_utils import MAIN_MONGO_CLIENT, MongoDataFrameUpdater
from goojia_utils import areautils
from goojia_utils import dateutils
from sklearn.mixture import GaussianMixture
from sklearn.neighbors import BallTree
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import StandardScaler
from sqlalchemy import create_engine
import multiprocessing
community_rate_client = MAIN_MONGO_CLIENT.get_collection("fangjia_stat", "community_rate")
region_rate_client = MAIN_MONGO_CLIENT.get_collection("fangjia_stat", "region_rate")
region_sell_stat_client = MAIN_MONGO_CLIENT.get_collection("fangjia_stat", "region_sell_stat")
sqmetre_rent_client = MAIN_MONGO_CLIENT.get_collection("fangjia", "sqmetre_rent")
def process_city(args):
city = args['city']
calc_year_month = args['calc_year_month']
community_rate = pd.DataFrame(list(community_rate_client.find({"city": city, "date": calc_year_month})))
if community_rate.empty:
logging.warning(f"{city}楼盘评级数据为0")
return
region_stat = community_rate.groupby(by=["city", "region", "date"]).agg({
"total_score" : 'mean',
"community_quality_score" :'mean',
"community_price_score" : 'mean',
"location_advantage_score" : 'mean',
"flowability_score" : 'mean',
"living_facilities_score" : 'mean',
"education_score" : 'mean',
"hospital_score" : 'mean',
"rating" : lambda x: x.mode().iloc[0] if not x.mode().empty else None,
"community_quality_rating" :lambda x: x.mode().iloc[0] if not x.mode().empty else None,
"community_price_rating" : lambda x: x.mode().iloc[0] if not x.mode().empty else None,
"location_advantage_rating" : lambda x: x.mode().iloc[0] if not x.mode().empty else None,
"flowability_rating" : lambda x: x.mode().iloc[0] if not x.mode().empty else None,
"living_facilities_rating" : lambda x: x.mode().iloc[0] if not x.mode().empty else None,
"education_rating" : lambda x: x.mode().iloc[0] if not x.mode().empty else None,
"hospital_rating" : lambda x: x.mode().iloc[0] if not x.mode().empty else None,
"resistance_coef" : 'mean'
})
region_stat.reset_index(inplace=True)
for col in region_stat.columns:
if 'score' in str(col):
region_stat[col] = region_stat[col].apply(lambda x: round(x, 2))
region_stat['resistance_coef'] = region_stat['resistance_coef'].apply(lambda x: int(x))
region_stat_keys = { "city": 1, "region": 1, "avg_price": 1, "mom": 1, "yoy": 1, "_id": 0 }
region_sell_stat = pd.DataFrame(region_sell_stat_client.find({"city": city, "date": calc_year_month}, region_stat_keys))
if region_sell_stat.empty:
return
region_sell_stat['yoy'] = region_sell_stat['yoy'] * 100
region_sell_stat['mom'] = region_sell_stat['mom'] * 100
region_sell_stat['yoy'] = region_sell_stat['yoy'].apply(lambda x: round(x, 2))
region_sell_stat['mom'] = region_sell_stat['mom'].apply(lambda x: round(x, 2))
three_month_before = int(dateutils.format_date(dateutils.parse_date(str(calc_year_month), fm='%Y%m') - relativedelta(months=3), fm='%Y%m'))
three_month_before_region_sell_stat = pd.DataFrame(region_sell_stat_client.find({"city": city, "date": three_month_before}, region_stat_keys))
three_month_before_region_sell_stat.rename(columns={"avg_price": "three_month_before_avg_price"}, inplace=True)
region_sell_stat = region_sell_stat.merge(three_month_before_region_sell_stat[["city", "region", "three_month_before_avg_price"]], on=["city", "region"])
region_sell_stat['qoq'] = (region_sell_stat['avg_price'] - region_sell_stat['three_month_before_avg_price']) * 100/region_sell_stat['three_month_before_avg_price']
region_sell_stat['qoq'] = region_sell_stat['qoq'].apply(lambda x: round(x, 2))
region_sell_stat = region_sell_stat[["city", "region",'avg_price','mom', 'yoy', 'qoq']]
sqmetre_rent = pd.DataFrame(list(sqmetre_rent_client.find({"s_date": calc_year_month, "cat": "region", "city": city},{"city": 1, "region": 1, "avg_price": 1, "_id": 0})))
sqmetre_rent = sqmetre_rent.rename(columns={"avg_price": "sqmetre_rent"})
region_sell_stat = region_sell_stat.merge(sqmetre_rent, on=['city', 'region'], how='left')
region_sell_stat['roi'] = round(region_sell_stat['sqmetre_rent'] * 12 / region_sell_stat['avg_price'] * 100, 2)
region_sell_stat['rent_to_price_ratio'] =region_sell_stat['sqmetre_rent'] /region_sell_stat['avg_price']
region_sell_stat['rent_to_price_ratio'] = region_sell_stat['rent_to_price_ratio'].apply(lambda x: round(x, 4))
region_stat = region_stat.merge(region_sell_stat, on=["city", "region"])
dtype = {"date": int, 'resistance_coef': int}
updater = MongoDataFrameUpdater(region_rate_client)
updater.bulk_insert_or_update_by_id(region_stat, id_fields=['city', 'region', 'date'], dtype=dtype)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--city', type=str, default='all')
parser.add_argument('--month', type=str, default='')
args = parser.parse_args()
if args.city == 'all':
cities = areautils.get_all_cities()
else:
cities = [city.strip() for city in args.city.split(',') if city.strip()]
if args.month == '':
calc_year_months = [int(dateutils.format_date(dateutils.add_months(datetime.now(), months=-1), "%Y%m"))]
else:
calc_year_months = [int(calc_year_month.strip()) for calc_year_month in args.month.split(',') if calc_year_month.strip()]
# for city in cities:
# args_list = [{"city": city, "calc_year_month": calc_year_month} for calc_year_month in calc_year_months]
# for args in args_list:
# process_city(args)
with multiprocessing.Pool(processes=min(8, len(calc_year_months))) as pool:
# for calc_year_month in calc_year_months:
# args_list = [{"calc_year_month": calc_year_month, "city": city} for city in cities]
# pool.map(process_city, args_list)
# for calc_year_month in calc_year_months:
# args_list = [{"calc_year_month": calc_year_month, "city": city} for city in cities]
# pool.map(process_city, args_list)
for city in cities:
args_list = [{"city": city, "calc_year_month": calc_year_month} for calc_year_month in calc_year_months]
pool.map(process_city, args_list)
+17
View File
@@ -0,0 +1,17 @@
from airflow import DAG
from airflow.operators.bash import BashOperator
import pendulum
with DAG(
dag_id="ai_nonghang_use_dag",
# 每天9:40
schedule="40 9 * * 1-5",
start_date=pendulum.datetime(2025, 2, 13, tz="Asia/Shanghai"),
description="AI估价农行使用情况",
catchup=True
) as dag:
t1 = BashOperator(
task_id='ai_nonghang_use',
bash_command='python /opt/airflow/dags/repo/dags/stat/aiprice/nonghang_use.py'
)
t1
@@ -0,0 +1,17 @@
from airflow.operators.bash import BashOperator
import pendulum
from airflow import DAG
with DAG(
dag_id="count_price_rent_dag",
# 每周日运行
schedule="0 10 * * 7",
start_date=pendulum.datetime(2023, 3, 17, tz="Asia/Shanghai"),
description="常用字段覆盖率统计",
catchup=True
) as dag:
t1 = BashOperator(
task_id='community_count_price_rent',
bash_command='python /opt/airflow/dags/repo/dags/stat/community/community_count_price_rent.py',
)
t1
+21
View File
@@ -0,0 +1,21 @@
from airflow import DAG
from airflow.operators.bash import BashOperator
import pendulum
with DAG(
dag_id="community_rating_dag",
# 每月的最后一天运行
schedule="0 20 * * 6",
start_date=pendulum.datetime(2025, 6, 9, tz="Asia/Shanghai"),
description="小区楼盘评级计算",
catchup=True
) as dag:
t1 = BashOperator(
task_id='community_rating',
bash_command='python /opt/airflow/dags/repo/dags/stat/community/community_rate.py --city "{{ dag_run.conf.get("city", "all")}}" --month "{{ dag_run.conf.get("month", "")}}"'
)
t2 = BashOperator(
task_id='region_rating',
bash_command='python /opt/airflow/dags/repo/dags/stat/community/region_rate.py --city "{{ dag_run.conf.get("city", "all")}}" --month "{{ dag_run.conf.get("month", "")}}"'
)
t1 >> t2
+20
View File
@@ -0,0 +1,20 @@
from airflow.operators.bash import BashOperator
import pendulum
from airflow import DAG
with DAG(
dag_id="district_sell_deal_dag",
# 每周五运行
schedule="0 1 * * 5",
start_date=pendulum.datetime(2023, 3, 17, tz="Asia/Shanghai"),
catchup=True
) as dag:
t1 = BashOperator(
task_id='district_count_thirdavg_deal',
bash_command='python /opt/airflow/dags/repo/dags/stat/evaluate/district_count_thirdavg_deal.py {{dag_run.conf["city_num"] if "city_num" in dag_run.conf}}',
)
t2 = BashOperator(
task_id='district_sell_property',
bash_command='python /opt/airflow/dags/repo/dags/stat/evaluate/district_sell_property.py {{dag_run.conf["sell_num"] if "sell_num" in dag_run.conf}}',
)
t1 >> t2
@@ -0,0 +1,17 @@
# from airflow.operators.bash import BashOperator
# import pendulum
# from airflow import DAG
#
# with DAG(
# dag_id="increase_decrease_city_region_dag",
# # 每月的最后一天运行
# schedule="0 10 L * *",
# start_date=pendulum.datetime(2024, 5, 30, tz="Asia/Shanghai"),
# description="城市区域涨跌幅数据统计",
# catchup=True
# ) as dag:
# t1 = BashOperator(
# task_id='increase_decrease_city_region',
# bash_command='python /opt/airflow/dags/repo/dags/stat/cityPrice/increase_decrease_city_region.py',
# )
# t1
View File
Binary file not shown.
@@ -0,0 +1,136 @@
"""
统计小区数量、近半年第三方均价、近半年成交信息
"""
import logging
from goojia_utils import MAIN_MONGO_CLIENT, ElasticSearchClient, dateutils
import pandas as pd
import datetime
import os
import sys
log = logging.getLogger(__name__)
city_num = sys.argv[1] if len(sys.argv) > 1 else None
if city_num is not None:
log.info("输出参数" + city_num)
df = pd.DataFrame()
if city_num is not None and int(city_num) == 92:
df = pd.read_excel('/opt/airflow/dags/repo/dags/stat/evaluate/data/估值92城市数据统计.xlsx')
else:
df = pd.read_excel('/opt/airflow/dags/repo/dags/stat/evaluate/data/估值数据统计.xlsx')
year_month_day = dateutils.format_date(datetime.datetime.now())
path = "/home/airflow/data/evaluate"
aim_file_name = path + '/估值数据统计结果' + year_month_day + '.xlsx'
if not os.path.exists(path):
os.makedirs(path)
seaweed_conn = MAIN_MONGO_CLIENT.get_collection('fangjia', 'seaweed')
es206_client = ElasticSearchClient(host='192.168.0.206')
district_stat_conn = MAIN_MONGO_CLIENT.get_collection('fangjia_stat', 'district_stat') # 成交
average_statistics_conn = MAIN_MONGO_CLIENT.get_collection('fangjia', 'average_statistics') # 第三方均价
deal_price_conn = MAIN_MONGO_CLIENT.get_collection('fangjia', 'deal_price')
seaweed_df = pd.DataFrame(
list(seaweed_conn.find({'cat': 'district', 'status': 0}, {'city': 1, 'region': 1, 'name': 1, 'mapping_alias': 1})
.batch_size(10000)))
seaweed_df = seaweed_df.rename(columns={'mapping_alias': 'alias'})
cities = df[['城市']].drop_duplicates(keep='first')['城市'].values.tolist()
def count_stat():
"""
统计小区数量
"""
result_df = pd.DataFrame(seaweed_conn.aggregate([
{'$match': {'cat': 'district', 'status': 0}},
{'$group': {'_id': '$city', 'community_count': {'$sum': 1}}}
]))
result_rename_df = result_df.rename(columns={'_id': '城市', 'community_count': '小区量'})
new_df = pd.merge(df, result_rename_df, how='left', on=['城市'])
new_df.to_excel(aim_file_name, index=False)
def third_avg_stat():
"""
近半年有第三方均价小区数量及占比
"""
new_df = pd.read_excel(aim_file_name)
s_date = dateutils.format_date(dateutils.add_months(dateutils.datetime.datetime.now(), days=-180), fm='%Y%m')
average_statistics_df = pd.DataFrame(
list(average_statistics_conn.find({'s_date': {'$gte': int(s_date)}, 'category': 'district'}).batch_size(10000)))
average_statistics_new_df = average_statistics_df[
['city', 'name', 'region', '58tc_esf_price', 'cityhouse_esf_price', 'soufang_esf_price', 'lianjia_esf_price',
'5i5j_esf_price', 'maitian_esf_price', '365house_esf_price', 'beike_esf_price', 'qfang_esf_price',
'fangtan_esf_price',
'tuboshi_esf_price', 'zhugezhaofang_esf_price', 'zhongyuan_esf_price', 'jiwu_esf_price', 'anjuke_esf_price']]
average_statistics_new_df.loc[:, 'has_esf_price'] = average_statistics_new_df['58tc_esf_price'] \
.combine_first(average_statistics_new_df['cityhouse_esf_price']) \
.combine_first(average_statistics_new_df['soufang_esf_price']) \
.combine_first(average_statistics_new_df['lianjia_esf_price']) \
.combine_first(average_statistics_new_df['5i5j_esf_price']) \
.combine_first(average_statistics_new_df['maitian_esf_price']) \
.combine_first(average_statistics_new_df['365house_esf_price']) \
.combine_first(average_statistics_new_df['beike_esf_price']) \
.combine_first(average_statistics_new_df['qfang_esf_price']) \
.combine_first(average_statistics_new_df['fangtan_esf_price']) \
.combine_first(average_statistics_new_df['tuboshi_esf_price']) \
.combine_first(average_statistics_new_df['zhugezhaofang_esf_price']) \
.combine_first(average_statistics_new_df['zhongyuan_esf_price']) \
.combine_first(average_statistics_new_df['jiwu_esf_price']) \
.combine_first(average_statistics_new_df['anjuke_esf_price'])
average_statistics_new_df.fillna(0, inplace=True)
average_statistics_new_df.loc[:, ['flag']] = average_statistics_new_df['has_esf_price'].apply(
lambda x: True if x > 0 else False)
average_statistics_new_df = average_statistics_new_df[average_statistics_new_df['flag'] == True]
average_statistics_new_df = average_statistics_new_df[['city', 'region', 'name']]
average_statistics_new_df = average_statistics_new_df.drop_duplicates(keep='first')
average_statistics_new_df['近半年有第三方均价小区数量'] = average_statistics_new_df.groupby('city')['city'].transform('size')
average_statistics_new_df = average_statistics_new_df[['city', '近半年有第三方均价小区数量']].drop_duplicates(keep='first')
average_statistics_new_df = average_statistics_new_df.rename(columns={'city': '城市'})
new_df = pd.merge(new_df, average_statistics_new_df, how='left', on=['城市'])
new_df['近半年有第三方均价小区占比'] = round(new_df['近半年有第三方均价小区数量'] * 100 / new_df['小区量'], 2)
new_df.to_excel(aim_file_name, index=False)
def deal_stat():
"""
近半年成交量及小区数量统计
"""
new_df = pd.read_excel(aim_file_name)
# 小区别名升级为单独df
actions = list()
for index, item in seaweed_df.iterrows():
if type(item['alias']) == list:
for name in item['alias']:
actions.append({'_id': item['_id'], 'city': item['city'], 'name': name, 'region': item['region']})
alias_df = pd.DataFrame(actions)
seaweed_alias_df = pd.concat([seaweed_df[['_id', 'city', 'region', 'name']], alias_df])
deal_price_df = pd.DataFrame(list(deal_price_conn.find(
{'trade_date': {'$gte': dateutils.add_months(dateutils.datetime.datetime.now(), days=-180)}},
{'city': 1, 'region': 1, 'district_name': 1, '_id': 0}).batch_size(10000)))
deal_price_df = deal_price_df.rename(columns={'district_name': 'name'})
deal_price_seaweed_df = pd.merge(deal_price_df, seaweed_alias_df, how='left', on=['city', 'region', 'name'])
# 剔除没有配到的小区
deal_price_seaweed_notnull_df = deal_price_seaweed_df.dropna(subset=['_id'])
deal_price_seaweed_notnull_df.loc[:, '近半年成交数据量'] = deal_price_seaweed_notnull_df.groupby(['city'])[
'city'].transform('size')
deal_price_half_year_df = deal_price_seaweed_notnull_df[['city', '近半年成交数据量']].drop_duplicates(keep='first')
deal_price_half_year_df = deal_price_half_year_df.rename(columns={'city': '城市'})
new_df = pd.merge(new_df, deal_price_half_year_df, how='left', on=['城市'])
seaweed_half_year_df = deal_price_seaweed_notnull_df[['city', '_id']]
seaweed_half_year_df = seaweed_half_year_df.drop_duplicates(subset=['city', '_id'], keep='first')
seaweed_half_year_df['近半年有成交小区数量'] = seaweed_half_year_df.groupby(['city'])['city'].transform('size')
seaweed_half_year_rename_df = seaweed_half_year_df[['city', '近半年有成交小区数量']].rename(columns={'city': '城市'})
seaweed_half_year_rename_df = seaweed_half_year_rename_df.drop_duplicates(keep='first')
new_df = pd.merge(new_df, seaweed_half_year_rename_df, how='left', on=['城市'])
new_df.to_excel(aim_file_name, index=False)
log.info("开始统计小区数量、近半年第三方均价、近半年成交信息")
count_stat()
# third_avg_stat()
deal_stat()
log.info("完成统计小区数量、近半年第三方均价、近半年成交信息")
@@ -0,0 +1,137 @@
"""
统计近三个月、近一年样本量及小区属性
"""
import logging
from goojia_utils import MAIN_MONGO_CLIENT, ElasticSearchClient, dateutils, commutils
import pandas as pd
import datetime
import sys
log = logging.getLogger(__name__)
sell_num = sys.argv[1] if len(sys.argv) > 1 else "2"
sell_num = int(sell_num)
log.info("输出参数" + str(sell_num))
year_month_day = dateutils.format_date(datetime.datetime.now())
aim_file_name = '/home/airflow/data/evaluate/估值数据统计结果' + year_month_day + '.xlsx'
start_time = dateutils.format_date(dateutils.add_months(dateutils.datetime.datetime.now(), days=-93))
one_year_time = dateutils.format_date(dateutils.add_months(dateutils.datetime.datetime.now(), days=-366))
seaweed_conn = MAIN_MONGO_CLIENT.get_collection('fangjia', 'seaweed')
es206_client = ElasticSearchClient(host='192.168.0.206')
seaweed_df = pd.DataFrame(list(seaweed_conn.find({'cat': 'district', 'status': 0}, {'city': 1, 'region': 1, 'name': 1, 'mapping_alias': 1})
.batch_size(10000)))
seaweed_df = seaweed_df.rename(columns={'mapping_alias': 'alias'})
def get_sell(df, daysBefore=365):
cities = df[['城市']].drop_duplicates(keep='first')['城市'].values.tolist()
city_one_year_count = list()
for city in cities:
flag = True
for item in city_one_year_count:
if item['城市'] == city:
flag = False
break
if flag == False:
continue
seaweed_temp_df = seaweed_df[seaweed_df['city'] == city]
count = 0
total_num = 0
all_num = 0
for index, item in seaweed_temp_df.iterrows():
names = list()
region = item['region']
names.append(item['name'])
if type(item['alias']) == list:
for alias_item in item['alias']:
names.append(alias_item)
names_str = "','".join(names)
names_str = "'" + names_str + "'"
try:
num = commutils.get_sample(city, region, names_str, daysBefore=daysBefore)
if num > sell_num:
count += 1
total_num += num
all_num += num
except Exception as e:
print(item)
print(e)
city_one_year_count.append({'城市': city, '近一年有样本小区数量': count, '近一年的样本总量': total_num, '总数量': all_num})
print(city + "已处理完, 近一年有样本小区数量" + str(count) + " 近一年的样本总量" + str(total_num))
result_df = pd.DataFrame(city_one_year_count)
return result_df
def sell_stat():
"""
最近一年有样本小区占比 最近3月有样本小区占比
"""
df = pd.read_excel(aim_file_name)
result_df = get_sell(df, 365)
result_df = result_df[['城市', '近一年有样本小区数量', '近一年的样本总量']]
df = pd.merge(df, result_df, how='left', on=['城市'])
df['近一年有样本小区占比'] = round(df['近一年有样本小区数量'] * 100 / df['小区量'], 2)
result_df = get_sell(df, 93)
result_df = result_df.rename(columns={'近一年有样本小区数量': '近三月有样本小区数量'})
result_df = result_df[['城市', '近三月有样本小区数量']]
df = pd.merge(df, result_df, how='left', on=['城市'])
df['近三月有样本小区占比'] = round(df['近三月有样本小区数量'] * 100 / df['小区量'], 2)
df.to_excel(aim_file_name, index=False)
def property_stat():
"""
建筑年代覆盖率 物业类型覆盖率 建筑类型覆盖率
"""
df = pd.read_excel(aim_file_name)
df['建筑年代'] = None
df['物业类型'] = None
df['建筑类型'] = None
for index, item in df.iterrows():
city = item['城市']
print(city)
count = seaweed_conn.count(
{'cat': 'district', 'status': 0, 'city': city, 'finish_building_date': {'$ne': None}})
df.loc[index, '建筑年代'] = round(count * 100 / item['小区量'], 2)
estate_type2_count = seaweed_conn.count(
{'cat': 'district', 'status': 0, 'city': city, 'estate_type2': {'$ne': None}})
df.loc[index, '物业类型'] = round(estate_type2_count * 100 / item['小区量'], 2)
build_type_count = seaweed_conn.count(
{'cat': 'district', 'status': 0, 'city': city, 'build_type': {'$ne': None}})
df.loc[index, '建筑类型'] = round(build_type_count * 100 / item['小区量'], 2)
df.to_excel(aim_file_name, index=False)
def merge_aim():
df = pd.read_excel(aim_file_name)
need_df = pd.read_excel('/opt/airflow/dags/repo/dags/stat/evaluate/data/估值二期项目数据投标.xlsx')
df = pd.merge(df, need_df, how='left', on=['城市'])
df.to_excel(aim_file_name, index=False)
def up_to_nextcloud():
"""
上传统计信息至nextcloud
"""
from nextcloud import NextCloud
NEXTCLOUD_URL = "https://nextcloud.fangjia.com"
NEXTCLOUD_USERNAME = "shenjian@fangjia.com"
NEXTCLOUD_PASSWORD = "goojia123456"
aim_file_path = '共享/二期估值数据每周统计/估值数据统计结果' + year_month_day + '.xlsx'
nxc = NextCloud(endpoint=NEXTCLOUD_URL, user=NEXTCLOUD_USERNAME, password=NEXTCLOUD_PASSWORD, json_output=True)
nxc.upload_file(aim_file_name, aim_file_path)
log.info("开始统计统计近三个月、近一年样本量及小区属性")
sell_stat()
property_stat()
merge_aim()
log.info("完成统计统计近三个月、近一年样本量及小区属性")
log.info("开始上传至云盘")
up_to_nextcloud()
log.info("云盘上传完成")
+58
View File
@@ -0,0 +1,58 @@
from goojia_utils import MAIN_MONGO_CLIENT, ElasticSearchClient, dateutils
from datetime import datetime
import pandas as pd
# uri = "mongodb://developer:G00IDCDEV12385@192.168.0.43:28017"
# client = pymongo.MongoClient(uri)
#
# fangjia = client.get_database("fangjia")
# fangjia_stat = client.get_database("fangjia_stat")
# business = client.get_database("business")
dear_price = MAIN_MONGO_CLIENT.get_collection('fangjia', 'deal_price')
district_stat = MAIN_MONGO_CLIENT.get_collection('fangjia_stat', 'district_stat')
# evaluate_ratio = business.district
server_area = MAIN_MONGO_CLIENT.get_collection('fangjia', 'server_area')
def query_city_avg_price():
cities = list(server_area.find({}))
print(str(cities.size()))
for city in cities:
city_name = city['display']
if city_name != '全国':
dear_price_r = dear_price.find({
'trade_date':
{
"$gte": datetime(2022, 6, 1, 0, 0),
"$lt": datetime(2022, 6, 30, 0, 0)
},
'city': city_name
}, {'city': 1, 'region': 1, 'district_name': 1, 'avg_price': 1})
# show(dear_price_r)
district_stat_r = district_stat.find({
'weekend':
{
"$gte": datetime(2022, 6, 1, 0, 0),
"$lt": datetime(2022, 6, 30, 0, 0)
},
'city': city_name
}, {'city': 1, 'region': 1, 'district_name': 1, 'avg_price': 1})
# show(district_stat_r)
df1 = pd.DataFrame(list(dear_price_r))
df2 = pd.DataFrame(list(district_stat_r))
print(len(df1))
print(len(df2))
if __name__ == '__main__':
query_city_avg_price()