Compare commits

...

10 Commits

11 changed files with 417 additions and 103 deletions
+17 -1
View File
@@ -1,9 +1,25 @@
poi/business/*
stat/evaluate/*
stat/community/*
stats/evaluate/*
stats/community/*
stats/aiprice/*
stats/cityPrice/*
stats/test/*
mt/supply/*
business/business/*
jh/merge/*
jh/para/*
jh/price/*
db/*
jh/sample/*
db/*
office/rent/*
office/sell/*
shop/rent/*
shop/sell/*
company/company/*
ai/stock/*
price_exponents/region_price_month.py
price_exponents/seaweed_price_month.py
test/*
train/*
+2 -2
View File
@@ -167,8 +167,8 @@ def export_and_send_njcb_statement(**context):
print(f"Excel文件生成成功: {excel_path}")
# 发送邮件
receiver = 'wangwenyan@fangjia.com'
cc_receiver = 'daijinshui@fangjia.com'
receiver = 'guyzh@njcb.com.cn'
cc_receiver = ['wangwenyan@fangjia.com', 'daijinshui@fangjia.com']
subject = f"南京银行{last_year}年{last_month:02d}月涉农API对公涉农调用流水"
html_content = f"""
<h3>顾老师:</h3>
+6 -2
View File
@@ -3,11 +3,15 @@
"""
from airflow.providers.standard.operators.bash import BashOperator
from airflow.operators.python import PythonOperator, BranchPythonOperator
from office.rent.base_price import calc
import pendulum
from airflow import DAG
def run_base_rent_calc(**kwargs):
from office.rent.base_price import calc
return calc(**kwargs)
def choose_task(**context):
"""根据 dag_run.conf 决定执行哪个任务"""
conf = context['dag_run'].conf or {}
@@ -50,7 +54,7 @@ with DAG(
# 任务2:写字楼租金计算
t2 = PythonOperator(
task_id='office_base_rent_calc',
python_callable=calc,
python_callable=run_base_rent_calc,
# 🛡️ 已移除 provide_context=True,防止 Airflow 3.3.0 报错崩溃
)
branch_task >> [t1, t2]
+12 -4
View File
@@ -1,13 +1,21 @@
from airflow.providers.standard.operators.bash import BashOperator
from airflow.operators.python import PythonOperator, BranchPythonOperator
from airflow.operators.empty import EmptyOperator
from office.sell.base_price import calc
from office.sell.fill_base_price import fill_base_price
import pendulum
from airflow import DAG
def run_base_price_calc(**kwargs):
from office.sell.base_price import calc
return calc(**kwargs)
def run_fill_base_price(**kwargs):
from office.sell.fill_base_price import fill_base_price
return fill_base_price(**kwargs)
def choose_task(**context):
"""根据 dag_run.conf 决定执行哪个任务"""
conf = context['dag_run'].conf or {}
@@ -56,14 +64,14 @@ with DAG(
# 任务1: 写字楼出售基础价格计算
t1 = PythonOperator(
task_id='office_sell_base_price_calc',
python_callable=calc,
python_callable=run_base_price_calc,
# 🛡️ 已安全移除 provide_context=True
)
# 任务2: 无样本写字楼出售基础价格填充
t2 = PythonOperator(
task_id='office_no_sample_sell_base_price_calc',
python_callable=fill_base_price,
python_callable=run_fill_base_price,
# 🛡️ 已安全移除 provide_context=True
)
+50 -5
View File
@@ -69,7 +69,7 @@ def calcByOffice(city, district, office_name):
# 只查询该小区的样本
year_time = dateutils.format_date(dateutils.datetime.datetime.now())
one_year_time = dateutils.format_date(dateutils.add_months(dateutils.datetime.datetime.now(), days=-365))
sql = f"select * from latest_seawater where cat='office_rent' and city='{city}' and region='{district}' and district_name in ({names_str}) and p_date > {one_year_time}"
sql = f"select * from latest_seawater where cat='office_rent' and city='{city}' and region='{district}' and district_name in ({names_str}) and p_date > {one_year_time} and avg_price>=30 and avg_price<=450"
sample = es.scan_by_sql_to_data_frame(sql)
location = {
@@ -114,7 +114,7 @@ def calcByOffice(city, district, office_name):
new_avg_price = round(average_price, 2)
elif len(sample) > 0:
# 取样本的平均值
new_avg_price = round(sample['avg_price'].mean(), 2)
new_avg_price = round((sample['avg_price'] / 30).mean(), 2)
if pd.notna(new_avg_price):
action = UpdateOne(
{'cat': 'office', 'city': city, 'district': district, 'name': office_name, 'date': curr_date},
@@ -186,11 +186,54 @@ def calculate_mom_yoy_for_office(city, district, office_name):
office_rent_stat_conn.bulk_write(actions)
def calculate_mom_yoy_by_month(year_month, city=None):
"""
批量计算某月所有写字楼的 mom (环比) 和 yoy (同比) 并更新
"""
curr_date = int(year_month)
year = curr_date // 100
month = curr_date % 100
prev_date = (year - 1) * 100 + 12 if month == 1 else curr_date - 1
ly_date = curr_date - 100
base_query = {'cat': 'office'}
if pd.notna(city) and city != '':
base_query['city'] = city
proj = {'_id': 1, 'city': 1, 'district': 1, 'name': 1, 'avg_price': 1}
curr_docs = list(office_rent_stat_conn.find({**base_query, 'date': curr_date}, proj))
if not curr_docs:
return
prev_docs = list(office_rent_stat_conn.find({**base_query, 'date': prev_date}, proj))
ly_docs = list(office_rent_stat_conn.find({**base_query, 'date': ly_date}, proj))
prev_map = {(d.get('city'), d.get('district'), d.get('name')): d.get('avg_price') for d in prev_docs if d.get('avg_price')}
ly_map = {(d.get('city'), d.get('district'), d.get('name')): d.get('avg_price') for d in ly_docs if d.get('avg_price')}
actions = []
for doc in curr_docs:
curr_price = doc.get('avg_price')
if not curr_price:
continue
key = (doc.get('city'), doc.get('district'), doc.get('name'))
prev_price = prev_map.get(key)
ly_price = ly_map.get(key)
mom = round((curr_price - prev_price) / prev_price * 100, 2) if prev_price else None
yoy = round((curr_price - ly_price) / ly_price * 100, 2) if ly_price else None
actions.append(UpdateOne({'_id': doc['_id']}, {'$set': {'mom': mom, 'yoy': yoy}}))
if len(actions) == 5000:
office_rent_stat_conn.bulk_write(actions)
actions.clear()
if actions:
office_rent_stat_conn.bulk_write(actions)
def calcByCity(city, year_month):
"""
写字楼基准价
"""
sql = "select * from latest_seawater where cat='office_rent' "
sql = "select * from latest_seawater where cat='office_rent' and avg_price>=30 and avg_price<=450 "
if pd.notna(city):
sql += "and city='" + city + "' "
if pd.notna(year_month):
@@ -212,9 +255,11 @@ def calcByCity(city, year_month):
office = getOffice(city)
update_office(city, office, sample, year_month)
calculate_mom_yoy_by_month(year_month, city)
def update_office(city, office, sample, year_month):
target_city = city
if 'bed_kind' not in office.columns:
office['bed_kind'] = None
if 'estate_type2' not in office.columns:
@@ -443,8 +488,8 @@ def update_office(city, office, sample, year_month):
actions.clear()
# 第五步
query = {'cat': 'office', 'date': year_month, 'calc_type': {'$in': [1, 2, 3]}}
if pd.notna(city):
query['city'] = city
if pd.notna(target_city) and target_city != '':
query['city'] = target_city
db_df = pd.DataFrame(list(office_rent_stat_conn.find(query)))
office_info = office[['city', 'region', 'name', 'lng', 'lat', 'estate_type2', 'bed_kind']].drop_duplicates(
keep='first')
+47 -20
View File
@@ -18,7 +18,7 @@ def calc(city, year_month):
raise Exception('年月格式错误yyyyMM')
office = es_client.scan_by_sql_to_data_frame(
"select * from latest_seawater where cat='office_rent' and city='" + city + "' and p_date>=" + str(
year_month) + "01 and p_date<=" + str(year_month) + "31 ")
year_month) + "01 and p_date<=" + str(year_month) + "31 and avg_price>=30 and avg_price<=450 ")
if len(office) > 0:
office['day_avg_price'] = office['avg_price'] / 30
# 计算总价的Z-score
@@ -37,22 +37,36 @@ def calc(city, year_month):
region_median_count_prices = {'median': {}, 'count': {}}
actions = list()
year_month = int(year_month)
last_month = int(
dateutils.format_date(dateutils.add_months(dateutils.parse_date(str(year_month), '%Y%m'), months=-1), '%Y%m'))
ly_month = year_month - 100
prev_city_stat = office_rent_stat_conn.find_one(
{'city': city, 'cat': 'city', 'date': {'$lte': int(last_month)}, 'avg_price': {'$lte': 15, '$gt': 0}},
sort=[('date', -1)]
)
if pd.isna(city_price):
# 处理均价为空情况,用上月均价替代
stat = office_rent_stat_conn.find_one({'city': city, 'cat': 'city', 'date': int(last_month)})
if pd.isna(stat):
if pd.isna(prev_city_stat):
return False
last_month_city_price = stat['avg_price']
last_month_city_price = prev_city_stat['avg_price']
if pd.isna(last_month_city_price):
return False
city_price = last_month_city_price
ly_city_stat = office_rent_stat_conn.find_one(
{'city': city, 'cat': 'city', 'date': int(ly_month), 'avg_price': {'$lte': 15, '$gt': 0}}
)
city_mom = round((city_price - prev_city_stat['avg_price']) / prev_city_stat['avg_price'] * 100, 2) if (
prev_city_stat and prev_city_stat.get('avg_price')) else None
city_yoy = round((city_price - ly_city_stat['avg_price']) / ly_city_stat['avg_price'] * 100, 2) if (
ly_city_stat and ly_city_stat.get('avg_price')) else None
# 写入MONGODB
action = UpdateOne({'city': city, 'cat': 'city', 'date': int(year_month)},
{'$set': {'city': city, 'cat': 'city', 'date': int(year_month), 'avg_price': city_price,
'mom': city_mom, 'yoy': city_yoy,
'updated_date': datetime.now()}},
upsert=True)
@@ -60,37 +74,50 @@ def calc(city, year_month):
for region in areautils.get_all_districts(city):
region_avg_prices = region_median_count_prices['median']
region_count = region_median_count_prices['count']
prev_district_stat = office_rent_stat_conn.find_one(
{'city': city, 'cat': 'district', 'date': {'$lte': int(last_month)}, 'district': region, 'avg_price': {'$lte': 15, '$gt': 0}},
sort=[('date', -1)]
)
if region in region_avg_prices and region_count[region] >= 10:
avg_price = region_avg_prices[region]
avg_price = round(region_avg_prices[region], 2)
else:
# 处理均价为空情况,用上月均价替代
district_stat = office_rent_stat_conn.find_one({'city': city, 'cat': 'district', 'date': int(last_month), 'district': region})
if pd.isna(district_stat):
if pd.isna(prev_district_stat):
continue
last_month_region_price = district_stat['avg_price']
last_month_region_price = prev_district_stat['avg_price']
if pd.isna(last_month_region_price):
continue
avg_price = last_month_region_price
avg_price = round(last_month_region_price, 2)
ly_district_stat = office_rent_stat_conn.find_one(
{'city': city, 'cat': 'district', 'date': int(ly_month), 'district': region, 'avg_price': {'$lte': 15, '$gt': 0}}
)
region_mom = round((avg_price - prev_district_stat['avg_price']) / prev_district_stat['avg_price'] * 100, 2) if (
prev_district_stat and prev_district_stat.get('avg_price')) else None
region_yoy = round((avg_price - ly_district_stat['avg_price']) / ly_district_stat['avg_price'] * 100, 2) if (
ly_district_stat and ly_district_stat.get('avg_price')) else None
action = UpdateOne({'city': city, 'cat': 'district', 'date': int(year_month), 'district': region},
{'$set': {'city': city, 'cat': 'district', 'date': int(year_month), 'district': region,
'avg_price': round(avg_price, 2), 'updated_date': datetime.now()}},
'avg_price': avg_price, 'mom': region_mom, 'yoy': region_yoy,
'updated_date': datetime.now()}},
upsert=True)
actions.append(action)
office_rent_stat_conn.bulk_write(actions)
log.info(f"{city} {year_month} 均价计算完毕!")
yearmonth = sys.argv[1] if len(sys.argv) > 1 else ''
if __name__ == "__main__":
yearmonth = sys.argv[1] if len(sys.argv) > 1 else ''
if yearmonth == '':
date = dateutils.add_months(datetime.today(), months=-1)
yearmonth = int(dateutils.format_date(date, '%Y%m'))
try:
for city in areautils.get_all_cities():
calc(city, yearmonth)
except Exception as e:
log.error(e)
if yearmonth == '':
date = dateutils.add_months(datetime.today(), months=-1)
yearmonth = int(dateutils.format_date(date, '%Y%m'))
try:
for city in areautils.get_all_cities():
calc(city, yearmonth)
except Exception as e:
log.error(e)
# # 初始化从2024年9月
# 创建从2024年9月到2024年12月的日期范围
+47 -2
View File
@@ -187,6 +187,49 @@ def calculate_mom_yoy_for_office(city, district, office_name):
office_sell_stat_conn.bulk_write(actions)
def calculate_mom_yoy_by_month(year_month, city=None):
"""
批量计算某月所有写字楼出售的 mom (环比) 和 yoy (同比) 并更新
"""
curr_date = int(year_month)
year = curr_date // 100
month = curr_date % 100
prev_date = (year - 1) * 100 + 12 if month == 1 else curr_date - 1
ly_date = curr_date - 100
base_query = {'cat': 'office'}
if pd.notna(city) and city != '':
base_query['city'] = city
proj = {'_id': 1, 'city': 1, 'district': 1, 'name': 1, 'avg_price': 1}
curr_docs = list(office_sell_stat_conn.find({**base_query, 'date': curr_date}, proj))
if not curr_docs:
return
prev_docs = list(office_sell_stat_conn.find({**base_query, 'date': prev_date}, proj))
ly_docs = list(office_sell_stat_conn.find({**base_query, 'date': ly_date}, proj))
prev_map = {(d.get('city'), d.get('district'), d.get('name')): d.get('avg_price') for d in prev_docs if d.get('avg_price')}
ly_map = {(d.get('city'), d.get('district'), d.get('name')): d.get('avg_price') for d in ly_docs if d.get('avg_price')}
actions = []
for doc in curr_docs:
curr_price = doc.get('avg_price')
if not curr_price:
continue
key = (doc.get('city'), doc.get('district'), doc.get('name'))
prev_price = prev_map.get(key)
ly_price = ly_map.get(key)
mom = round((curr_price - prev_price) / prev_price * 100, 2) if prev_price else None
yoy = round((curr_price - ly_price) / ly_price * 100, 2) if ly_price else None
actions.append(UpdateOne({'_id': doc['_id']}, {'$set': {'mom': mom, 'yoy': yoy}}))
if len(actions) == 5000:
office_sell_stat_conn.bulk_write(actions)
actions.clear()
if actions:
office_sell_stat_conn.bulk_write(actions)
def calcByCity(city, year_month):
"""
写字楼基准价
@@ -214,9 +257,11 @@ def calcByCity(city, year_month):
office = getOffice(city)
update_office(city, office, sample, year_month)
calculate_mom_yoy_by_month(year_month, city)
def update_office(city, office, sample, year_month):
target_city = city
if 'bed_kind' not in office.columns:
office['bed_kind'] = None
if 'estate_type2' not in office.columns:
@@ -446,8 +491,8 @@ def update_office(city, office, sample, year_month):
actions.clear()
# 第五步
query = {'cat': 'office', 'date': year_month, 'calc_type': {'$in': [1, 2, 3]}}
if pd.notna(city):
query['city'] = city
if pd.notna(target_city) and target_city != '':
query['city'] = target_city
db_df = pd.DataFrame(list(office_sell_stat_conn.find(query)))
office_info = office[['city', 'region', 'name', 'lng', 'lat', 'estate_type2', 'bed_kind']].drop_duplicates(
keep='first')
+29 -11
View File
@@ -1,20 +1,20 @@
from goojia_utils import DIDATA_DEV_ELASTIC_CLIENT, dateutils, MAIN_MONGO_CLIENT, threads, areautils
import pandas as pd
from datetime import datetime
from pymongo import UpdateOne
import logging
import sys
log = logging.getLogger(__name__)
office_sell_stat_conn = MAIN_MONGO_CLIENT.get_collection('fangjia_stat', 'office_sell_stat')
office_rent_stat_conn = MAIN_MONGO_CLIENT.get_collection('fangjia_stat', 'office_rent_stat')
def fill_base_price(**kwargs):
"""
写字楼基准价
"""
from goojia_utils import dateutils, MAIN_MONGO_CLIENT
office_sell_stat_conn = MAIN_MONGO_CLIENT.get_collection('fangjia_stat', 'office_sell_stat')
office_rent_stat_conn = MAIN_MONGO_CLIENT.get_collection('fangjia_stat', 'office_rent_stat')
# 从 Airflow 的 dag_run.conf 获取参数
conf = kwargs.get('dag_run').conf if kwargs.get('dag_run') else {}
city = conf.get('city', '')
@@ -38,12 +38,16 @@ def fill_base_price(**kwargs):
if len(office_rent) <= 0:
return
if year_month != '':
calc_by_yearmonth(office_sell, office_rent, year_month)
calc_by_yearmonth(office_sell, office_rent, year_month, office_sell_stat_conn)
else:
# 对于单个重算的不进行补充,已经自己补充过了
pass
def calc_by_yearmonth(office_sell, office_rent, year_month):
def calc_by_yearmonth(office_sell, office_rent, year_month, office_sell_stat_conn=None):
from goojia_utils import MAIN_MONGO_CLIENT, threads
if office_sell_stat_conn is None:
office_sell_stat_conn = MAIN_MONGO_CLIENT.get_collection('fangjia_stat', 'office_sell_stat')
office_sell_df = office_sell[['city', 'district', 'name', 'avg_price']]
office_sell_df = office_sell_df.rename(columns={'avg_price': 'sell_price'})
office_rent_df = office_rent[['city', 'district', 'name', 'avg_price', 'estate_type2', 'bed_kind', 'location']]
@@ -78,20 +82,34 @@ def calc_by_yearmonth(office_sell, office_rent, year_month):
merge2_df = threads.process_dataframe_multithread(merge2_df, deal, 10)
merge2_df = merge2_df[merge2_df['sell_price'].notna()]
curr_date = int(year_month)
year = curr_date // 100
month = curr_date % 100
prev_date = (year - 1) * 100 + 12 if month == 1 else curr_date - 1
ly_date = curr_date - 100
proj = {'_id': 0, 'city': 1, 'district': 1, 'name': 1, 'avg_price': 1}
prev_map = {(d.get('city'), d.get('district'), d.get('name')): d.get('avg_price') for d in office_sell_stat_conn.find({'cat': 'office', 'date': prev_date}, proj) if d.get('avg_price')}
ly_map = {(d.get('city'), d.get('district'), d.get('name')): d.get('avg_price') for d in office_sell_stat_conn.find({'cat': 'office', 'date': ly_date}, proj) if d.get('avg_price')}
actions = list()
count = 0
for index, row in merge2_df.iterrows():
curr_city = row['city']
region = row['district']
name = row['name']
sell_price = row['sell_price']
sell_price = int(row['sell_price'])
estate_type2 = row['estate_type2']
bed_kind = row['bed_kind']
location = row['location']
action = UpdateOne({'cat': 'office', 'city': curr_city, 'district': region, 'name': name, 'date': year_month},
{'$set': {'city': curr_city, 'cat': 'office', 'date': year_month, 'district': region,
prev_p = prev_map.get((curr_city, region, name))
ly_p = ly_map.get((curr_city, region, name))
mom = round((sell_price - prev_p) / prev_p * 100, 2) if prev_p else None
yoy = round((sell_price - ly_p) / ly_p * 100, 2) if ly_p else None
action = UpdateOne({'cat': 'office', 'city': curr_city, 'district': region, 'name': name, 'date': curr_date},
{'$set': {'city': curr_city, 'cat': 'office', 'date': curr_date, 'district': region,
'name': name,
'avg_price': int(sell_price), 'estate_type2': estate_type2, 'bed_kind': bed_kind,
'avg_price': sell_price, 'mom': mom, 'yoy': yoy,
'estate_type2': estate_type2, 'bed_kind': bed_kind,
'location': location,
'calc_type': 5, 'updated_date': datetime.now()}},
upsert=True)
+36 -12
View File
@@ -59,11 +59,25 @@ def calc(city, year_month):
merge2_df = threads.process_dataframe_multithread(merge2_df, deal_city, 10)
merge2_df = merge2_df[merge2_df['sell_price'].notna()]
year = year_month // 100
month = year_month % 100
prev_date = (year - 1) * 100 + 12 if month == 1 else year_month - 1
ly_date = year_month - 100
prev_city_map = {d.get('city'): d.get('avg_price') for d in office_sell_stat_conn.find({'date': prev_date, 'cat': 'city'}) if d.get('avg_price')}
ly_city_map = {d.get('city'): d.get('avg_price') for d in office_sell_stat_conn.find({'date': ly_date, 'cat': 'city'}) if d.get('avg_price')}
actions = list()
# 写入MONGODB
for index, row in merge2_df.iterrows():
sell_p = int(row['sell_price'])
prev_p = prev_city_map.get(row['city'])
ly_p = ly_city_map.get(row['city'])
mom = round((sell_p - prev_p) / prev_p * 100, 2) if prev_p else None
yoy = round((sell_p - ly_p) / ly_p * 100, 2) if ly_p else None
action = UpdateOne({'city': row['city'], 'cat': 'city', 'date': year_month},
{'$set': {'city': row['city'], 'cat': 'city', 'date': year_month, 'calc_type': 2, 'avg_price': int(row['sell_price']),
{'$set': {'city': row['city'], 'cat': 'city', 'date': year_month, 'calc_type': 2, 'avg_price': sell_p,
'mom': mom, 'yoy': yoy,
'updated_date': datetime.now()}},
upsert=True)
actions.append(action)
@@ -89,10 +103,19 @@ def calc(city, year_month):
merge2_df = threads.process_dataframe_multithread(merge2_df, deal_district, 10)
merge2_df = merge2_df[merge2_df['sell_price'].notna()]
prev_dist_map = {(d.get('city'), d.get('district')): d.get('avg_price') for d in office_sell_stat_conn.find({'date': prev_date, 'cat': 'district'}) if d.get('avg_price')}
ly_dist_map = {(d.get('city'), d.get('district')): d.get('avg_price') for d in office_sell_stat_conn.find({'date': ly_date, 'cat': 'district'}) if d.get('avg_price')}
# 写入MONGODB
for index, row in merge2_df.iterrows():
sell_p = int(row['sell_price'])
prev_p = prev_dist_map.get((row['city'], row['district']))
ly_p = ly_dist_map.get((row['city'], row['district']))
mom = round((sell_p - prev_p) / prev_p * 100, 2) if prev_p else None
yoy = round((sell_p - ly_p) / ly_p * 100, 2) if ly_p else None
action = UpdateOne({'city': row['city'], 'district': row['district'], 'cat': 'district', 'date': year_month},
{'$set': {'city': row['city'], 'district': row['district'], 'cat': 'district', 'date': year_month, 'calc_type': 2, 'avg_price': int(row['sell_price']),
{'$set': {'city': row['city'], 'district': row['district'], 'cat': 'district', 'date': year_month, 'calc_type': 2, 'avg_price': sell_p,
'mom': mom, 'yoy': yoy,
'updated_date': datetime.now()}},
upsert=True)
actions.append(action)
@@ -101,17 +124,18 @@ def calc(city, year_month):
log.info(f"均价补充完毕!")
yearmonth = sys.argv[1] if len(sys.argv) > 1 else ''
if __name__ == "__main__":
yearmonth = sys.argv[1] if len(sys.argv) > 1 else ''
if yearmonth == '':
date = dateutils.add_months(datetime.today(), months=-1)
yearmonth = int(dateutils.format_date(date, '%Y%m'))
try:
if type(yearmonth) is str:
yearmonth = int(yearmonth)
calc(None, yearmonth)
except Exception as e:
log.error(e)
if yearmonth == '':
date = dateutils.add_months(datetime.today(), months=-1)
yearmonth = int(dateutils.format_date(date, '%Y%m'))
try:
if type(yearmonth) is str:
yearmonth = int(yearmonth)
calc(None, yearmonth)
except Exception as e:
log.error(e)
# # 初始化从2024年9月
# 创建从2024年9月到2024年12月的日期范围
+51 -22
View File
@@ -37,22 +37,38 @@ def calc(city, year_month):
region_median_count_prices = {'median': {}, 'count': {}}
actions = list()
year_month = int(year_month)
last_month = int(
dateutils.format_date(dateutils.add_months(dateutils.parse_date(str(year_month), '%Y%m'), months=-1), '%Y%m'))
ly_month = year_month - 100
prev_city_stat = office_sell_stat_conn.find_one(
{'city': city, 'cat': 'city', 'date': {'$lte': last_month}, 'avg_price': {'$gt': 0}},
sort=[('date', -1)]
)
if pd.isna(city_price):
# 处理均价为空情况,用上月均价替代
stat = office_sell_stat_conn.find_one({'city': city, 'cat': 'city', 'date': last_month})
if pd.isna(stat):
if pd.isna(prev_city_stat):
return False
last_month_city_price = stat['avg_price']
last_month_city_price = prev_city_stat['avg_price']
if pd.isna(last_month_city_price):
return False
city_price = last_month_city_price
city_price = int(last_month_city_price)
else:
city_price = int(city_price)
ly_city_stat = office_sell_stat_conn.find_one(
{'city': city, 'cat': 'city', 'date': ly_month, 'avg_price': {'$gt': 0}}
)
city_mom = round((city_price - prev_city_stat['avg_price']) / prev_city_stat['avg_price'] * 100, 2) if (
prev_city_stat and prev_city_stat.get('avg_price')) else None
city_yoy = round((city_price - ly_city_stat['avg_price']) / ly_city_stat['avg_price'] * 100, 2) if (
ly_city_stat and ly_city_stat.get('avg_price')) else None
# 写入MONGODB
action = UpdateOne({'city': city, 'cat': 'city', 'date': year_month},
{'$set': {'city': city, 'cat': 'city', 'date': year_month, 'avg_price': int(city_price),
'mom': city_mom, 'yoy': city_yoy,
'updated_date': datetime.now()}},
upsert=True)
@@ -60,38 +76,51 @@ def calc(city, year_month):
for region in areautils.get_all_districts(city):
region_avg_prices = region_median_count_prices['median']
region_count = region_median_count_prices['count']
prev_district_stat = office_sell_stat_conn.find_one(
{'city': city, 'cat': 'district', 'date': {'$lte': last_month}, 'district': region, 'avg_price': {'$gt': 0}},
sort=[('date', -1)]
)
if region in region_avg_prices and region_count[region] >= 10:
avg_price = region_avg_prices[region]
avg_price = int(region_avg_prices[region])
else:
# 处理均价为空情况,用上月均价替代
district_stat = office_sell_stat_conn.find_one({'city': city, 'cat': 'district', 'date': last_month, 'district': region})
if pd.isna(district_stat):
if pd.isna(prev_district_stat):
continue
last_month_region_price = district_stat['avg_price']
last_month_region_price = prev_district_stat['avg_price']
if pd.isna(last_month_region_price):
continue
avg_price = last_month_region_price
avg_price = int(last_month_region_price)
ly_district_stat = office_sell_stat_conn.find_one(
{'city': city, 'cat': 'district', 'date': ly_month, 'district': region, 'avg_price': {'$gt': 0}}
)
region_mom = round((avg_price - prev_district_stat['avg_price']) / prev_district_stat['avg_price'] * 100, 2) if (
prev_district_stat and prev_district_stat.get('avg_price')) else None
region_yoy = round((avg_price - ly_district_stat['avg_price']) / ly_district_stat['avg_price'] * 100, 2) if (
ly_district_stat and ly_district_stat.get('avg_price')) else None
action = UpdateOne({'city': city, 'cat': 'district', 'date': year_month, 'district': region},
{'$set': {'city': city, 'cat': 'district', 'date': year_month, 'district': region,
'avg_price': int(avg_price), 'updated_date': datetime.now()}},
'avg_price': int(avg_price), 'mom': region_mom, 'yoy': region_yoy,
'updated_date': datetime.now()}},
upsert=True)
actions.append(action)
office_sell_stat_conn.bulk_write(actions)
log.info(f"{city} {year_month} 均价计算完毕!")
yearmonth = sys.argv[1] if len(sys.argv) > 1 else ''
if __name__ == "__main__":
yearmonth = sys.argv[1] if len(sys.argv) > 1 else ''
if yearmonth == '':
date = dateutils.add_months(datetime.today(), months=-1)
yearmonth = int(dateutils.format_date(date, '%Y%m'))
try:
if type(yearmonth) is str:
yearmonth = int(yearmonth)
for city in areautils.get_all_cities():
calc(city, yearmonth)
except Exception as e:
log.error(e)
if yearmonth == '':
date = dateutils.add_months(datetime.today(), months=-1)
yearmonth = int(dateutils.format_date(date, '%Y%m'))
try:
if type(yearmonth) is str:
yearmonth = int(yearmonth)
for city in areautils.get_all_cities():
calc(city, yearmonth)
except Exception as e:
log.error(e)
# # 初始化从2024年9月
# 创建从2024年9月到2024年12月的日期范围
+120 -22
View File
@@ -20,10 +20,11 @@ INDEX_NAME = "administrative_mapping_45"
ES_HOST = "192.168.0.206"
def get_amap_township(lon, lat, key=AMAP_KEY, max_retries=3):
def get_amap_township(lon, lat, key=AMAP_KEY, max_retries=5):
"""
调用高德逆地理编码接口获取 township (乡镇/街道)
https://restapi.amap.com/v3/geocode/regeo?location=lon,lat&extensions=base&roadlevel=0
遇 CUQPS_HAS_EXCEEDED_THE_LIMIT (code 10021) 时 sleep 0.2 秒后重试
"""
url = "https://restapi.amap.com/v3/geocode/regeo"
params = {
@@ -47,17 +48,84 @@ def get_amap_township(lon, lat, key=AMAP_KEY, max_retries=3):
return str(township[0]).strip()
return ""
else:
print(f"高德接口返回异常: {data.get('info')}, code: {data.get('infocode')}")
info = str(data.get("info", ""))
infocode = str(data.get("infocode", ""))
print(f"高德接口返回异常: {info}, code: {infocode}")
# 超出并发限制 (10021 / CUQPS_HAS_EXCEEDED_THE_LIMIT) 时等待 0.2 秒后重试
if infocode == "10021" or "CUQPS_HAS_EXCEEDED_THE_LIMIT" in info:
time.sleep(0.2)
continue
except Exception as e:
print(f"请求高德逆地理编码失败 (第{attempt+1}次): {e}")
time.sleep(0.5)
return ""
def get_amap_district_geocode(province, city, district, key=AMAP_KEY, max_retries=5):
"""
调用高德地理编码接口获取区域经纬度
https://restapi.amap.com/v3/geocode/geo?address=...&key=...
地址规则:省份+城市+区域 拼接(若城市与区域相同或城市为空/包含区域,避免重复拼接)
要求返回的 geocodes 中 level == '区县'
返回: "lon,lat" 或 ""
"""
url = "https://restapi.amap.com/v3/geocode/geo"
prov_str = str(province or "").strip()
city_str = str(city or "").strip()
dist_str = str(district or "").strip()
# 拼接地址:注意城市和区域有可能相同,避免重复拼接(如 海南省-文昌市-文昌市 -> 海南省文昌市)
addr_parts = [prov_str]
if city_str and city_str != prov_str:
addr_parts.append(city_str)
if dist_str and dist_str != city_str:
addr_parts.append(dist_str)
address = "".join(addr_parts)
params = {
"key": key,
"address": address
}
for attempt in range(max_retries):
try:
resp = requests.get(url, params=params, timeout=5)
if resp.status_code == 200:
data = resp.json()
if data.get("status") == "1":
geocodes = data.get("geocodes", [])
for item in geocodes:
if item.get("level") == "区县":
location = item.get("location", "")
if location and "," in location:
return location.strip()
# 如果没有精确匹配到 level=='区县'
return ""
else:
info = str(data.get("info", ""))
infocode = str(data.get("infocode", ""))
print(f"高德地理编码返回异常: {info}, code: {infocode}")
if infocode == "10021" or "CUQPS_HAS_EXCEEDED_THE_LIMIT" in info:
time.sleep(0.2)
continue
except Exception as e:
print(f"请求高德地理编码失败 (第{attempt+1}次): {e}")
time.sleep(0.5)
return ""
def check_gov_township_diff(**context):
"""
县政府所在乡镇街道比对主任务
县政府所在乡镇街道比对主任务,支持从 dag_run.conf 或 params 中传入自定义 amap_key
"""
dag_run = context.get('dag_run')
conf = (dag_run.conf if dag_run else {}) or {}
params = context.get('params') or {}
amap_key = conf.get('amap_key') or conf.get('key') or params.get('amap_key') or AMAP_KEY
amap_key = str(amap_key).strip()
print(f"[{datetime.now()}] 使用的高德 API Key: {amap_key[:6]}******{amap_key[-4:] if len(amap_key) > 10 else ''}")
print(f"[{datetime.now()}] 开始连接 206 ES 集群...")
es_client = ElasticSearchClient(host=ES_HOST)
@@ -79,6 +147,7 @@ def check_gov_township_diff(**context):
district_docs = es_client.scan(index=INDEX_NAME, query=query_district)
diff_list = []
missing_loc_list = []
total_districts = 0
processed_count = 0
@@ -87,28 +156,48 @@ def check_gov_township_diff(**context):
source = hit.get("_source", {})
doc_id = hit.get("_id")
province = source.get("province", "")
province = str(source.get("province", "")).strip()
city = source.get("city", "")
district = source.get("district", "")
district = str(source.get("district", "")).strip()
# 台湾省的行政区划跳过
if "台湾" in province:
continue
# 校验的是县政府驻扎地,如果区域是以“区”结尾(市辖区),直接跳过
if district.endswith("区"):
continue
mzb_district_code = source.get("mzb_district_code", "")
tjj_district_code = source.get("tjj_district_code", "")
location = source.get("location", {})
if not location or "lon" not in location or "lat" not in location:
print(f"区域 {province}-{city}-{district}({mzb_district_code}) 缺少有效经纬度,跳过")
continue
lon = location.get("lon") if isinstance(location, dict) else None
lat = location.get("lat") if isinstance(location, dict) else None
lon = location.get("lon")
lat = location.get("lat")
if not lon or not lat:
if not location or lon is None or lat is None or not str(lon).strip() or not str(lat).strip():
print(f"区域 {province}-{city}-{district}({mzb_district_code}) 缺少有效经纬度,调用高德地理编码获取...")
geo_location = get_amap_district_geocode(province, city, district, key=amap_key)
missing_loc_list.append({
"ES文档ID": doc_id,
"省份": province,
"城市": city,
"区域": district,
"民政部区划代码": mzb_district_code,
"统计局区划代码": tjj_district_code,
"经纬,维度": geo_location if geo_location else "",
"人工审核": "未审核",
"原因": "缺少有效经纬度(location)",
"登记时间": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
})
continue
processed_count += 1
if processed_count % 50 == 0:
print(f"已处理 {processed_count} 个区域, 当前发现差异 {len(diff_list)} 条...")
print(f"已处理 {processed_count} 个县/市/旗, 当前发现差异 {len(diff_list)} 条, 缺少经纬度 {len(missing_loc_list)} 条...")
# 2. 调用高德 API 获取 township
amap_township = get_amap_township(lon, lat)
# 2. 调用高德 API 获取 township(传入可配置的 amap_key)
amap_township = get_amap_township(lon, lat, key=amap_key)
# 3. 根据民政部区划代码 mzb_district_code 查询该区域下 has_gov='是' 的街道
query_street = {
@@ -175,17 +264,22 @@ def check_gov_township_diff(**context):
"排查时间": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
})
print(f"[{datetime.now()}] 扫描完成!共遍历区域: {processed_count} 个,发现不一致/缺失记录: {len(diff_list)} 条")
print(f"[{datetime.now()}] 扫描完成!共遍历有效区域: {processed_count} 个,缺少经纬度区域: {len(missing_loc_list)} 个,发现不一致/缺失街道: {len(diff_list)} 条")
# 5. 生成 Excel 并邮件发送
# 5. 生成 Excel 并邮件发送(包含两个 Sheet)
tmp_dir = os.path.join(os.path.expanduser('~'), 'tmp', 'gov_diff')
os.makedirs(tmp_dir, exist_ok=True)
today_str = datetime.now().strftime('%Y%m%d_%H%M%S')
excel_path = os.path.join(tmp_dir, f"县政府所在乡镇街道差异排查_{today_str}.xlsx")
df = pd.DataFrame(diff_list)
df.to_excel(excel_path, index=False, engine='openpyxl')
print(f"排查明细已写入 Excel: {excel_path}")
with pd.ExcelWriter(excel_path, engine='openpyxl') as writer:
df_diff = pd.DataFrame(diff_list)
df_diff.to_excel(writer, sheet_name='街道差异名单', index=False)
df_missing = pd.DataFrame(missing_loc_list)
df_missing.to_excel(writer, sheet_name='缺少经纬度区域', index=False)
print(f"排查明细已写入 Excel: {excel_path} (含 '街道差异名单' 与 '缺少经纬度区域' 两个 Sheet)")
# 发送邮件
receiver = "wangwenyan@fangjia.com"
@@ -196,10 +290,11 @@ def check_gov_township_diff(**context):
<p>您好!</p>
<p>系统已完成 206 ES <code>{INDEX_NAME}</code> 索引中县政府所在乡镇街道(<code>has_gov='是'</code>)与高德逆地理街道(<code>township</code>)的比对排查,详情如下:</p>
<ul>
<li><b>总排查区域数:</b> {processed_count} 个</li>
<li><b>发现差异/待核对记录数:</b> {len(diff_list)} 条</li>
<li><b>比对县/市/旗区域数:</b> {processed_count} 个</li>
<li><b>发现街道差异/待核对记录数:</b> {len(diff_list)} 条(见 Sheet: 街道差异名单)</li>
<li><b>缺少经纬度待补全区域数:</b> {len(missing_loc_list)} 个(见 Sheet: 缺少经纬度区域)</li>
</ul>
<p>详细差异名单已附在附件 Excel 中,请人工审核确认。</p>
<p>详细名单已整理在附件 Excel 中,请人工审核确认。</p>
"""
print(f"正在发送审核邮件至: {receiver}, 抄送: {cc_receiver} ...")
@@ -220,6 +315,9 @@ with DAG(
start_date=pendulum.datetime(2024, 1, 1, tz="Asia/Shanghai"),
catchup=False,
description="县政府所在乡镇街道核验排查(每月1日9点)",
params={
"amap_key": AMAP_KEY
},
tags=["poi", "gov", "audit"]
) as dag: